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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
558544dd02eb61df665f69b2bc4c75b7eccbe1b3 | 4be39d7d266a00f543cf89bcf5af111344783205 | /PortableFileSystemWatcher/inotify-cxx-example.cpp | e8b0a273f0f5588d177abbe26abb3c438867d3cb | [] | no_license | nkzxw/lastigen-haustiere | 6316bb56b9c065a52d7c7edb26131633423b162a | bdf6219725176ae811c1063dd2b79c2d51b4bb6a | refs/heads/master | 2021-01-10T05:42:05.591510 | 2011-02-03T14:59:11 | 2011-02-03T14:59:11 | 47,530,529 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | cpp | /* Simple inotify-cxx example which will output all events for /tmp. Exit via CTRL+C.
Author: Thomas Jarosch Licensed under the same licenses as inotify-cxx. */
#include
#include
#include "inotify-cxx.h"
using namespace std;
int main(void)
{
string watch_dir = "/tmp";
try
{
Inotify notify;
InotifyWatch watch(watch_dir, IN_ALL_EVENTS);
notify.Add(watch);
cout << "Watching directory " << watch_dir << endl << endl;
for (;;)
{
notify.WaitForEvents();
size_t count = notify.GetEventCount();
while (count > 0)
{
InotifyEvent event;
bool got_event = notify.GetEvent(&event);
if (got_event)
{
string mask_str;
event.DumpTypes(mask_str);
string filename = event.GetName();
cout << "[watch " << watch_dir << "] ";
cout << "event mask: \"" << mask_str << "\", ";
cout << "filename: \"" << filename << "\"" << endl;
}
count--;
}
}
}
catch (InotifyException &e)
{
cerr << "Inotify exception occured: " << e.GetMessage() << endl;
}
catch (exception &e)
{
cerr << "STL exception occured: " << e.what() << endl;
}
catch (...)
{
cerr << "unknown exception occured" << endl;
}
return 0;
} | [
"fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616"
] | [
[
[
1,
60
]
]
] |
251d45c5bd88e65b6f1927232ee03b08f40e172d | 0b1a87e3aac9d80f719a34e5522796cdb061d64d | /mp4v2wrapper.h | 26fb4b617f6645f92c996d01a89e002b1f361ae1 | [] | no_license | xiangruipuzhao/qaac | 6769239471d920d42095a916c94ab0e706a76619 | ed2a1392a3c6c9df2046bd559b6486965928af53 | refs/heads/master | 2021-01-21T01:39:23.237184 | 2011-02-05T14:01:10 | 2011-02-05T14:01:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | h | #ifndef MP4V2WRAPPER_H
#define MP4V2WRAPPER_H
#include <stdint.h>
#include <string>
#include <stdexcept>
#undef FindAtom
#include "impl.h"
std::string format_mp4error(const mp4v2::impl::MP4Error &e);
inline void handle_mp4error(mp4v2::impl::MP4Error *e)
{
std::runtime_error re(format_mp4error(*e));
delete e;
throw re;
}
class MP4FileX: public mp4v2::impl::MP4File {
public:
MP4FileX(uint32_t verbosity=0): mp4v2::impl::MP4File(verbosity) {}
MP4TrackId AddAlacAudioTrack(uint32_t timeScale, const uint8_t *cookie,
size_t cookieLength);
bool SetMetadataString(const char *atom, const char *value);
bool SetMetadataTrack(uint16_t track, uint16_t totalTracks);
bool SetMetadataDisk(uint16_t disk, uint16_t totalDisks);
bool SetMetadataUint8(const char *atom, uint8_t value);
bool SetMetadataUint16(const char *atom, uint16_t value);
bool SetMetadataFreeForm(const char *name, const char *mean,
const uint8_t* pValue, uint32_t valueSize,
mp4v2::impl::itmf::BasicType typeCode
=mp4v2::impl::itmf::BT_IMPLICIT);
protected:
mp4v2::impl::MP4DataAtom *CreateMetadataAtom(const char *name,
mp4v2::impl::itmf::BasicType typeCode);
mp4v2::impl::MP4DataAtom *FindOrCreateMetadataAtom(const char *atom,
mp4v2::impl::itmf::BasicType typeCode);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
3d2d1c21a791f5c3be86bec5d439e05350ee1723 | c0a577ec612a721b324bb615c08882852b433949 | /englishplayer/EnTranscription/AudioProcess.h | d131f65cfec2a73846da6856544ff6272778f929 | [] | no_license | guojerry/cppxml | ca87ca2e3e62cbe2a132d376ca784f148561a4cc | a4f8b7439e37b6f1f421445694c5a735f8beda71 | refs/heads/master | 2021-01-10T10:57:40.195940 | 2010-04-21T13:25:29 | 2010-04-21T13:25:29 | 52,403,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | #pragma once
#include "AudioDoc.h"
#include "Mfcc.h"
class CAudioProcess
{
public:
CAudioProcess(CAudioDoc* pParent);
virtual ~CAudioProcess(void);
public:
void Init(int nChannels);
void ProcessSample(char* pDataIn, DWORD dwSampleCounts);
void GetDrawData(int eType, float* pData, int& nLen);
private:
// CMfcc m_mfcc;
short m_buffer[2][FFT_LEN];
float m_waveform[4][FFT_LEN]; //Get to draw waveform, time domain
float m_cep[4][MFCCVECTOR]; //Get to draw cepstrum, qerfuency domain
float m_frequency[4][FREQBAND]; //Get to draw spectrum, frequency domain
double m_eTotalEnergy;
long m_nTotalWindow;
CAudioDoc* m_pParent;
int m_nCurrentIndex;
int m_nChannels;
float64 m_eMeans[2]; //Max 2 channels
};
| [
"oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9"
] | [
[
[
1,
29
]
]
] |
2933b61b088db75c660fd419ff48def2305d8e66 | a405cf24ef417f6eca00c688ceb9008d80f84e1a | /trunk/FileContent.cpp | 014b71e87b75b496c265aa18a7f49b7cd1ad4d69 | [] | no_license | BackupTheBerlios/nassiplugin-svn | 186ac2b1ded4c0bf7994e6309150aa23bc70b644 | abd9d809851d58d7206008b470680a23d0548ef6 | refs/heads/master | 2020-06-02T21:23:32.923994 | 2010-02-23T21:37:37 | 2010-02-23T21:37:37 | 40,800,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | cpp |
#include "FileContent.h"
#include <wx/wfstream.h>
#include <wx/msgdlg.h>
#include <wx/cmdproc.h>
FileContentObserver::FileContentObserver(){}
FileContentObserver::~FileContentObserver(){}
FileContent::FileContent():
observers(),
m_modified(false),
m_cmdProc(NULL)
{
if ( m_cmdProc ) delete m_cmdProc;
}
FileContent::~FileContent(void)
{
}
bool FileContent::Save(const wxString &filename)
{
wxFileOutputStream store(filename);
SaveObject(store);
if ( store.GetLastError() != wxSTREAM_NO_ERROR )
return false;
SetModified(false);
return true;
}
bool FileContent::Open(const wxString &filename)
{
wxFileInputStream store(filename);
LoadObject(store);
if ( store.GetLastError() != wxSTREAM_NO_ERROR )
return false;
SetModified(false);
NotifyObservers(NULL);
return true;
}
bool FileContent::GetModified(){return m_modified;}
void FileContent::SetModified( bool modified ) {m_modified = modified;}
void FileContent::Modify( bool modified ){SetModified(modified);}
bool FileContent::IsReadOnly(){ return false; }
void FileContent::NotifyObservers(wxObject* hint)
{
std::set<FileContentObserver *>::iterator it;
for (it = observers.begin(); it != observers.end(); it++)
(*it)->Update(hint);//FileContentObserver *
}
void FileContent::AddObserver(FileContentObserver *a)
{
observers.insert(a);
}
void FileContent::RemoveObserver(FileContentObserver *a)
{
observers.erase(a);
}
wxCommandProcessor *FileContent::CreateCommandProcessor()
{
if ( m_cmdProc ) delete m_cmdProc;
m_cmdProc = new wxCommandProcessor();
return m_cmdProc;
}
wxCommandProcessor* FileContent::GetCommandProcessor()
{
if ( !m_cmdProc ) m_cmdProc = CreateCommandProcessor();
return m_cmdProc;
}
| [
"danselmi@1ca45b2e-1973-0410-a226-9012aad761af"
] | [
[
[
1,
75
]
]
] |
4419cab524ccee3b927b86e1acefa04588c7190d | bc0a05b60c7ef7180120c577e377a977abd4c725 | /ColorConfiguration.h | 7534fbb40acfd956fe2deafb8c7479930d4dadf1 | [] | no_license | swak/stonesense | 7f0b821d4dcd48ba02b4c0df2850cd7355b4f2fa | 54b791c019d4874c0880fc44903b26af2925231f | refs/heads/master | 2021-01-06T20:37:39.613771 | 2011-08-04T16:55:09 | 2011-08-04T16:55:09 | 42,753,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | h | #pragma once
#include "common.h"
#include "dfhack/depends/tinyxml/tinyxml.h"
#include <map>
class ColorMaterialConfiguration
{
public:
ALLEGRO_COLOR color;
bool colorSet;
ColorMaterialConfiguration();
} ;
class ColorConfiguration
{
public:
vector<ColorMaterialConfiguration> colorMaterials;
ALLEGRO_COLOR color;
bool colorSet;
ColorConfiguration();
~ColorConfiguration();
} ;
bool addSingleColorConfig( TiXmlElement* elemRoot);
void flushColorConfig(vector<ColorConfiguration>& config);
| [
"Japa.Mala.Illo@4d48de78-bd66-11de-9616-7b1d4728551e"
] | [
[
[
1,
27
]
]
] |
31b98f9da2e4976a33c3cbf1bac33bea7384f8b6 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/include/TileMapLayerInfo.h | 9e47e97870dbc66d9f899aad9f1916ed8d26d14b | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,025 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TILEMAPLAYERINFO_H
#define TILEMAPLAYERINFO_H
#include "config.h"
#include "MC2SimpleString.h"
#include <vector>
#include <set>
class BitBuffer;
/**
* Class containing information about a layer.
*/
class TileMapLayerInfo {
public:
/// Creates an empty TileMapLayerInfo
TileMapLayerInfo();
#ifdef MC2_SYSTEM
/// Creates a full TileMapLayerInfo ( mc2 use )
inline TileMapLayerInfo( uint32 id,
const MC2SimpleString& name,
uint32 updatePeriodMin,
bool optional,
bool visibleByDefault,
bool alwaysFetchStrings,
bool affectedByACPMode = false,
bool fetchLayerWhenACPEnabled = false,
bool fetchLayerWhenACPDisabled = false
) :
m_id(id),
m_name(name),
m_updatePeriod( updatePeriodMin ),
m_transient( updatePeriodMin ),
m_isOptional( optional ),
m_serverOverride( 0 ),
// Assume that it is present in TMFD since it is created there.
m_presentInTileMapFormatDesc( true ),
m_visible( visibleByDefault ),
m_alwaysFetchStrings( alwaysFetchStrings ),
m_affectedByACPMode( affectedByACPMode ),
m_fetchLayerWhenACPEnabled( fetchLayerWhenACPEnabled ),
m_fetchLayerWhenACPDisabled( fetchLayerWhenACPDisabled ) {}
#endif
// Allowed to be set by the user
/// Fills in the period. 0 for non-updateable layers.
bool setUpdatePeriodMinutes( uint32 period );
/// Gets the update period
inline uint32 getUpdatePeriodMinutes() const;
/// Sets if the layer should be shown or not
bool setVisible( bool visible );
/// Returns true if the layer should be shown
inline bool isVisible() const;
// End allowed to be set by the user
/// Gets if the layer is optional and present, i.e. should be displayed.
inline bool isOptionalAndPresent() const;
/// Gets the name (UTF-8)
inline const MC2SimpleString& getName() const;
/// Sets if the layer is optional. @return modified
bool setOptional( int optional );
/// Return if the layer is optional
inline bool isOptional() const;
/// Sets if the layer is present in TMFD. @return modified
bool setPresent( bool present );
/// Returns if the layer is present in the TMFD
inline bool isPresent() const;
/// Gets the id
inline uint32 getID() const;
/// Returns true if the layer is transient and should not be saved in cache
inline bool isTransient() const;
/// Sets the server override number and returns true if changed.
bool setServerOverrideNumber( uint8 nbr );
/// Returns the server override number.
inline uint8 getServerOverrideNumber() const;
/// True if the strings should be fetched auto or when clicked.
inline bool alwaysFetchStrings() const;
/**
* Set if the ACP mode setting (enable/disable Access Controlled POIs)
* should apply for this layer.
* @return modified
*/
bool setAffectedByACPMode( bool affected );
/**
* Set if the ACP mode setting (enable/disable Access Controlled POIs)
* should apply for this layer.
*/
bool isAffectedByACPMode() const;
/**
* Only valid if isAffectedByACPMode() returns true!
*
* Set if the layer should be fetched when ACP mode is enabled.
* This setting should override any other visibility settings.
* @return modified
*/
bool setFetchLayerWhenACPEnabled( bool fetch );
/**
* Only valid if isAffectedByACPMode() returns true!
*
* Set if the layer should be fetched when ACP mode is enabled.
* This setting should override any other visibility settings.
*/
bool getFetchLayerWhenACPEnabled() const;
/**
* Only valid if isAffectedByACPMode() returns true!
*
* Set if the layer should be fetched when ACP mode is disabled.
* This setting should override any other visibility settings.
* @return modified
*/
bool setFetchLayerWhenACPDisabled( bool fetch );
/**
* Only valid if isAffectedByACPMode() returns true!
*
* Get if the layer should be fetched when ACP mode is disabled.
* This setting should override any other visibility settings.
*/
bool getFetchLayerWhenACPDisabled() const;
/// Fills in a new TileMapLayerInfo
void setIDAndName( uint32 id,
const MC2SimpleString& name );
/// Saves all contents in the buffer.
int save( BitBuffer& buf ) const;
/// Loads all contents from the buffer.
int load( BitBuffer& buf );
/// Return the size of the data in a buffer.
int getSizeInDataBuffer() const;
private:
/// The id of the layer
uint32 m_id;
/// The name of the layer
MC2SimpleString m_name;
/// Suggested update period for updatable layers.
uint32 m_updatePeriod;
/// True if the layer is transient. If 1 then don't save in file cache.
bool m_transient;
/// True if the layer is optional
bool m_isOptional;
/// Server override number
uint8 m_serverOverride;
/// True if the layer is present in the current TileMapFormatDesc
bool m_presentInTileMapFormatDesc;
/// True if the layer is visible
bool m_visible;
/// True if the strings should be fetched without click
bool m_alwaysFetchStrings;
/**
* If the ACP mode setting (enable/disable Access Controlled POIs)
* should apply for this layer.
*/
bool m_affectedByACPMode;
/**
* Only valid if m_affectedByACPMode is true!
*
* If the layer should be fetched when ACP mode is enabled.
* This setting should override any other visibility settings.
*/
bool m_fetchLayerWhenACPEnabled;
/**
* Only valid if m_affectedByACPMode is true!
*
* If the layer should be fetched when ACP mode is disabled.
* This setting should override any other visibility settings.
*/
bool m_fetchLayerWhenACPDisabled;
};
inline
bool
TileMapLayerInfo::isVisible() const
{
return m_visible;
}
inline
bool
TileMapLayerInfo::isTransient() const
{
return m_transient;
}
inline bool
TileMapLayerInfo::isOptional() const
{
return m_isOptional;
}
inline uint8
TileMapLayerInfo::getServerOverrideNumber() const
{
return m_serverOverride;
}
inline const MC2SimpleString&
TileMapLayerInfo::getName() const
{
return m_name;
}
inline uint32
TileMapLayerInfo::getID() const
{
return m_id;
}
inline uint32
TileMapLayerInfo::getUpdatePeriodMinutes() const
{
return m_updatePeriod;
}
inline bool
TileMapLayerInfo::isOptionalAndPresent() const
{
return m_isOptional && m_presentInTileMapFormatDesc;
}
inline bool
TileMapLayerInfo::isPresent() const
{
return m_presentInTileMapFormatDesc;
}
inline bool
TileMapLayerInfo::alwaysFetchStrings() const
{
return m_alwaysFetchStrings;
}
/**
* Container for the TileMapLayerInfos
*/
class TileMapLayerInfoVector : public std::vector<TileMapLayerInfo> {
public:
/**
* Updates the layers from the client settings, this is
* assumed to be the vector from the TileMapFormatDesc.
*/
bool updateLayers( TileMapLayerInfoVector& clientVector,
const std::set<int>& existingLayers );
/**
* Puts the id:s of the layers to be displayed into
* the set.
* @param acpModeEnabled If the ACP is enabled or disabled
* (i.e. POI Downloads: Normal / Minimize).
* @return true if the layers to display have changed.
*/
bool updateLayersToDisplay( std::set<int>& layerIDs,
bool acpModeEnabled ) const;
/// Returns the info for the layer with the supplied id
const TileMapLayerInfo* getLayerInfo( uint32 layerID ) const;
/// Saves all contents in the buffer.
int save( BitBuffer& buf ) const;
/// Loads all contents from the buffer.
int load( BitBuffer& buf );
/// Return the size of the data in a buffer.
int getSizeInDataBuffer() const;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
303
]
]
] |
b9a0204c1f70ed7f1ded3584f674597fd16f9f3c | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestnote/src/bctestnotedocument.cpp | c7ca23f87e3df24ca14f8766711860d93101a383 | [] | 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 | 2,139 | cpp | /*
* Copyright (c) 2006 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: Implements test bc for note control document.
*
*/
// INCLUDE FILES
#include "bctestnotedocument.h"
#include "bctestnoteappUi.h"
// ================= MEMBER FUNCTIONS ========================================
// ---------------------------------------------------------------------------
// CBCTestNoteDocument* CBCTestNoteDocument::NewL( CEikApplication& )
// Symbian OS two-phased constructor.
// ---------------------------------------------------------------------------
//
CBCTestNoteDocument* CBCTestNoteDocument::NewL( CEikApplication& aApp )
{
CBCTestNoteDocument* self = new( ELeave ) CBCTestNoteDocument( aApp );
return self;
}
// ---------------------------------------------------------------------------
// CBCTestNoteDocument::~CBCTestNoteDocument()
// Destructor.
// ---------------------------------------------------------------------------
//
CBCTestNoteDocument::~CBCTestNoteDocument()
{
}
// ---------------------------------------------------------------------------
// CBCTestNoteDocument::CBCTestNoteDocument( CEikApplication& )
// Overload constructor.
// ---------------------------------------------------------------------------
//
CBCTestNoteDocument::CBCTestNoteDocument( CEikApplication& aApp )
: CEikDocument( aApp )
{
}
// ---------------------------------------------------------------------------
// CEikAppUi* CBCTestNoteDocument::CreateAppUiL()
// Constructs CBCTestVolumeAppUi.
// ---------------------------------------------------------------------------
//
CEikAppUi* CBCTestNoteDocument::CreateAppUiL()
{
return new( ELeave ) CBCTestNoteAppUi;
}
| [
"none@none"
] | [
[
[
1,
63
]
]
] |
74603260b57e9831184d14d3cd3e917714305f0b | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/BASIC1/BASIC1.CPP | 07ec222c0101a528afee34c7c4c0d076adf87726 | [] | 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 | 2,988 | cpp | // Basic1.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include <afxdllx.h>
#define __Basic1_CPP
#include "sc_defs.h"
#include "scdver.h"
#include "Basic1.h"
#include "Models.h"
#include "sfe_srvr.h"
//===========================================================================
//
// Visual C++ Stuff
//
//===========================================================================
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
static AFX_EXTENSION_MODULE Basic1DLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE1("Basic1.DLL Initializing %08x!\n", hInstance);
// Extension DLL one-time initialization
if (!AfxInitExtensionModule(Basic1DLL, hInstance))
return 0;
// Insert this DLL into the resource chain
new CDynLinkLibrary(Basic1DLL);
if (!MakeVersionOK("Basic1.DLL", _MAKENAME, SCD_VERINFO_V0, SCD_VERINFO_V1, SCD_VERINFO_V2, SCD_VERINFO_V3))
return 0;
// ForceLoadModelLibrary();
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("Basic1.DLL Terminating!\n");
AfxTermExtensionModule(Basic1DLL);
}
return 1; // ok
}
//---------------------------------------------------------------------------
#define DLLEXPORT __declspec( dllexport )
//---------------------------------------------------------------------------
extern "C" DLLEXPORT BOOL FilterDllMsg(LPMSG lpMsg)
{
return AfxGetApp()->PreTranslateMessage(lpMsg);
}
//---------------------------------------------------------------------------
extern "C" DLLEXPORT void ProcessDllIdle()
{
// flush it all at once
long lCount = 0;
while (AfxGetApp()->OnIdle(lCount))
lCount++;
}
//---------------------------------------------------------------------------
extern "C" DLLEXPORT BOOL IsFlowLibDLL()
{
return TRUE;
}
//---------------------------------------------------------------------------
extern "C" DLLEXPORT BOOL GetDLLInfo(MDLLInfo* pDLLInfo)
{
pDLLInfo->iPriority = 3;
pDLLInfo->sName = "Basic1";
//pDLLInfo->AddDependentDLL("FlwLib");
pDLLInfo->AddDependentDLL("MdlBase");
return TRUE;
}
//---------------------------------------------------------------------------
extern "C" DLLEXPORT CMdlCfgBase* GetCfgPropPg(int iPage, CMdlCfgSheet * pSheet)
{
return NULL;
};
//===========================================================================
//
//
//
//===========================================================================
void ForceLoad_Basic1()
{
// Dummy Function to allow other libraries to force load this one
}
//===========================================================================
//
//
//
//===========================================================================
| [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
df806865e4f0050343d6c7abec53f5b0b2a8cd67 | 8a5788f252ecbe9c1a806b3ab82af618e075a122 | /sasdfasdf/iv_util.cpp | 1b4c852d99cf53d767a95a7bbce75240ab400f9f | [] | no_license | ivan4869/mydigger | 0ff29421268b4adbc960bd3dd123e4696b805c97 | 849b7e3129a2ec14f37e9a439ced099c1e02c781 | refs/heads/master | 2021-01-10T10:25:14.299264 | 2011-06-21T12:15:47 | 2011-06-21T12:15:47 | 36,677,468 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,112 | cpp | #include "iv_util.h"
namespace iv{
inline void staterr(void)
{
switch(errno)
{
case EBADF:
perror("Bad file descriptor!");
break;
case EIO:
perror("I/O error!");
break;
case EINVAL:
perror("Invalid parameter: buffer was NULL!");
break;
case ENOMEM:
perror("Not enough memory!");
break;
case EACCES:
perror("Permission denied!");
break;
case EBUSY:
perror("Device or resource busy!");
break;
case ENOENT:
perror("File or path not found.");
break;
default:
// An unrelated error occured
perror("Unexpected error!");
}
}
int stat(const string & fname, iv::stat_t *p_fstat)
{
int r;
if(-1 == (r=::_stat(fname.c_str(), p_fstat)))
staterr();
return r;
}
int checkopen(const string & fname, int flag, int pmod)
{
errno_t i_err;
int fh;
i_err = _sopen_s(&fh, fname.c_str(), flag, _SH_DENYNO, pmod);
if(i_err){
switch(i_err){
case EACCES:
errexit("Given path is a directory, or file is read-only, but an \
open-for-writing operation was attempted.");
break;
case EEXIST:
errexit("_O_CREAT and _O_EXCL flags were specified, but filename \
already exists.");
break;
case EINVAL:
errexit("Invalid oflag or pmode argument. ");
break;
case EMFILE:
errexit("No more file descriptors available (too many open files).");
break;
case ENOENT:
errexit("File or path not found.");
break;
default:
errexit("For more information about these and other return codes, see \
_doserrno, errno, _sys_errlist, and _sys_nerr.");
}
}
return fh;
}
int open_or_exit(const string & fname, int flag, int pmod)
{
errno_t i_err;
int fh;
i_err = _sopen_s(&fh, fname.c_str(), flag, _SH_DENYNO, pmod);
if(i_err){
switch(i_err){
case EACCES:
errexit("Given path is a directory, or file is read-only, but an \
open-for-writing operation was attempted.");
break;
case EEXIST:
errexit("_O_CREAT and _O_EXCL flags were specified, but filename \
already exists.");
break;
case EINVAL:
errexit("Invalid oflag or pmode argument. ");
break;
case EMFILE:
errexit("No more file descriptors available (too many open files).");
break;
case ENOENT:
errexit("File or path not found.");
break;
default:
errexit("For more information about these and other return codes, see \
_doserrno, errno, _sys_errlist, and _sys_nerr.");
}
}
return fh;
}
void make_path(const string & filename, const char *drive, const char *dir, const char *ext)
{
char path_buffer[_MAX_PATH];
string path;
size_t pos1=0, pos2=0;
_makepath_s(path_buffer, drive, dir, filename.c_str(), ext);
path = path_buffer;
pos2 = path.find_first_of("\\/", pos1);
while(string::npos != pos2){
string dir = path.substr(0, pos2);
if(dir.size()){
_mkdir(dir.c_str());
pos1 = pos2+1;
if(pos1 < path.size() )
pos2 = path.find_first_of("\\/", pos1);
else
break;
}
else{
pos1 = pos2+1;
if(pos1 < path.size() )
pos2 = path.find_first_of("\\/", pos1);
else
break;
}
}
return ;
}
int write_file(const string & filename, const unsigned char *buff, unsigned len){
int fh;
errno_t i_err;
int num = -1;
i_err = _sopen_s(&fh, filename.c_str(), _O_BINARY | _O_WRONLY | _O_CREAT | _O_TRUNC,
_SH_DENYNO, _S_IREAD | _S_IWRITE);
if(!i_err){
num = ::_write(fh, buff, len);
_close(fh);
}
else{
cerr << "It was failed to write the file " << filename << endl;
}
return num;
}
int writetail(int fd, const void *buff, unsigned int count){
int cnt=0;
if(_isatty(fd)){
::_lseeki64(fd, _filelengthi64(fd), 0);
cnt = write(fd, buff, count);
}
else
cerr << "fd `" << fd << "' has not been redirected to a file\n";
return cnt;
}
long long writef2f(int fd_dest, int fd_src){
long long cnt = -1;
if(_isatty(fd_dest) && _isatty(fd_src)){
unsigned long long pages;
unsigned tail;
const unsigned pagesize = 4096;// 4K per page
const unsigned addrlen = 12; // log2(4K)
char buf[pagesize];
cnt = ::_filelengthi64(fd_src);
pages = cnt >> addrlen;
tail = cnt % pagesize;
for(unsigned long long i=0; i<pages; i++){
read(fd_src, buf, pagesize);
write(fd_dest, buf, pagesize);
}
if(tail){
read(fd_src, buf, tail);
write(fd_dest, buf, tail);
}
}
return cnt;
}
long long filecat(int fd_dest, int fd_src){
long long cnt = -1;
if(_isatty(fd_dest) && _isatty(fd_src)){
unsigned long long pages;
unsigned tail;
const unsigned pagesize = 4096;// 4K per page
const unsigned addlen = 12; // log2(4K)
char buf[pagesize];
cnt = _filelengthi64(fd_src);
pages = cnt >> 12;
tail = cnt % pagesize;
::_lseeki64(fd_dest, _filelengthi64(fd_dest), 0);
for(unsigned long long i=0; i<pages; i++){
::_read(fd_src, buf, pagesize);
::_write(fd_dest, buf, pagesize);
}
if(tail){
::_read(fd_src, buf, tail);
::_write(fd_dest, buf, tail);
}
}
return cnt;
}
inline int write(int fd, const void *buff, unsigned count){
long r;
if(-1 == (r=::_write(fd, buff, count))){
switch(errno)
{
case EBADF:
perror("Bad file descriptor!");
break;
case ENOSPC:
perror("No space left on device!");
break;
case EINVAL:
perror("Invalid parameter: buffer was NULL!");
break;
default:
// An unrelated error occured
perror("Unexpected error!");
}
}
return r;
}
inline int read(int fd, void *buff, unsigned count){
int r;
if(-1 == (r=::_read(fd, buff, count))){
switch(errno)
{
case EBADF:
perror("Bad file descriptor!");
break;
case EIO:
perror("I/O error!");
break;
case EINVAL:
perror("Invalid parameter: buffer was NULL!");
break;
case ENOMEM:
perror("Not enough memory!");
break;
case EACCES:
perror("Permission denied!");
break;
case EBUSY:
perror("Device or resource busy!");
break;
default:
// An unrelated error occured
perror("Unexpected error!");
}
}
return r;
}
int close(int fd){
int r;
if(-1 == (r = ::_close(fd))){
staterr();
}
return r;
}
mbstate_t in_cvt_state;
mbstate_t out_cvt_state;
wstring s2ws(const std::string& s, const std::locale & sys_loc)
{
const char* src_str = s.c_str();
const size_t BUFFER_SIZE = s.size() + 1;
wchar_t* intern_buffer = new wchar_t[BUFFER_SIZE];
wmemset(intern_buffer, 0, BUFFER_SIZE);
const char* extern_from = src_str;
const char* extern_from_end = extern_from + s.size();
const char* extern_from_next = 0;
wchar_t* intern_to = intern_buffer;
wchar_t* intern_to_end = intern_to + BUFFER_SIZE;
wchar_t* intern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
CodecvtFacet::result cvt_rst =
std::use_facet<CodecvtFacet>(sys_loc).in(
in_cvt_state,
extern_from, extern_from_end, extern_from_next,
intern_to, intern_to_end, intern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch(cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check in_cvt_state."
<< std::endl;
}
std::wstring result = intern_buffer;
delete []intern_buffer;
return result;
}
string ws2s(const std::wstring& ws, const std::locale & sys_loc)
{
const wchar_t* src_wstr = ws.c_str();
const size_t MAX_UNICODE_BYTES = 4;
const size_t BUFFER_SIZE =
ws.size() * MAX_UNICODE_BYTES + 1;
char* extern_buffer = new char[BUFFER_SIZE];
memset(extern_buffer, 0, BUFFER_SIZE);
const wchar_t* intern_from = src_wstr;
const wchar_t* intern_from_end = intern_from + ws.size();
const wchar_t* intern_from_next = 0;
char* extern_to = extern_buffer;
char* extern_to_end = extern_to + BUFFER_SIZE;
char* extern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
CodecvtFacet::result cvt_rst =
std::use_facet<CodecvtFacet>(sys_loc).out(
out_cvt_state,
intern_from, intern_from_end, intern_from_next,
extern_to, extern_to_end, extern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch(cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check out_cvt_state."
<< std::endl;
}
std::string result = extern_buffer;
delete []extern_buffer;
return result;
}
}
| [
"shaoxul@16bbe4b2-c270-ae9f-36db-af6ef2b0ee23"
] | [
[
[
1,
383
]
]
] |
f80f111d149ba87a17f06ccd1f874ce659759864 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/DirectoryInfo.cpp | 954855166cf77974a79edb6b2a6451f672f88ddd | [] | 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 | 81 | cpp | #include <Halak/PCH.h>
#include <Halak/DirectoryInfo.h>
namespace Halak
{
} | [
"[email protected]"
] | [
[
[
1,
6
]
]
] |
012a90d3aad7674efe2f96fc48dfdd97c6f9fda6 | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/ReportAsistent/CSkeletonDoc.h | 46072945ab42999d0eb0cef5d7c1193cbbdd9bd9 | [] | no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,333 | h | // CSkeletonDoc.h : interface of the CSkeletonDoc class
//
/////////////////////////////////////////////////////////////////////////////
/*
This file is part of LM Report Asistent.
Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
LM Report Asistent is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if !defined(AFX_CSKELETONDOC_H__AF6E6924_ED51_4710_9D19_8B36BB8CCF94__INCLUDED_)
#define AFX_CSKELETONDOC_H__AF6E6924_ED51_4710_9D19_8B36BB8CCF94__INCLUDED_
class CSkeletonView;
//#define DONT_CLONE_REPORT_BEFORE_GENERATE
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/**
* class CSkeletonDoc: The class of every document of LM-RA application.
*
* @author
*/
class CSkeletonDoc : public CDocument
{
protected: // create from serialization only
CSkeletonDoc();
DECLARE_DYNCREATE(CSkeletonDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSkeletonDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
virtual BOOL OnSaveDocument(LPCTSTR lpszPathName);
//}}AFX_VIRTUAL
// Implementation
public:
BOOL InsertNewElementAndUpdateTreeCtrl( BOOL bEdit,CElementManager::elId_t el_what_id, HTREEITEM hParentItem,HTREEITEM hInsertAfter);
void FillTreeControl(CTreeCtrl & tree_control);
virtual ~CSkeletonDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
public:
static MSXML2::IXMLDOMElement * ElementFromItemData(LPARAM item_data);
protected:
CSkeletonView * GetFirstView();
//{{AFX_MSG(CSkeletonDoc)
afx_msg void OnElementEdit();
afx_msg void OnMmgenrep();
afx_msg void OnDelOrphans();
//}}AFX_MSG
afx_msg void OnMmnewelement(UINT nMessageID);
DECLARE_MESSAGE_MAP()
public:
static HTREEITEM InsertNodeToTreeCtrl(MSXML2::IXMLDOMElementPtr pElement,
HTREEITEM hParentItem,
CTreeCtrl & tree_control, HTREEITEM hInsertAfter = TVI_LAST);
private:
MSXML2::IXMLDOMDocumentPtr m_pXMLDom;
public:
static BOOL EditActiveElement(MSXML2::IXMLDOMElementPtr &element);
static LPARAM CreateItemData(MSXML2::IXMLDOMElementPtr & element);
protected:
BOOL InitAndClearXmlDom();
BOOL OpenSkeletonFile(LPCTSTR file_name);
void TransformAttrLinks(MSXML2::IXMLDOMElementPtr & element);
static CElementManager::elId_t ElementIdFromCommandId(UINT command);
BOOL EditElement(MSXML2::IXMLDOMElementPtr & selected_element);
MSXML2::IXMLDOMElementPtr InsertNewElement(CElementManager::elId_t elementID, MSXML2::IXMLDOMElementPtr & parent_element);
MSXML2::IXMLDOMElementPtr InsertNewElement(LPCTSTR element_name, MSXML2::IXMLDOMElementPtr & parent_element);
void GenerTransform1(MSXML2::IXMLDOMElementPtr & doc);
void TransformActiveElements(MSXML2::IXMLDOMElementPtr & element); //rekurzivni
public:
BOOL IsIDInTree (CString Id, MSXML2::IXMLDOMElementPtr pTree);
CString CreateNewIDFromOld(CString old_ID);
BOOL IsIDInTree(CString Id);
BOOL IsDescendantOfElement(MSXML2::IXMLDOMElementPtr pDescendantXMLElm,MSXML2::IXMLDOMElementPtr pAncestorXMLElm);
void ChangeIDsInTree(MSXML2::IXMLDOMElementPtr pXMLElm);
void Generate(BOOL new_word);
CString CreateNewID(CElementManager::elId_t element_type);
static void DeleteItemData(LPARAM data);
public:
afx_msg void OnShowXml();
public:
// renames (to new_publicID) ID of data source in each active element, which has current value of source old_publicID
BOOL updateAElSourcePublicID(LPCTSTR old_publicID, LPCTSTR new_publicID);
public:
// makes a list of "orphans" active elements in skeleton to pOrpList paramter, returns a number of orphans found
int findOrphans(MSXML2::IXMLDOMNodeListPtr & pOrpList);
public:
// finds list of all "orphans active elements" in skeleton and if supported, changes their datasources to default source. Returns number of updated elements
int changeOrphansDataSourceToDefault(void);
public:
BOOL SetReportSettings(LPCTSTR attribute, LPCTSTR value);
CString GetReportSettings(LPCTSTR attribute);
afx_msg void OnResetOrphans();
public:
static CString StrToHtml(CString sText);
public:
static CString HtmlToStr(CString sHtml);
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CSKELETONDOC_H__AF6E6924_ED51_4710_9D19_8B36BB8CCF94__INCLUDED_)
| [
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0",
"chrzm@fded5620-0c03-0410-a24c-85322fa64ba0",
"ibart@fded5620-0c03-0410-a24c-85322fa64ba0",
"kodyj1am@fded5620-0c03-0410-a24c-85322fa64ba0"
] | [
[
[
1,
3
],
[
6,
6
],
[
23,
36
],
[
42,
49
],
[
51,
65
],
[
67,
83
],
[
87,
87
],
[
89,
89
],
[
92,
112
],
[
116,
126
],
[
144,
151
]
],
[
[
4,
5
],
[
7,
22
],
[
37,
37
],
[
39,
41
]
],
[
[
38,
38
],
[
50,
50
],
[
66,
66
],
[
84,
86
],
[
88,
88
],
[
90,
91
],
[
113,
115
],
[
137,
138
],
[
140,
143
]
],
[
[
127,
136
],
[
139,
139
]
]
] |
5a43293ef2d23e143f399eab4e17e5fb5dd8d52d | f71e82b7ed19200280b7164a2e959310d9bfa210 | /ExampleAIModule/ExampleAIModule/CompaniaDefensiva.h | 22ca19782866ba8b6f2603ecb0aeac5cbdabe3dd | [] | no_license | albertouri/manolobot | 05cf4ee217e85f1332e0e063fcc209da4b71c7b5 | 44e7fee46abcf4f1efa6d292ea8ec7cdc57eb7c8 | refs/heads/master | 2021-01-02T08:32:48.281836 | 2011-02-03T23:28:08 | 2011-02-03T23:28:08 | 39,591,406 | 1 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,935 | h | #pragma once
#include <BWAPI.h>
#include <BWTA.h>
#include "Graficos.h"
#include "Utilidades.h"
using namespace BWAPI;
using namespace BWTA;
class CompaniaDefensiva
{
public:
CompaniaDefensiva(Color ID);
~CompaniaDefensiva(void);
// Metodo que se ejecuta en cada frame del juego para realizar distintas tareas
void onFrame();
// Elimina de la lista correspondiente las unidades destruidas, y retorna la cantidad de unidades vivas de la compaņia defensiva
int countMarines();
// Agrega la unidad pasada como parametro a la compaņia defensiva
void asignarUnidad(Unit *U);
// Ordena a los marines de la compaņía atacar la unidad pasada como parámetro
void atacar(Unit *u);
// Realiza un movimiento de ataque hacia la posicion pasada como parametro
void atacar(Position p);
// Retorna true si en la compaņia defensiva hay menos marines de los necesarios
bool faltanMarines();
// Retorna true si en la compaņia defensiva hay menos ghosts de los necesarios
bool faltanGhosts();
// Retorna true si en la compaņia defensiva hay menos medicos de los necesarios
bool faltanMedics();
private:
// Listas de unidades de la compaņia defensiva
std::list<Unit*> listMarines;
std::list<Unit*> listGhosts;
std::list<Unit*> listMedics;
// Color especifico para resaltar los soldados de cada compaņia, seteado en el constructor
Color c;
// Elimina de la lista correspondiente las unidades que no existan mas
void controlarEliminados();
// Busqueda de objetivos para cada tipo de unidad de la compaņia defensiva
Unit* buscarObjetivosGhost();
Unit* buscarObjetivosMedics();
Unit* buscarObjetivosMarines();
// Busca objetivos para cada tipo de unidad y los ataca
void defenderBaseGhosts();
void defenderBaseMedics();
void defenderBaseMarines();
// Resalta las unidades de la compaņia defensiva
void recuadrarUnidades();
};
| [
"marianomoreno3@82b963ee-1e64-6eb5-a9c5-6632919fd137"
] | [
[
[
1,
65
]
]
] |
786d3faacfd108897a9513948f97eded1c0120f3 | c5176b11a3c23df5f4d9d9788c325ba05aaef545 | /src/underTest/wpan/battery/Energy.h | 75cd61ccc0238519d3a8dc332a4a4d874585840c | [] | no_license | canthefason/inetmanet | 77711b5e42d6e80a68e132a2f525fa448f71ac19 | f8f3cdf1d5e139dc62cbc60e5e6e73de7ba30b0f | refs/heads/master | 2021-01-18T07:37:08.633900 | 2009-04-14T22:59:13 | 2009-04-14T22:59:13 | 176,460 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 558 | h | /**
* @short Class to hold the current energy level of the node.
* @author Isabel Dietrich
*/
#ifndef ENERGY_H
#define ENERGY_H
// SYSTEM INCLUDES
#include <omnetpp.h>
class Energy : public cPolymorphic
{
public:
// LIFECYCLE
Energy(double e=250) : cPolymorphic(), mEnergy(e) {};
// OPERATIONS
double GetEnergy() const { return mEnergy; }
void SetEnergy(double e) { mEnergy = e; }
void SubtractEnergy(double e) { mEnergy -= e; }
private:
// MEMBER VARIABLES
double mEnergy;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
6dc6c4facd32a957e6dadee0206139499f2988bb | 4360326fcaad7f6d8349b676dc5f00cdf29f7144 | /src/simulator/packets/head_realloc.h | 3af27c3204afd943f02f680fe55f53a686758cab | [] | no_license | raxter/WSN_SWEB_sim | 04cfddaaaed05fed17822dcabb27dd2196744de8 | 545e7d1727d913d8b6b90990bda7023fbdd6370f | refs/heads/master | 2020-04-05T23:44:14.001375 | 2009-05-25T02:10:36 | 2009-05-25T02:10:36 | 199,714 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 559 | h | #ifndef __WSN_SIMULATOR_PACKET_HEAD_REALLOC_H__
#define __WSN_SIMULATOR_PACKET_HEAD_REALLOC_H__
#include "../base_packet.h"
namespace WSN
{
namespace Simulator
{
namespace Packet
{
class HeadReAlloc : public BasePacket {
public:
HeadReAlloc (int sendStrength, const Node::BaseNode& node, int srcGrpId, int newHeadId);
~HeadReAlloc ();
const int srcGrpId;
const int newHeadId;
};
} /* end of namespace Packet */
} /* end of namespace Simulator */
} /* end of namespace WSN */
#endif // __WSN_SIMULATOR_PACKET_H__
| [
"richard@richard-laptop-old.(none)"
] | [
[
[
1,
36
]
]
] |
d51422c531388957728de7833853d81492c251c3 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/simon/Source/Board.h | dfdc6fb5e28341e853e745b1f1faed7c42399466 | [] | 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 | 542 | h | #ifndef _BOARD_H
#define _BOARD_H
#include "DebugPrintText2D.h"
#include <vector>
typedef enum ESymbols {SYMBOL_A, SYMBOL_B, SYMBOL_C, SYMBOL_D, SYMBOL_LAST};
class CBoard
{
public:
CBoard();
~CBoard();
void Init();
void ResetSymbols();
void Generate ();
ESymbols Show ();
bool Check (ESymbols symbol);
bool IsFinished ();
void ResetCount();
bool nextSymbol();
private:
std::vector<ESymbols> m_Symbols;
int m_Count;
bool m_isFinished;
};
#endif //_BOARD_H | [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
34
]
]
] |
cca71fdb3b2f97ed88371034eee9c23d3d01b5dd | 073dfce42b384c9438734daa8ee2b575ff100cc9 | /RCF/src/RCF/NamedPipeEndpoint.cpp | e640cc8e093d9ca2b04a5b487e387ad8ef0fcddf | [] | no_license | r0ssar00/iTunesSpeechBridge | a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf | 71a27a52e66f90ade339b2b8a7572b53577e2aaf | refs/heads/master | 2020-12-24T17:45:17.838301 | 2009-08-24T22:04:48 | 2009-08-24T22:04:48 | 285,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | cpp |
//******************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved.
// Consult your license for conditions of use.
// Version: 1.1
// Contact: jarl.lindrud <at> gmail.com
//******************************************************************************
#include <RCF/NamedPipeEndpoint.hpp>
#include <RCF/InitDeinit.hpp>
#ifdef RCF_USE_SF_SERIALIZATION
#include <SF/Registry.hpp>
#endif
#if defined(BOOST_WINDOWS)
#include <RCF/Win32NamedPipeClientTransport.hpp>
#include <RCF/Win32NamedPipeServerTransport.hpp>
#else
#include <RCF/UnixLocalServerTransport.hpp>
#include <RCF/UnixLocalClientTransport.hpp>
#endif
namespace RCF {
NamedPipeEndpoint::NamedPipeEndpoint()
{}
NamedPipeEndpoint::NamedPipeEndpoint(const tstring & pipeName) :
mPipeName(pipeName)
{}
#if defined(BOOST_WINDOWS)
ServerTransportAutoPtr NamedPipeEndpoint::createServerTransport() const
{
return ServerTransportAutoPtr(
new Win32NamedPipeServerTransport(mPipeName));
}
ClientTransportAutoPtr NamedPipeEndpoint::createClientTransport() const
{
return ClientTransportAutoPtr(
new Win32NamedPipeClientTransport(mPipeName));
}
#else
ServerTransportAutoPtr NamedPipeEndpoint::createServerTransport() const
{
return ServerTransportAutoPtr(new UnixLocalServerTransport(mPipeName));
}
ClientTransportAutoPtr NamedPipeEndpoint::createClientTransport() const
{
return ClientTransportAutoPtr(new UnixLocalClientTransport(mPipeName));
}
#endif
EndpointPtr NamedPipeEndpoint::clone() const
{
return EndpointPtr( new NamedPipeEndpoint(*this) );
}
inline void initNamedPipeEndpointSerialization()
{
#ifdef RCF_USE_SF_SERIALIZATION
SF::registerType( (NamedPipeEndpoint *) 0, "RCF::NamedPipeEndpoint");
SF::registerBaseAndDerived( (I_Endpoint *) 0, (NamedPipeEndpoint *) 0);
#endif
}
RCF_ON_INIT_NAMED( initNamedPipeEndpointSerialization(), InitNamedPipeEndpointSerialization );
} // namespace RCF
| [
"[email protected]"
] | [
[
[
1,
78
]
]
] |
19275865e6769f2d8f73ed1e114e28515c11c82d | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/signal_source.hpp | 6ab97b796bf45f0367949ac4253f991b66ff8926 | [] | 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 | 6,061 | hpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
/**
* @file
* @brief Generated from signal_source.xsd.
*/
#ifndef AOSLCPP_AOSL__SIGNAL_SOURCE_HPP
#define AOSLCPP_AOSL__SIGNAL_SOURCE_HPP
// Begin prologue.
//
#include <aoslcpp/common.hpp>
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include "aosl/signal_source_forward.hpp"
#include <memory> // std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include <xsd/cxx/tree/containers-wildcard.hxx>
#ifndef XSD_DONT_INCLUDE_INLINE
#define XSD_DONT_INCLUDE_INLINE
#undef XSD_DONT_INCLUDE_INLINE
#else
#endif // XSD_DONT_INCLUDE_INLINE
/**
* @brief C++ namespace for the %artofsequence.org/aosl/1.0
* schema namespace.
*/
namespace aosl
{
/**
* @brief Class corresponding to the %signal_source schema type.
*
* Name of a signal source, interpreted by the player/interpreter in an
* undefined way.
*
* @nosubgrouping
*/
class Signal_source: public ::xml_schema::String
{
public:
/**
* @name Constructors
*/
//@{
/**
* @brief Create an instance from initializers for required
* elements and attributes.
*/
Signal_source ();
/**
* @brief Create an instance from a C string and initializers
* for required elements and attributes.
*/
Signal_source (const char*);
/**
* @brief Create an instance from a string andinitializers
* for required elements and attributes.
*/
Signal_source (const ::std::string&);
/**
* @brief Create an instance from the ultimate base and
* initializers for required elements and attributes.
*/
Signal_source (const ::xml_schema::String&);
/**
* @brief Create an instance from a DOM element.
*
* @param e A DOM element to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Signal_source (const ::xercesc::DOMElement& e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a DOM attribute.
*
* @param a A DOM attribute to extract the data from.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Signal_source (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Create an instance from a string fragment.
*
* @param s A string fragment to extract the data from.
* @param e A pointer to DOM element containing the string fragment.
* @param f Flags to create the new instance with.
* @param c A pointer to the object that will contain the new
* instance.
*/
Signal_source (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy constructor.
*
* @param x An instance to make a copy of.
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
*
* For polymorphic object models use the @c _clone function instead.
*/
Signal_source (const Signal_source& x,
::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0);
/**
* @brief Copy the instance polymorphically.
*
* @param f Flags to create the copy with.
* @param c A pointer to the object that will contain the copy.
* @return A pointer to the dynamically allocated copy.
*
* This function ensures that the dynamic type of the instance is
* used for copying and should be used for polymorphic object
* models instead of the copy constructor.
*/
virtual Signal_source*
_clone (::xml_schema::Flags f = 0,
::xml_schema::Container* c = 0) const;
//@}
/**
* @brief Destructor.
*/
virtual
~Signal_source ();
};
}
#ifndef XSD_DONT_INCLUDE_INLINE
#endif // XSD_DONT_INCLUDE_INLINE
#include <iosfwd>
namespace aosl
{
::std::ostream&
operator<< (::std::ostream&, const Signal_source&);
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace aosl
{
}
#include <iosfwd>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
namespace aosl
{
void
operator<< (::xercesc::DOMElement&, const Signal_source&);
void
operator<< (::xercesc::DOMAttr&, const Signal_source&);
void
operator<< (::xml_schema::ListStream&,
const Signal_source&);
}
#ifndef XSD_DONT_INCLUDE_INLINE
#include "aosl/signal_source.inl"
#endif // XSD_DONT_INCLUDE_INLINE
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__SIGNAL_SOURCE_HPP
| [
"klaim@localhost"
] | [
[
[
1,
235
]
]
] |
2762c8105f2caf3427fbfaf641454f9e052e5f0b | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/PolyGridModifier.h | 1d45fa237068f6e192c2570e1bb7db46531770af | [] | no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,346 | h | // ----------------------------------------------------------------------- //
//
// MODULE : PolyGridModifier.h
//
// PURPOSE : Defines the object PolyGridModifier which exists entirely for
// creating modifiers for a polygrid so that they can be controlled
// easier by artists. Their data will be taken by the polygrids
// and used when updating the surface
//
// CREATED : 1/11/02
//
// ----------------------------------------------------------------------- //
#ifndef __POLYGRIDMODIFIER_H__
#define __POLYGRIDMODIFIER_H__
#include "ltengineobjects.h"
LINKTO_MODULE( PolyGridModifier );
class PolyGridModifier : public BaseClass
{
public :
PolyGridModifier();
~PolyGridModifier();
//the dimensions of this modifier
LTVector m_vDims;
//each time we accelerate, we need to accelerate N samples in the area
uint32 m_nNumAccelPoints;
//for each point we accelerate, we need to accelerate it this much
float m_fAccelAmount;
//whether or not this modifier starts out enabled or not
LTBOOL m_bStartEnabled;
protected :
uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData);
private :
LTBOOL ReadProp(ObjectCreateStruct *pData);
LTBOOL InitialUpdate(LTVector *pMovement);
};
#endif // __POLYGRIDMODIFIER_H__ | [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
c65b3935edace9231bd7e24b233306851f1e9975 | cfc474b8274183a4a2f4a4e06f16006f280e9e43 | /Sudoku/Solver.h | 9cba2313e0c55a24f6dce62d7b1bba4902a850c1 | [] | no_license | neilforrest/verysimplesudoku | 26b1569e611bbb15cb26a7cf0f80ff042ab78c4c | df225f4b98d2657abc2a895b5d73c7aca8847c6a | refs/heads/master | 2020-05-19T20:50:24.132502 | 2008-01-05T21:58:15 | 2008-01-05T21:58:15 | 33,373,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,409 | h | #pragma once
#include <vector>
#include "SudokuBoard.h"
// Position on the board
struct GridPos
{
int x;
int y;
};
class CSolver
{
public:
CSolver(void);
virtual ~CSolver(void);
// Attempt to complete the board, true iff success
bool Solve ( CSudokuBoard* board, bool* possible, int* count, int* curDepth, int* maxDepth, int* progress );
// Print remaining numbers
void PrintRemaining ( );
int* m_progress;
protected:
// Allocate and initialise to place vectors
void InitialiseToPlaceVector ( std::vector<int>*** vectors, int size );
// Remove numbers from to be placed vectors that have already been placed on board
void RemovePlacedNumbers ( CSudokuBoard* board );
// Get grid coords from square coords
void GetGridCoords ( CSudokuBoard* board, int square, int index, int* x, int* y );
// Is the specified number in the specified row
bool IsInRow ( int number, int row );
// Is the specified number in the specified col
bool IsInCol ( int number, int col );
// Is the specified number in the specified square
bool IsInSquare ( int number, int squ );
// Can number be placed in (x,y)
bool IsPlacable ( int number, int x, int y );
// Get square from grid coords
void GetSquareCoords ( CSudokuBoard* board, int *square, int x, int y );
// Returns true when complete
bool Iterate ( bool* possible, int* count, int* curDepth, int* maxDepth );
// Try and put the number in the specified row
bool PlaceInRow ( int number, int row, int *x, bool* possible,
std::vector<GridPos>* possiblePositions );
// Try and put the number in the specified col
bool PlaceInCol ( int number, int col, int *y, bool* possible,
std::vector<GridPos>* possiblePositions );
// Try and put the number in the specified square
bool PlaceInSquare ( int number, int square, int *index, bool* possible,
std::vector<GridPos>* possiblePositions );
// Place the number in the specified gird coordinates
void PlaceNumber ( int number, int x, int y );
// Is the board complete?
bool IsComplete ( );
// Numbers still to be placed in rows
std::vector<int>** rowsToPlace;
// Numbers still to be placed in cols
std::vector<int>** colsToPlace;
// Numbers still to be placed in squares
std::vector<int>** squaresToPlace;
// Current board
CSudokuBoard* m_board;
};
| [
"neil.david.forrest@1c60f1a0-0043-0410-b499-77e8d6643a01"
] | [
[
[
1,
85
]
]
] |
a72f30c23b3dc69899718a994b2f79eddb6371b3 | c524e82d892bc31ccb52abc91a46fcd9ce1d9241 | /core/SnookerCore.h | cd95259bc3aa34ed0a398e6b3ebeab2f5e4115b3 | [] | no_license | wenmengzi/snooker | 368fd1d341e48ed9a4cfc7acce6d8f0e02e7827b | 16ce9a55f334fa24d156dc9a7a6ceffc78ebcfb5 | refs/heads/master | 2021-01-10T01:38:56.748246 | 2007-06-23T16:59:21 | 2007-06-23T16:59:21 | 54,390,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,137 | h | // SnookerCore.h: interface for the CSnookerCore class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SNOOKERCORE_H__12958B13_01AD_4919_8A8C_06EF23099637__INCLUDED_)
#define AFX_SNOOKERCORE_H__12958B13_01AD_4919_8A8C_06EF23099637__INCLUDED_
#include "GLFrame.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define TP_BALL 1
#define TP_HOLE 2
#define TP_STICK 3
#define MAX_NUM_OBJ 42
#define GM_LBUTTONDOWN 1
#define GM_MOUSEMOVE 2
typedef unsigned long GState;
#define GS_RUNNING 0x1
struct FRECT
{
float left;
float top;
float right;
float bottom;
};
struct GAMEOBJECT
{
DWORD type;
BOOL alive;
FLOAT radius;
FLOAT color_r,color_g,color_b,color_a;
FLOAT x,y;
FLOAT vx,vy;
FLOAT ax,ay;
FLOAT rvx,rvy,rvz;
int score;
static FRECT tableface;
static FRECT besidehole[6];
static FLOAT u1;
static FLOAT u2;
static FLOAT k1;
static FLOAT k2;
static FLOAT alpha1;
static FLOAT alpha2;
static FLOAT auz;
static FLOAT vmax;
static int PPF;
static void LoadPhyArg();
};
class CSnookerCore : public CGLFrame
{
public:
void RenewStick();
void ShootWhiteBall();
void ResetObject();
CSnookerCore();
virtual ~CSnookerCore();
LRESULT PostGameMessage(UINT GMsg, WPARAM wParam, LPARAM lParam);
void OnCreate();
void OnPaint();
GAMEOBJECT gobject[MAX_NUM_OBJ];
//Control Message
void OnLButtonDown(UINT nFlags, float x, float y);
void OnLButtonUp(UINT nFlags, float x, float y);
void OnRButtonDown(UINT nFlags, float x, float y);
void OnRButtonUp(UINT nFlags, float x, float y);
void OnMouseMove(UINT nFlags, float x, float y);
//Game State
GState m_state;
int sel;
float lastradius;
// TEST
int frames;
DWORD startTime;
DWORD lastTime;
private:
inline void DrawBall(const GAMEOBJECT *pball);
inline void DrawTable();
inline void DrawStick(const GAMEOBJECT *pstick);
inline void SetLight();
float PhysicalProcess();
BYTE *tableimage;
};
#endif // !defined(AFX_SNOOKERCORE_H__12958B13_01AD_4919_8A8C_06EF23099637__INCLUDED_)
| [
"rickone2007@05450a0b-ae31-0410-b12f-21406559f0cb",
"kydef2007@05450a0b-ae31-0410-b12f-21406559f0cb"
] | [
[
[
1,
14
],
[
16,
16
],
[
23,
59
],
[
62,
78
],
[
81,
88
],
[
90,
90
],
[
92,
98
]
],
[
[
15,
15
],
[
17,
22
],
[
60,
61
],
[
79,
80
],
[
89,
89
],
[
91,
91
]
]
] |
274072744b10926694f363692fdc0e1071533e27 | 05f4bd87bd001ab38701ff8a71d91b198ef1cb72 | /TPDatos/src1/utils/StringUtils.h | 7216ae3415ecb8119f7b17129c0c8578de04c2c1 | [] | no_license | oscarcp777/tpfontela | ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12 | 2489442b81dab052cf87b6dedd33cbb51c2a0a04 | refs/heads/master | 2016-09-01T18:40:21.893393 | 2011-12-03T04:26:33 | 2011-12-03T04:26:33 | 35,110,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | h | #ifndef __STRINGUTILS_H__
#define __STRINGUTILS_H__
#include <string>
#include <iostream>
#include <sstream>
#include <list>
#include <vector>
using namespace std;
class StringUtils{
public:
StringUtils();
/**
* Este metodo quita los espacios en blanco entre los tag
* de una cadena de caracteres
*
*/
static std::string getValorTag(std::string nombretag,vector<string>& tokens);
static string trim(std::string cadena);
static string trimPorTag(std::string cadena);
static std::string trimPalabra(std::string cadena);
static std::string actualizarCadena(string cadena,char char_reemplazable);
static void Tokenize(const string& str, vector<string>& tokens, const string& delimiters );
static int contadorTag(std::string cadena);
static std::string convertirAString( int numero);
private:
};
#endif
| [
"santiagodonikian@a1477896-89e5-11dd-84d8-5ff37064ad4b",
"caceres.oscar7@a1477896-89e5-11dd-84d8-5ff37064ad4b"
] | [
[
[
1,
26
],
[
28,
32
]
],
[
[
27,
27
]
]
] |
b8879fedc0f106bba8b2bde2b1f5136201721da9 | 97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a | /3dc/MEM3DCPP.CPP | aa282777bf08d6303eb0f3436591a94fc83a9fb5 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | SR-dude/AvP-Wine | 2875f7fd6b7914d03d7f58e8f0ec4793f971ad23 | 41a9c69a45aacc2c345570ba0e37ec3dc89f4efa | refs/heads/master | 2021-01-23T02:54:33.593334 | 2011-09-17T11:10:07 | 2011-09-17T11:10:07 | 2,375,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cpp | #include "mem3dc.h"
#if DBGMALLOC
#if 1
// try and turn C++ new/delete tracking on such that
// we can do a malloc dump when the global objects
// with associated memory allocated is recored, the
// deallocation is recored, and then a malloc dump
// is done
// note that some global objects wont have their memory
// allocations/deallocations in the constructor/destructor
// tracked through record_malloc/record_free, but since
// global objects are deconstructed in the reverse order
// from construction, the deallocation type in the destructor
// will correspond to the allocation type in the constructor
int __cpp_new_recording = 0;
class DebugObject
{
public:
DebugObject();
~DebugObject();
};
DebugObject::DebugObject()
{
__cpp_new_recording = 1;
}
DebugObject::~DebugObject()
{
__cpp_new_recording = 0;
DumpMallocInfo(DUMPTOFILE);
}
static DebugObject dbo;
#else
int __cpp_new_recording = 1;
#endif
#endif
| [
"a_jagers@ANTHONYJ.(none)"
] | [
[
[
1,
48
]
]
] |
4c787db5f79ee259f88a486623ec1d06b6ec2b8e | 14bc620a0365e83444dad45611381c7f6bcd052b | /ITUEngine/Managers/SceneGraphManager.cpp | 974aa884e13c29c030741fe187846afdd961bd21 | [] | no_license | jumoel/itu-gameengine | a5750bfdf391ae64407217bfc1df8b2a3db551c7 | 062dd47bc1be0f39a0add8615e81361bcaa2bd4c | refs/heads/master | 2020-05-03T20:39:31.307460 | 2011-12-19T10:54:10 | 2011-12-19T10:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | cpp | #include <Managers/SceneGraphManager.hpp>
#include <SDL.h>
#include "GL/glew.h"
#include <iostream>
#include <memory>
#include <Events/EventData/EventData.hpp>
#include <Math/Vector3f.hpp>
#include <Templates/TSingleton.hpp>
#include "MediaManager.hpp"
#include <Subsystems/Physics/PhysicsSystem.hpp>
#include <Subsystems/Physics/PhysicsModels/PhysicsModel.hpp>
#include <Abstractions/Time.hpp>
SceneGraphManager::SceneGraphManager(Camera *CameraObject, Object *RootNode) :
m_CameraObject(CameraObject),
m_RootNode(RootNode),
LastTime(0),
DeltaTime(0)
{
safeAddListener(EventListenerPointer(this), EventType("mouseClickHUDEvent"));
}
SceneGraphManager::~SceneGraphManager()
{
delete m_CameraObject;
DeleteGraph(m_RootNode);
}
void SceneGraphManager::DeleteGraph(Object* node)
{
if(node->children->size() > 0)
{
for (auto it = node->children->begin(); it != node->children->end(); ++it)
{
DeleteGraph(&(*it));
}
}
//delete node;
}
char const * SceneGraphManager::GetName()
{
return "SceneGraphManager";
}
bool SceneGraphManager::HandleEvent( IEventData const & event )
{
shared_ptr<EventData<Vector3f>> data = dynamic_pointer_cast<EventData<Vector3f>, IEventData>(event.Copy());
auto val = data->GetValue();
//If inside defined box... DO:
Rectangle physicsBox(Point(-0.5f, -0.5f), 1.0f, 1.0f);
auto box = new Object();
box->Name = "HUDBox";
box->model = SINGLETONINSTANCE( MediaManager )->boxModel;
StaticObjectModel* tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE);
box->physicsModel = tempStaticObject;
box->physicsModel->InitializeAsRectangle(physicsBox);
SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject);
srand(Time::GetCurrentMS());
float x = (float)(rand() % 400) / 10.0f;
float y = (float)(rand() % 400) / 10.0f;
box->SetPos2D(x, y);
box->SetScale(2.0f, 2.0f, 5.0f);
m_RootNode->children->push_back(*box);
SINGLETONINSTANCE(PhysicsSystem)->SetStaticPathMap();
return true;
} | [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
13,
14
],
[
17,
19
],
[
21,
21
]
],
[
[
3,
4
]
],
[
[
5,
12
],
[
15,
16
],
[
20,
20
],
[
22,
25
],
[
39,
75
]
],
[
[
26,
38
],
[
76,
76
]
]
] |
2964436e42e8372b977deed98783d244ca62635e | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/v0-1/engine/sound/include/SoundManager.h | 8e7b10be3785bbbf2bb6dfe175918fae505f0582 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,884 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef SOUNDMANAGER_H
#define SOUNDMANAGER_H
#include <OgreResourceManager.h>
#include <OgreSingleton.h>
#include <OgreResourceGroupManager.h>
#include <list>
#include <boost/thread/mutex.hpp>
#include "SoundPrerequisites.h"
#include "SoundSubsystem.h"
namespace rl {
typedef std::list<Ogre::String> StringList;
/**
* Der SoundManager verwaltet die Sounds, die das Spiel benutzt.
* Die Sounds werden geladen und entladen, je nachdem, ob die
* Speichergrenze ueberschritten wurde.
* @author JoSch
* @version 1.0
* @date 04-26-2004
* @version 2.0
* @date 06-29-2005
*/
class _RlSoundExport SoundManager: public Ogre::ResourceManager,
public Ogre::Singleton<SoundManager> {
public:
/// Gibt das Singleton zurueck.
static SoundManager& getSingleton();
/// Gibt einen Zeiger auf das Singleton zurueck.
static SoundManager* getSingletonPtr();
/// Eine Resource erzeugen
/// Konstruktor
SoundManager();
/// Alle Sounds in die Resourcenliste eintragen.
virtual void addSounds(const Ogre::String& groupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
/// erzeugt einen Sound und fügt ihn hinzufuegen (Mit Mutex mittelbar)
virtual void add(const Ogre::String& filename, const Ogre::String& groupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
/// Eine Namesliste erzeugen
StringList getSounds();
virtual Ogre::ResourcePtr create(const Ogre::String& name, const Ogre::String& group,
bool isManual = false, Ogre::ManualResourceLoader* loader = 0,
const Ogre::NameValuePairList* createParams = 0);
protected:
virtual Ogre::Resource* createImpl(const Ogre::String& name, Ogre::ResourceHandle handle,
const Ogre::String& group, bool isManual, Ogre::ManualResourceLoader* loader,
const Ogre::NameValuePairList* createParams);
private:
/// Ein MutEx, um das Hinzufügen der Sounds zu synchronisieren.
boost::mutex mResListMutex;
/// Welche Dateiendung soll verwendet werden.
virtual StringList getExtension();
};
}
#endif
| [
"blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
76
]
]
] |
7bed2af89d599ea79b01142f15110ee91f944404 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Colors.cpp | c2ae9ae73230e5c8c24d19d4162bcce48d32cfb7 | [] | 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 | 14,729 | cpp | #include <Halak/PCH.h>
#include <Halak/Colors.h>
#include <algorithm>
namespace Halak
{
Colors::ItemCollection Colors::items;
const Color* Colors::Find(const String& name)
{
if (items.empty())
FillItems();
struct ComparePredicate
{
bool operator () (const Item& a, const Item& b) const
{
return a.Name.Compare(b.Name) < 0;
}
};
ItemCollection::const_iterator it = std::lower_bound(items.begin(), items.end(), Item(name, Colors::TransparentBlack), ComparePredicate());
if ((*it).Name == name)
return &(*it).Value;
else
return nullptr;
}
const Color Colors::TransparentBlack = Color(0, 0, 0, 0);
const Color Colors::TransparentWhite = Color(255, 255, 255, 0);
const Color Colors::AliceBlue = Color(0xFFF0F8FF);
const Color Colors::AntiqueWhite = Color(0xFFFAEBD7);
const Color Colors::Aqua = Color(0xFF00FFFF);
const Color Colors::AquaMarine = Color(0xFF7FFFD4);
const Color Colors::Azure = Color(0xFFF0FFFF);
const Color Colors::Beige = Color(0xFFF5F5DC);
const Color Colors::Bisque = Color(0xFFFFE4C4);
const Color Colors::Black = Color(0xFF000000);
const Color Colors::BlanchedAlmond = Color(0xFFFFEBCD);
const Color Colors::Blue = Color(0xFF0000FF);
const Color Colors::BlueViolet = Color(0xFF8A2BE2);
const Color Colors::Brown = Color(0xFFA52A2A);
const Color Colors::BurlyWood = Color(0xFFDEB887);
const Color Colors::CadetBlue = Color(0xFF5F9EA0);
const Color Colors::Chartreuse = Color(0xFF7FFF00);
const Color Colors::Chocolate = Color(0xFFD2691E);
const Color Colors::Coral = Color(0xFFFF7F50);
const Color Colors::CornflowerBlue = Color(0xFF6495ED);
const Color Colors::Cornsilk = Color(0xFFFFF8DC);
const Color Colors::Crimson = Color(0xFFDC143C);
const Color Colors::Cyan = Color(0xFF00FFFF);
const Color Colors::DarkBlue = Color(0xFF00008B);
const Color Colors::DarkCyan = Color(0xFF008B8B);
const Color Colors::DarkGoldenRod = Color(0xFFB8860B);
const Color Colors::DarkGray = Color(0xFFA9A9A9);
const Color Colors::DarkGreen = Color(0xFF006400);
const Color Colors::DarkKhaki = Color(0xFFBDB76B);
const Color Colors::DarkMagenta = Color(0xFF8B008B);
const Color Colors::DarkOliveGreen = Color(0xFF556B2F);
const Color Colors::DarkOrange = Color(0xFFFF8C00);
const Color Colors::DarkOrchid = Color(0xFF9932CC);
const Color Colors::DarkRed = Color(0xFF8B0000);
const Color Colors::DarkSalmon = Color(0xFFE9967A);
const Color Colors::DarkSeaGreen = Color(0xFF8FBC8F);
const Color Colors::DarkSlateBlue = Color(0xFF483D8B);
const Color Colors::DarkSlateGray = Color(0xFF2F4F4F);
const Color Colors::DarkTurquoise = Color(0xFF00CED1);
const Color Colors::DarkViolet = Color(0xFF9400D3);
const Color Colors::DeepPink = Color(0xFFFF1493);
const Color Colors::DeepSkyBlue = Color(0xFF00BFFF);
const Color Colors::DimGray = Color(0xFF696969);
const Color Colors::DodgerBlue = Color(0xFF1E90FF);
const Color Colors::FireBrick = Color(0xFFB22222);
const Color Colors::FloralWhite = Color(0xFFFFFAF0);
const Color Colors::ForestGreen = Color(0xFF228B22);
const Color Colors::Fuchsia = Color(0xFFFF00FF);
const Color Colors::Gainsboro = Color(0xFFDCDCDC);
const Color Colors::GhostWhite = Color(0xFFF8F8FF);
const Color Colors::Gold = Color(0xFFFFD700);
const Color Colors::GoldenRod = Color(0xFFDAA520);
const Color Colors::Gray = Color(0xFF808080);
const Color Colors::Green = Color(0xFF008000);
const Color Colors::GreenYellow = Color(0xFFADFF2F);
const Color Colors::HoneyDew = Color(0xFFF0FFF0);
const Color Colors::HotPink = Color(0xFFFF69B4);
const Color Colors::IndianRed = Color(0xFFCD5C5C);
const Color Colors::Indigo = Color(0xFF4B0082);
const Color Colors::Ivory = Color(0xFFFFFFF0);
const Color Colors::Khaki = Color(0xFFF0E68C);
const Color Colors::Lavender = Color(0xFFE6E6FA);
const Color Colors::LavenderBlush = Color(0xFFFFF0F5);
const Color Colors::LawnGreen = Color(0xFF7CFC00);
const Color Colors::LemonChiffon = Color(0xFFFFFACD);
const Color Colors::LightBlue = Color(0xFFADD8E6);
const Color Colors::LightCoral = Color(0xFFF08080);
const Color Colors::LightCyan = Color(0xFFE0FFFF);
const Color Colors::LightGoldenRodYellow = Color(0xFFFAFAD2);
const Color Colors::LightGrey = Color(0xFFD3D3D3);
const Color Colors::LightGreen = Color(0xFF90EE90);
const Color Colors::LightPink = Color(0xFFFFB6C1);
const Color Colors::LightSalmon = Color(0xFFFFA07A);
const Color Colors::LightSeaGreen = Color(0xFF20B2AA);
const Color Colors::LightSkyBlue = Color(0xFF87CEFA);
const Color Colors::LightSlateGray = Color(0xFF778899);
const Color Colors::LightSteelBlue = Color(0xFFB0C4DE);
const Color Colors::LightYellow = Color(0xFFFFFFE0);
const Color Colors::Lime = Color(0xFF00FF00);
const Color Colors::LimeGreen = Color(0xFF32CD32);
const Color Colors::Linen = Color(0xFFFAF0E6);
const Color Colors::Magenta = Color(0xFFFF00FF);
const Color Colors::Maroon = Color(0xFF800000);
const Color Colors::MediumAquaMarine = Color(0xFF66CDAA);
const Color Colors::MediumBlue = Color(0xFF0000CD);
const Color Colors::MediumOrchid = Color(0xFFBA55D3);
const Color Colors::MediumPurple = Color(0xFF9370D8);
const Color Colors::MediumSeaGreen = Color(0xFF3CB371);
const Color Colors::MediumSlateBlue = Color(0xFF7B68EE);
const Color Colors::MediumSpringGreen = Color(0xFF00FA9A);
const Color Colors::MediumTurquoise = Color(0xFF48D1CC);
const Color Colors::MediumVioletRed = Color(0xFFC71585);
const Color Colors::MidnightBlue = Color(0xFF191970);
const Color Colors::MintCream = Color(0xFFF5FFFA);
const Color Colors::MistyRose = Color(0xFFFFE4E1);
const Color Colors::Moccasin = Color(0xFFFFE4B5);
const Color Colors::NavajoWhite = Color(0xFFFFDEAD);
const Color Colors::Navy = Color(0xFF000080);
const Color Colors::OldLace = Color(0xFFFDF5E6);
const Color Colors::Olive = Color(0xFF808000);
const Color Colors::OliveDrab = Color(0xFF6B8E23);
const Color Colors::Orange = Color(0xFFFFA500);
const Color Colors::OrangeRed = Color(0xFFFF4500);
const Color Colors::Orchid = Color(0xFFDA70D6);
const Color Colors::PaleGoldenRod = Color(0xFFEEE8AA);
const Color Colors::PaleGreen = Color(0xFF98FB98);
const Color Colors::PaleTurquoise = Color(0xFFAFEEEE);
const Color Colors::PaleVioletRed = Color(0xFFD87093);
const Color Colors::PapayaWhip = Color(0xFFFFEFD5);
const Color Colors::PeachPuff = Color(0xFFFFDAB9);
const Color Colors::Peru = Color(0xFFCD853F);
const Color Colors::Pink = Color(0xFFFFC0CB);
const Color Colors::Plum = Color(0xFFDDA0DD);
const Color Colors::PowderBlue = Color(0xFFB0E0E6);
const Color Colors::Purple = Color(0xFF800080);
const Color Colors::Red = Color(0xFFFF0000);
const Color Colors::RosyBrown = Color(0xFFBC8F8F);
const Color Colors::RoyalBlue = Color(0xFF4169E1);
const Color Colors::SaddleBrown = Color(0xFF8B4513);
const Color Colors::Salmon = Color(0xFFFA8072);
const Color Colors::SandyBrown = Color(0xFFF4A460);
const Color Colors::SeaGreen = Color(0xFF2E8B57);
const Color Colors::SeaShell = Color(0xFFFFF5EE);
const Color Colors::Sienna = Color(0xFFA0522D);
const Color Colors::Silver = Color(0xFFC0C0C0);
const Color Colors::SkyBlue = Color(0xFF87CEEB);
const Color Colors::SlateBlue = Color(0xFF6A5ACD);
const Color Colors::SlateGray = Color(0xFF708090);
const Color Colors::Snow = Color(0xFFFFFAFA);
const Color Colors::SpringGreen = Color(0xFF00FF7F);
const Color Colors::SteelBlue = Color(0xFF4682B4);
const Color Colors::Tan = Color(0xFFD2B48C);
const Color Colors::Teal = Color(0xFF008080);
const Color Colors::Thistle = Color(0xFFD8BFD8);
const Color Colors::Tomato = Color(0xFFFF6347);
const Color Colors::Turquoise = Color(0xFF40E0D0);
const Color Colors::Violet = Color(0xFFEE82EE);
const Color Colors::Wheat = Color(0xFFF5DEB3);
const Color Colors::White = Color(0xFFFFFFFF);
const Color Colors::WhiteSmoke = Color(0xFFF5F5F5);
const Color Colors::Yellow = Color(0xFFFFFF00);
const Color Colors::YellowGreen = Color(0xFF9ACD32);
void Colors::FillItems()
{
HKAssertDebug(items.empty());
items.reserve(150);
# define HKAddNamedColor(name) items.push_back(Item(#name, name));
HKAddNamedColor(AliceBlue);
HKAddNamedColor(AntiqueWhite);
HKAddNamedColor(Aqua);
HKAddNamedColor(AquaMarine);
HKAddNamedColor(Azure);
HKAddNamedColor(Beige);
HKAddNamedColor(Bisque);
HKAddNamedColor(Black);
HKAddNamedColor(BlanchedAlmond);
HKAddNamedColor(Blue);
HKAddNamedColor(BlueViolet);
HKAddNamedColor(Brown);
HKAddNamedColor(BurlyWood);
HKAddNamedColor(CadetBlue);
HKAddNamedColor(Chartreuse);
HKAddNamedColor(Chocolate);
HKAddNamedColor(Coral);
HKAddNamedColor(CornflowerBlue);
HKAddNamedColor(Cornsilk);
HKAddNamedColor(Crimson);
HKAddNamedColor(Cyan);
HKAddNamedColor(DarkBlue);
HKAddNamedColor(DarkCyan);
HKAddNamedColor(DarkGoldenRod);
HKAddNamedColor(DarkGray);
HKAddNamedColor(DarkGreen);
HKAddNamedColor(DarkKhaki);
HKAddNamedColor(DarkMagenta);
HKAddNamedColor(DarkOliveGreen);
HKAddNamedColor(DarkOrange);
HKAddNamedColor(DarkOrchid);
HKAddNamedColor(DarkRed);
HKAddNamedColor(DarkSalmon);
HKAddNamedColor(DarkSeaGreen);
HKAddNamedColor(DarkSlateBlue);
HKAddNamedColor(DarkSlateGray);
HKAddNamedColor(DarkTurquoise);
HKAddNamedColor(DarkViolet);
HKAddNamedColor(DeepPink);
HKAddNamedColor(DeepSkyBlue);
HKAddNamedColor(DimGray);
HKAddNamedColor(DodgerBlue);
HKAddNamedColor(FireBrick);
HKAddNamedColor(FloralWhite);
HKAddNamedColor(ForestGreen);
HKAddNamedColor(Fuchsia);
HKAddNamedColor(Gainsboro);
HKAddNamedColor(GhostWhite);
HKAddNamedColor(Gold);
HKAddNamedColor(GoldenRod);
HKAddNamedColor(Gray);
HKAddNamedColor(Green);
HKAddNamedColor(GreenYellow);
HKAddNamedColor(HoneyDew);
HKAddNamedColor(HotPink);
HKAddNamedColor(IndianRed);
HKAddNamedColor(Indigo);
HKAddNamedColor(Ivory);
HKAddNamedColor(Khaki);
HKAddNamedColor(Lavender);
HKAddNamedColor(LavenderBlush);
HKAddNamedColor(LawnGreen);
HKAddNamedColor(LemonChiffon);
HKAddNamedColor(LightBlue);
HKAddNamedColor(LightCoral);
HKAddNamedColor(LightCyan);
HKAddNamedColor(LightGoldenRodYellow);
HKAddNamedColor(LightGrey);
HKAddNamedColor(LightGreen);
HKAddNamedColor(LightPink);
HKAddNamedColor(LightSalmon);
HKAddNamedColor(LightSeaGreen);
HKAddNamedColor(LightSkyBlue);
HKAddNamedColor(LightSlateGray);
HKAddNamedColor(LightSteelBlue);
HKAddNamedColor(LightYellow);
HKAddNamedColor(Lime);
HKAddNamedColor(LimeGreen);
HKAddNamedColor(Linen);
HKAddNamedColor(Magenta);
HKAddNamedColor(Maroon);
HKAddNamedColor(MediumAquaMarine);
HKAddNamedColor(MediumBlue);
HKAddNamedColor(MediumOrchid);
HKAddNamedColor(MediumPurple);
HKAddNamedColor(MediumSeaGreen);
HKAddNamedColor(MediumSlateBlue);
HKAddNamedColor(MediumSpringGreen);
HKAddNamedColor(MediumTurquoise);
HKAddNamedColor(MediumVioletRed);
HKAddNamedColor(MidnightBlue);
HKAddNamedColor(MintCream);
HKAddNamedColor(MistyRose);
HKAddNamedColor(Moccasin);
HKAddNamedColor(NavajoWhite);
HKAddNamedColor(Navy);
HKAddNamedColor(OldLace);
HKAddNamedColor(Olive);
HKAddNamedColor(OliveDrab);
HKAddNamedColor(Orange);
HKAddNamedColor(OrangeRed);
HKAddNamedColor(Orchid);
HKAddNamedColor(PaleGoldenRod);
HKAddNamedColor(PaleGreen);
HKAddNamedColor(PaleTurquoise);
HKAddNamedColor(PaleVioletRed);
HKAddNamedColor(PapayaWhip);
HKAddNamedColor(PeachPuff);
HKAddNamedColor(Peru);
HKAddNamedColor(Pink);
HKAddNamedColor(Plum);
HKAddNamedColor(PowderBlue);
HKAddNamedColor(Purple);
HKAddNamedColor(Red);
HKAddNamedColor(RosyBrown);
HKAddNamedColor(RoyalBlue);
HKAddNamedColor(SaddleBrown);
HKAddNamedColor(Salmon);
HKAddNamedColor(SandyBrown);
HKAddNamedColor(SeaGreen);
HKAddNamedColor(SeaShell);
HKAddNamedColor(Sienna);
HKAddNamedColor(Silver);
HKAddNamedColor(SkyBlue);
HKAddNamedColor(SlateBlue);
HKAddNamedColor(SlateGray);
HKAddNamedColor(Snow);
HKAddNamedColor(SpringGreen);
HKAddNamedColor(SteelBlue);
HKAddNamedColor(Tan);
HKAddNamedColor(Teal);
HKAddNamedColor(Thistle);
HKAddNamedColor(Tomato);
HKAddNamedColor(TransparentBlack);
HKAddNamedColor(TransparentWhite);
HKAddNamedColor(Turquoise);
HKAddNamedColor(Violet);
HKAddNamedColor(Wheat);
HKAddNamedColor(White);
HKAddNamedColor(WhiteSmoke);
HKAddNamedColor(Yellow);
HKAddNamedColor(YellowGreen);
# undef HKAddNamedColor
}
} | [
"[email protected]"
] | [
[
[
1,
322
]
]
] |
fdeb444c96c0acfc7024765c42518b80cd02d5c9 | fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68 | /actions.cpp | 891a204693f28829904ae3ca70699e203425de71 | [] | no_license | divinity76/ancient-divinity-ots | d29efe620cea3fe8d61ffd66480cf20c8f77af13 | 0c7b5bfd5b9277c97d28de598f781dbb198f473d | refs/heads/master | 2020-05-16T21:01:29.130756 | 2010-10-11T22:58:07 | 2010-10-11T22:58:07 | 29,501,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,208 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "const76.h"
#include "player.h"
#include "monster.h"
#include "npc.h"
#include "game.h"
#include "item.h"
#include "container.h"
#include "combat.h"
#include "house.h"
#include "tasks.h"
#include "tools.h"
#include "spells.h"
#include "configmanager.h"
//[ added for beds system
#include "beds.h"
//]
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
//#include <boost/bind.hpp>
#include <sstream>
#include "actions.h"
extern Game g_game;
extern Spells* g_spells;
extern Actions* g_actions;
extern ConfigManager g_config;
Actions::Actions() :
m_scriptInterface("Action Interface")
{
m_scriptInterface.initState();
}
Actions::~Actions()
{
clear();
}
inline void Actions::clearMap(ActionUseMap& map)
{
ActionUseMap::iterator it = map.begin();
while(it != map.end()){
delete it->second;
map.erase(it);
it = map.begin();
}
}
void Actions::clear()
{
clearMap(useItemMap);
clearMap(uniqueItemMap);
clearMap(actionItemMap);
m_scriptInterface.reInitState();
m_loaded = false;
}
LuaScriptInterface& Actions::getScriptInterface()
{
return m_scriptInterface;
}
std::string Actions::getScriptBaseName()
{
return "actions";
}
Event* Actions::getEvent(const std::string& nodeName)
{
if(asLowerCaseString(nodeName) == "action"){
return new Action(&m_scriptInterface);
}
else{
return NULL;
}
}
bool Actions::registerEvent(Event* event, xmlNodePtr p)
{
Action* action = dynamic_cast<Action*>(event);
if(!action)
return false;
int value;
if(readXMLInteger(p,"itemid",value)){
useItemMap[value] = action;
}
else if(readXMLInteger(p,"uniqueid",value)){
uniqueItemMap[value] = action;
}
else if(readXMLInteger(p,"actionid",value)){
actionItemMap[value] = action;
}
else{
return false;
}
return true;
}
ReturnValue Actions::canUse(const Player* player, const Position& pos)
{
const Position& playerPos = player->getPosition();
if(pos.x != 0xFFFF){
if(playerPos.z > pos.z){
return RET_FIRSTGOUPSTAIRS;
}
else if(playerPos.z < pos.z){
return RET_FIRSTGODOWNSTAIRS;
}
else if(!Position::areInRange<1,1,0>(playerPos, pos)){
return RET_TOOFARAWAY;
}
}
return RET_NOERROR;
}
bool Actions::hasAction(const Item* item) const
{
return (getAction(item, ACTION_UNIQUEID) != NULL) ||
(getAction(item, ACTION_ACTIONID) != NULL) ||
(getAction(item, ACTION_ITEMID) != NULL) ||
(getAction(item, ACTION_RUNEID) != NULL);
}
ReturnValue Actions::canUse(const Player* player, const Position& pos, const Item* item)
{
Action* action = getAction(item, ACTION_UNIQUEID);
if(action){
ReturnValue ret = action->canExecuteAction(player, pos);
if(ret != RET_NOERROR){
return ret;
}
return RET_NOERROR;
}
action = getAction(item, ACTION_ACTIONID);
if(action){
ReturnValue ret = action->canExecuteAction(player, pos);
if(ret != RET_NOERROR){
return ret;
}
return RET_NOERROR;
}
action = getAction(item, ACTION_ITEMID);
if(action){
ReturnValue ret = action->canExecuteAction(player, pos);
if(ret != RET_NOERROR){
return ret;
}
return RET_NOERROR;
}
action = getAction(item, ACTION_RUNEID);
if(action){
ReturnValue ret = action->canExecuteAction(player, pos);
if(ret != RET_NOERROR){
return ret;
}
return RET_NOERROR;
}
return RET_NOERROR;
}
ReturnValue Actions::canUseFar(const Creature* creature, const Position& toPos, bool checkLineOfSight)
{
if(toPos.x == 0xFFFF){
return RET_NOERROR;
}
const Position& creaturePos = creature->getPosition();
if(creaturePos.z > toPos.z){
return RET_FIRSTGOUPSTAIRS;
}
else if(creaturePos.z < toPos.z){
return RET_FIRSTGODOWNSTAIRS;
}
else if(!Position::areInRange<7,5,0>(toPos, creaturePos)){
return RET_TOOFARAWAY;
}
if(checkLineOfSight && !g_game.canThrowObjectTo(creaturePos, toPos)){
return RET_CANNOTTHROW;
}
return RET_NOERROR;
}
Action* Actions::getAction(const Item* item, ActionType_t type /* = ACTION_ANY*/) const
{
if(item->getUniqueId() != 0 && (type == ACTION_ANY || type == ACTION_UNIQUEID) ){
ActionUseMap::const_iterator it = uniqueItemMap.find(item->getUniqueId());
if(it != uniqueItemMap.end()){
return it->second;
}
}
if(item->getActionId() != 0 && (type == ACTION_ANY || type == ACTION_ACTIONID)){
ActionUseMap::const_iterator it = actionItemMap.find(item->getActionId());
if (it != actionItemMap.end()){
return it->second;
}
}
if(type == ACTION_ANY || type == ACTION_ITEMID){
ActionUseMap::const_iterator it = useItemMap.find(item->getID());
if(it != useItemMap.end()){
return it->second;
}
}
if(type == ACTION_ANY || type == ACTION_RUNEID){
//rune items
Action* runeSpell = g_spells->getRuneSpell(item->getID());
if(runeSpell){
return runeSpell;
}
}
return NULL;
}
bool Actions::executeUse(Action* action, Player* player, Item* item,
const PositionEx& posEx, uint32_t creatureId)
{
if(!action->executeUse(player, item, posEx, posEx, false, creatureId)){
return false;
}
return true;
}
ReturnValue Actions::internalUseItem(Player* player, const Position& pos,
uint8_t index, Item* item, uint32_t creatureId)
{
//check if it is a house door
if(Door* door = item->getDoor()){
if(!door->canUse(player)){
return RET_CANNOTUSETHISOBJECT;
}
}
int32_t stack = item->getParent()->__getIndexOfThing(item);
PositionEx posEx(pos, stack);
bool foundAction = false;
Action* action = getAction(item, ACTION_UNIQUEID);
if(action){
//only continue with next action in the list if the previous returns false
if(executeUse(action, player, item, posEx, creatureId)){
return RET_NOERROR;
}
foundAction = true;
}
action = getAction(item, ACTION_ACTIONID);
if(action){
//only continue with next action in the list if the previous returns false
if(executeUse(action, player, item, posEx, creatureId)){
return RET_NOERROR;
}
foundAction = true;
}
action = getAction(item, ACTION_ITEMID);
if(action){
//only continue with next action in the list if the previous returns false
if(executeUse(action, player, item, posEx, creatureId)){
return RET_NOERROR;
}
foundAction = true;
}
action = getAction(item, ACTION_RUNEID);
if(action){
//only continue with next action in the list if the previous returns false
if(executeUse(action, player, item, posEx, creatureId)){
return RET_NOERROR;
}
foundAction = true;
}
if(BedItem* bed = item->getBed()){
if(!bed->canUse(player)){
return RET_CANNOTUSETHISOBJECT;
}
bed->sleep(player);
return RET_NOERROR;
}
//if it is a container try to open it
if(Container* container = item->getContainer()){
Container* openContainer = NULL;
//depot container
if(Depot* depot = container->getDepot()){
Depot* myDepot = player->getDepot(depot->getDepotId(), true);
myDepot->setParent(depot->getParent());
openContainer = myDepot;
}
else{
openContainer = container;
}
//open/close container
int32_t oldcid = player->getContainerID(openContainer);
if(oldcid != -1){
player->onCloseContainer(openContainer);
player->closeContainer(oldcid);
}
else{
player->addContainer(index, openContainer);
player->onSendContainer(openContainer);
}
return RET_NOERROR;
}
if(item->isReadable()){
if(item->canWriteText()){
player->setWriteItem(item, item->getMaxWriteLength());
player->sendTextWindow(item, item->getMaxWriteLength(), true);
}
else{
player->setWriteItem(NULL);
player->sendTextWindow(item, 0, false);
}
return RET_NOERROR;
}
if(foundAction){
return RET_NOERROR;
}
return RET_CANNOTUSETHISOBJECT;
}
bool Actions::useItem(Player* player, const Position& pos, uint8_t index,
Item* item)
{
if(!player->canDoAction()){
return false;
}
player->setNextActionTask(NULL);
player->stopWalk();
ReturnValue ret = internalUseItem(player, pos, index, item, 0);
if(ret != RET_NOERROR){
player->sendCancelMessage(ret);
return false;
}
player->setNextAction(OTSYS_TIME() + g_config.getNumber(ConfigManager::MIN_ACTIONTIME));
return true;
}
bool Actions::executeUseEx(Action* action, Player* player, Item* item, const PositionEx& fromPosEx,
const PositionEx& toPosEx, uint32_t creatureId)
{
if(!action->executeUse(player, item, fromPosEx, toPosEx, true, creatureId)){
return false;
}
return true;
}
ReturnValue Actions::internalUseItemEx(Player* player, const PositionEx& fromPosEx, const PositionEx& toPosEx,
Item* item, uint32_t creatureId, bool& isSuccess)
{
isSuccess = false;
Action* action = getAction(item, ACTION_UNIQUEID);
if(action){
ReturnValue ret = action->canExecuteAction(player, toPosEx);
if(ret != RET_NOERROR){
return ret;
}
//only continue with next action in the list if the previous returns false
isSuccess = executeUseEx(action, player, item, fromPosEx, toPosEx, creatureId);
if(isSuccess || action->hasOwnErrorHandler()){
return RET_NOERROR;
}
}
action = getAction(item, ACTION_ACTIONID);
if(action){
ReturnValue ret = action->canExecuteAction(player, toPosEx);
if(ret != RET_NOERROR){
isSuccess = false;
return ret;
}
//only continue with next action in the list if the previous returns false
isSuccess = executeUseEx(action, player, item, fromPosEx, toPosEx, creatureId);
if(isSuccess || action->hasOwnErrorHandler()){
return RET_NOERROR;
}
}
action = getAction(item, ACTION_ITEMID);
if(action){
ReturnValue ret = action->canExecuteAction(player, toPosEx);
if(ret != RET_NOERROR){
return ret;
}
//only continue with next action in the list if the previous returns false
isSuccess = executeUseEx(action, player, item, fromPosEx, toPosEx, creatureId);
if(isSuccess || action->hasOwnErrorHandler()){
return RET_NOERROR;
}
}
action = getAction(item, ACTION_RUNEID);
if(action){
ReturnValue ret = action->canExecuteAction(player, toPosEx);
if(ret != RET_NOERROR){
return ret;
}
//only continue with next action in the list if the previous returns false
isSuccess = executeUseEx(action, player, item, fromPosEx, toPosEx, creatureId);
if(isSuccess || action->hasOwnErrorHandler()){
return RET_NOERROR;
}
}
return RET_CANNOTUSETHISOBJECT;
}
bool Actions::useItemEx(Player* player, const Position& fromPos, const Position& toPos,
uint8_t toStackPos, Item* item, uint32_t creatureId /* = 0*/)
{
if(!player->canDoAction()){
return false;
}
player->setNextActionTask(NULL);
player->stopWalk();
Action* action = getAction(item);
if(!action){
player->sendCancelMessage(RET_CANNOTUSETHISOBJECT);
return false;
}
int32_t fromStackPos = item->getParent()->__getIndexOfThing(item);
PositionEx fromPosEx(fromPos, fromStackPos);
PositionEx toPosEx(toPos, toStackPos);
ReturnValue ret = RET_NOERROR;
bool isSuccess = false;
ret = internalUseItemEx(player, fromPosEx, toPosEx, item, creatureId, isSuccess);
if(ret != RET_NOERROR){
player->sendCancelMessage(ret);
return false;
}
player->setNextAction(OTSYS_TIME() + g_config.getNumber(ConfigManager::MIN_ACTIONEXTIME));
return true;
}
Action::Action(LuaScriptInterface* _interface) :
Event(_interface)
{
allowFarUse = false;
checkLineOfSight = true;
}
Action::~Action()
{
//
}
bool Action::configureEvent(xmlNodePtr p)
{
int intValue;
if(readXMLInteger(p, "allowfaruse", intValue)){
if(intValue != 0){
setAllowFarUse(true);
}
}
if(readXMLInteger(p, "blockwalls", intValue)){
if(intValue == 0){
setCheckLineOfSight(false);
}
}
return true;
}
std::string Action::getScriptEventName()
{
return "onUse";
}
ReturnValue Action::canExecuteAction(const Player* player, const Position& toPos)
{
ReturnValue ret = RET_NOERROR;
if(!getAllowFarUse()){
ret = g_actions->canUse(player, toPos);
if(ret != RET_NOERROR){
return ret;
}
}
else{
ret = g_actions->canUseFar(player, toPos, getCheckLineOfSight());
if(ret != RET_NOERROR){
return ret;
}
}
return RET_NOERROR;
}
bool Action::executeUse(Player* player, Item* item, const PositionEx& fromPos,
const PositionEx& toPos, bool extendedUse, uint32_t creatureId)
{
//onUse(cid, item1, position1, item2, position2)
if(m_scriptInterface->reserveScriptEnv()){
ScriptEnviroment* env = m_scriptInterface->getScriptEnv();
#ifdef __DEBUG_LUASCRIPTS__
std::stringstream desc;
desc << player->getName() << " - " << item->getID() << " " << fromPos << "|" << toPos;
env->setEventDesc(desc.str());
#endif
env->setScriptId(m_scriptId, m_scriptInterface);
env->setRealPos(player->getPosition());
uint32_t cid = env->addThing(player);
uint32_t itemid1 = env->addThing(item);
lua_State* L = m_scriptInterface->getLuaState();
m_scriptInterface->pushFunction(m_scriptId);
lua_pushnumber(L, cid);
LuaScriptInterface::pushThing(L, item, itemid1);
LuaScriptInterface::pushPosition(L, fromPos, fromPos.stackpos);
//std::cout << "posTo" << (Position)posTo << " stack" << (int)posTo.stackpos <<std::endl;
Thing* thing = g_game.internalGetThing(player, toPos, toPos.stackpos);
if(thing && (!extendedUse || thing != item)){
uint32_t thingId2 = env->addThing(thing);
LuaScriptInterface::pushThing(L, thing, thingId2);
LuaScriptInterface::pushPosition(L, toPos, toPos.stackpos);
}
else{
LuaScriptInterface::pushThing(L, NULL, 0);
Position posEx;
LuaScriptInterface::pushPosition(L, posEx, 0);
}
int32_t result = m_scriptInterface->callFunction(5);
m_scriptInterface->releaseScriptEnv();
return (result != LUA_FALSE);
}
else{
std::cout << "[Error] Call stack overflow. Action::executeUse" << std::endl;
return false;
}
}
| [
"[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e"
] | [
[
[
1,
600
]
]
] |
a66718b207c37c894d8907605c0ef11cf7728d73 | 37426b6752e2a3f0a254f76168f55fed549594da | /unit_test++/src/DeferredTestReporter.h | 17ac1c3a3a03fd1ecc1fa547238604c239a67fe0 | [
"MIT"
] | permissive | Over-Zero/amf3lib | 09c3db95b3b60bcdd78791e282a9803fc6e2cfee | 527c3e1c66b5fb858a859c4bc631733e23c91132 | refs/heads/master | 2021-01-22T03:01:28.063344 | 2011-11-08T15:42:04 | 2011-11-08T15:42:04 | 2,732,494 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 671 | h | #ifndef UNITTEST_DEFERREDTESTREPORTER_H
#define UNITTEST_DEFERREDTESTREPORTER_H
#include "TestReporter.h"
#include "DeferredTestResult.h"
#include <vector>
namespace UnitTest
{
class DeferredTestReporter : public TestReporter
{
public:
virtual void ReportTestStart(TestDetails const& details);
virtual void ReportFailure(TestDetails const& details, Char const* failure);
virtual void ReportTestFinish(TestDetails const& details, float secondsElapsed);
typedef std::vector< DeferredTestResult > DeferredTestResultList;
DeferredTestResultList& GetResults();
private:
DeferredTestResultList m_results;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
be6fb16b6e6962193a4ce01d77cb003850f17133 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Pilot/Lokapala_Observe/Raptor/ObserveFacade.h | a516d2cd5e448e19718592202254bdc2166bdc1a | [] | 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 | UHC | C++ | false | false | 973 | h | /**@file ObserveFacade.h
* @brief Observe Manager의 Facade 정의.
* author siva
*/
#ifndef OBSERVE_FACADE_H
#define OBSERVE_FACADE_H
#include "ObserveBI.h"
/**@ingroup GroupOSM
* @class CObserveFacade
* @brief OSM의 Facade.
* @remarks SingleTon을 사용한다.
*/
class CObserveFacade : public CObserveBI
{
public :
/**@brief singleton을 생성, 반환한다.
* @return singleton
* @remarks static 함수이므로 어디서든 호출 할 수 있다.
*/
static CObserveFacade *Instance()
{
if(!m_instance)
{
m_instance = new CObserveFacade();
}
return m_instance;
}
virtual void StartProcessObservation();
virtual void StopProcessObservation();
virtual void ReceiveExecutedProcess(CString a_executedProcess);
protected :
/**@brief 생성자 */
CObserveFacade(){}
/**@brief 소멸자 */
~CObserveFacade(){}
private :
/**@brief singleton */
static CObserveFacade *m_instance;
};
#endif | [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] | [
[
[
1,
45
]
]
] |
a8667d28592d23c8a0c229f7af70ca826e422c8f | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/SmartWires/BitmapUtils/DelayLoadFuncs.h | 322d8272aae3c556b878ec43fd86eaae8243972a | [] | no_license | meiercn/wiredplane-wintools | b35422570e2c4b486c3aa6e73200ea7035e9b232 | 134db644e4271079d631776cffcedc51b5456442 | refs/heads/master | 2021-01-19T07:50:42.622687 | 2009-07-07T03:34:11 | 2009-07-07T03:34:11 | 34,017,037 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | h | // SupportClasses.h: interface for the SupportClasses class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(DELAYLOAD__INCLUDED_)
#define DELAYLOAD__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <afxmt.h>
#include <afxtempl.h>
#include "../SystemUtils/Macros.h"
#ifndef HIMETRIC_PER_INCH
#define HIMETRIC_PER_INCH 2540
#endif
#ifndef MAP_PIX_TO_LOGHIM
#define MAP_PIX_TO_LOGHIM(x,ppli) ( (HIMETRIC_PER_INCH*(x) + ((ppli)>>1)) / (ppli) )
#endif
#ifndef MAP_LOGHIM_TO_PIX
#define MAP_LOGHIM_TO_PIX(x,ppli) ( ((ppli)*(x) + HIMETRIC_PER_INCH/2) / HIMETRIC_PER_INCH )
#endif
typedef int (CALLBACK *FARPROCG) (HWND hwnd, LPWSTR lpString, int nMaxCount);
typedef BOOL (CALLBACK *FARPROCL) (HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
typedef BOOL (CALLBACK *FARPROCW) (HWND hwnd, BOOL bExpand);
typedef BOOL (CALLBACK *FARPROCA) (HWND hwnd, DWORD, DWORD);
typedef BOOL (CALLBACK *FARPROCLOCKFOREG) (BOOL bLock);
#if _WIN32_WINNT == 0x0400
#define AW_HOR_POSITIVE 0x00000001
#define AW_HOR_NEGATIVE 0x00000002
#define AW_VER_POSITIVE 0x00000004
#define AW_VER_NEGATIVE 0x00000008
#define AW_CENTER 0x00000010
#define AW_HIDE 0x00010000
#define AW_ACTIVATE 0x00020000
#define AW_SLIDE 0x00040000
#define AW_BLEND 0x00080000
#endif
class CNTWnWrap
{
public:
HMODULE m_hUser32Instance;
FARPROCG InternalGetWindowText;
FARPROCL SetLayerAttribs;
FARPROCW SwitchToWnd;
FARPROCA fAnimate;
FARPROCLOCKFOREG fLock;
CNTWnWrap()
{
SetLayerAttribs=NULL;
SwitchToWnd=NULL;
fAnimate=NULL;
fLock=NULL;
m_hUser32Instance=LoadLibrary("User32.dll");
}
~CNTWnWrap()
{
if(m_hUser32Instance){
FreeLibrary(m_hUser32Instance);
}
}
};
CNTWnWrap& getCNTWnWrap();
BOOL SetLayeredWindowStyle(HWND m_hWnd, BOOL bSet);
BOOL SetWndAlpha(HWND m_hWnd, DWORD dwPercent, BOOL bAlpha);
typedef struct MYtagMENUINFO
{
DWORD cbSize;
DWORD fMask;
DWORD dwStyle;
UINT cyMax;
HBRUSH hbrBack;
DWORD dwContextHelpID;
DWORD dwMenuData;
} MYMENUINFO, FAR *MYLPMENUINFO;
typedef MYMENUINFO CONST FAR *MYLPCMENUINFO;
BOOL SwitchToWindow(HWND hWnd, BOOL bMoveFocus=TRUE);
void User32Animate(HWND hWnd,DWORD dwMilli,DWORD dwFlags);
void ILockSetForegroundWindow(BOOL bDir);
BOOL SafeGetWindowText(HWND hWnd, CString& out);
BOOL BlockInputMy(BOOL bBlock);
void MyLockSetForegroundWindow(BOOL bLock);
BOOL MySetMenuInfo(HMENU hMenu,MYLPCMENUINFO cmi);
HANDLE MyOpenThread(DWORD dwDesiredAccess, BOOL bInheritHandle,DWORD dwThreadId);
BOOL MyIsHungAppWindow(HWND hw);
#endif // !defined(DELAYLOAD__INCLUDED_)
| [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
] | [
[
[
1,
91
]
]
] |
db305aedd14c47ec3dda18359fc67895a7a4d5ea | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /WEBServer/src/WEBCollector.cpp | ac228687fe2d4842917540c94deac2d03bf6fd21 | [] | no_license | radtek/eibsuite | 0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd | 4504fcf4fa8c7df529177b3460d469b5770abf7a | refs/heads/master | 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,471 | cpp | #include "WEBCollector.h"
#include "WEBServer.h"
CWebCollector::CWebCollector() :
_stop(false),
_schedule(ScheduledCommandComparison())
{
}
CWebCollector::~CWebCollector()
{
}
void CWebCollector::run()
{
CWEBServer& server = CWEBServer::GetInstance();
CEibAddress function;
unsigned char value[10];
unsigned char value_len = 0;
CTime t;
t.SetNow();
CTime time_count;
time_count.SetNow();
time_count += 60;
int len = 0;
while(!_stop)
{
if(time_count.secTo() == 0){
CheckForScheduledCommand();
time_count.SetNow();
time_count += 60;
}
len = server.ReceiveEIBNetwork(function,value,value_len,1000);
if(len == 0){
value_len = 0;
continue;
}
CWEBServer::GetInstance().GetLog().Log(LOG_LEVEL_DEBUG,"[Received] CEMI frame from EIB Server (%d bytes).",len);
//CString address = function.ToString();
//CWEBServer::GetInstance().GetLog().Log(LOG_LEVEL_DEBUG,"func: %s val_len: %d", address.GetBuffer(), value_len);
_db.AddRecord(function,value,value_len);
}
}
void CWebCollector::Close()
{
_stop = true;
}
void CWebCollector::CheckForScheduledCommand()
{
JTCSynchronized sync(*this);
if(_schedule.empty()){
return;
}
ScheduledCommand cmd = _schedule.top();
CTime t;
t.SetNow();
while(cmd._time <= t)
{
//remove
_schedule.pop();
//execute
CWEBServer::GetInstance().SendEIBNetwork(cmd._dst, cmd._value, cmd._value_len, NON_BLOCKING);
//get next
if(_schedule.empty()){
return;
}
cmd = _schedule.top();
}
}
bool CWebCollector::AddScheduledCommand(const CTime& time,
const CEibAddress& dst,
unsigned char* value,
unsigned char val_len,
CString& err_str)
{
JTCSynchronized sync(*this);
CTime t;
t.SetNow();
if(time <= t){
err_str += "Cannot schedule task in the past. a Time Machine should be used instead.";
//cannot schedule command in the past...
return false;
}
ScheduledCommand cmd = ScheduledCommand(time,dst,value,val_len);
_schedule.push(ScheduledCommand(time,dst,value,val_len));
return true;
}
CStatsDB CWebCollector::GetStatsDB()
{
return _db;
}
void CWebCollector::ScheduleToHtml(CDataBuffer& content)
{
ADD_TO_CONTENT(HTML_H2_OPEN_ADD_ATTRIBUTES);
ADD_TO_CONTENT(HTML_ALIGN_LEFT);
ADD_TO_CONTENT(HTML_TAG_CLOSE);
ADD_TO_CONTENT(HTML_FONT_OPEN);
ADD_TO_CONTENT("face=\"sans-serif\" color=\"blue\">");
ADD_TO_CONTENT("Scheduled EIB Commands");
ADD_TO_CONTENT(HTML_FONT_CLOSE);
ADD_TO_CONTENT(HTML_H2_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_OPEN);
ADD_TO_CONTENT(HTML_ALIGN_LEFT);
ADD_TO_CONTENT(HTML_BORDER_1);
ADD_TO_CONTENT(HTML_TAG_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_ROW_OPEN);
ADD_TO_CONTENT(HTML_TABLE_HEADER_OPEN);
ADD_TO_CONTENT("Address");
ADD_TO_CONTENT(HTML_TABLE_HEADER_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_HEADER_OPEN);
ADD_TO_CONTENT("Time");
ADD_TO_CONTENT(HTML_TABLE_HEADER_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_HEADER_OPEN);
ADD_TO_CONTENT("Value");
ADD_TO_CONTENT(HTML_TABLE_HEADER_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_ROW_CLOSE);
SchedQueue temp = _schedule;
while(temp.size() > 0)
{
ScheduledCommand cmd = temp.top();
temp.pop();
ADD_TO_CONTENT(HTML_TABLE_ROW_OPEN_CENTERED);
ADD_TO_CONTENT(HTML_TABLE_DATA_OPEN);
ADD_TO_CONTENT(HTML_FONT_OPEN);
ADD_TO_CONTENT("face=\"sans-serif\" color=\"purple\" size=\"2\">");
ADD_TO_CONTENT(cmd._dst.ToString());
ADD_TO_CONTENT(HTML_FONT_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_OPEN);
ADD_TO_CONTENT(HTML_FONT_OPEN);
ADD_TO_CONTENT("face=\"sans-serif\" color=\"purple\" size=\"2\">");
ADD_TO_CONTENT(cmd._time.Format());
ADD_TO_CONTENT(HTML_FONT_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_OPEN);
ADD_TO_CONTENT(HTML_FONT_OPEN);
ADD_TO_CONTENT("face=\"sans-serif\" color=\"purple\" size=\"2\">");
ADD_TO_CONTENT("0x");
for(int i =0; i < cmd._value_len; ++i)
{
ADD_TO_CONTENT(ToHex((int)cmd._value[i]));
}
ADD_TO_CONTENT(HTML_FONT_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_DATA_OPEN);
//add "Remove" check box here...
ADD_TO_CONTENT(HTML_TYPE_EQUALS_BUTTON);
ADD_TO_CONTENT(HTML_TABLE_DATA_CLOSE);
ADD_TO_CONTENT(HTML_TABLE_ROW_CLOSE);
}
ADD_TO_CONTENT(HTML_TABLE_CLOSE);
}
| [
"[email protected]"
] | [
[
[
1,
184
]
]
] |
7ca6c2eb3c677069cac4c198ff6cb33e364c7f4f | 50ec9ffd7c7fab28b27e58dd4f12fa38d678bb69 | /ImageProcessing.cpp | 0f8af5336d61471b3e02df7fe859fb0942b8a1ed | [] | no_license | manisoftwartist/manibaktha-tactical-visual-servoing | a2c40a88f0dd65546baba90d44049e8103d1dd1d | 9510c2e885e744fc8efa329e3c2770e5d5e0c57f | refs/heads/master | 2020-04-15T05:34:24.551897 | 2011-05-27T10:35:14 | 2011-05-27T10:35:14 | 32,143,772 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 76,213 | cpp |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011 Shawn T. Hunt
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "ImageProcessing.h"
///////////////////////////////////////////////////////////////////////////////
//
// free2DArray
//
///////////////////////////////////////////////////////////////////////////////
void free2DArray(int **p, int rows)
{
for (int i=0; i<rows; i++) {
free(p[i]);
}
free(p);
} // end free2DArray
///////////////////////////////////////////////////////////////////////////////
//
// make2DArray
//
///////////////////////////////////////////////////////////////////////////////
int **make2DArray(int rows, int cols)
{
int **p;
p = (int **)malloc(rows * sizeof(int *));
if (p == NULL)
return NULL;
for (int i=0; i<rows; i++) {
p[i] = (int *)malloc(cols * sizeof(int));
if (p[i] == NULL)
return NULL;
}
return p;
} // end make2DArray
///////////////////////////////////////////////////////////////////////////////
//
// mean2
//
///////////////////////////////////////////////////////////////////////////////
double mean2 (int **imageIn, int rows, int cols, int numberPlanes)
{
printf("In mean2, rows = %d, cols=%d\n", rows, cols);
float sum = 0;
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
sum = sum + (double)imageIn[i][j];
}
}
return sum / (rows * cols * numberPlanes);
} // end mean2
///////////////////////////////////////////////////////////////////////////////
//
// SDLImageTo2DArrayOnePlane
//
///////////////////////////////////////////////////////////////////////////////
int **SDLImageTo2DArrayOnePlane (SDL_Surface *image, int rows, int cols, int plane)
{
SDL_PixelFormat *fmt;
fmt = image->format;
Uint32 temp, pixel;
Uint8 red, green, blue, alpha;
int bpp = image->format->BytesPerPixel;
int **onePlane2D = make2DArray(rows, cols);
// create the 2D array
for (int y=0; y<rows; y++) {
for (int x=0; x<cols; x++) {
// pixel = *((Uint32*)image->pixels + y * image->pitch /4 + x * bpp);
pixel = *((Uint32*)image->pixels + y * image->pitch /4 + x);
// r=1, g=2, 3=b
if (plane == 1) {
// get the red component
temp = pixel & fmt->Rmask; // isolate red component
temp = temp >> fmt->Rshift; // shift it down to 8-bit
temp = temp << fmt->Rloss; // expand to a full 8-bit number
red = (Uint8)temp;
onePlane2D[y][x] = (int)red;
}
if (plane == 2) {
// get the green component
temp = pixel & fmt->Gmask; // isolate green component
temp = temp >> fmt->Gshift; // shift it down to 8-bit
temp = temp << fmt->Gloss; // expand to a full 8-bit number
green = (Uint8)temp;
onePlane2D[y][x] = (int)green;
}
if (plane == 3) {
// get the blue component
temp = pixel & fmt->Bmask; // isolate blue component
temp = temp >> fmt->Bshift; // shift it down to 8-bit
temp = temp << fmt->Bloss; // expand to a full 8-bit number
blue = (Uint8)temp;
onePlane2D[y][x] = (int)blue;
}
// i don't care about the alpha channel but i'll leave it here anyway
if (plane == 4) {
// get alpha component
temp = pixel & fmt->Amask; // isolate alpha component
temp = temp >> fmt->Ashift; // shift it down to 8-bit
temp = temp << fmt->Aloss; // expand to a full 8-bit number
alpha = (Uint8)temp;
}
}
}
return onePlane2D;
} // end SDLImageTo2DArrayOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// SDLImageTo1DArrayOnePlane
//
///////////////////////////////////////////////////////////////////////////////
int *SDLImageTo1DArrayOnePlane (SDL_Surface *image, int rows, int cols, int plane)
{
SDL_PixelFormat *fmt;
fmt = image->format;
Uint32 temp, pixel;
Uint8 red, green, blue, alpha;
int bpp = image->format->BytesPerPixel;
int *onePlane1D = new int[rows * cols];
int count=0;
// create the 1D array
for (int y=0; y<rows; y++) {
for (int x=0; x<cols; x++) {
// pixel = *((Uint32*)image->pixels + y * image->pitch /4 + x * bpp);
pixel = *((Uint32*)image->pixels + y * image->pitch /4 + x);
// r=1, g=2, 3=b
if (plane == 1) {
// get the red component
temp = pixel & fmt->Rmask; // isolate red component
temp = temp >> fmt->Rshift; // shift it down to 8-bit
temp = temp << fmt->Rloss; // expand to a full 8-bit number
red = (Uint8)temp;
onePlane1D[count] = (int)red;
}
if (plane == 2) {
// get the green component
temp = pixel & fmt->Gmask; // isolate green component
temp = temp >> fmt->Gshift; // shift it down to 8-bit
temp = temp << fmt->Gloss; // expand to a full 8-bit number
green = (Uint8)temp;
onePlane1D[count] = (int)green;
}
if (plane == 3) {
// get the blue component
temp = pixel & fmt->Bmask; // isolate blue component
temp = temp >> fmt->Bshift; // shift it down to 8-bit
temp = temp << fmt->Bloss; // expand to a full 8-bit number
blue = (Uint8)temp;
onePlane1D[count] = (int)blue;
}
// i don't care about the alpha channel but i'll leave it here anyway
if (plane == 4) {
// get alpha component
temp = pixel & fmt->Amask; // isolate alpha component
temp = temp >> fmt->Ashift; // shift it down to 8-bit
temp = temp << fmt->Aloss; // expand to a full 8-bit number
alpha = (Uint8)temp;
}
count++;
}
}
return onePlane1D;
} // end SDLImageTo1DArrayOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// ImageArray1DToIplImageOnePlane
//
///////////////////////////////////////////////////////////////////////////////
IplImage *ImageArray1DToIplImageOnePlane (int *imageIn, int rows, int cols)
{
CvSize frameSize;
frameSize.width = cols;
frameSize.height = rows;
// allocate space for the IplImage
IplImage *imageWork = cvCreateImage(frameSize, 8, 1);
// load the IplImage up
for (int i=0; i<rows*cols; i++) {
((uchar *)imageWork->imageData)[i] = (uchar)imageIn[i];
}
return imageWork;
} // end ImageArrayToIplImageOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// ImageArray2DToIplImageOnePlane
//
///////////////////////////////////////////////////////////////////////////////
IplImage *ImageArray2DToIplImageOnePlane (int **imageIn, int rows, int cols)
{
CvSize frameSize;
frameSize.width = cols;
frameSize.height = rows;
// allocate space for the IplImage
IplImage *imageWork = cvCreateImage(frameSize, 8, 1);
// convert the 2D array to 1D
int count = 0;
int *tempArray = new int[rows*cols];
for (int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
tempArray[count] = imageIn[i][j];
((uchar *)imageWork->imageData)[count] = (uchar)imageIn[i][j];
count++;
}
}
// free memory
delete [] tempArray;
return imageWork;
} // end ImageArrayToIplImageOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// ImageArray1DToIplImageThreePlanes
//
///////////////////////////////////////////////////////////////////////////////
IplImage *ImageArray1DToIplImageThreePlanes (int *imageIn, int rows, int cols)
{
CvSize frameSize;
frameSize.width = cols;
frameSize.height = rows;
// allocate space for the IplImage
IplImage *imageWork = cvCreateImage(frameSize, 8, 3);
// load the IplImage up
int count = 0;
for (int i=0; i<rows*cols*3; i+=3) {
((uchar *)imageWork->imageData)[i] = (uchar)imageIn[count];
((uchar *)imageWork->imageData)[i+1] = (uchar)imageIn[count];
((uchar *)imageWork->imageData)[i+2] = (uchar)imageIn[count];
count++;
}
return imageWork;
} // end ImageArray2DToIplImageThreePlanes
///////////////////////////////////////////////////////////////////////////////
//
// ImageArray2DToIplImageThreePlanes
//
///////////////////////////////////////////////////////////////////////////////
IplImage *ImageArray2DToIplImageThreePlanes (int **imageIn, int rows, int cols)
{
CvSize frameSize;
frameSize.width = cols;
frameSize.height = rows;
// allocate space for the IplImage
IplImage *imageWork = cvCreateImage(frameSize, 8, 3);
// convert the 2D array to 1D
int count = 0;
int *tempArray = new int[rows*cols];
for (int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
tempArray[count] = imageIn[i][j];
count++;
}
}
// load the IplImage up
count = 0;
for (int i=0; i<rows*cols*3; i+=3) {
((uchar *)imageWork->imageData)[i] = (uchar)tempArray[count];
((uchar *)imageWork->imageData)[i+1] = (uchar)tempArray[count];
((uchar *)imageWork->imageData)[i+2] = (uchar)tempArray[count];
count++;
}
// free memory
delete [] tempArray;
return imageWork;
} // end ImageArray2DToIplImageThreePlanes
///////////////////////////////////////////////////////////////////////////////
//
// SDLImageTo2DArrayOnePlane2
//
///////////////////////////////////////////////////////////////////////////////
int **SDLImageTo2DArrayOnePlane2 (SDL_Surface *image, int rows, int cols, int plane)
{
SDL_PixelFormat *fmt;
fmt = image->format;
Uint32 temp, pixel;
Uint8 red, green, blue, alpha;
int **onePlane2D = make2DArray(rows, cols);
// create the 2D array
for (int y=0; y<rows; y++) {
for (int x=0; x<cols; x++) {
pixel = getpixel(image, x, y);
SDL_GetRGB(pixel, fmt, &red, &green, &blue);
onePlane2D[y][x] = green;
}
}
return onePlane2D;
} // end SDLImageTo2DArrayOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// getpixel
//
///////////////////////////////////////////////////////////////////////////////
Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
int bpp = surface->format->BytesPerPixel;
// Here p is the address to the pixel we want to retrieve
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1:
return *p;
case 2:
return *(Uint16 *)p;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
return p[0] << 16 | p[1] << 8 | p[2];
} else {
return p[0] | p[1] << 8 | p[2] << 16;
}
case 4:
return *(Uint32 *)p;
default:
return 0;
}
} // end getpixel
/////////////////////////////////////////////////////////////////////
//
// runHistogramEqualization
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> runHistogramEqualization(TNT::Array2D <double> array)
{
int height = array.dim1(), width = array.dim2();
int max = 255, range = 255;
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <long int> histogram;
histogram = getHistogram(array);
double sum=0;
sum = histogram[0];
// get the weighted sum of the histogram
for (int i=1; i<max; i++) {
sum += 2 * histogram[i];
}
sum += histogram[max];
double scale = range/sum;
TNT::Array1D <int> lut(range+1, 0);
lut[0] = 0;
sum = histogram[0];
for (int i=1; i<max; i++) {
double delta = histogram[i];
sum += delta;
lut[i] = (sum*scale)+0.5;
sum += delta;
}
lut[max] = max;
// finally, apply the table
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
a[i][j] = lut[(int)(array[i][j])&0xff];
}
}
return a;
} // end runHistogramEqualization
/////////////////////////////////////////////////////////////////////
//
// getHistogram
//
/////////////////////////////////////////////////////////////////////
TNT::Array1D <long int> getHistogram (TNT::Array2D <double> array)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <long int> a(256, static_cast< long int>(0));
for (int m=0; m<height; m++) {
for (int n=0; n<width; n++) {
a[static_cast<int>(array[m][n])] += 1;
}
}
return a;
} // end getHistogram
/////////////////////////////////////////////////////////////////////
//
// getArrayFromIplImage
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D<double> getArrayFromIplImage(IplImage *frame)
{
int width = frame->width, height = frame->height;
TNT::Array2D <double> array(height, width, 0.0);
printf("getArrayFromIplImage :: height = %d, width = %d\n", height, width);
int plane = 2;
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
// plane (1=R, 2=G, 3=B)
if (plane == 1) {
array[y][x] = ((uchar*)(frame->imageData + frame->widthStep*y))[x*3];
} else if (plane == 2) {
array[y][x] = ((uchar*)(frame->imageData + frame->widthStep*y))[x*3+1];
} else if (plane == 3) {
array[y][x] = ((uchar*)(frame->imageData + frame->widthStep*y))[x*3+2];
}
}
}
return array;
} // end getArrayFromIplImage
/////////////////////////////////////////////////////////////////////
//
// getIplImageFromArray
//
/////////////////////////////////////////////////////////////////////
IplImage *getIplImageFromArray(const TNT::Array2D<double> &array)
{
int height = array.dim1(), width = array.dim2();
unsigned char intensity;
printf("getIplImageFromArray :: height = %d, width = %d\n", height, width);
IplImage *imageWork = cvCreateImage(cvSize(width, height), 8, 1);
int count = 0;
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
if (array[y][x] > 255) {
intensity = 255;
} else if (array[y][x] < 0) {
intensity = 0;
} else {
intensity = static_cast<unsigned char>(array[y][x]);
}
((uchar *)imageWork->imageData)[count] = intensity;
count++;
}
}
return imageWork;
} // end getIplImageFromArray
/////////////////////////////////////////////////////////////////////
//
// getIplImageFromArray2
//
/////////////////////////////////////////////////////////////////////
IplImage *getIplImageFromArray2(const TNT::Array2D<double> &array)
{
int height = array.dim1(), width = array.dim2();
unsigned char intensity;
printf("getIplImageFromArray :: height = %d, width = %d\n", height, width);
IplImage *imageWork = cvCreateImage(cvSize(width, height), 8, 3);
int count = 0;
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
if (array[y][x] > 255) {
intensity = 255;
} else if (array[y][x] < 0) {
intensity = 0;
} else {
intensity = static_cast<unsigned char>(array[y][x]);
}
((uchar *)imageWork->imageData)[count] = intensity;
((uchar *)imageWork->imageData)[count+1] = intensity;
((uchar *)imageWork->imageData)[count+2] = intensity;
count+=3;
}
}
return imageWork;
} // end getIplImageFromArray
/////////////////////////////////////////////////////////////////////
//
// getIplImageFromArray2
//
/////////////////////////////////////////////////////////////////////
void getIplImageFromArray2(const TNT::Array2D<double> &array, IplImage *imageWork)
{
printf("getIplImageFromArray2 start...\n");
int height = array.dim1(), width = array.dim2();
unsigned char intensity;
printf("getIplImageFromArray :: height = %d, width = %d\n", height, width);
int count = 0;
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
if (array[y][x] > 255) {
intensity = 255;
} else if (array[y][x] < 0) {
intensity = 0;
} else {
intensity = static_cast<unsigned char>(array[y][x]);
}
((uchar *)&imageWork->imageData)[count] = intensity;
((uchar *)&imageWork->imageData)[count+1] = intensity;
((uchar *)&imageWork->imageData)[count+2] = intensity;
count+=3;
}
}
printf("getIplImageFromArray2 end...\n");
} // end getIplImageFromArray
/////////////////////////////////////////////////////////////////////
//
// findLUT
//
/////////////////////////////////////////////////////////////////////
TNT::Array1D <int> findLUT(TNT::Array2D <double> array, int r1, int s1, int r2, int s2)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <int> yAxis(256, 0);
if ((r1==s1) && (r2==s2)) {
for (int i=0; i<256; i++) {
yAxis[i] = i;
}
} else {
for (int i=0; i<=r1; i++) {
yAxis[i] = findYCoordRect(i, 0, 0, r1, s1);
}
if (r1==r2) {
yAxis[r1]=s2;
} else {
for (int i=r1+1; i<=r2; i++) {
yAxis[i] = findYCoordRect(i, r1, s1, r2, s2);
}
}
for (int i=r2; i<=255; i++) {
yAxis[i]=findYCoordRect(i,r2,s2,255,255);
}
}
return yAxis;
} // end findLUT
///////////////////////////////////////////////////////////////////////////////
//
// laplacian
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> laplacian(TNT::Array2D <double> array)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
// create horizontal and vertical arrays
TNT::Array2D <double> hh;
TNT::Array2D <double> vv;
hh = getHorizontalHessian(array, FLT_EPSILON);
vv = getVerticalHessian(array, FLT_EPSILON);
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = hh[i][j] + vv[i][j];
}
}
return a;
} // end laplacian
///////////////////////////////////////////////////////////////////////////////
//
// logarithm
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> logarithm(TNT::Array2D <double> array, float constant)
{
int height = array.dim1(), width = array.dim2();
int s=0, temp=0;
TNT::Array2D <double> a(height, width, 0.0);
for (int i=0; i<height;i++) {
for (int j=0;j<width;j++) {
temp = array[i][j];
s = log((float)temp) * (float)255/log((float)255) * constant;
a[i][j] = s;
}
}
return a;
} // end logarithm
///////////////////////////////////////////////////////////////////////////////
//
// max
//
// This function calculates the maximum of a kxk pixel
// neighborhood (including center pixel)
//
///////////////////////////////////////////////////////////////////////////////
int max (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
int t=0, number=0;
int *supp = new int [k*k];
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp[t] = array[y-1+i][x-1+j];
t++;
number++;
}
}
}
if (number == 0) {
delete [] supp;
return 0;
}
sortArray(supp, k*k);
int temp = supp[k*k-1];
delete [] supp;
return temp;
} // end max
///////////////////////////////////////////////////////////////////////////////
//
// meanArithmetic
//
///////////////////////////////////////////////////////////////////////////////
int meanArithmetic(TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
int sum=0, number=0;
for(int i=0;i<k;i++) {
for(int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
sum = sum + array[y-1+i][x-1+j];
number++;
}
}
}
if (number==0) {
return 0;
}
return (sum/number);
} // end meanArithmetic
///////////////////////////////////////////////////////////////////////////////
//
// meanContraharmonic
//
// Calculates the contraharmonic mean of a kxk pixel neighborhood
// (including center pixel)
//
// array - input image (2d array)
// k - dimension of the kernel
// width - width of the image
// height - height of the image
// x - x coordinate of the center pixel of the array
// y - y coordinate of the center pixel of the array
// q - order of the filter
//
///////////////////////////////////////////////////////////////////////////////
int meanContraharmonic (TNT::Array2D <double> array, int k, int width, int height, int x, int y, float q)
{
double sum1=0, sum2=0, number=0, supp=0;
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp=(double)array[y-1+i][x-1+j];
sum1 = sum1 + pow(supp,(double)q+1);
sum2 = sum2 + pow(supp,(double)q);
number++;
}
}
}
if (number==0) {
return 0;
}
double result=sum1/sum2;
if (result<0) {
result=0;
}
if (result>255) {
result=255;
}
return (int)result;
} // end meanContraharmonic
///////////////////////////////////////////////////////////////////////////////
//
// meanGeometric
//
// Calculates the geometric mean of a kxk pixel neighborhood
// (including center pixel)
//
// array - input image (2d array)
// k - dimension of the kernel
// width - width of the image
// height - height of the image
// x - x coordinate of the center pixel of the array
// y - y coordinate of the center pixel of the array
//
///////////////////////////////////////////////////////////////////////////////
int meanGeometric(TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
double product=1, number=0;
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
product = product * array[y-1+i][x-1+j];
number++;
}
}
}
if (number==0) {
return 0;
}
double eps=1/number;
double result=pow(product,eps);
if (result<0) {
result=0;
}
if(result>255) {
result=255;
}
return (int)result;
} // end meanGeometric
///////////////////////////////////////////////////////////////////////////////
//
// meanHarmonic
//
// Calculates the harmonic mean of a kxk pixel neighborhood
// (including center pixel)
//
// array - input image (2d array)
// k - dimension of the kernel
// width - width of the image
// height - height of the image
// x - x coordinate of the center pixel of the array
// y - y coordinate of the center pixel of the array
//
///////////////////////////////////////////////////////////////////////////////
int meanHarmonic (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
double sum=0, number=0, supp=0;
for(int i=0;i<k;i++) {
for(int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp = array[y-1+i][x-1+j];
sum = sum + 1/supp;
number++;
}
}
}
if (number==0) {
return 0;
}
double result=number/sum;
if (result<0) {
result=0;
}
if (result>255) {
result=255;
}
return (int)result;
} // end meanHarmonic
/////////////////////////////////////////////////////////////////////
//
// meanLocal
//
// This function calculates the mean of a kxk pixel
// neighborhood (including center pixel)
//
/////////////////////////////////////////////////////////////////////
int meanLocal (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
double sum=0, number=0;
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
sum = sum+array[y-1+1][x-1+j];
number++;
}
}
}
if (number == 0) {
return 0;
}
return sum/number;
} // end meanLocal
/////////////////////////////////////////////////////////////////////
//
// median
//
/////////////////////////////////////////////////////////////////////
int median (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
int t=0, number=0;
int *supp = new int [k*k];
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp[t] = array[y-1+i][x-1+j];
t++;
number++;
}
}
}
if (number == 0) {
delete [] supp;
return 0;
}
sortArray(supp, k*k);
int temp = supp[k*k-1];
delete [] supp;
return temp/2;
} // end median
///////////////////////////////////////////////////////////////////////////////
//
// min
//
// This function calculates the minimum of a kxk pixel
// neighborhood (including center pixel)
//
///////////////////////////////////////////////////////////////////////////////
int min (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
int t=0, number=0;
int *supp = new int [k*k];
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp[t] = array[y-1+i][x-1+j];
t++;
number++;
}
}
}
if (number == 0) {
delete [] supp;
return 0;
}
sortArray(supp, k*k);
int temp = supp[0];
delete [] supp;
return temp;
} // end min
///////////////////////////////////////////////////////////////////////////////
//
// negative
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> negative(TNT::Array2D <double> array)
{
int height = array.dim1(), width = array.dim2();
int l=256, s=0, temp=0;
TNT::Array2D <double> a(height, width, 0.0);
for (int i=0; i<height; i++) {
for (int j=0;j<width;j++) {
temp = array[i][j];
s = l-1-temp;
a[i][j] = s;
}
}
return a;
} // end negative
///////////////////////////////////////////////////////////////////////////////
//
// findYCoordRect
//
///////////////////////////////////////////////////////////////////////////////
int findYCoordRect (int x, int x0, int y0, int x1, int y1)
{
int y;
if (y0==y1) {
y = y1;
} else if (x0==x1) {
y = y1;
} else {
y=(int)((((float)(x-x0)/(x1-x0))*(y1-y0))+y0);
}
return y;
} // end find YCoordRect
///////////////////////////////////////////////////////////////////////////////
//
// getHessian
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getHessian (TNT::Array1D <double> c)
{
TNT::Array1D <double> h(2, 0.0);
h[0] = -2.0;
h[1] = 1.0;
TNT::Array1D <double> a;
a = symmetricFirMirrorOnBounds(h, c);
return a;
} // end getHessian
///////////////////////////////////////////////////////////////////////////////
//
// getHorizontalGradient
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> getHorizontalGradient(TNT::Array2D <double> array, double tolerance)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <double> line;
TNT::Array1D <double> spline;
TNT::Array1D <double> gradient;
for (int i=0; i<height; i++) {
line = getRow2(array, i);
spline = getSplineInterpolationCoefficients(line, tolerance);
gradient = getGradient(spline);
// putRow(&a, width, height, hessian, i);
putRow2(&a, width, height, gradient, i);
line = spline = gradient = 0.0;
}
return a;
} // end getHorizontalGradient
///////////////////////////////////////////////////////////////////////////////
//
// getHorizontalHessian
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> getHorizontalHessian(TNT::Array2D <double> array, double tolerance)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <double> line;
TNT::Array1D <double> spline;
TNT::Array1D <double> hessian;
for (int i=0; i<height; i++) {
line = getRow2(array, i);
spline = getSplineInterpolationCoefficients(line, tolerance);
hessian = getHessian(spline);
// putRow(&a, width, height, hessian, i);
putRow2(&a, width, height, hessian, i);
line = spline = hessian = 0.0;
int tmp = line.dim1();
int noop=0;
}
return a;
} // end getHorizontalHessian
///////////////////////////////////////////////////////////////////////////////
//
// getInitialAntiCausalCoefficientMirrorOnBounds
//
///////////////////////////////////////////////////////////////////////////////
double getInitialAntiCausalCoefficientMirrorOnBounds(TNT::Array1D <double> line, double z, double tolerance)
{
return ((z * line[line.dim1()-2] + line[line.dim1()-1]) * z / (z * z - 1.0));
} // end getInitialAntiCausalCoefficientMirrorOnBounds
///////////////////////////////////////////////////////////////////////////////
//
// getInitialCausalCoefficientMirrorOnBounds
//
///////////////////////////////////////////////////////////////////////////////
double getInitialCausalCoefficientMirrorOnBounds(TNT::Array1D <double> line, double z, double tolerance)
{
int size = line.dim1();
double z1 = z;
double zn = pow(z, size-1);
double sum = line[0] + zn * line[size - 1];
int horizon = line.dim1();
if (0.0 < tolerance) {
horizon = 2 + (int) log(tolerance) / log(abs(z));
horizon = (horizon < line.dim1()) ? (horizon) : (line.dim1());
}
zn = zn * zn;
for (int n=1; n<horizon-1; n++) {
zn = zn/z;
sum = sum + (z1+zn) * line[n];
z1 = z1 * z;
}
return (sum/(1.0-pow(z, 2 * line.dim1() - 2)));
} // end getInitialCausalCoefficientMirrorOnBounds
///////////////////////////////////////////////////////////////////////////////
//
// getRow
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getRow(TNT::Array2D <double> array, int row)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <double> a(width, 0.0);
TNT::Array1D <double> temp(width*height, 0.0);
int rowLength = height;
int y = row;
y *= rowLength;
temp = convert2DTo1D(array);
for (int i=0; i<width; i++) {
a[i] = temp[y++];
}
return a;
} // end getRow
///////////////////////////////////////////////////////////////////////////////
//
// getRow2
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getRow2(TNT::Array2D <double> array, int row)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <double> a(width, 0.0);
TNT::Array1D <double> temp(width*height, 0.0);
int rowLength = width;
int y = row;
y *= rowLength;
temp = convert2DTo1D(array);
for (int i=0; i<width; i++) {
a[i] = temp[y++];
}
return a;
} // end getRow2
///////////////////////////////////////////////////////////////////////////////
//
// getSplineInterpolationCoefficients
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getSplineInterpolationCoefficients(TNT::Array1D <double> line, double tolerance)
{
int size = line.dim1();
double zSize = 1;
double lambda=1.0;
TNT::Array1D <double> z (zSize, 0.0);
TNT::Array1D <double> a (size, 0.0);
// copy line to a
for (int i=0; i<size; i++) {
a[i] = line[i];
}
z[0] = sqrt(3.0) - 2.0;
for (int k=0; k<zSize; k++) {
lambda = lambda * (1.0 - z[k]) * (1.0 - 1.0 / z[k]);
}
for (int n=0; n<size; n++) {
a[n] = a[n] * lambda;
}
for (int k=0; k<zSize; k++) {
a[0] = getInitialCausalCoefficientMirrorOnBounds(a, z[k], tolerance);
for (int n=1; n<size; n++) {
a[n] = a[n] + z[k] * a[n-1];
}
a[size-1] = getInitialAntiCausalCoefficientMirrorOnBounds(a, z[k], tolerance);
for (int n=size-2; 0 <= n; n--) {
a[n] = z[k] * (a[n+1] - a[n]);
}
}
return a;
} // end getSplineInterpolationCoefficients
///////////////////////////////////////////////////////////////////////////////
//
// getVerticalGradient
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> getVerticalGradient(TNT::Array2D <double> array, double tolerance)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <double> line;
TNT::Array1D <double> spline;
TNT::Array1D <double> gradient;
for (int i=0; i<width; i++) {
line = getCol2(array, i);
spline = getSplineInterpolationCoefficients(line, tolerance);
gradient = getGradient(spline);
// putRow(&a, width, height, hessian, i);
putCol2(&a, width, height, gradient, i);
line = spline = gradient = 0.0;
}
return a;
} // end getVerticalGradient
///////////////////////////////////////////////////////////////////////////////
//
// getVerticalHessian
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> getVerticalHessian(TNT::Array2D <double> array, double tolerance)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <double> line;
TNT::Array1D <double> spline;
TNT::Array1D <double> hessian;
for (int i=0; i<width; i++) {
line = getCol(array, i);
spline = getSplineInterpolationCoefficients(line, tolerance);
hessian = getHessian(spline);
// putCol(&a, width, height, hessian, i);
putCol2(&a, width, height, hessian, i);
}
return a;
} // end getVerticalHessian
///////////////////////////////////////////////////////////////////////////////
//
// gradient
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> gradient(TNT::Array2D <double> array)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
TNT::Array1D <double> temp(height*width, 0.0);
// create horizontal and vertical arrays
TNT::Array2D <double> hh;
TNT::Array2D <double> vv;
TNT::Array1D <double> hhTemp, vvTemp, aTemp;
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = array[i][j];
}
}
hh = getHorizontalGradient(array, FLT_EPSILON);
vv = getVerticalGradient(array, FLT_EPSILON);
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = sqrt(hh[i][j] * hh[i][j] + vv[i][j] * vv[i][j]);
}
}
return a;
} // end gradient
///////////////////////////////////////////////////////////////////////////////
//
// sortArray
//
///////////////////////////////////////////////////////////////////////////////
void sortArray(int *arrayIn, int size)
{
// throw this to a vector and sort
vector <int> v;
for (int i=0; i<size; i++) {
v.push_back(arrayIn[i]);
}
sort(v.begin(), v.end());
// put sorted values back to array
for (int i=0; i<size; i++) {
arrayIn[i] = v[i];
}
} // end sortArray
///////////////////////////////////////////////////////////////////////////////
//
// symmetricFirMirrorOnBounds
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> symmetricFirMirrorOnBounds(TNT::Array1D <double> h, TNT::Array1D <double> c)
{
TNT::Array1D <double> a (c.dim1(), 0.0);
int temp = c.dim1();
int fun=0;
a[0] = h[0] * c[0] + 2.0 * h[1] * c[1];
for (int i=1; (i<(c.dim1()-1)); i++) {
a[i] = h[0] * c[i] + h[1] * (c[i - 1] + c[i + 1]);
}
a[c.dim1()-1] = h[0] * c[c.dim1()-1] + 2.0 * h[1] * c[c.dim1()-2];
return a;
} // end symmetricFirMirrorOnBounds
///////////////////////////////////////////////////////////////////////////////
//
// getGradient
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getGradient (TNT::Array1D <double> c)
{
TNT::Array1D <double> h(2, 0.0);
h[0] = 0.0;
h[1] = -1.0/2.0;
TNT::Array1D <double> a;
a = antiSymmetricFirMirrorOnBounds(h, c);
return a;
} // end getGradient
///////////////////////////////////////////////////////////////////////////////
//
// putRow2
//
///////////////////////////////////////////////////////////////////////////////
void putRow2(TNT::Array2D <double> *array, int width, int height, TNT::Array1D <double> rowIn, int row)
{
TNT::Array1D <double> temp(width * height, 0.0);
int rowLength = width;
int y = row;
y *= rowLength;
temp = convert2DTo1D(*array);
for (int i=0; i<width; i++) {
temp[y++] = rowIn[i];
}
*array = convert1DTo2D(temp, width, height);
} // end putRow2
///////////////////////////////////////////////////////////////////////////////
//
// convert2DTo1D
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> convert2DTo1D(TNT::Array2D <double> arrayIn)
{
int height = arrayIn.dim1(), width = arrayIn.dim2(), size=0;
size = height * width;
TNT::Array1D <double> a(size, 0.0);
int index=0;
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
a[index] = arrayIn[i][j];
index++;
}
}
return a;
} // end convert2DTo1D
///////////////////////////////////////////////////////////////////////////////
//
// getCol
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getCol(TNT::Array2D <double> array, int col)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <double> a(height, 0.0);
TNT::Array1D <double> temp(height*width, 0.0);
int x = col;
temp = convert2DTo1D(array);
for (int i=0; i<height; i++) {
a[i] = temp[x];
x += width;
}
return a;
} // end getCol
///////////////////////////////////////////////////////////////////////////////
//
// getCol2
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> getCol2(TNT::Array2D <double> array, int col)
{
int height = array.dim1(), width = array.dim2();
TNT::Array1D <double> a(height, 0.0);
TNT::Array1D <double> temp(height*width, 0.0);
int x = col;
temp = convert2DTo1D(array);
for (int i=0; i<height; i++) {
a[i] = temp[x];
x += width;
}
return a;
} // end getCol2
///////////////////////////////////////////////////////////////////////////////
//
// putCol2
//
///////////////////////////////////////////////////////////////////////////////
void putCol2(TNT::Array2D <double> *array, int width, int height, TNT::Array1D <double> colIn, int col)
{
TNT::Array1D <double> temp(width*height, 0.0);
int x = col;
temp = convert2DTo1D(*array);
for (int i=0; i<height; i++) {
temp[x] = colIn[i];
x += width;
}
*array = convert1DTo2D(temp, width, height);
} // end putCol2
///////////////////////////////////////////////////////////////////////////////
//
// antiSymmetricFirMirrorOnBounds
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array1D <double> antiSymmetricFirMirrorOnBounds(TNT::Array1D <double> h, TNT::Array1D <double> c)
{
TNT::Array1D <double> a (c.dim1(), 0.0);
int temp = c.dim1();
int fun=0;
a[0] = 0.0;
for (int i=1; (i<(c.dim1()-1)); i++) {
a[i] = h[1] * ((c[i + 1] - c[i - 1]));
}
a[c.dim1()-1] = 0.0;
return a;
} // end antiSymmetricFirMirrorOnBounds
///////////////////////////////////////////////////////////////////////////////
//
// convert1DTo2D
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> convert1DTo2D(TNT::Array1D <double> arrayIn, int width, int height)
{
TNT::Array2D <double> a(height, width, 0.0);
int index=0;
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
a[i][j] = arrayIn[index];
index++;
}
}
return a;
} // end convert1DTo2D
///////////////////////////////////////////////////////////////////////////////
//
// runCannyEdge
//
///////////////////////////////////////////////////////////////////////////////
IplImage *runCannyEdge(IplImage *imageIn)
{
// do we have a color image? if so, convert it to grayscale first
if (imageIn->nChannels == 3) {
IplImage *gray = cvCreateImage(cvGetSize(imageIn), imageIn->depth, 1);
printf("loaded\n");
cvCvtColor(imageIn, gray, CV_BGR2GRAY);
printf("converted to grayscale\n");
IplImage *temp = cvCreateImage(cvGetSize(imageIn), 8, 1);
cvCanny(gray, temp, 10, 100);
IplImage *out = convert1PlaneIPLImageTo3Plane(temp);
printf("ran canny\n");
return out;
cvReleaseImage(&gray);
} else {
//cvCanny(imageIn, imageOut, 10, 100, 3);
}
} // end runCannyEdge
///////////////////////////////////////////////////////////////////////////////
//
// runSobelEdge
//
///////////////////////////////////////////////////////////////////////////////
IplImage *runSobelEdge(IplImage *imageIn)
{
// do we have a color image? if so, convert it to grayscale first
if (imageIn->nChannels == 3) {
IplImage *gray = cvCreateImage(cvGetSize(imageIn), imageIn->depth, 1);
printf("loaded\n");
cvCvtColor(imageIn, gray, CV_BGR2GRAY);
printf("converted to grayscale\n");
IplImage *temp = cvCreateImage(cvGetSize(imageIn), 8, 1);
cvSobel(gray, temp, 1, 0, 3);
printf("ran canny\n");
IplImage *out = convert1PlaneIPLImageTo3Plane(temp);
cvReleaseImage(&gray);
return out;
} else {
//cvCanny(imageIn, imageOut);
}
} // end runCannyEdge
/////////////////////////////////////////////////////////////////////
//
// contrastStretching
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> contrastStretching(TNT::Array2D <double> array, TNT::Array1D <int> lut)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = (int)lut[(int)(array[i][j])&0xff];
}
}
return a;
} // end contrastStretching
///////////////////////////////////////////////////////////////////////////////
//
// powerLaw
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> powerLaw(TNT::Array2D <double> array, float constant, float gamma)
{
int height = array.dim1(), width = array.dim2();
float s=0, temp=0;
TNT::Array2D <double> a(height, width, 0.0);
for (int i=0; i<height;i++) {
for (int j=0; j<width;j++) {
temp = array[i][j];
s = pow((float)temp/255, gamma) * 255;
s = s * constant;
if (s > 255) {
s = 255;
}
if (s < 0) {
s = 0;
}
a[i][j] = s;
}
}
return a;
} // end powerLaw
///////////////////////////////////////////////////////////////////////////////
//
// bitPlaneSlicing
//
// This function implements bit plane slicing
//
// array - input image (2d array)
// plane - plane to slice at
//
///////////////////////////////////////////////////////////////////////////////
TNT::Array2D <double> bitPlaneSlicing(TNT::Array2D <double> array, int plane)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int mask = (int)(pow(2, plane));
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
if ((int)(array[i][j])&(mask)) {
a[i][j] = 255;
} else {
a[i][j] = 0;
}
}
}
return a;
} // end bitPlaneSlicing
/////////////////////////////////////////////////////////////////////
//
// applyAdaptiveFilter
//
// Takes an image and applies the adaptive filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyAdaptiveFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
double meanL=0, varianceL=0, varNoise=1000;
int value=0;
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
meanL = meanLocal(array, k, width, height, j, i);
varianceL = varianceLocal(array, k, width, height, j, i, meanL);
double ratio=0;
if (varNoise > varianceL) {
ratio = 1;
} else {
ratio = varNoise/varianceL;
}
value = array[i][j] - (int)(ratio * (array[i][j] - meanL));
if (value < 0) {
value = 0;
}
if (value > 255) {
value = 255;
}
a[i][j] = value;
}
}
return a;
} // end applyAdaptiveFilter
/////////////////////////////////////////////////////////////////////
//
// applyAdaptiveMedianFilter
//
// Takes an image and applies the adaptive median filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
// sMax is hardcoded
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyAdaptiveMedianFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
int zMin=0, zMax=0, zMed=0, z=0, sMax=11;
bool supp=false;
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
int dim=k;
int value=0;
while (dim < sMax+1) {
zMin = min(array, dim, width, height, j, i);
zMax = max(array, dim, width, height, j, i);
zMed = median(array, dim, width, height, j, i);
z = array[i][j];
int a1 = zMed - zMin;
int a2 = zMed - zMax;
if ((a1>0) && (a2<0)) {
int b1 = z - zMin;
int b2 = z - zMax;
if ((b1>0) && (b2<0)) {
value = z;
} else {
value = zMed;
}
break;
} else {
dim = dim+2;
if (dim <= sMax) {
continue;
} else {
value = z;
break;
}
}
}
if (value < 0) {
value = 0;
}
if (value > 255) {
value = 255;
}
a[i][j] = value;
}
}
return a;
} // end applyAdaptiveMedianFilter
/////////////////////////////////////////////////////////////////////
//
// applyAlphaTrimmed
//
// Takes an image and applies the alpha trimmed filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyAlphaTrimmed(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = alphaTrimmed(array, k, width, height, j, i);
}
}
return a;
}
/////////////////////////////////////////////////////////////////////
//
// applyContraharmonicFilter
//
// Takes an image and applies the contraharmonic filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyContraharmonicFilter(TNT::Array2D <double> array, int size, float q)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = meanContraharmonic(array, k, width, height, j, i, q);
}
}
return a;
} // end applyContraharmonicFilter
/////////////////////////////////////////////////////////////////////
//
// applyGeometricFilter
//
// Takes an image and applies the geometric filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyGeometricFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = meanGeometric(array, k, width, height, j, i);
}
}
return a;
} // end applyGeometricFilter
/////////////////////////////////////////////////////////////////////
//
// applyHarmonicFilter
//
// Takes an image and applies the harmonic filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyHarmonicFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = meanHarmonic(array, k, width, height, j, i);
}
}
return a;
} // end applyHarmonicFilter
/////////////////////////////////////////////////////////////////////
//
// applyMaxFilter
//
// Takes an image and applies the max filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyMaxFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = max(array, k, width, height, j, i);
}
}
return a;
} // end applyMaxFilter
/////////////////////////////////////////////////////////////////////
//
// applyMeanFilter
//
// Takes an image and applies the mean filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyMeanFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = meanArithmetic(array, k, width, height, j, i);
}
}
return a;
} // end applyMeanFilter
/////////////////////////////////////////////////////////////////////
//
// applyMedianFilter
//
// Takes an image and applies the median filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyMedianFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = median(array, k, width, height, j, i);
}
}
return a;
} // end applyMedianFilter
/////////////////////////////////////////////////////////////////////
//
// applyMidpointFilter
//
// Takes an image and applies the midpoint filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyMidpointFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
int t1=0, t2=0;
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
t1 = min(array, k, width, height, j, i);
t2 = max(array, k, width, height, j, i);
a[j][i] = (t1+t2)/2;
}
}
return a;
} // end applyMidPointFilter
/////////////////////////////////////////////////////////////////////
//
// applyMinFilter
//
// Takes an image and applies the min filter with the
// specified dimension of the kernel
//
// array - input image (2d array)
// size - dimension of the kernel (0=1x1, 1=3x3, 2=5x5, 3=7x7)
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> applyMinFilter(TNT::Array2D <double> array, int size)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int k=0, sum=0;
if (size == 0) {
k=1;
} else if (size == 1) {
k=3;
} else if (size == 2) {
k=5;
} else if (size == 3) {
k=7;
}
for (int i=0;i<height;i++) {
for (int j=0;j<width;j++) {
a[i][j] = min(array, k, width, height, j, i);
}
}
return a;
} // end applyMinFilter
/////////////////////////////////////////////////////////////////////
//
// alphaTrimmed
//
// Adds impulse (salt and pepper) noise to an image
//
// array - input image (2d array)
// k - dimension of the kernel
// width - width of the image
// height - height of the image
// x - x coordinate of the center pixel of the array
// y - y coordinate of the center pixel of the array
//
/////////////////////////////////////////////////////////////////////
int alphaTrimmed (TNT::Array2D <double> array, int k, int width, int height, int x, int y)
{
int t=0, sum=0, number=0;
int *supp = new int [k*k];
int atAlpha=3;
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
supp[t] = array[y-1+i][x-1+j];
t++;
number++;
}
}
}
if (number == 0) {
delete [] supp;
return 0;
}
sortArray(supp, k*k);
for (int u=0; u<(atAlpha/2); u++) {
supp[u] = -1;
}
for (int v=number-1; v>number-1-(atAlpha/2); v--) {
supp[v] = -1;
}
for (int w=0; w<number; w++) {
if (supp[w] != -1) {
sum = sum+supp[w];
}
}
delete [] supp;
if (sum == 0) {
return 0;
} else {
return (sum/(number-atAlpha));
}
}
/////////////////////////////////////////////////////////////////////
//
// varianceLocal
//
// This function calculates the variance of a kxk pixel
// neighborhood (including center pixel)
//
/////////////////////////////////////////////////////////////////////
int varianceLocal (TNT::Array2D <double> array, int k, int width, int height, int x, int y, double m)
{
double sum=0, number=0;
for (int i=0;i<k;i++) {
for (int j=0;j<k;j++) {
if(((x-1+j)>=0) && ((y-1+i)>=0) && ((x-1+j)<width) && ((y-1+i)<height)) {
sum = sum + pow((array[y-1+i][x-1+j]-m), 2);
number++;
}
}
}
if (number == 0) {
return 0;
}
return sum/number;
}
/////////////////////////////////////////////////////////////////////
//
// addNoiseGamma
//
// Adds Gamma noise to an image
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> addNoiseGamma(TNT::Array2D <double> array, float variance, float alpha)
{
int height = array.dim1(), width = array.dim2();
double A =sqrt((double)variance/(double)alpha)/2;
double noise=0, theta=0, rx=0, ry=0, temp=0;
TNT::Array2D <double> ret(height, width, 0.0);
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
for (int a=0; a<alpha; a++) {
//noise = sqrt(-2*A*log(1.0-drand48()));
//theta = (drand48() * 6.28318530718 - 3.14159265359);
noise = sqrt(-2*A*log(1.0-rand()));
theta = (rand() * 6.28318530718 - 3.14159265359);
rx = noise*cos(theta);
ry = noise*sin(theta);
noise = rx*rx+ry*ry;
temp = array[i][j];
temp = temp + noise;
if (temp < 0) {
temp = 0;
}
if (temp > 255) {
temp = 255;
}
ret[i][j] = temp;
}
}
}
return ret;
} // end addNoiseGamma
/////////////////////////////////////////////////////////////////////
//
// addNoiseGaussian
//
// Adds Gaussian noise to an image
//
// array - input image (2d array)
// mean - mean
// variance - variance
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> addNoiseGaussian(TNT::Array2D <double> array, float mean, float variance)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
double temp=0, pixel=0;
// randomize the seed
srand(time(NULL));
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
pixel = array[i][j];
temp = pixel + mean + sqrt(variance)*gaussianRandom();
if (temp < 0) {
temp = 0;
}
if (temp > 255) {
temp = 255;
}
a[i][j] = temp;
}
}
return a;
} // end addNoiseGaussian
/////////////////////////////////////////////////////////////////////
//
// addNoiseImpulse
//
// Adds impulse (random white pixels) noise to an image
//
// array - input image (2d array)
// percent - percentage of image to add noise to
//
/////////////////////////////////////////////////////////////////////
TNT::Array2D <double> addNoiseImpulse(TNT::Array2D <double> array, float percent)
{
int height = array.dim1(), width = array.dim2();
TNT::Array2D <double> a(height, width, 0.0);
int n = (int)((percent/100) * width * height);
int rx=0, ry=0;
int xMin=0, yMin=0, xMax=width, yMax=height;
// copy the original image
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
a[i][j] = array[i][j];
}
}
// add the noise
for (int i=0; i<n; i++) {
rx = rand() % xMax + xMin;
ry = rand() % yMax + yMin;
a[ry][rx] = 0;
}
return a;
} // end addNoiseImpulse
/////////////////////////////////////////////////////////////////////
//
// gaussianRandom()
//
/////////////////////////////////////////////////////////////////////
double gaussianRandom()
{
static double V1, V2, S;
static int phase = 0;
double X;
if (phase == 0) {
do {
double U1 = (double)rand() / RAND_MAX;
double U2 = (double)rand() / RAND_MAX;
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
} else {
X = V2 * sqrt(-2 * log(S) / S);
}
phase = 1 - phase;
return X;
}
///////////////////////////////////////////////////////////////////////////////
//
// iplImageTo2DArrayOnePlane
//
// This function assumes that the image comes in as RGB
//
// algorithm :: determines which method is used for the conversion
//
// 0 = grab the green plane
// 1 = lightness method -> (max(R,G,B) + min(R,G,B)) / 2
// 2 = average -> (R+G+B) / 3
// 3 = luminosity (weighted average) -> 0.21R + 0.71G + 0.07B
//
///////////////////////////////////////////////////////////////////////////////
int **IplImageToOnePlane2D (IplImage *imageIn, int algorithm, int plane)
{
int **onePlane2D = make2DArray(imageIn->height,imageIn->width);
///////////////////////////////////////////////////////////////////////////
//
// grab one plane
//
///////////////////////////////////////////////////////////////////////////
if (algorithm == 0) {
// create the 2D array
for (int y=0; y<imageIn->height; y++) {
for (int x=0; x<imageIn->width; x++) {
// plane (1=R, 2=G, 3=B)
if (plane == 1) {
onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3];
} else if (plane == 2) {
onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+1];
} else if (plane == 3) {
onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+2];
}
} // end inner for
} // end outer for
} // end-if algorithm
///////////////////////////////////////////////////////////////////////////
//
// lightness method : (max(R,G,B) + min(R,G,B)) / 2
//
///////////////////////////////////////////////////////////////////////////
if (algorithm == 1) {
// create the 2D array
for (int y=0; y<imageIn->height; y++) {
for (int x=0; x<imageIn->width; x++) {
// grab the pixel values of each
int r = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3];
int g = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+1];
int b = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+2];
// what is the max?
int maxRGB = 0;
if (r>maxRGB) maxRGB=r;
if (g>maxRGB) maxRGB=g;
if (b>maxRGB) maxRGB=b;
// what is the min?
int minRGB = 255;
if (r<minRGB) minRGB=r;
if (g<minRGB) minRGB=g;
if (b<minRGB) minRGB=b;
int pixValue = (maxRGB + minRGB) / 2;
if (pixValue > 255) pixValue = 255;
if (pixValue < 0) pixValue = 0;
onePlane2D[y][x] = pixValue;
} // end inner for
} // end outer for
} // end-if algorithm #1
///////////////////////////////////////////////////////////////////////////
//
// average
//
///////////////////////////////////////////////////////////////////////////
if (algorithm == 2) {
// create the 2D array
for (int y=0; y<imageIn->height; y++) {
for (int x=0; x<imageIn->width; x++) {
// grab the pixel values of each
int r = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3];
int g = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+1];
int b = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+2];
// calculate the average
int pixValue = (r + g + b) / 2;
if (pixValue > 255) pixValue = 255;
if (pixValue < 0) pixValue = 0;
onePlane2D[y][x] = pixValue;
} // end inner for
} // end outer for
} // end-if algorithm #2
///////////////////////////////////////////////////////////////////////////
//
// luminosity -> 0.21R + 0.71G + 0.07B
//
///////////////////////////////////////////////////////////////////////////
if (algorithm == 3) {
// create the 2D array
for (int y=0; y<imageIn->height; y++) {
for (int x=0; x<imageIn->width; x++) {
// grab the pixel values of each
int r = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3];
int g = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+1];
int b = onePlane2D[y][x] = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3+2];
// calculate the luminosity
int pixValue = (int)(0.21 * (float)r + 0.5) + (int)(0.71 * (float)g + 0.5) + (int)(0.07 * (float)b + 0.5);
if (pixValue > 255) pixValue = 255;
if (pixValue < 0) pixValue = 0;
onePlane2D[y][x] = pixValue;
} // end inner for
} // end outer for
} // end-if algorithm #3
return onePlane2D;
} // end IplImageToOnePlane
///////////////////////////////////////////////////////////////////////////////
//
// convolveWithOpenCV
//
///////////////////////////////////////////////////////////////////////////////
IplImage *convolveWithOpenCV (IplImage *in, int horizontal1Vertical2)
{
IplImage *out = cvCreateImage(cvGetSize(in), 8, 1);
CvMat *kernel = cvCreateMat(3, 3, CV_64FC1);
if (horizontal1Vertical2 == 1) {
cvmSet(kernel, 0, 0, -1.0); cvmSet(kernel, 0, 1, -1.0); cvmSet(kernel, 0, 2, -1.0);
cvmSet(kernel, 1, 0, 0.0); cvmSet(kernel, 1, 1, 0.0); cvmSet(kernel, 1, 2, 0.0);
cvmSet(kernel, 2, 0, 1.0); cvmSet(kernel, 2, 1, 1.0); cvmSet(kernel, 2, 2, 1.0);
} else if (horizontal1Vertical2 == 2) {
cvmSet(kernel, 0, 0, -1.0); cvmSet(kernel, 0, 1, 0.0); cvmSet(kernel, 0, 2, 1.0);
cvmSet(kernel, 1, 0, -1.0); cvmSet(kernel, 1, 1, 0.0); cvmSet(kernel, 1, 2, 1.0);
cvmSet(kernel, 2, 0, -1.0); cvmSet(kernel, 2, 1, 0.0); cvmSet(kernel, 2, 2, 1.0);
}
cvFilter2D(in, out, kernel);
return out;
} // end convolveWithOpenCV
///////////////////////////////////////////////////////////////////////////////
//
// convert1PlaneIPLImageTo3Plane
//
///////////////////////////////////////////////////////////////////////////////
IplImage *convert1PlaneIPLImageTo3Plane (IplImage *imageIn)
{
IplImage *out = cvCreateImage(cvGetSize(imageIn), 8, 3);
int counter = 0;
// create the 2D array
// for (int y=0; y<imageIn->height; y++) {
// for (int x=0; x<imageIn->width; x++) {
// grab the pixel value of the grayscale image
//int val = ((uchar*)(imageIn->imageData + imageIn->widthStep*y))[x*3];
for (int i=0; i<imageIn->height*imageIn->width; i++) {
int val = ((uchar *)imageIn->imageData)[i];
// populate the same value to the out image
((uchar *)out->imageData)[counter] = (char)val;
((uchar *)out->imageData)[counter+1] = (char)val;
((uchar *)out->imageData)[counter+2] = (char)val;
counter +=3;
}
// }
// }
return out;
} // end convert1PlaneIPLImageTo3Plane
| [
"lab@lab-laptop",
"[email protected]"
] | [
[
[
1,
1
],
[
29,
60
],
[
62,
65
],
[
67,
81
],
[
83,
83
],
[
85,
85
],
[
91,
91
],
[
93,
104
],
[
107,
107
],
[
110,
110
],
[
112,
112
],
[
114,
114
],
[
118,
118
],
[
121,
121
],
[
134,
134
],
[
152,
152
],
[
155,
155
],
[
162,
162
],
[
164,
164
],
[
166,
166
],
[
168,
179
],
[
182,
182
],
[
185,
185
],
[
187,
187
],
[
189,
189
],
[
191,
194
],
[
196,
196
],
[
199,
199
],
[
202,
202
],
[
212,
212
],
[
230,
230
],
[
233,
233
],
[
240,
240
],
[
242,
242
],
[
244,
246
],
[
248,
261
],
[
263,
263
],
[
266,
266
],
[
271,
271
],
[
273,
286
],
[
288,
288
],
[
291,
291
],
[
295,
295
],
[
303,
303
],
[
306,
306
],
[
308,
321
],
[
323,
323
],
[
326,
326
],
[
335,
335
],
[
337,
350
],
[
352,
352
],
[
355,
355
],
[
359,
359
],
[
366,
366
],
[
375,
375
],
[
378,
378
],
[
380,
391
],
[
394,
394
],
[
397,
397
],
[
399,
399
],
[
403,
403
],
[
407,
407
],
[
409,
409
],
[
411,
411
],
[
413,
416
],
[
422,
424
],
[
429,
432
],
[
639,
639
],
[
644,
644
],
[
646,
648
],
[
650,
650
]
],
[
[
2,
28
],
[
61,
61
],
[
66,
66
],
[
82,
82
],
[
84,
84
],
[
86,
90
],
[
92,
92
],
[
105,
106
],
[
108,
109
],
[
111,
111
],
[
113,
113
],
[
115,
117
],
[
119,
120
],
[
122,
133
],
[
135,
151
],
[
153,
154
],
[
156,
161
],
[
163,
163
],
[
165,
165
],
[
167,
167
],
[
180,
181
],
[
183,
184
],
[
186,
186
],
[
188,
188
],
[
190,
190
],
[
195,
195
],
[
197,
198
],
[
200,
201
],
[
203,
211
],
[
213,
229
],
[
231,
232
],
[
234,
239
],
[
241,
241
],
[
243,
243
],
[
247,
247
],
[
262,
262
],
[
264,
265
],
[
267,
270
],
[
272,
272
],
[
287,
287
],
[
289,
290
],
[
292,
294
],
[
296,
302
],
[
304,
305
],
[
307,
307
],
[
322,
322
],
[
324,
325
],
[
327,
334
],
[
336,
336
],
[
351,
351
],
[
353,
354
],
[
356,
358
],
[
360,
365
],
[
367,
374
],
[
376,
377
],
[
379,
379
],
[
392,
393
],
[
395,
396
],
[
398,
398
],
[
400,
402
],
[
404,
406
],
[
408,
408
],
[
410,
410
],
[
412,
412
],
[
417,
421
],
[
425,
428
],
[
433,
638
],
[
640,
643
],
[
645,
645
],
[
649,
649
],
[
651,
2958
]
]
] |
6e437f8dab50dfb0542a6403f7f4866341aa0339 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DXGI/DXGIKeyedMutex.h | 226ab54b21248d5f007b2cd212c941d30dbbf7cd | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "DXGIDeviceSubObject.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace DXGI {
using namespace System;
/// <summary>
/// Represents a keyed mutex, which allows exclusive access to a shared resource
/// that is used by multiple devices.
/// <para>(Also see DirectX SDK: IDXGIKeyedMutex)</para>
/// </summary>
public ref class KeyedMutex :
public Microsoft::WindowsAPICodePack::DirectX::DXGI::DeviceSubObject
{
public:
/// <summary>
/// Using a key, acquires exclusive rendering access to a shared resource.
/// <para>(Also see DirectX SDK: IDXGIKeyedMutex::AcquireSync)</para>
/// </summary>
/// <param name="Key">A value that indicates which device to give access to.
/// This method will succeed when the device that currently owns the surface calls
/// the KeyedMutex.ReleaseSync method using the same value.
/// This value can be any UINT64 value.</param>
/// <param name="dwMilliseconds">The time-out interval, in milliseconds.
/// This method will return if the interval elapses, and the keyed mutex has not
/// been released using the specified Key.
/// If this value is set to zero, the AcquireSync method will test to see if
/// the keyed mutex has been released and returns immediately.
/// If this value is set to INFINITE, the time-out interval will never elapse.</param>
void AcquireSync(UInt64 Key, DWORD dwMilliseconds);
/// <summary>
/// Using a key, releases exclusive rendering access to a shared resource
/// <para>(Also see DirectX SDK: IDXGIKeyedMutex::ReleaseSync)</para>
/// </summary>
/// <param name="Key">A value that indicates which device to give access to. This method will succeed when the device that currently owns the surface calls the KeyedMutex.ReleaseSync method using the same value. This value can be any UINT64 value.</param>
void ReleaseSync(UInt64 Key);
internal:
KeyedMutex()
{
}
internal:
KeyedMutex(IDXGIKeyedMutex* pNativeIDXGIKeyedMutex)
{
Attach(pNativeIDXGIKeyedMutex);
}
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
53
]
]
] |
f1cdbbcf346c9bb2f2da4c2685deeb1d089e6e77 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/SceneData/Mesh/hkxMeshSection.h | 37dd45e09fab7f615049e91ad6514612f6d29e3a | [] | 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 | 3,263 | 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 HKSCENEDATA_MESH_HKXMESHSECTION_HKCLASS_H
#define HKSCENEDATA_MESH_HKXMESHSECTION_HKCLASS_H
/// hkxMeshSection meta information
extern const class hkClass hkxMeshSectionClass;
#include <Common/SceneData/Mesh/hkxIndexBuffer.h>
#include <Common/SceneData/Mesh/hkxVertexBuffer.h>
#include <Common/SceneData/Material/hkxMaterial.h>
/// A serialization wrapper for the relationship between a Vertex buffer and a set
/// of primitives.
class hkxMeshSection : public hkReferencedObject
{
//+vtable(true)
//+version(1)
public:
HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA );
HK_DECLARE_REFLECTION();
hkxMeshSection() { }
hkxMeshSection(const hkxMeshSection& other);
hkxMeshSection(hkFinishLoadedObjectFlag f ) : hkReferencedObject(f), m_vertexBuffer(f), m_indexBuffers(f), m_material(f), m_userChannels(f) { }
//
// Members
//
public:
/// The vertex buffer used by this section of the mesh.
hkRefPtr< class hkxVertexBuffer > m_vertexBuffer;
/// The set of primitives that use the vertex buffer.
hkArray< hkRefPtr<hkxIndexBuffer> > m_indexBuffers;
/// The material to use for this mesh. May be a multi material or a plain single
/// material, or null.
hkRefPtr< class hkxMaterial > m_material;
/// User channels are expected to contain per-vertex, per-edge or per-face information
/// It will remove ref on them
hkArray< hkRefVariant > m_userChannels;
public:
/// Returns the number of triangles
hkUint32 getNumTriangles () const;
void getTriangleIndices (hkUint32 triIndex, hkUint32& indexAOut, hkUint32& indexBOut, hkUint32& indexCOut) const;
//
// Utility methods
//
/// Collects all vertex positions to the given array.
void collectVertexPositions (hkArray<hkVector4>& verticesInOut) const;
/// Constructs a hkGeometry object based on this mesh section and merges it with geometryInOut.
void appendGeometry (struct hkGeometry& geometryInOut, int materialIndex = -1);
};
#endif // HKSCENEDATA_MESH_HKXMESHSECTION_HKCLASS_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,
86
]
]
] |
759768fa8fc9a42b61e73a6f73345d71b50297e4 | 395391c1b84e984e16d5d60fe02eee00fbd5c10a | /src/engine/sprites.cpp | 218fdefa05bd631d37541468a26a2a2375a84b0e | [] | no_license | bronzean/open-rock-raiders-c | 70104449a6d9d9ee689f0f6c34a62f2218f6ff67 | aac1a653738b12bc1743c6898867fad06716f007 | refs/heads/master | 2021-01-19T14:12:52.531935 | 2011-08-31T06:18:38 | 2011-08-31T06:18:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | /* Copyright the ORR-C Dev Team */
#include "../main.hpp"
int load_sprites()
{
/*teleport_button_spr = img_load2(teleport_button_path);
if(teleport_button_spr == NULL)
{
std::cout << "\nFailed loading teleport button sprite\n";
return 1;
}
no_teleport_button_spr = img_load2(no_teleport_button_path);
if(no_teleport_button_spr == NULL)
{
std::cout << "Failed loading disabled teleport button sprite\n";
return 1;
}*/
return 0;
}
| [
"CiliesJ@43b2f215-69ce-7cdb-bcbe-f39a4413677e"
] | [
[
[
1,
21
]
]
] |
78a5cc75c94b341795b26bf0cf66466b1a1bc9af | fa134e5f64c51ccc1c2cac9b9cb0186036e41563 | /GT/CommunicationTestDialog.h | f1b3936136013b6a42b20b240190bb1a4ef75014 | [] | no_license | dlsyaim/gradthes | 70b626f08c5d64a1d19edc46d67637d9766437a6 | db6ba305cca09f273e99febda4a8347816429700 | refs/heads/master | 2016-08-11T10:44:45.165199 | 2010-07-19T05:44:40 | 2010-07-19T05:44:40 | 36,058,688 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,015 | h | #pragma once
// CCommunicationTestDialog 对话框
class CCommunicationTestDialog : public CDialog
{
DECLARE_DYNAMIC(CCommunicationTestDialog)
public:
CCommunicationTestDialog(CWnd* pParent = NULL); // 标准构造函数
virtual ~CCommunicationTestDialog();
// 对话框数据
enum { IDD = IDD_COMMUNICATIONTEST_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
// Attributest
private:
CString commandDisplayer;
CString returnMessageDisplayer;
CString commandEdit;
// Operations
public:
afx_msg void OnBnClickedCommunicationTestFailure();
afx_msg void OnBnClickedCommunicationTestPass();
afx_msg void OnBnClickedDefaultTestButton();
afx_msg void OnBnClickedCommunicationTestButton();
afx_msg LRESULT OnReplyMsgArrived(WPARAM w, LPARAM l);
afx_msg void OnBnClickCancel();
private:
// Send the communication test command to the server
void sendCommunicationTestCommand(CString content);
};
| [
"[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6"
] | [
[
[
1,
37
]
]
] |
c9ad09796a895d6851aa7e72ea00a7e0de97d9c2 | dadae22098e24c412a8d8d4133c8f009a8a529c9 | /tp2/src/vertex_shader.cpp | 2b41c31f1ced8b61cdeea09cde841b8c5de93d97 | [] | no_license | maoueh/PHS4700 | 9fe2bdf96576975b0d81e816c242a8f9d9975fbc | 2c2710fcc5dbe4cd496f7329379ac28af33dc44d | refs/heads/master | 2021-01-22T22:44:17.232771 | 2009-10-06T18:49:30 | 2009-10-06T18:49:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | #include "vertex_shader.h"
#include "application_manager.h"
VertexShader::VertexShader(const STRING& filename) : Shader(filename),
mHandle(NULL)
{
mHandle = glCreateShader(GL_VERTEX_SHADER);
}
VertexShader::~VertexShader()
{
glDeleteShader(mHandle);
}
void VertexShader::load()
{
const CHAR* sources[1] = { mSource.c_str() };
glShaderSource(mHandle, 1, sources, NULL);
glCompileShader(mHandle);
#ifdef DEBUG
printLog();
#endif
}
UINT VertexShader::getHandle()
{
return mHandle;
}
void VertexShader::printLog()
{
ApplicationManager::get()->log("====== Vertex Shader Log (%s) ======", mFilename.c_str());
INT logMessageLength = 0;
glGetShaderiv(mHandle, GL_INFO_LOG_LENGTH, &logMessageLength);
if ( logMessageLength > 1 )
{
INT charactersWritten = 0;
CHAR* logMessage = (CHAR*) malloc(logMessageLength);
glGetShaderInfoLog(mHandle, logMessageLength, &charactersWritten, logMessage);
ApplicationManager::get()->log(logMessage);
//ApplicationManager::get()->log(""); // Newline
free(logMessage);
}
else
{
ApplicationManager::get()->log("Compilation Successful\n");
}
} | [
"[email protected]"
] | [
[
[
1,
53
]
]
] |
d82fb9fe124dcae98d44364f3b9c0f0b1819c1d3 | de2f72b217bc8a9b1f780090bedf425a2ad9587a | /Pangea/Physics/include/force/Force.h | ab06415faf64c68b28228ce9066d7f2333c708ac | [] | no_license | axelwass/oliveira | 65b32a7f16cb7e00a95cdf3051a731a2004aaf5f | 4c34730a720465311e367f8e25cc1cced46801c7 | refs/heads/master | 2021-01-18T14:18:42.622080 | 2011-04-18T18:39:08 | 2011-04-18T18:39:08 | 32,120,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | h | /*
* Force.h
*
* Created on: Sep 23, 2010
* Author: mmerchan
*/
#include "../particle/ParticleData.h"
#include "../particle/DerivativeData.h"
#include "../../../Generic/Generic.h"
#include <iostream>
#include <list>
#include <tr1/memory>
using namespace std;
#ifndef FORCE_H_
#define FORCE_H_
class Force;
typedef tr1::shared_ptr<Force> ForcePtr;
class Force {
private:
virtual DerivativeData _evaluate(real t, ParticleData * data) = 0;
virtual Force * _clone() = 0;
list<Force *> forces;
public:
Force() {
}
virtual ~Force() {
/* cout << "Eliminando funcion..." << forces.size() <<endl;
list<Force *>::iterator itr;
for(itr=forces.begin();itr!=forces.end();itr++){
Force * del = (*itr);
delete del;
}*/
}
// Evaluation function
DerivativeData evaluate(real t, ParticleData * data) {
DerivativeData out = this->_evaluate(t, data);
list<Force *>::iterator itr;
for (itr = forces.begin(); itr != forces.end(); itr++) {
out = out + (*itr)->_evaluate(t, data);
}
return out;
}
// Assign a vector
void operator+=(Force * other) {
Force * copy = other->_clone();
forces.push_back(copy);
}
};
#endif /* FORCE_H_ */
| [
"merchante.mariano@d457d4b0-f835-b411-19da-99c4f284aa10"
] | [
[
[
1,
59
]
]
] |
0ba470799295f664af14511d8eeb99e8f931fd19 | 1b974521c0a29f5e8935bee1fc8730c283682902 | /team0073.cpp | a43adc6a21a3e35773b0ca148ef19974726594ae | [] | no_license | deepankgupta/ai-challenge | 37702052238f44b8d9be77750ca0e5eb48341a78 | 3b6167f67ce4b7a3d065923e32da56395b1687d1 | refs/heads/master | 2020-05-31T09:07:39.930125 | 2008-10-21T16:39:50 | 2008-10-21T16:39:50 | 32,131,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,772 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
class team0005 //here the class name is given to be team0002 assuming that the registration no. of the participant was 2
{
private: //private fns and variables defined
int pl,ph,player_num,player_no,pl1,ph1,strmin;
int preqp(int finalx,int finaly, int initialx ,int initialy ) //function which tells the strength req by player to move from
{float req; //place to another
req=floor(sqrt(pow((finalx-initialx),2)+pow((finaly-initialy),2)));
return (int)req;}
int preqbp(int finalx,int finaly, int initialx ,int initialy ) //function which tells the strength req by hitter of ball to hit
{float req; int i; //the ball from one place to another
req=2*(floor(sqrt(pow((finalx-initialx),2)+pow((finaly-initialy),2))));
//i=req;
return int(req);}
//public functions
public:
int init(int team_number, struct player *p,char farray[][51]) //the mandatory function which initialises the team no. of the
{ //participant and tells him the initial field distribution
player_no = team_number;
}
int shoot_area(int ball_player,struct player *p) //to check if player is in shooting range
{
if( (player_no==1 && p[ball_player].x>60) || (player_no==2 && p[ball_player].x<40))
{ int y=10,x,j;
if(player_no==1)
{
strmin=preqbp(86,y,p[ball_player].x,p[ball_player].y);
}
else
{
strmin=preqbp(14,y,p[ball_player].x,p[ball_player].y);
}
for(y;y<=40;y++)
{
if(player_no==1)
{
x=preqbp(86,y,p[ball_player].x,p[ball_player].y);
}
else
{
x=preqbp(14,y,p[ball_player].x,p[ball_player].y);
}
if(x<strmin)
{
strmin=x;
j=y;
}
}
if(p[ball_player].strength>=strmin)
{
// check interception
if(player_no==1)
{
if(p[12].y!=j)
{
p[0].x=86;
p[0].y=j;
}
}
else
{
if(p[1].y!=j)
{
p[0].x=14;
p[0].y=j;
}
}
return 0;
}
else
{
return 1;
}
}
}
int player( struct player *p) //main player func
{
static int z=0;
int i,j,ball_player,a; //ball_player is used to find which player is having the possession of the ball or whether the ball
//is at empty slot
//assigning limits according to player no.
if(player_no==1)
{
pl=1; //pl shows the lower limit and ph shows the upper limit of players in the array of structures ,i.e. if player
ph=11;
pl1=12;
ph1=22; //is 1st then his players will be 1 to 11 and if he is 2nd then his players will be 12 to 22
player_num=1;
}
else
{
pl=12;
ph=22;
pl1=1;
ph1=11;
player_num=2;
}
// moving my attackers from my half to opposite half
/* if((z==0 || (p[5].x==30)&&(p[5].y==10)&&(p[6].x==30)&&(p[7].x==30)&&(p[6].y==25)&&(p[7].y==40))&& player_no==1)
{
p[5].x=60;
p[5].y=11;
p[6].x=71;
p[6].y=21;
p[7].x=60;
p[7].y=39;
p[11].x=50;
p[11].y=25;
p[0].x=60;
p[0].y=11;
z++;
return 11;
}
else
if(z==0 || ((p[16].x==70)&&(p[16].y==10)&&(p[17].x==70)&&(p[18].x==70)&&(p[17].y==25)&&(p[18].y==40)))
{
p[16].x=40;
p[16].y=11;
p[17].x=29;
p[17].x=21;
p[18].x=40;
p[18].y=39;
z++;
}
*/
if(z==0 || z==1)
{
if(player_num==1)
{
if(z==0)
{
p[1].x=15 ;p[1].y=25 ;
// p[2].x=27 ;p[2].y=10 ;
// p[3].x=27 ;p[3].y=40 ;
// p[4].x=40 ;p[4].y=20 ;
p[5].x=40 ;p[5].y= 30 ;
// p[6].x=50 ;p[6].y=5 ;
p[7].x= 65 ;p[7].y= 25 ;
p[8].x= 50 ;p[8].y= 45 ;
p[9].x= 60 ;p[9].y= 10 ;
p[10].x= 60 ;p[10].y= 40 ;
p[11].x= 50 ;p[11].y= 25 ; // positioning of players in my very first move
}
int min,q[4],t,s;
q[4]={2,3,4,6};
for(int k=pl1;k<=ph2;k++)
{
if(p[k].x<=40)
{
s=0;
min=strreq(p[k].x,p[k].y,p[q[i]].x,p[[q]i].y);
for(int y=0;y<4;y++)
{
if((strreq(p[k].x,p[k].y,p[q[i]].x,p[[q]i].y)<min)
{
min=strreq(p[k].x,p[k].y,p[q[i]],p[q[i].].y);
t=i;
}
}
}
p[t].x=p[k].x;
p[t].y=p[k].y;
}
}
else
{
p[12].x=85 ;p[12].y=25 ;
// p[12].x=73 ;p[i++].y= 10 ;
// p[i].x=73 ;p[i++].y= 40 ;
//p[i].x=60 ;p[i++].y= 20 ;
p[16].x= 60 ;p[16].y= 30 ;
// p[i].x=50 ;p[i++].y= 5 ;
p[18].x=35 ;p[18].y= 25 ;
p[19].x= 50 ;p[19].y= 45;
p[20].x=40 ;p[20].y= 10;
p[21].x= 40 ;p[21].y= 40 ;
p[22].x=50 ;p[22].y= 25 ; // positioning of players in my very first move
int min,q[4],t,s;
q[4]={2,3,4,6};
int a1=
for(int k=pl1;k<=ph2;k++)
{
if(p[k].x<=40)
{
s=0;
min=strreq(p[k].x,p[k].y,p[q[s]].x,p[[q]s].y);
for(int y=0;y<4;y++)
{
if((strreq(p[k].x,p[k].y,p[q[s]].x,p[q[s]].y)<min)
{
min=strreq(p[k].x,p[k].y,p[q[s]],p[q[s].].y);
t=s;
}
}
}
p[t].x=p[k].x;
p[t].y=p[k].y;
}
z++;
}
// checking where is ball
//player having the ball
for(i=1;i<23;i++)
if( p[0].x==p[i].x && p[0].y==p[i].y )
{
ball_player=i;
break;
}
if(i==23)
{
//so no player is having the ball
a=case3(p);
return a; //returns the hitter of the ball to the controller
}
if((i<=11&&player_no==1)||(i>11&&player_no==2))
{
//then ball is with my team player
a=case1(i,p);
return a;
}
// ball with opp team player
else
{
a=case2(i,p);
return a;
}
}//end of player func.
//definition of case1() , when the ball is with my player
int case1(int ball_player,struct player * p)
{
int i=pl;
int j=23,max=mstrength(i,p);
if(shoot_area(ball_player,p)!=0)
{
if((player_no==1 && p[0].x<40) || (player_no==2 && p[0].x>60))
{
++i;
}
for(i;i<=ph;i++)
{
if(ball_player!=i)
{
if((player_no==1 && p[i].x>=p[ball_player].x) || (player_no==2 && p[i].x<=p[ball_player].x))
{
if(preqbp(p[i].x,p[i].y,p[ball_player].x,p[ball_player].y)>=0)
{
if(mstrength(i,p)>max)
{
max=mstrength(i,p);
j=i;
}
}
}
}
}
if(j!=23)
{
int x=p[ball_player].x;
int y=p[ball_player].y;
// to check interception
int flag=0;
for(int i=pl1;i<=ph1;i++)
{
if( (p[i].x>p[ball_player].x && player_no==1) || (p[i].x<p[ball_player].x && player_no==2))
{
if(p[j].y>=y)
{
while( (x>=p[j].x && player_no==2 && y<=p[j].y) || (x<=p[j].x && player_no==1 && y<=p[j].y) )
{
if(player_no==1)
{
x++;
}
else
{
x--;
}
y++;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}// end of while
while (!(p[j].x==x && p[j].y==y))
{
if(x==p[j].x)
{
y++;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
else
{
if(player_no==1)
{
x++;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
else
{
x--;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
}
}
}// end of if
else
{
while( (x<=p[j].x && player_no==2 && y>=p[j].y ) || ( x>=p[j].x && player_no==1 && y>=p[j].y ) )
{
if(player_no==1)
{
x++;
}
else
{
x--;
}
y--;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}// end of while
while (!(p[j].x==x && p[j].y==y))
{
if(x==p[j].x)
{
y--;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
else
{
if(player_no==1)
{
x++;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
else
{
x--;
if(p[i].x==x && p[i].y==y)
{
++flag;
break;
}
}
}
}
}//end of else
}
}//end of for
if(flag!=0)// if ball is intercepted backpass the ball
{
for(int t=pl;t<=ph;t++)
{
if( (p[t].x<p[ball_player].x && player_no==1) || (p[t].x>p[ball_player].x && player_no==2))
{
if( preqbp(p[t].x,p[t].y,p[ball_player].x,p[ball_player].y)-p[ball_player].strength >=0 && (fintercept_check(p[t].x,p[t].y,p[ball_player].x,p[ball_player].y,p)==0))
{
p[0].x=p[t].x;
p[0].y=p[t].y;
}
}
}
//p[0].y=p[ball_player].y + 1;
}
else
{
p[0].x=p[j].x;
p[0].y=p[j].y;
}
}
}
// obstructing the ball by goalkeeper
if(player_no==1)
{
if(p[0].x<=40)
{
if(p[pl].strength-preqp(p[pl].x,p[0].y,p[pl].x,p[pl].y)>=0)
{
p[pl].y=p[0].y;
}
}
}
else
{
if(p[0].x>=60)
{
if(p[pl].strength-preqp(p[pl].x,p[0].y,p[pl].x,p[pl].y)>=0)
{
p[pl].y=p[0].y;
}
}
}
return ball_player;
} // end of case1() func.
//definition of mstrength()
int mstrength(int k,struct player *p)
{
int q;
int min;
min=p[k].strength-(p[pl1].strength-preqp(p[k].x,p[k].y,p[pl1].x,p[pl1].y));
for(int i=pl1;i<=ph1;i++)
{
q=( p[k].strength-(p[i].strength-preqp(p[k].x,p[k].y,p[i].x,p[i].y)));
if(q<min)
{
min=q;
}
}
return q;
}
// Definition of case2() func.
//ball is with opp team's player
int case2(int ball_player,struct player * p)
{ int i=pl,a;
int strreq;
int maxstr;
maxstr=((p[i].strength-preqp(p[ball_player].x,p[ball_player].y,p[i].x,p[i].y))-p[ball_player].strength);
//this for loop searches for a player who has more strength than the opponent's player having possession of the ball ,after
//reaching at the ball's position and if such player is found then the case becomes similar to one when my player was having the
//possession of the ball ,so the case1 function is called and finally the hitter of ball is returned to controller
for(i=pl;i<=ph;i++)
{
strreq=((p[i].strength-preqp(p[ball_player].x,p[ball_player].y,p[i].x,p[i].y))-p[ball_player].strength);
if(strreq>maxstr)
{
maxstr=strreq;
a=i;
}
if( maxstr>0 )
{
p[a].x=p[0].x;
p[a].y=p[0].y;
return case1(a,p);
}
else
{
p[a].x=p[0].x;
p[a].y=p[0].y;
return -1;
}
//if no such player is found then it simply returns a -1 i.e. , it don't want to hit the ball and skips the turn
}//end of case2 func.
}
//definition of case3() func.
//when ball is with no player
int case3(struct player * p)
{
int player_n=23,i=pl,a,strreq,large=0;
//this for loop searches for a player of my team such that after reaching at the position of the ball it is having the maximum
//strength left to hit the ball
for(i;i<=ph;i++)
{
strreq=preqp(p[0].x,p[0].y,p[i].x,p[i].y);
if( (p[i].strength - strreq ) > large) //large is having max strength of the player after reaching there
{ //player_no is having the no. of the desired player
player_n=i;
large=p[i].strength-strreq;
} //end of if
} //end of for loop
//if such player is found having maximum and non-zero strength left after reaching the position of the ball then that player
//is moved to ball's position and case1 function is called as the situation is similar to that when my player is having the
//possession of the ball
if(player_n!=23)
{
p[player_n].x=p[0].x;
p[player_n].y=p[0].y;
a=case1(player_n,p);
return a;
}
//if no player is found having non-zero strength after reaching the ball's position the move is skipped
return -1;
} // end of case3()
//in_range is a function defined by the participant
//it checks wheter the ball is in the range of the goal or not and returns 1 or 0 accordingly
int in_range(int ball_player,struct player * p)
{
if( (p[ball_player].y>=10) && (p[ball_player].y<=40) )
return 1;
return 0;
}
////////////////////////////////
int fintercept_check(int ix,int iy,int fx,int fy,struct player *p)//fx initial ix final
{
int validposx,validposy,xdiffb,ydiffb;int i;
char status='0';
int l;
validposx=fx;validposy=fy;
while((validposx!=ix)&&(validposy!=iy))
{
xdiffb=validposx-ix; //calculates the difference between changed coordinates and initial coordinates of the
ydiffb=validposy-iy; //ball
if(validposx!=ix)
(xdiffb<0)?(validposx)++:(validposx)--;
if(validposy!=iy)
(ydiffb<0)?(validposy)++:(validposy)--;
if(player_no==1)
{
for(i=12;i<=22;i++)
{
if((validposx==p[i].x)&&(validposy==p[i].y))
{
status='i';
l=0;
break;
}
}
if(l==0)
break;
}
else
{
for(i=1;i<=11;i++)
{
if((validposx==p[i].x)&&(validposy==p[i].y))
{
status='i';
l=0;
break;
}
}
if(l==0)
break;
}
}
if(status=='i')
return 1;
else
return 0;
}
}; //end of the class team0002
| [
"mohitgenii@dd1e002a-cb53-0410-ab0d-ab7dcae0fab8"
] | [
[
[
1,
711
]
]
] |
839b5104552ace74375d50cabf441b120c189132 | 57d74ff818cabf449d3ad457bcc54c5d78550352 | /8.0/SpiraTestCompletePlugIn/stdafx.cpp | ae7d7d9cc91b963461b35210c74fe55413d11bb1 | [] | no_license | Inflectra/spira-testing-test-complete | f6e28f558b97689331ee2107501eb121341aabdb | 9bcf5d3286dd3bba492bc432511be193becca547 | refs/heads/main | 2023-04-09T07:14:02.796898 | 2010-08-05T17:39:00 | 2010-08-05T17:39:00 | 359,174,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | cpp | // stdafx.cpp : source file that includes just the standard includes
// SpiraTestCompletePlugIn.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"asandman@5d4b435c-4d46-d949-aab2-e601ca53af14"
] | [
[
[
1,
5
]
]
] |
9885b5e97a4d7f9e9f4ec2e6df5fedcd2b616478 | 6e9f5476bb32a474c326f8d0412845c65ec40f46 | /epoch/nkgt.cpp | 48778f6b9cede081023097cb36c25eb1b5dc2ce4 | [] | no_license | nikolakn/gepoch | 8bd588033dd8ef8cfbe5c89b6acf0b41dfa265c5 | 6605fabea0ad245769b0b7f4e1b1ba2015a44fc6 | refs/heads/master | 2021-01-10T07:10:12.975817 | 2011-11-07T09:21:28 | 2011-11-07T09:21:28 | 43,171,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41 | cpp | #include "nkgt.h"
nkgt::nkgt()
{
}
| [
"bagatplus@4e4f1dd0-b059-00ba-97fa-1b68b94eb201"
] | [
[
[
1,
5
]
]
] |
30fdd88929bad269e4d5afea69748322f41fdece | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /include/Archive.h | 46579ec94f47829e2b957e68dc0d98db47bff824 | [] | no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,608 | h | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <assert.h>
#include <Ogre.h>
class Archive
{
public:
class Buffer
{
public:
enum AllocType
{
atDoNotTouch = 0, //will refuse to deallocate
atMalloc = 1, //using malloc()
atNew = 2, //using new char[x]
atOgreMalloc = 3//, //using OGRE_MALLOC (category MEMCATEGORY_RESOURCE)
//atOgreNew = 4, //using OGRE_NEW
};
//default constructor with everything empty
Buffer()
{
data = NULL;
length = 0;
aType = atDoNotTouch;
}
/*Buffer(size_t length, AllocType aType)
{
allocate(length,aType);
}*/
//returns length
inline size_t getLength()
{
return length;
}
//returns the data as a char*
char *asCharPtr()
{
return static_cast<char*>(data);
}
//returns the data as a unsigned char*
unsigned char *asUCharPtr()
{
return static_cast<unsigned char*>(data);
}
//returns data as a void*
void *asVoidPtr()
{
return data;
}
//just sets generic data, for when some function wants the data to be wrapped in a Buffer object
//whereever the data comes from, it has to take care of deallocation itself, Buffer will not be able to do so
void setData(void *newData, size_t length)
{
this->length = length;
data = newData;
aType = atDoNotTouch;
}
//like the one which takes a void*, but takes a char*
void setData(char *newData, size_t length)
{
this->length = length;
data = static_cast<void*>(newData);
aType = atDoNotTouch;
}
//like the one which takes a void*, but takes a unsigned char*
void setData(unsigned char *newData, size_t length)
{
this->length = length;
data = static_cast<void*>(newData);
aType = atDoNotTouch;
}
//allocate length bytes with the specified allocation method
bool allocate(size_t length, AllocType at = atNew)
{
this->length = length;
aType = at;
switch(at)
{
case atMalloc:
data = malloc(length);
if(!data)
return false;
return true;
case atNew:
{
char *tempData = new char[length];
data = static_cast<void*>(tempData);
return true;
}
case atOgreMalloc://using OGRE_MALLOC (category MEMCATEGORY_RESOURCE)
{
data = OGRE_MALLOC(length,Ogre::MEMCATEGORY_RESOURCE);
return true;
}
//case atOgreNew: //using OGRE_NEW
// {
// char *tempData = OGRE_NEW (char[length]);
// data = static_cast<void*>(tempData);
// return true;
// }
}
this->length = 0;
aType = atDoNotTouch;
return false;
}
//deallocates the buffer
bool deallocate()
{
switch(aType)
{
case atDoNotTouch:
return false;
case atMalloc:
free(data);
break;
case atNew:
{
char *tempData = asCharPtr();
delete tempData;
}
break;
case atOgreMalloc://using OGRE_MALLOC (category MEMCATEGORY_RESOURCE)
{
OGRE_FREE(data,Ogre::MEMCATEGORY_RESOURCE);
//data = OGRE_MALLOC(length,MEMCATEGORY_RESOURCE);
}
//case atOgreNew: //using OGRE_NEW
// {
// char *tempData = asCharPtr();
// OGRE_DELETE tempData;
// }
default:
return false;//and no reset
}
data = NULL;
length = 0;
aType = atDoNotTouch;
return true;
}
inline unsigned char operator [] (const size_t index) const
{
assert(index < length);
return (static_cast<unsigned char*>(data)[index]);
}
inline unsigned char & operator [] (const size_t index)
{
assert(index < length);
return (asUCharPtr()[index]);
}
inline bool isEmpty()
{
return data == NULL;
}
private:
AllocType aType;
void *data;
size_t length;
};
public:
Archive()
{
defaultAllocType = Buffer::atNew;
}
/*
virtual bool openRead();
virtual bool openWrite();
*/
/*virtual void addFile();
virtual void removeFile();*/
virtual bool hasFile(Ogre::String filename) = 0;
virtual Buffer getFile(Ogre::String filename,Buffer::AllocType allocWith = Buffer::atNew, bool nullTerminated = false) = 0;
virtual bool addFile(Ogre::String filename, Buffer data, bool overwrite = true) = 0;
virtual bool removeFile(Ogre::String filename) = 0;
inline void setDefaultAllocType(Buffer::AllocType type)
{
defaultAllocType = type;
}
inline Buffer::AllocType getDefaultAllocType()
{
return defaultAllocType;
}
protected:
Buffer::AllocType defaultAllocType;
}; | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] | [
[
[
1,
214
]
]
] |
bad9cb50b9f0abfd5abe8566f3fd3a4fd803eaa0 | f7be460272b02f7b582430396ede89dc14b50b88 | /stlfile.cpp | 1e638a1d96ac86796a497d6df5b6c24a4957e201 | [
"MIT"
] | permissive | ShenRen/stlviewer | 400934c125e557342bd3d8e81c1974e0a51082a9 | 3ed2415af299ace5564f6486344c04a680d625ea | refs/heads/master | 2021-01-15T22:14:20.658542 | 2011-01-18T20:54:29 | 2011-01-18T20:54:29 | 99,892,752 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,361 | cpp | // Copyright (c) 2009 Olivier Crave
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <QtCore/QtGlobal>
#include <QtGui/QApplication>
#include <QErrorMessage>
#include <math.h>
#include <string>
#include <algorithm>
#include <cctype>
#include <vector>
#include "stlfile.h"
#define HEADER_SIZE 84
#define JUNK_SIZE 80
#define SIZE_OF_FACET 50
#define ASCII_LINES_PER_FACET 7
StlFile::StlFile() {
facets = 0;
}
StlFile::~StlFile() {
close();
}
void StlFile::open(const ::std::string& fileName) {
initialize(fileName);
allocate();
readData(0, 1);
file.close();
}
void StlFile::write(const ::std::string& fileName) {
if (facets != 0) {
if (stats.type == ASCII)
writeAscii(fileName);
else
writeBinary(fileName);
}
}
void StlFile::close() {
if (facets != 0) {
delete[] facets;
facets = 0;
}
}
void StlFile::setFormat(const int format) {
if (format == ASCII)
stats.type = ASCII;
else if (format == BINARY)
stats.type = BINARY;
}
void StlFile::initialize(const ::std::string& fileName) {
stats.numFacets = 0;
stats.numPoints = 0;
stats.surface = -1.0;
stats.volume = -1.0;
facets = 0;
// Open the file
file.open(fileName.c_str(), ::std::ios::binary);
if (file.is_open()) {
int numFacets;
// Find length of file
file.seekg(0, ::std::ios::end);
int fileSize = file.tellg();
// Check for binary or ASCII file
file.seekg(0, ::std::ios::beg);
stats.type = BINARY;
int c;
while((c = file.get()) != EOF && c <= 127)
;
if(c == EOF) {
stats.type = ASCII;
}
file.seekg(0, ::std::ios::beg);
// Get the header and the number of facets in the .STL file
// If the .STL file is binary, then do the following
if (stats.type == BINARY) {
// Test if the STL file has the right size
if ((fileSize - HEADER_SIZE) % SIZE_OF_FACET != 0) {
::std::cerr << "The file " << file << " has a wrong size."
<< ::std::endl;
throw wrong_header_size();
}
numFacets = (fileSize - HEADER_SIZE) / SIZE_OF_FACET;
// Read the header
char buffer[JUNK_SIZE];
file.read(buffer, JUNK_SIZE);
stats.header = buffer;
// Read the int following the header.
// This should contain the number of facets
int headerNumFacets = readIntFromBytes(file);
if (numFacets != headerNumFacets) {
::std::cerr << "Warning: File size doesn't match number of "
<< "facets in the header." << ::std::endl;
QErrorMessage errMessage;
errMessage.showMessage("File size doesn't match number of facets "
"in the header.");
QApplication::restoreOverrideCursor();
errMessage.exec();
QApplication::setOverrideCursor(Qt::WaitCursor);
}
}
else { // Otherwise, if the .STL file is ASCII, then do the following
file.seekg(0, ::std::ios::beg);
// Get the header
getline(file, stats.header);
// Find the number of facets
int numLines = 0;
::std::string line;
while (!getline(file, line).eof()) {
if (line.size() > 4) { // don't count short lines
numLines++;
}
}
file.seekg(0, ::std::ios::beg);
numFacets = numLines / ASCII_LINES_PER_FACET;
}
stats.numFacets += numFacets;
} else {
::std::cerr << "The file " << file << " could not be found." << ::std::endl;
throw error_opening_file();
}
}
void StlFile::allocate() {
// Allocate memory for the entire .STL file
facets = new Facet[stats.numFacets];
if (facets == 0) {
::std::cerr << "Problem allocating memory" << ::std::endl;
throw ::std::bad_alloc();
}
}
void StlFile::readData(int firstFacet, int first) {
if (stats.type == BINARY) {
file.seekg(HEADER_SIZE, ::std::ios::beg);
} else {
file.seekg(0, ::std::ios::beg);
::std::string line;
// Skip the first line of the file
getline(file, line);
}
Facet facet;
for (int i = firstFacet; i < stats.numFacets; i++) {
if (stats.type == BINARY) { // Read a single facet from a binary .STL file
facet.normal.x = readFloatFromBytes(file);
facet.normal.y = readFloatFromBytes(file);
facet.normal.z = readFloatFromBytes(file);
facet.vector[0].x = readFloatFromBytes(file);
facet.vector[0].y = readFloatFromBytes(file);
facet.vector[0].z = readFloatFromBytes(file);
facet.vector[1].x = readFloatFromBytes(file);
facet.vector[1].y = readFloatFromBytes(file);
facet.vector[1].z = readFloatFromBytes(file);
facet.vector[2].x = readFloatFromBytes(file);
facet.vector[2].y = readFloatFromBytes(file);
facet.vector[2].z = readFloatFromBytes(file);
facet.extra[0] = file.get();
facet.extra[1] = file.get();
} else { // Read a single facet from an ASCII .STL file
::std::string junk;
file >> junk >> junk;
file >> facet.normal.x >> facet.normal.y >> facet.normal.z;
file >> junk >> junk >> junk;
file >> facet.vector[0].x >> facet.vector[0].y >> facet.vector[0].z;
file >> junk;
file >> facet.vector[1].x >> facet.vector[1].y >> facet.vector[1].z;
file >> junk;
file >> facet.vector[2].x >> facet.vector[2].y >> facet.vector[2].z;
file >> junk >> junk;
}
// Write the facet into memory.
facets[i] = facet;
// While we are going through all of the facets, let's find the
// maximum and minimum values for x, y, and z
// Initialize the max and min values the first time through
if (first) {
stats.max.x = facet.vector[0].x;
stats.min.x = facet.vector[0].x;
stats.max.y = facet.vector[0].y;
stats.min.y = facet.vector[0].y;
stats.max.z = facet.vector[0].z;
stats.min.z = facet.vector[0].z;
float xDiff = qAbs(facet.vector[0].x - facet.vector[1].x);
float yDiff = qAbs(facet.vector[0].y - facet.vector[1].y);
float zDiff = qAbs(facet.vector[0].z - facet.vector[1].z);
float maxDiff = qMax(xDiff, yDiff);
maxDiff = qMax(zDiff, maxDiff);
stats.shortestEdge = maxDiff;
first = 0;
}
// Now find the max and min values
stats.max.x = qMax(stats.max.x, facet.vector[0].x);
stats.min.x = qMin(stats.min.x, facet.vector[0].x);
stats.max.y = qMax(stats.max.y, facet.vector[0].y);
stats.min.y = qMin(stats.min.y, facet.vector[0].y);
stats.max.z = qMax(stats.max.z, facet.vector[0].z);
stats.min.z = qMin(stats.min.z, facet.vector[0].z);
stats.max.x = qMax(stats.max.x, facet.vector[1].x);
stats.min.x = qMin(stats.min.x, facet.vector[1].x);
stats.max.y = qMax(stats.max.y, facet.vector[1].y);
stats.min.y = qMin(stats.min.y, facet.vector[1].y);
stats.max.z = qMax(stats.max.z, facet.vector[1].z);
stats.min.z = qMin(stats.min.z, facet.vector[1].z);
stats.max.x = qMax(stats.max.x, facet.vector[2].x);
stats.min.x = qMin(stats.min.x, facet.vector[2].x);
stats.max.y = qMax(stats.max.y, facet.vector[2].y);
stats.min.y = qMin(stats.min.y, facet.vector[2].y);
stats.max.z = qMax(stats.max.z, facet.vector[2].z);
stats.min.z = qMin(stats.min.z, facet.vector[2].z);
}
stats.size.x = stats.max.x - stats.min.x;
stats.size.y = stats.max.y - stats.min.y;
stats.size.z = stats.max.z - stats.min.z;
stats.boundingDiameter = sqrt(stats.size.x * stats.size.x +
stats.size.y * stats.size.y +
stats.size.z * stats.size.z);
stats.numPoints = getNumPoints();
stats.surface = getSurface();
stats.volume = getVolume();
}
int StlFile::readIntFromBytes(::std::ifstream& file) {
int value;
value = file.get() & 0xFF;
value |= (file.get() & 0xFF) << 0x08;
value |= (file.get() & 0xFF) << 0x10;
value |= (file.get() & 0xFF) << 0x18;
return(value);
}
float StlFile::readFloatFromBytes(::std::ifstream& file) {
union {
int intValue;
float floatValue;
} value;
value.intValue = file.get() & 0xFF;
value.intValue |= (file.get() & 0xFF) << 0x08;
value.intValue |= (file.get() & 0xFF) << 0x10;
value.intValue |= (file.get() & 0xFF) << 0x18;
return(value.floatValue);
}
void StlFile::writeBytesFromInt(::std::ofstream& file, int valueIn) {
union {
int intValue;
char charValue[4];
} value;
value.intValue = valueIn;
int newValue = value.charValue[0] & 0xFF;
newValue |= (value.charValue[1] & 0xFF) << 0x08;
newValue |= (value.charValue[2] & 0xFF) << 0x10;
newValue |= (value.charValue[3] & 0xFF) << 0x18;
file.write(reinterpret_cast<char *>(&newValue), sizeof(newValue));
}
void StlFile::writeBytesFromFloat(::std::ofstream& file, float valueIn) {
union {
float floatValue;
char charValue[4];
} value;
value.floatValue = valueIn;
int newValue = value.charValue[0] & 0xFF;
newValue |= (value.charValue[1] & 0xFF) << 0x08;
newValue |= (value.charValue[2] & 0xFF) << 0x10;
newValue |= (value.charValue[3] & 0xFF) << 0x18;
file.write(reinterpret_cast<char *>(&newValue), sizeof(newValue));
}
void StlFile::writeBinary(const ::std::string& fileName) {
// Open the file
::std::ofstream file(fileName.c_str(), ::std::ios::out|::std::ios::binary);
if (file.is_open()) {
for (int i = 0; i < JUNK_SIZE; i++) file.put(0);
writeBytesFromInt(file, stats.numFacets);
for (int i = 0; i < stats.numFacets; i++) {
writeBytesFromFloat(file, facets[i].normal.x);
writeBytesFromFloat(file, facets[i].normal.y);
writeBytesFromFloat(file, facets[i].normal.z);
writeBytesFromFloat(file, facets[i].vector[0].x);
writeBytesFromFloat(file, facets[i].vector[0].y);
writeBytesFromFloat(file, facets[i].vector[0].z);
writeBytesFromFloat(file, facets[i].vector[1].x);
writeBytesFromFloat(file, facets[i].vector[1].y);
writeBytesFromFloat(file, facets[i].vector[1].z);
writeBytesFromFloat(file, facets[i].vector[2].x);
writeBytesFromFloat(file, facets[i].vector[2].y);
writeBytesFromFloat(file, facets[i].vector[2].z);
file << facets[i].extra[0];
file << facets[i].extra[1];
}
file.close();
} else {
::std::cerr << "The file " << file << " could not be found." << ::std::endl;
throw error_opening_file();
}
}
void StlFile::writeAscii(const ::std::string& fileName) {
// Open the file
::std::ofstream file(fileName.c_str(), ::std::ios::out);
file.setf(::std::ios::scientific);
file.precision(8);
if (file.is_open()) {
file << "solid" << ::std::endl;
for (int i = 0; i < stats.numFacets; i++) {
file << " facet normal " << facets[i].normal.x << " "
<< facets[i].normal.y << " " << facets[i].normal.z << ::std::endl;
file << " outer loop " << ::std::endl;
file << " Vector " << facets[i].vector[0].x << " "
<< facets[i].vector[0].y << " " << facets[i].vector[0].z
<< ::std::endl;
file << " Vector " << facets[i].vector[1].x << " "
<< facets[i].vector[1].y << " " << facets[i].vector[1].z
<< ::std::endl;
file << " Vector " << facets[i].vector[2].x << " "
<< facets[i].vector[2].y << " " << facets[i].vector[2].z
<< ::std::endl;
file << " endloop" << ::std::endl;
file << " endfacet" << ::std::endl;
}
file << "endsolid" << ::std::endl;
file.close();
} else {
::std::cerr << "The file " << file << " could not be found." << ::std::endl;
throw error_opening_file();
}
/*FILE *fp = fopen(fileName.c_str(), "w");
fprintf(fp, "solid\n");
for (int i = 0; i < stats.numFacets; i++) {
fprintf(fp, " facet normal % 0.8f % 0.8f % 0.8f\n",
facets[i].normal.x, facets[i].normal.y,
facets[i].normal.z);
fprintf(fp, " outer loop\n");
fprintf(fp, " vertex % 0.8f % 0.8f % 0.8f\n",
facets[i].vector[0].x, facets[i].vector[0].y,
facets[i].vector[0].z);
fprintf(fp, " vertex % 0.8f % 0.8f % 0.8f\n",
facets[i].vector[1].x, facets[i].vector[1].y,
facets[i].vector[1].z);
fprintf(fp, " vertex % 0.8f % 0.8f % 0.8f\n",
facets[i].vector[2].x, facets[i].vector[2].y,
facets[i].vector[2].z);
fprintf(fp, " endloop\n");
fprintf(fp, " endfacet\n");
}
fprintf(fp, "endsolid\n");
fclose(fp);*/
}
static bool compareVectors(Vector i, Vector j)
{
Vector diff;
diff = i - j;
return (diff.Magnitude() < 0);
}
static bool equalVectors(Vector i, Vector j)
{
Vector diff;
diff = i - j;
return (diff.Magnitude() == 0);
}
int StlFile::getNumPoints() {
::std::vector<Vector> vectors;
for (int i = 0; i < stats.numFacets; i++) {
for (int j = 0; j < 3; j++) {
vectors.push_back(facets[i].vector[j]);
}
}
::std::sort(vectors.begin(), vectors.end(), compareVectors);
::std::unique(vectors.begin(), vectors.end(), equalVectors);
return vectors.size();
}
float StlFile::getVolume() {
Vector p0;
Vector p;
float volume = 0.0;
// Choose a point, any point as the reference
p0.x = facets[0].vector[0].x;
p0.y = facets[0].vector[0].y;
p0.z = facets[0].vector[0].z;
for (int i = 0; i < stats.numFacets; i++) {
p.x = facets[i].vector[0].x - p0.x;
p.y = facets[i].vector[0].y - p0.y;
p.z = facets[i].vector[0].z - p0.z;
// Do dot product to get distance from point to plane
Normal n = facets[i].normal;
float height = (n.x * p.x) + (n.y * p.y) + (n.z * p.z);
float area = getArea(&facets[i]);
volume += (area * height) / 3.0;
}
if (volume < 0.0) {
volume = -volume;
}
return volume;
}
float StlFile::getSurface() {
float surface = 0.0;
for (int i = 0; i < stats.numFacets; i++) {
float area = getArea(&facets[i]);
surface += area;
}
if (surface < 0.0) {
surface = -surface;
}
return surface;
}
float StlFile::getArea(Facet *facet) {
float cross[3][3];
float sum[3];
float n[3];
for (int i = 0; i < 3; i++) {
cross[i][0] = ((facet->vector[i].y * facet->vector[(i + 1) % 3].z) -
(facet->vector[i].z * facet->vector[(i + 1) % 3].y));
cross[i][1] = ((facet->vector[i].z * facet->vector[(i + 1) % 3].x) -
(facet->vector[i].x * facet->vector[(i + 1) % 3].z));
cross[i][2] = ((facet->vector[i].x * facet->vector[(i + 1) % 3].y) -
(facet->vector[i].y * facet->vector[(i + 1) % 3].x));
}
sum[0] = cross[0][0] + cross[1][0] + cross[2][0];
sum[1] = cross[0][1] + cross[1][1] + cross[2][1];
sum[2] = cross[0][2] + cross[1][2] + cross[2][2];
// This should already be done. But just in case, let's do it again
calculateNormal(n, facet);
normalizeVector(n);
float area = 0.5 * (n[0] * sum[0] + n[1] * sum[1] + n[2] * sum[2]);
return area;
}
void StlFile::calculateNormal(float normal[], Facet *facet) {
float v1[3];
float v2[3];
v1[0] = facet->vector[1].x - facet->vector[0].x;
v1[1] = facet->vector[1].y - facet->vector[0].y;
v1[2] = facet->vector[1].z - facet->vector[0].z;
v2[0] = facet->vector[2].x - facet->vector[0].x;
v2[1] = facet->vector[2].y - facet->vector[0].y;
v2[2] = facet->vector[2].z - facet->vector[0].z;
normal[0] = (float)((double)v1[1] * (double)v2[2])
- ((double)v1[2] * (double)v2[1]);
normal[1] = (float)((double)v1[2] * (double)v2[0])
- ((double)v1[0] * (double)v2[2]);
normal[2] = (float)((double)v1[0] * (double)v2[1])
- ((double)v1[1] * (double)v2[0]);
}
void StlFile::normalizeVector(float v[]) {
double length = sqrt((double)v[0] * (double)v[0]
+ (double)v[1] * (double)v[1]
+ (double)v[2] * (double)v[2]);
float minNormalLength = 0.000000000001;
if (length < minNormalLength) {
v[0] = 1.0;
v[1] = 0.0;
v[2] = 0.0;
return;
}
double factor = 1.0 / length;
v[0] *= factor;
v[1] *= factor;
v[2] *= factor;
} | [
"cravesoft@939d4a90-b6fe-4fe1-83ef-7ae222a9c67a"
] | [
[
[
1,
494
]
]
] |
49634144eb7f721402811f2ac223d0f9964ca4fb | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/GpsSocket.h | 7cc95fb82cee99d4958a11c9b9f666a9b17f056d | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,970 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __GPSSOCKET_H__
#define __GPSSOCKET_H__
#include <in_sock.h>
#include "TimeOutNotify.h"
#include "Nav2.h"
class CTimeOutTimer;
/**
* CGpsSocket
* This class is the main engine part of the sockets application.
* It establishes a TCP connection using its server name and port number (performing a DNS lookup
* operation first, if appropriate).
* It creates instances of separate active objects to perform reading from, and writing to, the socket.
*/
class CGpsSocket : public CActive,
public MTimeOutNotify
{
public: // Constructors & Destructor
static class CGpsSocket* CGpsSocket::NewL(isab::Nav2::Channel* aNav2Channel,
const TDesC& aHost);
/**
* NewL
* Create a CGpsSocket object
* @param aConsole console to use for ui output
* @return a pointer to the created instance of CGpsSocket
*/
static CGpsSocket* NewL( isab::Nav2::Channel* aNav2Channel );
/**
* NewLC
* Create a CGpsSocket object
* @param aConsole console to use for ui output
* @return a pointer to the created instance of CGpsSocket
*/
static CGpsSocket* NewLC( isab::Nav2::Channel* aNav2Channel );
/**
* ~CGpsSocket
* Destroy the object and release all memory objects
*/
~CGpsSocket();
public: // new methods
/**
* Initiate connection of socket, using iServerName and iPort
*/
void ConnectL();
/**
* Disconnect socket
*/
void Disconnect();
/**
* Return true if we're in state connected.
*/
TBool IsConnected();
public: // from MTimeOutNotify
/**
* TimerExpired
* The function to be called when a timeout occurs
*/
void TimerExpired();
protected: // from CActive
/**
* DoCancel
* cancel any outstanding operation
*/
void DoCancel();
/**
* RunL
* called when operation complete
*/
void RunL();
private: // New methods
/**
* Perform the first phase of two phase construction
* @param aConsole the console to use for ui output
*/
CGpsSocket( isab::Nav2::Channel* aNav2Channel );
/**
* Perform the second phase construction of a CGpsSocket
*/
void ConstructL();
void ConstructL(const TDesC& aHost);
void SetServerName(const TDesC& aName);
/**
* Write data to socket
*/
void SendData();
/**
* Initiate read of data from socket
*/
void ReadData();
enum TSocketState
{
ENotConnected,
EConnecting,
EConnected,
EDisconnecting
};
private: // Member variables
/// This object's current status
TSocketState iState;
/// Console for displaying text etc
CWayFinderAppUi* iWfAppUi;
/// The actual socket only used for read.
RSocket iSocket;
/// The socket server
RSocketServ iSocketServ;
/// Timer active object
CTimeOutTimer* iTimer;
TInt iCounter;
TInetAddr iAddress;
/// Port number to connect to
TInt iPort;
/// Server name to connect to
TBuf<64> iServerName;
/// Buffer for reciving the data
TBuf8<64> iBuf;
isab::Nav2::Channel* iNav2Channel;
};
#endif // __GPSSOCKET_H__
| [
"[email protected]"
] | [
[
[
1,
167
]
]
] |
de6bdfbc65ac80257dcdd21a1d8ae4aa40ba9c86 | 070c58893ddb68626557793241b4c9c960737d86 | /dEspresso/dEspresso/WidgetList.h | 5bce04cb2b23fb079274692e62a6bd7bda3b6907 | [] | no_license | jongha/despresso | f84f328f77b0a338b31e8cf8debcda07ef49154d | 8986bbd6e710ee68fa341218c02f9b2aa7d1866d | refs/heads/master | 2020-05-18T07:16:32.144386 | 2010-09-28T05:14:56 | 2010-09-28T05:14:56 | 32,111,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | h | #pragma once
// CWidgetList dialog
class CWidgetList : public CDialog
{
DECLARE_DYNAMIC(CWidgetList)
public:
CWidgetList(CWnd* pParent = NULL); // standard constructor
virtual ~CWidgetList();
// Dialog Data
enum { IDD = IDD_WIDGETLIST };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedClock();
afx_msg void OnBnClickedCalendar();
afx_msg void OnBnClickedAddressbook();
afx_msg void OnBnClickedScrap();
afx_msg void OnBnClickedPicture();
afx_msg LRESULT LaunchWidget(WPARAM, LPARAM);
private:
CString m_strCurrentPath;
void MakeBasePath();
};
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
6262f22c975f23b19a05dbd1987de18bc4ffacd0 | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/fusion/view/single_view/single_view_iterator.hpp | b5cb3304cc99a28d3b860fc98a5719a0c691d506 | [
"BSL-1.0"
] | permissive | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 1,648 | hpp | /*=============================================================================
Copyright (c) 2001-2006 Joel de Guzman
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)
==============================================================================*/
#if !defined(FUSION_SINGLE_VIEW_ITERATOR_05052005_0340)
#define FUSION_SINGLE_VIEW_ITERATOR_05052005_0340
#include <boost/fusion/support/detail/access.hpp>
#include <boost/fusion/support/iterator_base.hpp>
#include <boost/fusion/view/single_view/detail/deref_impl.hpp>
#include <boost/fusion/view/single_view/detail/next_impl.hpp>
#include <boost/fusion/view/single_view/detail/value_of_impl.hpp>
namespace boost { namespace fusion
{
struct single_view_iterator_tag;
struct forward_traversal_tag;
template <typename SingleView>
struct single_view_iterator_end
: iterator_base<single_view_iterator_end<SingleView> >
{
typedef single_view_iterator_tag fusion_tag;
typedef forward_traversal_tag category;
};
template <typename SingleView>
struct single_view_iterator
: iterator_base<single_view_iterator<SingleView> >
{
typedef single_view_iterator_tag fusion_tag;
typedef forward_traversal_tag category;
typedef typename SingleView::value_type value_type;
typedef SingleView single_view_type;
explicit single_view_iterator(single_view_type const& view)
: val(view.val) {}
value_type val;
};
}}
#endif
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] | [
[
[
1,
47
]
]
] |
fc5fdd8b4e903c9ef87d47006d77ba54f029f6c4 | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/game/cinematic/file_cinematic.cc | a36b6579cb1781ebc422f437ebfd81d065aaaeb2 | [] | no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cc | #include "file_cinematic.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
FileCinematic::FileCinematic()
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
FileCinematic::~FileCinematic()
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void FileCinematic::Update()
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void FileCinematic::Start(const std::string& parArg)
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void FileCinematic::Finish()
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
] | [
[
[
1,
39
]
]
] |
d61d8ad02342c7bc6a4d6bff7bccd1129caeffd6 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/cube/dialog/PreferencesCategoriesModel.cpp | ba0119cce5ff98764d7297de2b5051469c3d6db5 | [
"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 | 4,044 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2008, mC2 Team
//
// Sources and Binaries of: mC2
//
// 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"
#include <win32cpp/ApplicationThread.hpp>
#include <cube/dialog/PreferencesCategoriesModel.hpp>
//////////////////////////////////////////////////////////////////////////////
using namespace musik::cube::dialog;
//////////////////////////////////////////////////////////////////////////////
PreferencesCategoriesModel::PreferencesCategoriesModel()
{
// Fill category tree with data
PreferencesCategory items[] = {
/* title level identifier (for inserts etc.) */
{_(_T("Libraries")), 0, Categories::Libraries},
{_(_T("Client/Server")), 0, Categories::ClientServer},
{_(_T("Audio Settings")), 0, Categories::AudioSettings},
{_(_T("Output")), 1, Categories::AudioSettings_Output},
{_(_T("Display")), 0, Categories::Display},
{_(_T("Ordering")), 1, Categories::Display_Ordering},
{_(_T("Tray settings")), 1, Categories::Display_TraySettings},
{_(_T("Show tray icon")), 2, Categories::Display_TraySettings_ShowTrayIcon},
{_(_T("Minimize to tray")), 2, Categories::Display_TraySettings_MinimizeToTray}
};
for(int i = 0; i < sizeof(items) / sizeof(PreferencesCategory); i++) {
categoryTree.push_back(items[i]);
}
}
int PreferencesCategoriesModel::ItemCount()
{
return (int)categoryTree.size();
}
int PreferencesCategoriesModel::ItemToIndent(int index)
{
if(index >= 0 && index < categoryTree.size()) {
return categoryTree[index].indent;
}
return 0;
}
uistring PreferencesCategoriesModel::ItemToString(int index)
{
if(index >= 0 && index < categoryTree.size()) {
return categoryTree[index].title;
}
return uistring();
}
LPARAM PreferencesCategoriesModel::ItemToExtendedData(int index)
{
if(index >= 0 && index < categoryTree.size()) {
return categoryTree[index].data;
}
return 0;
} | [
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
101
]
]
] |
302d7b410f218b22a00fd44ee2a57cf5be1b59d3 | 51e4aeb0d5e29ae1e8a9d8cf467797da2054b0f1 | /src/gameMenu.hpp | f0f98055c141f09528de120e6d3dacd8e2d5be2f | [] | no_license | vashero/tachyon-game | b3340272ee58c11077eef077485f8a01e4c81881 | 5fc2daac314c0b3b19b7336f8eb29d81a5e05729 | refs/heads/master | 2016-09-09T23:47:14.315285 | 2009-05-10T17:47:53 | 2009-05-10T17:47:53 | 32,647,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,149 | hpp | /*==============================================================
* Copyright (c) 2009 Blake Fisher. All Rights Reserved.
*
* This software is released under the BSD License
* <http://www.opensource.org/licenses/bsd-license.php>
*==============================================================
*/
#pragma once
#include "inputRouter.hpp"
#include "CEGUISystem.h"
#include "CEGUIWindow.h"
#include "Ogre.h"
using namespace Ogre;
#include <stack>
using namespace std;
/** States that the menu can be in */
typedef enum {
MAIN_MENU_ROOT, /**< The top of the main menu */
MAIN_MENU_OPTIONS, /**< The top-level options menu */
MAIN_MENU_OPTIONS_MORE,
MAIN_MENU_MODEL
} GameMenuState;
/** Filenames of the sheet corresponding to each state */
const String GAME_MENU_LAYOUT_FILENAMES[] = {
"gui_root.layout", "gui_options.layout", "gui_options_more.layout", "gui_model.layout"
};
const String GAME_MENU_ROOT_NAME = "rootWindow";
/**
The base class for each menu. Handles initializing the gui
for the relevant scene, and allows creation of various preset
windows
*/
class GameMenu: public InputListener
{
public:
GameMenu(RenderWindow *win, SceneManager *sceneMgr);
~GameMenu();
/** Push a menu state onto the top of the
state stack, and switch to that state
@param state The state to switch to
@return The window created from pushing the new menu state
*/
CEGUI::Window *push_state(GameMenuState state);
/** Remove the currently active state and
activate the state above it
*/
CEGUI::Window *pop_state();
/** Get the top-level window */
CEGUI::Window *get_root();
/** Get the prefix of the current state */
String get_prefix_name();
// Static functions -----------------
/** Get the prefix associated with the passed state
@param state The relevant state
*/
static String get_prefix_name(GameMenuState state);
// Listener functions
virtual bool mouseMoved(const OIS::MouseEvent &arg);
virtual bool mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
virtual bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
virtual bool keyPressed(const OIS::KeyEvent &arg);
virtual bool keyReleased(const OIS::KeyEvent &arg);
protected:
// Variables --------------------
SceneManager *mSceneMgr;
RenderWindow *mWin;
stack<GameMenuState> mStateStack;
CEGUI::System *mSystem;
String mResourceGroup;
String mSchemeFilename;
String mSchemeName;
String mMouseName;
String mFontFilename;
String mFontName;
String mRootLayoutFilename;
// Methods --------------------
/** Set the provided menu state
@param state The state to switch to
@return The window created from setting the new state
*/
CEGUI::Window *set_state(GameMenuState state);
/** Unset the provided menu state
@param state The state to unset
@param visible If this is false, the relevant menu is made invisible
*/
void unset_state(GameMenuState state, bool visible);
/** Initialize CEGUI resources */
bool initialize_gui();
};
| [
"[email protected]@b90cb52e-2f47-11de-8816-6191455234fe"
] | [
[
[
1,
110
]
]
] |
dc8b340792a10d57e883aae9c40980ac0bf4bb27 | 3ef49f2a62aaef8fd370468c68904e95ee5466aa | /glVector2.cpp | 2173674e313d6182d676c62e3e28d25f67814b3b | [] | no_license | xf0e/pixelcity | 6f42f6204b52882da391467c21d92fa2c6f01e1a | 959796a68a0727d73e327cc8de5471daacecd0b7 | refs/heads/master | 2020-03-08T23:19:34.771087 | 2009-05-23T23:17:44 | 2009-05-23T23:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,629 | cpp | /*-----------------------------------------------------------------------------
Vector2.cpp
2006 Shamus Young
-------------------------------------------------------------------------------
Functions for dealing with 2d (usually texture mapping) values.
-----------------------------------------------------------------------------*/
#ifdef WINDOWS
#include <windows.h>
#endif
#include <float.h>
#include <math.h>
#include <GL/gl.h>
#include "glTypes.h"
#include "Math.h"
#include "Macro.h"
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVectorNormalize (GLvector2 v)
{
float length;
length = glVectorLength (v);
if (length < 0.000001f)
return v;
return v * (1.0f / length);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
float glVectorLength (GLvector2 v)
{
return (float)sqrt (v.x * v.x + v.y * v.y);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVectorSinCos (float a)
{
GLvector2 val;
a *= DEGREES_TO_RADIANS;
val.x = sinf (a);
val.y = cosf (a);
return val;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVector (float x, float y)
{
GLvector2 val;
val.x = x;
val.y = y;
return val;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVectorAdd (GLvector2 val1, GLvector2 val2)
{
GLvector2 result;
result.x = val1.x + val2.x;
result.y = val1.y + val2.y;
return result;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVectorInterpolate (GLvector2 v1, GLvector2 v2, float scalar)
{
GLvector2 result;
result.x = MathInterpolate (v1.x, v2.x, scalar);
result.y = MathInterpolate (v1.y, v2.y, scalar);
return result;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
GLvector2 glVectorSubtract (GLvector2 val1, GLvector2 val2)
{
GLvector2 result;
result.x = val1.x - val2.x;
result.y = val1.y - val2.y;
return result;
}
/*-----------------------------------------------------------------------------
+
-----------------------------------------------------------------------------*/
GLvector2 GLvector2::operator+ (const GLvector2& c)
{
return glVector (x + c.x, y + c.y);
}
GLvector2 GLvector2::operator+ (const float& c)
{
return glVector (x + c, y + c);
}
void GLvector2::operator+= (const GLvector2& c)
{
x += c.x;
y += c.y;
}
void GLvector2::operator+= (const float& c)
{
x += c;
y += c;
}
GLvector2 GLvector2::operator- (const GLvector2& c)
{
return glVector (x - c.x, y - c.y);
}
GLvector2 GLvector2::operator- (const float& c)
{
return glVector (x - c, y - c);
}
void GLvector2::operator-= (const GLvector2& c)
{
x -= c.x;
y -= c.y;
}
void GLvector2::operator-= (const float& c)
{
x -= c;
y -= c;
}
GLvector2 GLvector2::operator* (const GLvector2& c)
{
return glVector (x * c.x, y * c.y);
}
GLvector2 GLvector2::operator* (const float& c)
{
return glVector (x * c, y * c);
}
void GLvector2::operator*= (const GLvector2& c)
{
x *= c.x;
y *= c.y;
}
void GLvector2::operator*= (const float& c)
{
x *= c;
y *= c;
}
GLvector2 GLvector2::operator/ (const GLvector2& c)
{
return glVector (x / c.x, y / c.y);
}
GLvector2 GLvector2::operator/ (const float& c)
{
return glVector (x / c, y / c);
}
void GLvector2::operator/= (const GLvector2& c)
{
x /= c.x;
y /= c.y;
}
void GLvector2::operator/= (const float& c)
{
x /= c;
y /= c;
}
bool GLvector2::operator== (const GLvector2& c)
{
if (x == c.x && y == c.y)
return true;
return false;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
14,
14
],
[
17,
18
],
[
20,
21
],
[
24,
225
]
],
[
[
13,
13
],
[
15,
16
],
[
19,
19
],
[
22,
23
],
[
226,
226
]
]
] |
bde053b06cd807895226ea7671337786b10cdf9c | 13314d3b1af22579685991a2cd7bfb68e67ba80e | /adware/ie/updater/Source Code/UpdaterSvc/FileDownloadManager.h | 10663bd5d9b353ba4fd48083167232f18126d659 | [] | no_license | MZ-EUR/h4zy | f38c8e38d7e0c9770c42f429ff4f091604481826 | 2bcc791a0491f92cec03d538c5f7c01e76b1bb23 | refs/heads/master | 2021-01-12T00:03:03.815891 | 2011-05-26T01:21:54 | 2011-05-26T01:21:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | h | // FileDownloadManager.h: interface for the CFileDownloadManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FILEDOWNLOADMANAGER_H__92A0629C_02C7_4777_9BBE_A045162FDF4D__INCLUDED_)
#define AFX_FILEDOWNLOADMANAGER_H__92A0629C_02C7_4777_9BBE_A045162FDF4D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CFileDownloadManager
{
_bstr_t m_sURL;
_bstr_t m_sLocalFilePath;
_bstr_t m_sErrorDescription;
void UpdateLocalFilePath();
BOOL IsFileDownloadedOK(_bstr_t cr_sFilePath);
public:
void GetLastError(_bstr_t& cr_sError);
BOOL DoDownload();
void GetDownloadedFilePath(_bstr_t& cr_sFilePath);
void SetURLToDownload(_bstr_t cr_sURL);
CFileDownloadManager();
virtual ~CFileDownloadManager();
};
#endif // !defined(AFX_FILEDOWNLOADMANAGER_H__92A0629C_02C7_4777_9BBE_A045162FDF4D__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
89dfb3db4fa460331d27c7e931c7841d336cd325 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osg/LightModel | cec4745695394193765a2a19160cfe253613c48b | [] | 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 | 3,023 | /* -*-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_LIGHTMODEL
#define OSG_LIGHTMODEL 1
#include <osg/StateAttribute>
#include <osg/Vec4>
namespace osg {
class OSG_EXPORT LightModel : public StateAttribute
{
public :
LightModel();
/** Copy constructor using CopyOp to manage deep vs shallow copy. */
LightModel(const LightModel& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
StateAttribute(lw,copyop),
_ambient(lw._ambient),
_colorControl(lw._colorControl),
_localViewer(lw._localViewer),
_twoSided(lw._twoSided) {}
META_StateAttribute(osg, LightModel, LIGHTMODEL);
/** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
virtual int compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Paramter macro's below.
COMPARE_StateAttribute_Types(LightModel,sa)
// compare each parameter in turn against the rhs.
COMPARE_StateAttribute_Parameter(_ambient)
COMPARE_StateAttribute_Parameter(_colorControl)
COMPARE_StateAttribute_Parameter(_localViewer)
COMPARE_StateAttribute_Parameter(_twoSided)
return 0; // passed all the above comparison macros, must be equal.
}
void setAmbientIntensity(const osg::Vec4& ambient) { _ambient = ambient; }
const osg::Vec4& getAmbientIntensity() const { return _ambient; }
enum ColorControl
{
SEPARATE_SPECULAR_COLOR,
SINGLE_COLOR
};
void setColorControl(ColorControl cc) { _colorControl = cc; }
inline ColorControl getColorControl() const { return _colorControl; }
void setLocalViewer(bool localViewer) { _localViewer=localViewer; }
inline bool getLocalViewer() const { return _localViewer; }
void setTwoSided(bool twoSided) { _twoSided = twoSided; }
inline bool getTwoSided() const { return _twoSided; }
virtual void apply(State& state) const;
protected :
virtual ~LightModel();
osg::Vec4 _ambient;
ColorControl _colorControl;
bool _localViewer;
bool _twoSided;
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
95
]
]
] |
|
c138b348916c64d7bd02a4a7caff867f85d5fe1f | ef25bd96604141839b178a2db2c008c7da20c535 | /src/src/Test/Obj3d/GameCamera.cpp | 3b27614e2f37907d6b731121112fd9c87d080fff | [] | no_license | OtterOrder/crock-rising | fddd471971477c397e783dc6dd1a81efb5dc852c | 543dc542bb313e1f5e34866bd58985775acf375a | refs/heads/master | 2020-12-24T14:57:06.743092 | 2009-07-15T17:15:24 | 2009-07-15T17:15:24 | 32,115,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,601 | cpp | #include "GameCamera.h"
#include "Core/Inputs/InputManager.h"
//******************************************************************
void GameCamera::Update()
{
/*InputManager *pIM = InputManager::GetInstance();
Point2f point = pIM->GetMouseOffset();
//OffsetCurseur -> Camera
const int sensibilite = 15;
int offsetCursor;
if( pIM->IsKeyPressed( 'Z' ) )
{
Vector3f pos = GetPosition();
Vector3f target = GetTarget();
Vector3f vectDir = target - pos;
float distance = sqrt( vectDir.x*vectDir.x + vectDir.y*vectDir.y + vectDir.z*vectDir.z );
float angleY = GetOrientationYRad();
//float s = sin( angleY );
float c = cos( angleY );
//pos.x = pos.x + s;
pos.z = pos.z + c/2;
if( distance>60.0f )
SetPosition( pos );
}
if( pIM->IsKeyPressed( 'S' ) )
{
Vector3f pos = GetPosition();
Vector3f target = GetTarget();
Vector3f vectDir = target - pos;
float distance = sqrt( vectDir.x*vectDir.x + vectDir.y*vectDir.y + vectDir.z*vectDir.z );
float angleY = GetOrientationYRad();
//float s = sin( angleY );
float c = cos( angleY );
//pos.x = pos.x + s;
pos.z = pos.z - c/2;
if( distance<300.0f )
SetPosition( pos );
}
if( pIM->IsKeyPressed( 'A' ) )
{
InitAngle();
SetPosition(Vector3f(0.0f, 10.0f, -100.0f));
}
if( point.x != 0 )
{
offsetCursor = (int)point.x%sensibilite;
SetOrientationY( -offsetCursor );
}
if( point.y != 0 )
{
offsetCursor = (int)point.y%sensibilite;
SetOrientationX( offsetCursor );
}
UpdateMatrixView();*/
}
| [
"mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b"
] | [
[
[
1,
71
]
]
] |
2a141d527b29766e5dcd7c17a5951b8886393c72 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/DSBaseClass/stdafx.cpp | 3ac18f1e1af573474db80e05349674fad06e68fd | [] | no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | cpp | // stdafx.cpp : source file that includes just the standard includes
// DSAppClasses.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | [
[
[
1,
8
]
]
] |
f0646931072f86b5393ec8c170e21268733c67c5 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/date_time/date_facet.hpp | 94523ae94014aa7c651025566a317e6b0c2b9384 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,510 | hpp | #ifndef _DATE_TIME_DATE_FACET__HPP___
#define _DATE_TIME_DATE_FACET__HPP___
/* Copyright (c) 2004-2005 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0)
* Author: Martin Andrian, Jeff Garland, Bart Garst
* $Date: 2005/09/05 21:10:50 $
*/
#include "boost/algorithm/string/replace.hpp"
#include "boost/date_time/period.hpp"
#include "boost/date_time/special_values_formatter.hpp"
#include "boost/date_time/period_formatter.hpp"
#include "boost/date_time/period_parser.hpp"
#include "boost/date_time/date_generator_formatter.hpp"
#include "boost/date_time/date_generator_parser.hpp"
#include "boost/date_time/format_date_parser.hpp"
#include <string>
#include <vector>
namespace boost { namespace date_time {
/*! Class that provides format based I/O facet for date types.
*
* This class allows the formatting of dates by using format string.
* Format strings are:
*
* - %A => long_weekday_format - Full name Ex: Tuesday
* - %a => short_weekday_format - Three letter abbreviation Ex: Tue
* - %B => long_month_format - Full name Ex: October
* - %b => short_month_format - Three letter abbreviation Ex: Oct
* - %x => standard_format_specifier - defined by the locale
* - %Y-%b-%d => default_date_format - YYYY-Mon-dd
*
* Default month format == %b
* Default weekday format == %a
*/
template <class date_type,
class CharT,
class OutItrT = std::ostreambuf_iterator<CharT, std::char_traits<CharT> > >
class date_facet : public std::locale::facet {
public:
typedef typename date_type::duration_type duration_type;
// greg_weekday is gregorian_calendar::day_of_week_type
typedef typename date_type::day_of_week_type day_of_week_type;
typedef typename date_type::day_type day_type;
typedef typename date_type::month_type month_type;
typedef boost::date_time::period<date_type,duration_type> period_type;
typedef std::basic_string<CharT> string_type;
typedef CharT char_type;
typedef boost::date_time::period_formatter<CharT> period_formatter_type;
typedef boost::date_time::special_values_formatter<CharT> special_values_formatter_type;
typedef std::vector<std::basic_string<CharT> > input_collection_type;
// used for the output of the date_generators
typedef date_generator_formatter<date_type, CharT> date_gen_formatter_type;
typedef partial_date<date_type> partial_date_type;
typedef nth_kday_of_month<date_type> nth_kday_type;
typedef first_kday_of_month<date_type> first_kday_type;
typedef last_kday_of_month<date_type> last_kday_type;
typedef first_kday_after<date_type> kday_after_type;
typedef first_kday_before<date_type> kday_before_type;
static const char_type long_weekday_format[3];
static const char_type short_weekday_format[3];
static const char_type long_month_format[3];
static const char_type short_month_format[3];
static const char_type default_period_separator[4];
static const char_type standard_format_specifier[3];
static const char_type iso_format_specifier[7];
static const char_type iso_format_extended_specifier[9];
static const char_type default_date_format[9]; // YYYY-Mon-DD
static std::locale::id id;
#if defined (__SUNPRO_CC) && defined (_RWSTD_VER)
std::locale::id& __get_id (void) const { return id; }
#endif
explicit date_facet(::size_t a_ref = 0)
: std::locale::facet(a_ref),
//m_format(standard_format_specifier)
m_format(default_date_format),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format)
{}
explicit date_facet(const char_type* format_str,
const input_collection_type& short_names,
::size_t ref_count = 0)
: std::locale::facet(ref_count),
m_format(format_str),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format),
m_month_short_names(short_names)
{}
explicit date_facet(const char_type* format_str,
period_formatter_type per_formatter = period_formatter_type(),
special_values_formatter_type sv_formatter = special_values_formatter_type(),
date_gen_formatter_type dg_formatter = date_gen_formatter_type(),
::size_t ref_count = 0)
: std::locale::facet(ref_count),
m_format(format_str),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format),
m_period_formatter(per_formatter),
m_date_gen_formatter(dg_formatter),
m_special_values_formatter(sv_formatter)
{}
void format(const char_type* const format_str) {
m_format = format_str;
}
virtual void set_iso_format()
{
m_format = iso_format_specifier;
}
virtual void set_iso_extended_format()
{
m_format = iso_format_extended_specifier;
}
void month_format(const char_type* const format_str) {
m_month_format = format_str;
}
void weekday_format(const char_type* const format_str) {
m_weekday_format = format_str;
}
void period_formatter(period_formatter_type per_formatter) {
m_period_formatter= per_formatter;
}
void special_values_formatter(const special_values_formatter_type& svf)
{
m_special_values_formatter = svf;
}
void short_weekday_names(const input_collection_type& short_names)
{
m_weekday_short_names = short_names;
}
void long_weekday_names(const input_collection_type& long_names)
{
m_weekday_long_names = long_names;
}
void short_month_names(const input_collection_type& short_names)
{
m_month_short_names = short_names;
}
void long_month_names(const input_collection_type& long_names)
{
m_month_long_names = long_names;
}
void date_gen_phrase_strings(const input_collection_type& new_strings,
typename date_gen_formatter_type::phrase_elements beg_pos=date_gen_formatter_type::first)
{
m_date_gen_formatter.elements(new_strings, beg_pos);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const date_type& d) const
{
if (d.is_special()) {
return do_put_special(next, a_ios, fill_char, d.as_special());
}
//The following line of code required the date to support a to_tm function
return do_put_tm(next, a_ios, fill_char, to_tm(d), m_format);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const duration_type& dd) const
{
if (dd.is_special()) {
return do_put_special(next, a_ios, fill_char, dd.get_rep().as_special());
}
typedef std::num_put<CharT, OutItrT> num_put;
if (std::has_facet<num_put>(a_ios.getloc())) {
return std::use_facet<num_put>(a_ios.getloc()).put(next, a_ios, fill_char, dd.get_rep().as_number());
}
else {
num_put* f = new num_put();
std::locale l = std::locale(a_ios.getloc(), f);
a_ios.imbue(l);
return f->put(next, a_ios, fill_char, dd.get_rep().as_number());
}
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const month_type& m) const
{
//if (d.is_special()) {
// return do_put_special(next, a_ios, fill_char, d.as_special());
//}
//The following line of code required the date to support a to_tm function
tm dtm;
init_tm(dtm);
dtm.tm_mon = m -1;
return do_put_tm(next, a_ios, fill_char, dtm, m_month_format);
}
//! puts the day of month
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const day_type& day) const
{
tm dtm;
init_tm(dtm);
dtm.tm_mday = day.as_number();
char_type tmp[3] = {'%','d'};
string_type temp_format(tmp);
return do_put_tm(next, a_ios, fill_char, dtm, temp_format);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const day_of_week_type& dow) const
{
//if (d.is_special()) {
// return do_put_special(next, a_ios, fill_char, d.as_special());
//}
//The following line of code required the date to support a to_tm function
tm dtm;
init_tm(dtm);
dtm.tm_wday = dow;
return do_put_tm(next, a_ios, fill_char, dtm, m_weekday_format);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const period_type& p) const
{
return m_period_formatter.put_period(next, a_ios, fill_char, p, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const partial_date_type& pd) const
{
return m_date_gen_formatter.put_partial_date(next, a_ios, fill_char, pd, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const nth_kday_type& nkd) const
{
return m_date_gen_formatter.put_nth_kday(next, a_ios, fill_char, nkd, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const first_kday_type& fkd) const
{
return m_date_gen_formatter.put_first_kday(next, a_ios, fill_char, fkd, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const last_kday_type& lkd) const
{
return m_date_gen_formatter.put_last_kday(next, a_ios, fill_char, lkd, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const kday_before_type& fkb) const
{
return m_date_gen_formatter.put_kday_before(next, a_ios, fill_char, fkb, *this);
}
OutItrT put(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const kday_after_type& fka) const
{
return m_date_gen_formatter.put_kday_after(next, a_ios, fill_char, fka, *this);
}
protected:
//! Helper function to initialize all fields in a tm struct
tm init_tm(tm& tm_value) const
{
tm_value.tm_sec = 0; /* seconds */
tm_value.tm_min = 0; /* minutes */
tm_value.tm_hour = 0; /* hours */
tm_value.tm_mday = 0; /* day of the month */
tm_value.tm_mon = 0; /* month */
tm_value.tm_year = 0; /* year */
tm_value.tm_wday = 0; /* day of the week */
tm_value.tm_yday = 0; /* day in the year */
tm_value.tm_isdst = 0; /* daylight saving time */
return tm_value;
}
virtual OutItrT do_put_special(OutItrT next,
std::ios_base& /*a_ios*/,
char_type /*fill_char*/,
const boost::date_time::special_values sv) const
{
m_special_values_formatter.put_special(next, sv);
return next;
}
virtual OutItrT do_put_tm(OutItrT next,
std::ios_base& a_ios,
char_type fill_char,
const tm& tm_value,
string_type a_format) const
{
// update format string with custom names
if (m_weekday_long_names.size()) {
boost::algorithm::replace_all(a_format,
long_weekday_format,
m_weekday_long_names[tm_value.tm_wday]);
}
if (m_weekday_short_names.size()) {
boost::algorithm::replace_all(a_format,
short_weekday_format,
m_weekday_short_names[tm_value.tm_wday]);
}
if (m_month_long_names.size()) {
boost::algorithm::replace_all(a_format,
long_month_format,
m_month_long_names[tm_value.tm_mon]);
}
if (m_month_short_names.size()) {
boost::algorithm::replace_all(a_format,
short_month_format,
m_month_short_names[tm_value.tm_mon]);
}
// use time_put facet to create final string
return std::use_facet<std::time_put<CharT> >(a_ios.getloc()).put(next, a_ios,
fill_char,
&tm_value,
&*a_format.begin(),
&*a_format.begin()+a_format.size());
}
protected:
string_type m_format;
string_type m_month_format;
string_type m_weekday_format;
period_formatter_type m_period_formatter;
date_gen_formatter_type m_date_gen_formatter;
special_values_formatter_type m_special_values_formatter;
input_collection_type m_month_short_names;
input_collection_type m_month_long_names;
input_collection_type m_weekday_short_names;
input_collection_type m_weekday_long_names;
private:
};
template <class date_type, class CharT, class OutItrT>
std::locale::id date_facet<date_type, CharT, OutItrT>::id;
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::long_weekday_format[3] = {'%','A'};
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::short_weekday_format[3] = {'%','a'};
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::long_month_format[3] = {'%','B'};
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::short_month_format[3] = {'%','b'};
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::default_period_separator[4] = { ' ', '/', ' '};
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::standard_format_specifier[3] =
{'%', 'x' };
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::iso_format_specifier[7] =
{'%', 'Y', '%', 'm', '%', 'd' };
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::iso_format_extended_specifier[9] =
{'%', 'Y', '-', '%', 'm', '-', '%', 'd' };
template <class date_type, class CharT, class OutItrT>
const typename date_facet<date_type, CharT, OutItrT>::char_type
date_facet<date_type, CharT, OutItrT>::default_date_format[9] =
{'%','Y','-','%','b','-','%','d'};
//! Input facet
template <class date_type,
class CharT,
class InItrT = std::istreambuf_iterator<CharT, std::char_traits<CharT> > >
class date_input_facet : public std::locale::facet {
public:
typedef typename date_type::duration_type duration_type;
// greg_weekday is gregorian_calendar::day_of_week_type
typedef typename date_type::day_of_week_type day_of_week_type;
typedef typename date_type::day_type day_type;
typedef typename date_type::month_type month_type;
typedef typename date_type::year_type year_type;
typedef boost::date_time::period<date_type,duration_type> period_type;
typedef std::basic_string<CharT> string_type;
typedef CharT char_type;
typedef boost::date_time::period_parser<date_type, CharT> period_parser_type;
typedef special_values_parser<date_type,CharT> special_values_parser_type;
typedef std::vector<std::basic_string<CharT> > input_collection_type;
typedef format_date_parser<date_type, CharT> format_date_parser_type;
// date_generators stuff goes here
typedef date_generator_parser<date_type, CharT> date_gen_parser_type;
typedef partial_date<date_type> partial_date_type;
typedef nth_kday_of_month<date_type> nth_kday_type;
typedef first_kday_of_month<date_type> first_kday_type;
typedef last_kday_of_month<date_type> last_kday_type;
typedef first_kday_after<date_type> kday_after_type;
typedef first_kday_before<date_type> kday_before_type;
static const char_type long_weekday_format[3];
static const char_type short_weekday_format[3];
static const char_type long_month_format[3];
static const char_type short_month_format[3];
static const char_type four_digit_year_format[3];
static const char_type two_digit_year_format[3];
static const char_type default_period_separator[4];
static const char_type standard_format_specifier[3];
static const char_type iso_format_specifier[7];
static const char_type iso_format_extended_specifier[9];
static const char_type default_date_format[9]; // YYYY-Mon-DD
static std::locale::id id;
explicit date_input_facet(::size_t a_ref = 0)
: std::locale::facet(a_ref),
m_format(default_date_format),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format),
m_year_format(four_digit_year_format),
m_parser(m_format, std::locale::classic())
// default period_parser & special_values_parser used
{}
explicit date_input_facet(const string_type& format_str,
::size_t a_ref = 0)
: std::locale::facet(a_ref),
m_format(format_str),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format),
m_year_format(four_digit_year_format),
m_parser(m_format, std::locale::classic())
// default period_parser & special_values_parser used
{}
explicit date_input_facet(const string_type& format_str,
const format_date_parser_type& date_parser,
const special_values_parser_type& sv_parser,
const period_parser_type& per_parser,
const date_gen_parser_type& date_gen_parser,
::size_t ref_count = 0)
: std::locale::facet(ref_count),
m_format(format_str),
m_month_format(short_month_format),
m_weekday_format(short_weekday_format),
m_year_format(four_digit_year_format),
m_parser(date_parser),
m_date_gen_parser(date_gen_parser),
m_period_parser(per_parser),
m_sv_parser(sv_parser)
{}
void format(const char_type* const format_str) {
m_format = format_str;
}
virtual void set_iso_format()
{
m_format = iso_format_specifier;
}
virtual void set_iso_extended_format()
{
m_format = iso_format_extended_specifier;
}
void month_format(const char_type* const format_str) {
m_month_format = format_str;
}
void weekday_format(const char_type* const format_str) {
m_weekday_format = format_str;
}
void year_format(const char_type* const format_str) {
m_year_format = format_str;
}
void period_parser(period_parser_type per_parser) {
m_period_parser = per_parser;
}
void short_weekday_names(const input_collection_type& weekday_names)
{
m_parser.short_weekday_names(weekday_names);
}
void long_weekday_names(const input_collection_type& weekday_names)
{
m_parser.long_weekday_names(weekday_names);
}
void short_month_names(const input_collection_type& month_names)
{
m_parser.short_month_names(month_names);
}
void long_month_names(const input_collection_type& month_names)
{
m_parser.long_month_names(month_names);
}
void date_gen_element_strings(const input_collection_type& col)
{
m_date_gen_parser.element_strings(col);
}
void date_gen_element_strings(const string_type& first,
const string_type& second,
const string_type& third,
const string_type& fourth,
const string_type& fifth,
const string_type& last,
const string_type& before,
const string_type& after,
const string_type& of)
{
m_date_gen_parser.element_strings(first,second,third,fourth,fifth,last,before,after,of);
}
void special_values_parser(special_values_parser_type sv_parser)
{
m_sv_parser = sv_parser;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& /*a_ios*/,
date_type& d) const
{
d = m_parser.parse_date(from, to, m_format, m_sv_parser);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& /*a_ios*/,
month_type& m) const
{
m = m_parser.parse_month(from, to, m_month_format);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& /*a_ios*/,
day_of_week_type& wd) const
{
wd = m_parser.parse_weekday(from, to, m_weekday_format);
return from;
}
//! Expects 1 or 2 digit day range: 1-31
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& /*a_ios*/,
day_type& d) const
{
d = m_parser.parse_var_day_of_month(from, to);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& /*a_ios*/,
year_type& y) const
{
y = m_parser.parse_year(from, to, m_year_format);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
duration_type& dd) const
{
// skip leading whitespace
while(std::isspace(*from) && from != to) { ++from; }
/* num_get.get() will always consume the first character if it
* is a sign indicator (+/-). Special value strings may begin
* with one of these signs so we'll need a copy of it
* in case num_get.get() fails. */
char_type c = '\0';
// TODO Are these characters somewhere in the locale?
if(*from == '-' || *from == '+') {
c = *from;
}
typedef std::num_get<CharT, InItrT> num_get;
typename duration_type::duration_rep_type val = 0;
std::ios_base::iostate err = std::ios_base::goodbit;
if (std::has_facet<num_get>(a_ios.getloc())) {
from = std::use_facet<num_get>(a_ios.getloc()).get(from, to, a_ios, err, val);
}
else {
num_get* ng = new num_get();
std::locale l = std::locale(a_ios.getloc(), ng);
a_ios.imbue(l);
from = ng->get(from, to, a_ios, err, val);
}
if(err & std::ios_base::failbit){
typedef typename special_values_parser_type::match_results match_results;
match_results mr;
if(c == '-' || c == '+') { // was the first character consumed?
mr.cache += c;
}
m_sv_parser.match(from, to, mr);
if(mr.current_match == match_results::PARSE_ERROR) {
throw std::ios_base::failure("Parse failed. No match found for '" + mr.cache + "'");
}
dd = duration_type(static_cast<special_values>(mr.current_match));
}
else {
dd = duration_type(val);
}
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
period_type& p) const
{
p = m_period_parser.get_period(from, to, a_ios, p, duration_type::unit(), *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
nth_kday_type& nkd) const
{
nkd = m_date_gen_parser.get_nth_kday_type(from, to, a_ios, *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
partial_date_type& pd) const
{
pd = m_date_gen_parser.get_partial_date_type(from, to, a_ios, *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
first_kday_type& fkd) const
{
fkd = m_date_gen_parser.get_first_kday_type(from, to, a_ios, *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
last_kday_type& lkd) const
{
lkd = m_date_gen_parser.get_last_kday_type(from, to, a_ios, *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
kday_before_type& fkb) const
{
fkb = m_date_gen_parser.get_kday_before_type(from, to, a_ios, *this);
return from;
}
InItrT get(InItrT& from,
InItrT& to,
std::ios_base& a_ios,
kday_after_type& fka) const
{
fka = m_date_gen_parser.get_kday_after_type(from, to, a_ios, *this);
return from;
}
protected:
string_type m_format;
string_type m_month_format;
string_type m_weekday_format;
string_type m_year_format;
format_date_parser_type m_parser;
date_gen_parser_type m_date_gen_parser;
period_parser_type m_period_parser;
special_values_parser_type m_sv_parser;
private:
};
template <class date_type, class CharT, class OutItrT>
std::locale::id date_input_facet<date_type, CharT, OutItrT>::id;
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::long_weekday_format[3] = {'%','A'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::short_weekday_format[3] = {'%','a'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::long_month_format[3] = {'%','B'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::short_month_format[3] = {'%','b'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::four_digit_year_format[3] = {'%','Y'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::two_digit_year_format[3] = {'%','y'};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::default_period_separator[4] = { ' ', '/', ' '};
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::standard_format_specifier[3] =
{'%', 'x' };
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::iso_format_specifier[7] =
{'%', 'Y', '%', 'm', '%', 'd' };
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::iso_format_extended_specifier[9] =
{'%', 'Y', '-', '%', 'm', '-', '%', 'd' };
template <class date_type, class CharT, class OutItrT>
const typename date_input_facet<date_type, CharT, OutItrT>::char_type
date_input_facet<date_type, CharT, OutItrT>::default_date_format[9] =
{'%','Y','-','%','b','-','%','d'};
} } // namespaces
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
775
]
]
] |
874873da8cd44a185c19c79e698e5341d8b8c491 | c86a845a7873e3f543b307c8c03ac92a724c8beb | /finalapp/vis.cpp | 2532b0097ce3176d2053881b59122220d4a3a49e | [] | no_license | smyang/remobj | 58e4c3305a27b1a33e9f96f986911a39c22178d8 | d9bce0847b98c598500e2d72ec02bc88c54d8e93 | refs/heads/master | 2016-09-10T13:58:42.452434 | 2010-05-01T21:36:26 | 2010-05-01T21:36:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,364 | cpp | // vis.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "vision_utilities.hpp"
#include "bundleout.hpp"
#include <math.h>
#include "../taucs/taucsaddon.h"
#include "matrix.h"
#include "vis.h"
void copy_image(ImageColor* imgsrc, ImageColor* imgdest)
{
int row = getNRowsColor(imgsrc);
int col = getNColsColor(imgsrc);
for (int i=0;i<row;i++) {
for (int j=0;j<col;j++) {
setPixelColor(imgdest, i, j, getPixelColor(imgsrc, i, j, 1), getPixelColor(imgsrc, i, j, 2), getPixelColor(imgsrc, i, j, 3));
}
}
}
double mult_f_and_r(double px, double py, double f, double k1, double k2, double val)
{
return f*(1.0f+k1*(px*px+py*py)+k2*(px*px+py*py)*(px*px+py*py))*val;
}
void image_point_to_scene_point(double x, double y, Position* point_3d, Camera* cam, Plane p)
{
if (x==0) x=1; // XXX: a big workaround to divide by zero
// TODO: handle divide by zero case
// p' = f * r(p) * p
double left = 0;
double right = x;
double px = x/2;
double py = y/2;
int counter =0;
/*if (x==0) {
left = 0;
right = y;
while (1) {
if (counter++ >= 100) { // quit and error if more than 100 iterations
fprintf(stderr, "image_point_to_Scene_point: error in iterative method\n");
return;
}
double estimate_y = mult_f_and_r(px, py, cam->f, cam->k1, cam->k2, py);
if (abs(y-estimate_y<0.0000001))
break;
if (abs(estimate_y) > abs(y)) {
right = py;
py = (left+right)/2;
}else {
left = py;
py = (left+right)/2;
}
}*/
//}else {
while (1) {
if (counter++ >= 100) { // quit and error if more than 100 iterations
fprintf(stderr, "image_point_to_Scene_point: error in iterative method\n");
return;
}
double estimate_x = mult_f_and_r(px, py, cam->f, cam->k1, cam->k2, px);
double estimate_y = mult_f_and_r(px, py, cam->f, cam->k1, cam->k2, py);
if (abs(x-estimate_x)<0.0000001) { // px, py are good enough
break;
}
if (abs(estimate_x) > abs(x)) {
right = px;
px = (left+right)/2;
py = px * y / x;
}else {
left = px;
px = (left+right)/2;
py = px * y / x;
}
}
//}
//printf("%lf %lf\n", px, py);
double pz = 1;
// p = -P / P.z
// P = R * X + t
// X = [ X Y Z ] is our target point in 3d (unknown)
// R is rotation matrix, t is translation vector
// p is [px py pz]'
// so R11*X+R12*Y+R13*Z+tx=Px
// R21*X+R22*Y+R23*Z+ty=Py
// R31*X+R32*Y+R33*Z+tz=Pz
// and px = -Px / Pz
// py = -Py / Pz
// plus plane constraint AX+BY+Z+D=0
// solve the linear equations
double rhs[3];
// equation1 : (R11+px*R31)x+(R12+px*R32)y+(R13+px*R33)z+(t1+px*t3)=0
// write to ijv file
FILE* fp = fopen("3d_recover.ijv", "w");
fprintf(fp, "1 1 %lf\n", cam->rotation[0][0]+px*cam->rotation[2][0]);
fprintf(fp, "1 2 %lf\n", cam->rotation[0][1]+px*cam->rotation[2][1]);
fprintf(fp, "1 3 %lf\n", cam->rotation[0][2]+px*cam->rotation[2][2]);
rhs[0] = -cam->translation[0]-px*cam->translation[2];
fprintf(fp, "2 1 %lf\n", cam->rotation[1][0]+py*cam->rotation[2][0]);
fprintf(fp, "2 2 %lf\n", cam->rotation[1][1]+py*cam->rotation[2][1]);
fprintf(fp, "2 3 %lf\n", cam->rotation[1][2]+py*cam->rotation[2][2]);
rhs[1] = -cam->translation[1]-py*cam->translation[2];
fprintf(fp, "3 1 %lf\n", p.a);
fprintf(fp, "3 2 %lf\n", p.b);
fprintf(fp, "3 3 %lf\n", 1.0f);
rhs[2] = -p.d;
fclose(fp);
taucs_ccs_matrix *pB = taucs_ccs_read_ijv("3d_recover.ijv", TAUCS_DOUBLE);
double result[3];
// Run the solver, "LU" means no symmetry is required
char* options[] = { "taucs.factor.LU=true", NULL };
if (taucs_linsolve(pB, NULL, 1, result, rhs, options, NULL) != TAUCS_SUCCESS) {
printf("Solver failed\n");
}
printf("result %lf %lf %lf\n", result[0], result[1], result[2]);
point_3d->x = result[0];
point_3d->y = result[1];
point_3d->z = result[2];
taucs_free(pB);
/*
double test_x = 0.901753f, test_y=-0.323782f, test_z=-4.808777f;
//double test_x = result[0], test_y=result[1], test_z=result[2];
double myp3 = cam->rotation[2][0]*test_x+cam->rotation[2][1]*test_y+cam->rotation[2][2]*test_z+cam->translation[2];
double myp1 = cam->rotation[0][0]*test_x+cam->rotation[0][1]*test_y+cam->rotation[0][2]*test_z+cam->translation[0];
printf("%lf\n", -myp1/myp3);
printf("%lf \n", myp3*px+myp1);
printf("eq1 %lf\n", (cam->rotation[0][0]+px*cam->rotation[2][0])*test_x +
(cam->rotation[0][1]+px*cam->rotation[2][1])*test_y +
(cam->rotation[0][2]+px*cam->rotation[2][2])*test_z - rhs[0]);
printf("eq2 %lf\n", (cam->rotation[1][0]+py*cam->rotation[2][0])*test_x +
(cam->rotation[1][1]+py*cam->rotation[2][1])*test_y +
(cam->rotation[1][2]+py*cam->rotation[2][2])*test_z - rhs[1]);
printf("eq3 %lf\n", p.a*test_x+p.b*test_y+test_z+p.d);
*/
}
void scene_point_to_image_point(Position* point_3d, Camera* cam, double* x, double* y)
{
/////////////////////
// map from 3D point to 2D image
// R: rotation matrix
math::matrix<double> R;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
R(i,j) = cam->rotation[i][j];
R.SetSize(3,3);
// X: the 3d point
math::matrix<double> X;
X(0,0) = point_3d->x;
X(1,0) = point_3d->y;
X(2,0) = point_3d->z;
X.SetSize(3,1);
math::matrix<double> t;
t(0,0) = cam->translation[0];
t(1,0) = cam->translation[1];
t(2,0) = cam->translation[2];
t.SetSize(3,1);
math::matrix<double> P;
P = R * X + t;
math::matrix<double> p;
p = -P / P(2,0);
double norm = p.Norm();
double rp = 1.0f + cam->k1*norm*norm + cam->k2*norm*norm*norm*norm;
math::matrix<double> p2;
p2 = cam->f*rp*p;
*x = p2(0,0);
*y = p2(1,0);
//printf("p: %lf %lf %lf\n", p(0,0), p(1,0), p(2,0));
//printf("p2: %lf %lf %lf\n", p2(0,0), p2(1,0), p2(2,0));
}
void big_dot(ImageColor* img, int r, int c)
{
setPixelColor(img, r, c, 255, 0, 0);
setPixelColor(img, r+1, c, 255, 0, 0);
setPixelColor(img, r, c+1, 255, 0, 0);
setPixelColor(img, r-1, c, 255, 0, 0);
setPixelColor(img, r, c-1, 255, 0, 0);
}
void get_least_square_plane(Position* pos, int num_points, double* a, double* b, double* d)
{
// three equations:
// sum((ax_i+by_i+z_i+d)*x_i) = 0; a*p1 + b*p2 + p3 + d*p4 = 0
// sum((ax_i+by_i+z_i+d)*y_i) = 0; a*q1 + b*q2 + q3 + d*q4 = 0
// sum((ax_i+by_i+z_i+d)) = 0; a*r1 + b*r2 + r3 + d*r4 = 0
double p1=0, p2=0, p3=0, p4=0;
double q1=0, q2=0, q3=0, q4=0;
double r1=0, r2=0, r3=0, r4=0;
for (int i=0;i<num_points;i++) {
double x_i = pos[i].x;
double y_i = pos[i].y;
double z_i = pos[i].z;
p1 += x_i*x_i;
p2 += y_i*x_i;
p3 += z_i*x_i;
p4 += x_i;
q1 += x_i*y_i;
q2 += y_i*y_i;
q3 += z_i*y_i;
q4 += y_i;
r1 += x_i;
r2 += y_i;
r3 += z_i;
r4 += 1;
}
// write to ijv file
FILE* fp = fopen("least_square.ijv", "w");
fprintf(fp, "1 1 %lf\n", p1);
fprintf(fp, "1 2 %lf\n", p2);
fprintf(fp, "1 3 %lf\n", p4);
fprintf(fp, "2 1 %lf\n", q1);
fprintf(fp, "2 2 %lf\n", q2);
fprintf(fp, "2 3 %lf\n", q4);
fprintf(fp, "3 1 %lf\n", r1);
fprintf(fp, "3 2 %lf\n", r2);
fprintf(fp, "3 3 %lf\n", r4);
fclose(fp);
taucs_ccs_matrix *pB = taucs_ccs_read_ijv("least_square.ijv", TAUCS_DOUBLE);
double rhs[3] = {-p3, -q3, -r3};
double result[3];
// Run the solver, "LU" means no symmetry is required
char* options[] = { "taucs.factor.LU=true", NULL };
if (taucs_linsolve(pB, NULL, 1, result, rhs, options, NULL) != TAUCS_SUCCESS) {
printf("Solver failed\n");
}
printf("least square plane %lf %lf %lf\n", result[0], result[1], result[2]);
*a = result[0];
*b = result[1];
*d = result[2];
taucs_free(pB);
double sum=0;
double var=0;
for (int i=0;i<num_points;i++) {
double x_i = pos[i].x;
double y_i = pos[i].y;
double z_i = pos[i].z;
double diff = x_i**a+y_i**b+z_i+*d;
sum += abs(diff);
var += diff*diff;
}
double avg = sum/num_points;
var = var;
double std = sqrt(var);
int counter=0;
for (int i=0;i<num_points;i++) {
double x_i = pos[i].x;
double y_i = pos[i].y;
double z_i = pos[i].z;
double diff = x_i**a+y_i**b+z_i+*d;
if ((abs(diff)) > avg)
counter++;
}
}
int interpolate(int start1, int end1, int mid1, int start2, int end2)
{
if (end1==start1) return start2;
return (int)(start2 + (end2-start2)*(mid1-start1)/(double)(end1-start1));
}
#if 0
int _tmain(int argc, _TCHAR* argv[])
{
// parse input parameters
// 1st set
/*
const char *inputFilename1 = "IMG_0437.ppm";
const char *inputFilename2 = "IMG_0438.ppm";
const char *outputFilename1 = "IMG_0437_out.ppm";
const char *outputFilename2 = "IMG_0438_out.ppm";
*/
const char *inputFilename1 = "IMG_1149.ppm";
const char *inputFilename2 = "IMG_1150.ppm";
const char *outputFilename1 = "IMG_1149_out.ppm";
const char *outputFilename2 = "IMG_1150_out.ppm";
char *bundle_out_filename = "bundle.sas3.out";
ImageColor img1, img2, imgout1, imgout2;
if (readImageColor(&img1, inputFilename1)==0)
printf("Gray-scale image \"%s\" properly read\n", inputFilename1);
else {
printf("Error reading binary image \"%s\"\n", inputFilename1);
return -1;
}
if (readImageColor(&img2, inputFilename2)==0)
printf("Gray-scale image \"%s\" properly read\n", inputFilename2);
else {
printf("Error reading binary image \"%s\"\n", inputFilename2);
return -1;
}
int row1 = getNRowsColor(&img1);
int col1 = getNColsColor(&img1);
int row2 = getNRowsColor(&img2);
int col2 = getNColsColor(&img2);
setSizeColor(&imgout1, row1, col1*2);
setColorsColor(&imgout1, 255);
setColorsColor(&imgout2, 255);
copy_image(&img1, &imgout1);
//copy_image(&img2, &imgout2);
for (int i=0;i<row1;i++)
for (int j=0;j<col1;j++)
setPixelColor(&imgout1, i, col1+j, getPixelColor(&img2, i, j, 1), getPixelColor(&img2, i, j, 2), getPixelColor(&img2, i, j, 3));
big_dot(&imgout1, -142, 92);
//big_dot(&imgout2, -84, 29);
BundleOut bundle_out;
bundle_out.parse_file(bundle_out_filename);
int x[] = {217,367,207,368};
int y[] = {289,293,442,450};
int c_x = col1/2;
int c_y = row1/2;
printf("num %d\n", bundle_out.num_points);
for (int i=0;i<bundle_out.num_points;i++) {
//for (int j=0;j<4;j++) {
// int x_diff = x[j]-c_x-bundle_out.points[i][0];
// int y_diff = y[j]-c_y+bundle_out.points[i][1];
// if (sqrt((float)(x_diff*x_diff+y_diff*y_diff)) < 50) {
//printf("y=%d x=%d, y=%d x=%d, i=%d, j=%d\n", c_y-bundle_out.points[i][1], bundle_out.points[i][0]+c_x, c_y-bundle_out.points[i][3], bundle_out.points[i][2]+c_x, i, j);
// big_dot(&imgout1, c_y-bundle_out.points[i][1], bundle_out.points[i][0]+c_x);
// big_dot(&imgout1, c_y-bundle_out.points[i][3], bundle_out.points[i][2]+c_x+col1);
// }
//}
}
// get least square plane
double a,b,d;
get_least_square_plane(bundle_out.points_3d, bundle_out.num_points, &a, &b, &d);
double myx,myy;
printf("3d test point %lf %lf %lf\n", bundle_out.points_3d[0], bundle_out.points_3d[1], bundle_out.points_3d[2]);
scene_point_to_image_point(&bundle_out.points_3d[0], &bundle_out.camera[0], &myx, &myy);
Plane plane;
plane.a = a;
plane.b = b;
plane.d = d;
//plane.a = 3.0f;
//plane.b = 5.0f;
//plane.d = 3.722428;
Position pos;
//image_point_to_scene_point(myx, myy, &pos, &bundle_out.camera[0], plane);
image_point_to_scene_point(bundle_out.points[0][0], bundle_out.points[0][1], &pos, &bundle_out.camera[0], plane);
double myx2, myy2;
scene_point_to_image_point(&pos, &bundle_out.camera[1], &myx2, &myy2);
big_dot(&imgout1, c_y-bundle_out.points[0][1], c_x+bundle_out.points[0][0]);
big_dot(&imgout1, c_y-myy2, c_x+col1+myx2);
printf("image1: %d %d\n", bundle_out.points[0][0], bundle_out.points[0][1]);
printf("image2: bundler(%d %d) reconstruct(%lf %lf)\n", bundle_out.points[0][2], bundle_out.points[0][3], myx2, myy2);
// draw feature points matched by bundler
/*for (int i=0;i<bundle_out.num_points;i++) {
if (bundle_out.points_3d[i].z + 19 > 3)
big_dot(&imgout1, c_y-bundle_out.points[i][1], bundle_out.points[i][0]+c_x);
}*/
#ifdef BLEND
// right triangle
int pair1[4] = {245,234,229,148}; // row1, col1, row2, col2, CV notation
int pair2[4] = {250,367,234,282};
//int pair3[4] = {302,228,285,147};
int pair3[4] = {477,205,477,223};
// triangle
//
// |\ vec_right_up
// vec_left | \
// | /
// |/ vec_right_down
int vec1_left[2] = {pair3[0]-pair1[0], pair3[1]-pair1[1]}; // the left vector of image1
int vec1_right_up[2] = {pair2[0]-pair1[0], pair2[1]-pair1[1]}; // the upper right vector of image1
int vec1_right_down[2] = {pair3[0]-pair2[0], pair3[1]-pair2[1]}; // the lower right vector of image1
int vec2_left[2] = {pair3[2]-pair1[2], pair3[3]-pair1[3]}; // the left vector of image2
int vec2_right[2] = {pair2[2]-pair1[2], pair2[3]-pair1[3]}; // the right vector of image2
// upper half
for (int y=pair1[0]; y<=pair2[0];y++) {
int left = pair1[1] + (int)(vec1_left[1] *(y-pair1[0])/(double)(vec1_left[0]));
int right = pair1[1] + (int)(vec1_right_up[1]*(y-pair1[0])/(double)(vec1_right_up[0]));
for (int x=left; x<=right; x++) {
// vector (p,q): from pair1 to current point
int p = x-pair1[1];
int q = y-pair1[0];
// (p,q) can be represented as a*vec1_left+b*vec1_right
int x1=vec1_left[1], y1=vec1_left[0];
int x2=vec1_right_up[1], y2=vec1_right_up[0];
double a,b;
if (y1*x2-x1*y2==0) {
printf("denominator is zero!\n");
a=0;
b=0;
}else {
a = (q*x2-p*y2)/(double)(y1*x2-x1*y2);
b = (p*y1-q*x1)/(double)(y1*x2-x1*y2);
}
// find the point on second image
int image2_y = (int)(pair1[2] + a*vec2_left[0] + b*vec2_right[0]);
int image2_x = (int)(pair1[3] + a*vec2_left[1] + b*vec2_right[1]);
setPixelColor(&imgout1, y, x, getPixelColor(&img2, image2_y, image2_x, 1),
getPixelColor(&img2, image2_y, image2_x, 2), getPixelColor(&img2, image2_y, image2_x, 3));
//printf("%d %d %d %d\n", y, x, image2_y, image2_x);
}
//lineColor(&imgout1, y, left, y, right, 255, 255, 255);
//printf("%d %d\n", left, right);
}
for (int y=pair2[0]; y<=pair3[0];y++) {
int left = pair1[1] + (int)(vec1_left[1] *(y-pair1[0])/(double)(vec1_left[0]));
int right = pair2[1] + (int)(vec1_right_down[1]*(y-pair2[0])/(double)(vec1_right_down[0]));
for (int x=left; x<=right; x++) {
// vector (p,q): from pair1 to current point
int p = x-pair1[1];
int q = y-pair1[0];
// (p,q) can be represented as a*vec1_left+b*vec1_right
int x1=vec1_left[1], y1=vec1_left[0];
int x2=vec1_right_up[1], y2=vec1_right_up[0];
double a,b;
if (y1*x2-x1*y2==0) {
printf("denominator is zero!\n");
a=0;
b=0;
}else {
a = (q*x2-p*y2)/(double)(y1*x2-x1*y2);
b = (p*y1-q*x1)/(double)(y1*x2-x1*y2);
}
// find the point on second image
int image2_y = (int)(pair1[2] + a*vec2_left[0] + b*vec2_right[0]);
int image2_x = (int)(pair1[3] + a*vec2_left[1] + b*vec2_right[1]);
setPixelColor(&imgout1, y, x, getPixelColor(&img2, image2_y, image2_x, 1),
getPixelColor(&img2, image2_y, image2_x, 2), getPixelColor(&img2, image2_y, image2_x, 3));
//printf("%d %d %d %d\n", y, x, image2_y, image2_x);
}
}
#endif //BLEND
for (int i=0;i<bundle_out.num_points;i++) {
//for (int i=20;i<40;i++) {
//lineColor(&imgout1, row1/2-bundle_out.points[i][3], col1+col1/2+b.points[i][2], row1/2-bundle_out.points[i][1], col1/2+bundle_out.points[i][0], 255, 255, 255);
//printf("%lf %lf %lf\n", bundle_out.points_3d[i].x, bundle_out.points_3d[i].y, bundle_out.points_3d[i].z);
}
printf("ok\n");
if (writeImageColor(&imgout1, outputFilename1)==0 )
printf("Gray-scale image %s written\n", outputFilename1);
else
printf("Error writing gray-scale image %s\n", outputFilename1);
/*
if (writeImageColor(&imgout2, outputFilename2)==0)
printf("Gray-scale image %s written\n", outputFilename2);
else
printf("Error writing gray-scale image %s\n", outputFilename2);
*/
return 0;
}
#endif | [
"[email protected]"
] | [
[
[
1,
523
]
]
] |
9f68d0f5e3b8eab595dbeae44382b7ef9b6a1605 | d67b01b820739ea2d63968389a83c36c4b0ff163 | /UnitTests/QuizBotUnitTest/QuizBotUnitTest/ParticipantManager.h | 134b28265ec4c1d6674d479641a1edca88d1520e | [] | no_license | iamukasa/pookas | 114458dc7347c66844ff8cf3023ec75ce4c486b5 | bd5bf9178d2a2a37b3251a07eb3e6afa96f66c67 | refs/heads/master | 2021-01-13T02:08:54.947799 | 2009-11-04T00:52:06 | 2009-11-04T00:52:06 | 35,762,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,263 | h | /** \class ParticipantManager
Manages quiz players.
*/
#ifndef _PARTICIPANT_MANAGER_H_
#define _PARTICIPANT_MANAGER_H_
#include <Vector>
#include <iostream>
#include <string>
#include "QuizParticipant.h"
#include "aw.h"
class ParticipantManager
{
public:
ParticipantManager(void);
~ParticipantManager(void);
void destroy();
void setUser( int session, PlayerState state );
void setAllUsers ( PlayerState state );
void removeUser( int session );
void removeAllUsers();
void removeAllWithState( PlayerState state );
int userExists( int session );
PlayerState getState( int session );
void setState( int session, PlayerState state );
void print();
void setStartingPlayer( int session );
int getStartingPlayer();
void setPlayerName( int session, std::string name );
std::string getPlayerName( int session );
void broadcast( std::string message, int r, int g, int b, int bold, int italic );
static void whisper( int session, std::string message, int r, int g, int b, int bold, int italic );
void checkAnswers( Vect3D objPos, int radius );
void broadcastTopScores();
void reset();
std::vector <QuizParticipant*> quizUsers;
int startingPlayerSID;
int topScore;
};
#endif | [
"lab4games@40cc54bc-b367-11de-8ef2-6d788aed22ac"
] | [
[
[
1,
52
]
]
] |
27712e15e9919ac535ba9f14cbd339ac374a78f4 | de1e5905af557c6155ee50f509758a549e458ef3 | /src/ui/ui_search.h | 2b65e210c24565675d26fa627c667d24dfa74efd | [] | no_license | alltom/taps | f15f0a5b234db92447a581f3777dbe143d78da6c | a3c399d932314436f055f147106d41a90ba2fd02 | refs/heads/master | 2021-01-13T01:46:24.766584 | 2011-09-03T23:20:12 | 2011-09-03T23:20:12 | 2,486,969 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,701 | h | //-----------------------------------------------------------------------------
// name: ui_search.h
// desc: birdbrain ui
//
// authors: Ananya Misra ([email protected])
// Ge Wang ([email protected])
// Perry R. Cook ([email protected])
// Philip Davidson ([email protected])
// date: Autumn 2004
//-----------------------------------------------------------------------------
#ifndef __UI_SEARCH_H__
#define __UI_SEARCH_H__
//#include "birdbrain.h"
//#include "audicle_def.h"
#include "ui_library.h"
#include "audicle_face.h"
#include "audicle_gfx.h"
#include "ui_audio.h"
// libsndfile
#ifndef __USE_SNDFILE_PRECONF__
#include <sndfile.h>
#else
#include "util_sndfile.h"
#endif
// feature database
#include "FeatureLibrary.h"
// forward reference
struct UI_Element;
struct UI_Template;
struct Template;
struct Timeline;
//-----------------------------------------------------------------------------
// name: class UISearch
// desc: ...
//-----------------------------------------------------------------------------
class UISearch : public AudicleFace
{
public:
UISearch( );
virtual ~UISearch( );
public:
virtual t_CKBOOL init();
virtual t_CKBOOL destroy();
public:
virtual void render_pre( );
virtual void render_post( );
virtual t_CKUINT render( void * data );
virtual void render_view( );
virtual t_CKUINT on_activate( );
virtual t_CKUINT on_deactivate( t_CKDUR duration = 0.0 );
virtual t_CKUINT on_event( const AudicleEvent & event );
public:
void render_library_pane();
void render_matches_pane();
void render_values_pane();
void render_weights_pane();
void play_template( UI_Template * playme );
t_CKBOOL check_library_event( InputEvent * ie, Library * lib, t_CKBOOL &released );
t_CKBOOL handle_keyboard_event( char key );
t_CKBOOL handle_motion_event( InputEvent * ie );
t_CKBOOL load_features_from_db( Template * temp, int index );
t_CKBOOL extract_features( Template * temp );
t_CKBOOL load_match( int index );
protected:
t_CKBOOL m_init;
AudioCentral * m_audio;
UI_Element ** ui_elements;
UI_Template * selected;
bool selected_from_matches; // selected from matches or library? (if no selected, indifferent)
std::string filename;
Point3D curr_pt;
Point3D prev_pt;
Point3D orig_pt;
Color4D linecol;
Color4D highlight;
UI_Template * down;
// database
FeatureLibrary * db;
int * db_indices;
float * db_distances;
std::string db_path;
std::string db_filename;
// fog
GLuint fog_mode[4]; // Storage For Three/Four Types Of Fog
GLuint fog_filter; // Which Fog To Use
GLfloat fog_density; // Fog Density
// bounding boxes
BBox * m_bboxs;
int m_nbboxs;
int m_cur_bbox;
bool m_highlight;
// view region indices/ids
int m_vr_library_id;
int m_vr_matches_id;
int m_vr_values_id;
int m_vr_weights_id;
// last hit position (for knowing what to delete from if there are both timelines and bags)
Point2D last_hit_pos;
// load sliders from selected?
bool load_sliders;
// view in list mode versus 3d
bool m_list_view;
// "center" on selected template
bool m_center;
// center coordinates. there must be a better way to do this.
float x_center, y_center, z_center;
bool xyz_center_init;
};
// pointer
//extern UISearch * g_search_face;
// helping along : map given value in [val_low, val_high] to [low, high], return offset from low
float offset_in_range( float value, float val_low, float val_high, float low, float high);
#endif
| [
"[email protected]"
] | [
[
[
1,
137
]
]
] |
7c4250e84b5bf66acce76f77c9e3717588c8c539 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/validators/datatype/IDREFDatatypeValidator.hpp | 0020103ee4d4ed85ec46e166db84122957f1dc7d | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,455 | hpp | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: IDREFDatatypeValidator.hpp,v 1.9 2004/09/08 13:56:53 peiyongz Exp $
* $Log: IDREFDatatypeValidator.hpp,v $
* Revision 1.9 2004/09/08 13:56:53 peiyongz
* Apache License Version 2.0
*
* Revision 1.8 2004/01/29 11:51:22 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.7 2003/12/17 00:18:39 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.6 2003/11/12 20:32:03 peiyongz
* Statless Grammar: ValidationContext
*
* Revision 1.5 2003/09/30 18:17:53 peiyongz
* Implementation of Serialization/Deserialization
*
* Revision 1.4 2003/05/15 18:53:26 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.3 2002/12/18 14:17:55 gareth
* Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf.
*
* Revision 1.2 2002/11/04 14:53:28 tng
* C++ Namespace Support.
*
* Revision 1.1.1.1 2002/02/01 22:22:41 peiyongz
* sane_include
*
* Revision 1.8 2001/11/22 20:23:20 peiyongz
* _declspec(dllimport) and inline warning C4273
*
* Revision 1.7 2001/10/09 20:49:38 peiyongz
* init(): take 1 arg
*
* Revision 1.6 2001/09/27 13:51:25 peiyongz
* DTV Reorganization: ctor/init created to be used by derived class
*
* Revision 1.5 2001/09/25 14:23:42 peiyongz
* DTV Reorganization: checkValueSpace()
*
* Revision 1.4 2001/08/24 17:12:01 knoaman
* Add support for anySimpleType.
* Remove parameter 'baseValidator' from the virtual method 'newInstance'.
*
* Revision 1.3 2001/07/25 17:58:08 tng
* Fix compilation errors.
*
* Revision 1.2 2001/07/24 21:23:40 tng
* Schema: Use DatatypeValidator for ID/IDREF/ENTITY/ENTITIES/NOTATION.
*
* Revision 1.1 2001/07/04 20:16:59 peiyongz
* IDREFDatatypeValidator
*
*/
#if !defined(IDREF_DATATYPEVALIDATOR_HPP)
#define IDREF_DATATYPEVALIDATOR_HPP
#include <xercesc/validators/datatype/StringDatatypeValidator.hpp>
#include <xercesc/framework/XMLRefInfo.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class VALIDATORS_EXPORT IDREFDatatypeValidator : public StringDatatypeValidator
{
public:
// -----------------------------------------------------------------------
// Public ctor/dtor
// -----------------------------------------------------------------------
/** @name Constructors and Destructor */
//@{
IDREFDatatypeValidator
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
IDREFDatatypeValidator
(
DatatypeValidator* const baseValidator
, RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const int finalSet
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
virtual ~IDREFDatatypeValidator();
//@}
// -----------------------------------------------------------------------
// Validation methods
// -----------------------------------------------------------------------
/** @name Validation Function */
//@{
/**
* validate that a string matches the boolean datatype
* @param content A string containing the content to be validated
*
* @exception throws InvalidDatatypeException if the content is
* is not valid.
*/
virtual void validate
(
const XMLCh* const content
, ValidationContext* const context = 0
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@}
/**
* Returns an instance of the base datatype validator class
* Used by the DatatypeValidatorFactory.
*/
virtual DatatypeValidator* newInstance
(
RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const int finalSet
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//deprecated
inline void setIDRefList(RefHashTableOf<XMLRefInfo>* fIDRefList);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(IDREFDatatypeValidator)
protected:
//
// ctor provided to be used by derived classes
//
IDREFDatatypeValidator
(
DatatypeValidator* const baseValidator
, RefHashTableOf<KVStringPair>* const facets
, const int finalSet
, const ValidatorType type
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
virtual void checkValueSpace(const XMLCh* const content
, MemoryManager* const manager);
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
IDREFDatatypeValidator(const IDREFDatatypeValidator&);
IDREFDatatypeValidator& operator=(const IDREFDatatypeValidator&);
// -----------------------------------------------------------------------
// Private data members
//
//
// -----------------------------------------------------------------------
};
// -----------------------------------------------------------------------
// Validation methods
// -----------------------------------------------------------------------
inline void IDREFDatatypeValidator::setIDRefList(RefHashTableOf<XMLRefInfo>* )
{
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file IDREFDatatypeValidator.hpp
*/
| [
"[email protected]"
] | [
[
[
1,
197
]
]
] |
bd35c8eb9c214e2543bf80d818717bea3046d600 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/NewAudioServer.h | baa3a349cbf772081a157b701f6b1be9329d8470 | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,413 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef NEWAUDIOSERVER_H
#define NEWAUDIOSERVER_H
#include "NewAudioPlayer.h"
#include "NewAudioConverter.h"
#include "NewAudioServerTypes.h"
#include <e32base.h>
#include <mdaaudiosampleeditor.h>
#include <mdaaudiooutputstream.h>
#include <vector>
#include <badesca.h>
#define TRUST_PLAY_COMPLETE
#if defined NAV2_CLIENT_SERIES80 || defined NAV2_CLIENT_SERIES90_V1
# undef TRUST_PLAY_COMPLETE
#endif
// In the emulator, MaoscPlayComplete is called after playing.
#if defined NAV2_CLIENT_SERIES60_V2 && !defined(__WINS__)
# undef TRUST_PLAY_COMPLETE
#endif
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
class CNewAudioServer : public CServer2
#else
class CNewAudioServer : public CServer
#endif
{
public:
static CNewAudioServer * NewLC();
virtual ~CNewAudioServer();
/// Returns the special string for the timing marker sound
static const TDesC& getTimingMarker();
/// Returns the special string for the end marker.
static const TDesC& getEndMarker();
public:
void StopServerL();
protected:
/**
* Internal class that interfaces with the audio
* subsystem of the phone. The sessions call on
* it to handle the requests.
*
* TODO: Do not copy the memory used by clips containing same data.
* Reuse old clips instead.
* TODO: Do not convert the same clip more than once for each
* sound-list.
*/
class CPlayerControl : public CBase,
public NewAudioPlayerListener,
public NewAudioConverterListener {
public:
static CPlayerControl * NewLC();
virtual ~CPlayerControl();
protected:
CPlayerControl();
void ConstructL();
public:
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
void HandleRequest( const RMessage2 & aMessage);
#else
void HandleRequest( const RMessage & aMessage);
#endif
void StopServerL();
protected:
/**
* Store the given sound length in the buffer
* supplied by the client as a part of the call
* to PrepareSound().
*/
void StoreSoundLengthReply(TInt aSoundLengthTenthsOfSec);
// From NewAudioPlayerListener
/// Called by NewAudioPlayer when complete
void playCompleteL( TInt aError );
// From NewAudioConverterListener
/// Called by NewAudioConverter when complete
void conversionCompleteL( TInt aError, long durationMS );
// Functions not in any interface
/**
* Reads clip-names from aMessage and the address space of the
* other thread. Then it parses it runs prepClips.
*/
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
void decodeAndPrepClipsL( const RMessage2& aMessage );
#else
void decodeAndPrepClipsL( const RMessage& aMessage );
#endif
/// Prepare clips. Move from wanted list to load list etc.
void prepClips( const MDesCArray& filenames );
/// Complete the current request if it is active
void completeRequest( TInt aError );
protected:
/// Message that caused the current activity.
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
RMessage2 iMessage;
#else
RMessage iMessage;
#endif
/// True if we have an active request and message.
TBool m_requestActive;
/// True if we are cancelling the currently active request.
TBool m_cancelling;
/// True if we are stopping the server.
TBool iStopping;
/// The audio player
NewAudioPlayer* m_audioPlayer;
/// The audio converter
NewAudioConverter* m_audioConverter;
/// The clips are placed here. Some are loaded, some are not.
TClips m_clips;
/**
* Linear search from begin to end-1 for a clip with
* filename <code>filename</code>.
* @return <code>end</code> if not found.
*/
static TClips::iterator findClip(TClips::iterator begin,
TClips::iterator end,
const TDesC& filename );
};
// Handle connections from one client
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
class CNewAudioSession : public CSession2
#else
class CNewAudioSession : public CSharableSession
#endif
{
public:
CNewAudioSession(CPlayerControl & aPlayerControl);
virtual ~CNewAudioSession();
protected:
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
void ServiceL(const RMessage2 &aMessage);
#else
void ServiceL(const RMessage& aMessage);
#endif
protected:
CPlayerControl & iPlayerControl;
};
protected: // From CServer
#if defined NAV2_CLIENT_UIQ3 || defined NAV2_CLIENT_SERIES60_V3
CSession2* NewSessionL(const TVersion &aVersion, const RMessage2& aMessage) const;
#else
CSharableSession* NewSessionL(const TVersion& aVersion) const;
#endif
protected:
CNewAudioServer();
void ConstructL();
protected:
CPlayerControl * iPlayerControl;
};
#endif /* NEWAUDIOSERVER_H */
| [
"[email protected]"
] | [
[
[
1,
207
]
]
] |
6f340139c128041af2d9f72209fe6f75a016d75f | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Agent/ConvexAgent/Gjk/hkpClosestPointManifold.h | ed76104e142966d69909f5ae568a1bc9a010089e | [] | 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 | 3,695 | 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 HK_COLLIDE2_CLOSEST_POINT_MANIFOLD_H
#define HK_COLLIDE2_CLOSEST_POINT_MANIFOLD_H
class hkpCdBody;
struct hkpProcessCollisionOutput;
class hkpContactMgr;
class hkpClosestPointManifold
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_CDINFO, hkpClosestPointManifold );
enum { HK_NUM_MAX_CONTACTS = 4 };
class hkpAgentContactPoint
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpClosestPointManifold::hkpAgentContactPoint );
//
// members
//
hkVector4 m_pointA; // in object space A .w is the pointA weight
hkVector4 m_pointB; // in object space B .wi is the contactPointId
hkVector4 m_normal; // in world space .w is the distance
//
// The next three functions are only to be called after the above hkVector4 have been set
//
float& getDistance(){ return m_normal(3); }
float getDistance() const { return m_normal(3); }
const hkVector4& getSeparatingNormal() const { return m_normal; }
float & getPointAWeight(){ return m_pointA(3); }
unsigned getContactPointId() const { return m_pointB.getInt24W(); }
void setContactPointId( int id ){ m_pointB.setInt24W( id ); }
};
inline hkpClosestPointManifold( );
/// Adds a point to the point array. Note: this class does not check for overflows, therefore the maximum number of points is 4
static void HK_CALL addPoint( const hkpCdBody& ca, const hkpCdBody& cb, const hkpProcessCollisionInput &input, hkpProcessCollisionOutput& output, const struct hkpExtendedGskOut& cpInfo, hkReal createContactRangeMax, hkpContactMgr* contactMgr, hkCollisionConstraintOwner& constraintOwner, hkpAgentContactPoint* pointArray, int& numPoints );
static void HK_CALL getPoints( const hkpCdBody& ca, const hkpCdBody& cb, const hkpProcessCollisionInput &input, hkReal dist, hkpAgentContactPoint* pointArray, int& numPoints, hkpProcessCollisionOutput& contactPointsOut, hkpContactMgr* contactMgr, hkCollisionConstraintOwner& constraintOwner );
static void HK_CALL cleanup( hkpAgentContactPoint* pointArray, int& numPoints, hkpContactMgr* mgr, hkCollisionConstraintOwner& info );
static int HK_CALL findRedundant5thPoint( const hkVector4** points);
public:
int m_numPoints;
hkpAgentContactPoint m_contactPoints[HK_NUM_MAX_CONTACTS];
};
hkpClosestPointManifold::hkpClosestPointManifold()
{
m_numPoints = 0;
}
#endif // HK_COLLIDE2_CLOSEST_POINT_MANIFOLD_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,
85
]
]
] |
b8944d0bf21598ac9339a16b9fe29c21562fa6f8 | 20c74d83255427dd548def97f9a42112c1b9249a | /src/libsrc/rendering/imageinfo.cpp | 4e3e0f65ed0f8e6d6511a58cf59e1eb1e7e85d15 | [] | no_license | jonyzp/roadfighter | 70f5c7ff6b633243c4ac73085685595189617650 | d02cbcdcfda1555df836379487953ae6206c0703 | refs/heads/master | 2016-08-10T15:39:09.671015 | 2011-05-05T12:00:34 | 2011-05-05T12:00:34 | 54,320,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | cpp | #include "imageinfo.h"
ImageInfo::ImageInfo(string n, string fp, string fn,int nf, int csx)
{
path = fp + fn;
name = n;
numFrames = nf;
cellSizeX = csx;
cellSizeY = csx;
}
ImageInfo::ImageInfo(string n, string fp, string fn, int nf, int csx, int csy)
{
path = fp + fn;
name = n;
numFrames = nf;
cellSizeX = csx;
cellSizeY = csy;
}
ImageInfo::ImageInfo(string n, string fp, string fn)
{
path = fp + fn;
name = n;
}
ImageInfo::ImageInfo(string n, string fp, string fn, int nf)
{
path = fp + fn;
name = n;
numFrames = nf;
}
ImageInfo::ImageInfo()
{
}
ImageInfo::~ImageInfo()
{
}
void ImageInfo::setCellSizeX(int cs)
{
cellSizeX = cs;
}
int ImageInfo::getCellSizeX()
{
return cellSizeX;
}
void ImageInfo::setCellSizeY(int cs)
{
cellSizeY = cs;
}
int ImageInfo::getCellSizeY()
{
return cellSizeY;
}
void ImageInfo::setNumFrames(int nf)
{
numFrames = nf;
}
int ImageInfo::getNumFrames()
{
return numFrames;
}
void ImageInfo::setName(string n)
{
name = n;
}
string ImageInfo::getName()
{
return name;
}
void ImageInfo::setPath(string p)
{
path = p;
}
string ImageInfo::getPath()
{
return path;
}
| [
"[email protected]"
] | [
[
[
1,
92
]
]
] |
d07954bbeacc037a6fe2caaac811589f627822d1 | 62207628c4869e289975cc56be76339a31525c5d | /Source/Star Foxes Skeleton/standardShipClass.cpp | 71ef2b54bd30ed2b9018dec77d939c644be71049 | [] | no_license | dieno/star-foxes | f596e5c6b548fa5bb4f5d716b73df6285b2ce10e | eb6a12c827167fd2b7dd63ce19a1f15d7b7763f8 | refs/heads/master | 2021-01-01T16:39:47.800555 | 2011-05-29T03:51:35 | 2011-05-29T03:51:35 | 32,129,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | #include "standardShipClass.h"
float StandardShipClass::afterburnerSpeed_ = 5.0f*.8f; | [
"[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a",
"[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a"
] | [
[
[
1,
2
]
],
[
[
3,
3
]
]
] |
05a6eba5910c5074078049acd9ee5e24d1fe3485 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/Game/GameDll/ClientGameTokenSynch.cpp | a673c6d0aceaf105ddbdc1091111ca7eefa9c099 | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 6,890 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2008.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 5:9:2008 13:11 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "ClientGameTokenSynch.h"
#include "ServerGameTokenSynch.h"
//------------------------------------------------------------------------
void CClientGameTokenSynch::DefineProtocol(IProtocolBuilder *pBuilder)
{
pBuilder->AddMessageSink(this, CServerGameTokenSynch::GetProtocolDef(), CClientGameTokenSynch::GetProtocolDef());
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, ResetMsg, eNRT_ReliableOrdered, eMPF_BlocksStateChange)
{
Reset();
return true;
}
//------------------------------------------------------------------------
CClientGameTokenSynch::CResetMsg::CResetMsg(int _channelId)
: INetMessage(CClientGameTokenSynch::ResetMsg),
channelId(_channelId)
{
};
//------------------------------------------------------------------------
EMessageSendResult CClientGameTokenSynch::CResetMsg::WritePayload(TSerialize ser, uint32 currentSeq, uint32 basisSeq)
{
return eMSR_SentOk;
}
//------------------------------------------------------------------------
void CClientGameTokenSynch::CResetMsg::UpdateState(uint32 fromSeq, ENetSendableStateUpdate)
{
}
//------------------------------------------------------------------------
size_t CClientGameTokenSynch::CResetMsg::GetSize()
{
return sizeof(this);
};
//------------------------------------------------------------------------
// GLOBAL
//------------------------------------------------------------------------
#define DEFINE_MESSAGE(class, type, msgdef) \
CClientGameTokenSynch::class::class(int _channelId, TGameTokenName _name, TGameTokenValue &_value) \
: CSetMsg(CClientGameTokenSynch::msgdef, _channelId, _name, _value) {}; \
EMessageSendResult CClientGameTokenSynch::class::WritePayload(TSerialize ser, uint32 currentSeq, uint32 basisSeq) \
{ CClientGameTokenSynch::SerializeGameToken(ser, name, value, NTypelist::IndexOf<type, TGameTokenValueTypes>::value); \
return eMSR_SentOk; }
#define IMPLEMENT_IMMEDIATE_MESSAGE(type) \
TGameTokenName name; \
TGameTokenValue value; \
CClientGameTokenSynch::SerializeGameToken(ser, name, value, NTypelist::IndexOf<type, TGameTokenValueTypes>::value); \
m_pGTS->SetOrCreateToken(name, value); \
return true;
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetIntMsg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(int);
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetFloatMsg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(float);
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetEntityIdMsg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(EntityId);
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetVec3Msg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(Vec3);
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetStringMsg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(string);
}
//------------------------------------------------------------------------
NET_IMPLEMENT_IMMEDIATE_MESSAGE(CClientGameTokenSynch, SetBoolMsg, eNRT_ReliableUnordered, 0)
{
IMPLEMENT_IMMEDIATE_MESSAGE(bool);
}
//------------------------------------------------------------------------
CClientGameTokenSynch::CSetMsg::CSetMsg(const SNetMessageDef *pDef, int _channelId, TGameTokenName &_name, TGameTokenValue &_value)
: channelId(_channelId),
name(_name),
value(_value),
INetMessage(pDef)
{
SetGroup( 'stor' );
};
//------------------------------------------------------------------------
EMessageSendResult CClientGameTokenSynch::CSetMsg::WritePayload(TSerialize ser, uint32 currentSeq, uint32 basisSeq)
{
return eMSR_SentOk;
}
//------------------------------------------------------------------------
void CClientGameTokenSynch::CSetMsg::UpdateState(uint32 fromSeq, ENetSendableStateUpdate)
{
}
//------------------------------------------------------------------------
size_t CClientGameTokenSynch::CSetMsg::GetSize()
{
return sizeof(this);
};
DEFINE_MESSAGE(CSetIntMsg, int, SetIntMsg);
DEFINE_MESSAGE(CSetFloatMsg, float, SetFloatMsg);
DEFINE_MESSAGE(CSetVec3Msg, Vec3, SetVec3Msg);
DEFINE_MESSAGE(CSetEntityIdMsg, EntityId, SetEntityIdMsg);
DEFINE_MESSAGE(CSetStringMsg, string, SetStringMsg);
DEFINE_MESSAGE(CSetBoolMsg, bool, SetBoolMsg);
#undef DEFINE_MESSAGE
#undef IMPLEMENT_IMMEDIATE_MESSAGE
//------------------------------------------------------------------------
void CClientGameTokenSynch::SerializeGameToken(TSerialize ser, TGameTokenName &name, TGameTokenValue &value, int type)
{
ser.Value("name", name);
switch (type)
{
case eFDT_Int:
{
int i;
if (ser.IsWriting())
i=*value.GetPtr<int>();
ser.Value("value", i);
if (ser.IsReading())
value.Set(i);
}
break;
case eFDT_Float:
{
float f;
if (ser.IsWriting())
f=*value.GetPtr<float>();
ser.Value("value", f);
if (ser.IsReading())
value.Set(f);
}
break;
case eFDT_Vec3:
{
Vec3 v;
if (ser.IsWriting())
v=*value.GetPtr<Vec3>();
ser.Value("value", v);
if (ser.IsReading())
value.Set(v);
}
break;
case eFDT_EntityId:
{
EntityId e;
if (ser.IsWriting())
e=*value.GetPtr<EntityId>();
ser.Value("value", e);
if (ser.IsReading())
value.Set(e);
}
break;
case eFDT_String:
{
static string s;
s.resize(0);
if (ser.IsWriting())
s=*value.GetPtr<string>();
ser.Value("value", s);
if (ser.IsReading())
value.Set(s);
}
break;
case eFDT_Bool:
{
bool b;
if (ser.IsWriting())
b=*value.GetPtr<bool>();
ser.Value("value", b);
if (ser.IsReading())
value.Set(b);
}
break;
default:
assert(0);
break;
}
}
//------------------------------------------------------------------------
void CClientGameTokenSynch::GetMemoryUsage(ICrySizer *pSizer) const
{
pSizer->Add(*this);
}
| [
"[email protected]"
] | [
[
[
1,
229
]
]
] |
e1021baf7935ef27f32c24390c96d7da28e267dc | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Common/Serialize/UnitTest/Nullname/NullName.h | 46c9150fd407539841fd06d3a50a1ca518859212 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,531 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKSERIALIZE_NullName_H
#define HKSERIALIZE_NullName_H
class hkNullName
{
public:
HK_DECLARE_REFLECTION();
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_DEMO,hkNullName);
hkNullName():
m_c1("hello"),
m_c2(""),
m_c3(HK_NULL)
{
}
~hkNullName(){}
public:
char* m_c1;
char* m_c2;
char* m_c3;
};
#endif
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
51
]
]
] |
a8245b45721cfd9ff390118b4926a816ca3ee5bf | f64b888affed8c6db2cc56d4618c72c923fe1a7c | /include/lockmgr/ipthreadmutex.hxx | 63b94e741b31c29607137ca54391a8fbcde31f61 | [
"BSD-2-Clause"
] | permissive | wilx/lockmgr | 64ca319f87ccf96214d9c4a3e1095f783fb355d8 | 9932287c6a49199730abfb4332f85c9ca05d9511 | refs/heads/master | 2021-01-10T02:19:35.039497 | 2008-06-09T11:24:32 | 2008-06-09T11:24:32 | 36,984,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,181 | hxx | // Copyright (c) 2008, Václav Haisman
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if ! defined (LOCKMANAGER_LOCKMGR_IPTHREADMUTEX_HXX)
#define LOCKMANAGER_LOCKMGR_IPTHREADMUTEX_HXX
#include <pthread.h>
#include "lockmgr/dlldef.hxx"
namespace lockmgr
{
//! Interface for mutex with lock manager.
class LOCKMGR_INTERFACE IPthreadMutexLock
{
public:
//! Method for locking given mutex.
virtual int pthread_mutex_lock (pthread_mutex_t *) = 0;
//! Method for unlocking locked mutex.
virtual int pthread_mutex_unlock (pthread_mutex_t *) = 0;
//! Method for removing bookkeeping information for given mutex.
virtual void pthread_mutex_forget (pthread_mutex_t *) = 0;
protected:
virtual ~IPthreadMutexLock () = 0;
};
} // namespace lockmgr
#endif // LOCKMANAGER_LOCKMGR_IPTHREADMUTEX_HXX
| [
"[email protected]"
] | [
[
[
1,
58
]
]
] |
7fac13a65c040f6050dd48d7e4c5cebe2df0e439 | 7dd19b99378bc5ca4a7c669617a475f551015d48 | /opencamera_Lite/rtsp_stack/rsa_crypto.cpp | f275dc6b5d171e81e6d9204c27498da56ab2571f | [] | no_license | Locnath/openpernet | 988a822eb590f8ed75f9b4e8c2aa7b783569b9da | 67dad1ac4cfe7c336f8a06b8c50540f12407b815 | refs/heads/master | 2020-06-14T14:32:17.351799 | 2011-06-23T08:51:04 | 2011-06-23T08:51:04 | 41,778,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,925 | cpp | #include "rsa_crypto.h"
#include <stdio.h>
#include <cstring>
#include "Debug.h"
// This function should be rewritten on a specific platform
char* get_public_key()
{
return NULL;
}
void* init_crypto_key(unsigned char* pub_key, unsigned int pub_key_len, unsigned char* priv_key, unsigned int priv_key_len)
{
RSA* rsa = RSA_new();
unsigned char* pub, *priv;
pub = new unsigned char[pub_key_len/2];
priv = new unsigned char[priv_key_len/2];
hex2array((char*)pub_key, pub_key_len, pub, pub_key_len/2);
hex2array((char*)priv_key, priv_key_len, priv, priv_key_len/2);
rsa->n = BN_bin2bn(pub, pub_key_len/2, rsa->n);
rsa->d = BN_bin2bn(priv, priv_key_len/2, rsa->d);
rsa->e = BN_bin2bn(crypto_common, 1, rsa->e);
delete [] pub;
delete [] priv;
return rsa;
}
int crypto_encode(void* handle, unsigned char* input, unsigned int input_length,
unsigned char* output, unsigned int output_length)
{
RSA* rsa = (RSA*)handle;
unsigned char* pack_output = new unsigned char[output_length];
int num = RSA_public_encrypt(input_length, input, pack_output, rsa,
RSA_PKCS1_PADDING);
if (num > 0)
{
num = array2hex(pack_output, num, (char*)output, output_length);
}
else if (num == -1)
{
unsigned long err = ERR_get_error();
Debug(ckite_log_message, "Error string %s\n", ERR_error_string(err, NULL));
}
delete [] pack_output;
return num;
}
int crypto_decode(void* handle, unsigned char* input, unsigned int input_length,
unsigned char* output, unsigned int output_length)
{
RSA* rsa = (RSA*)handle;
unsigned char* pack_input = new unsigned char[input_length/2];
hex2array((char*)input, input_length, pack_input, input_length/2);
int num = RSA_private_decrypt(input_length/2, pack_input, output, rsa,
RSA_PKCS1_PADDING);
return num;
}
void release_crypto_key(void* handle)
{
RSA* rsa = (RSA*)handle;
delete rsa;
}
int hex_digit(unsigned char hex)
{
if (hex >= '0' && hex <= '9')
return hex - '0';
if (hex >= 'A' && hex <= 'F')
return hex - 'A' + 10;
if (hex >= 'a' && hex <= 'f')
return hex - 'a' + 10;
return 0;
}
char hex_value(unsigned int digit)
{
if (digit >= 0 && digit <= 9)
return '0' + digit;
else if (digit >= 10 && digit <= 15)
return 'A' + (digit-10);
else
return '0';
}
int hex2array(char* hex, int hex_len, unsigned char* array, int array_len)
{
int i;
if (array_len < hex_len/2)
return -1;
if (hex_len & 1) // hex_len must be even!
return -1;
for (i=0; i<hex_len; i+=2)
{
array[i/2] = hex_digit(hex[i])*16 + hex_digit(hex[i+1]);
}
return hex_len/2;
}
int array2hex(unsigned char* array, int array_len, char* hex, int hex_len)
{
int i;
if (hex_len < array_len*2)
return -1;
for (i=0; i<array_len; i++)
{
hex[2*i] = hex_value(array[i] >> 4);
hex[2*i+1] = hex_value(array[i] & 0x0f);
}
return 2*array_len;
}
| [
"[email protected]"
] | [
[
[
1,
114
]
]
] |
58202b5ab32e02ca067b4eb0ffaadc2696efeaaf | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DirectObject.h | e59177a48876133f2f297d5d8e4f03327fce7ce4 | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX {
/// <summary>
/// Base for classes supporting an internal interface that is not an IUnknown
/// </summary>
public ref class DirectObject abstract
{
internal:
template <typename T>
T* GetInterface()
{
return static_cast<T*>(nativeObject.Get());
}
void Attach(void* _right);
void Attach(void* _right, bool _deletable);
DirectObject();
DirectObject(void* _ptr);
DirectObject(void* _ptr, bool _deletable);
public:
/// <summary>
/// Get the internal native pointer for the wrapped native object
/// </summary>
/// <returns>
/// A pointer to the wrapped native interfac.
/// </returns>
property IntPtr NativeObject
{
IntPtr get()
{
return IntPtr(nativeObject.Get());
}
}
private:
AutoPointer<void> nativeObject;
};
} } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
49
]
]
] |
563d0ebe9704f97806e662b739869d5a786a6fe7 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/mirserver/LoginGate/ClientSockMsg.cpp | 48d92b95bed68998b7ff09db424b96ab731f8843 | [] | no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,214 | cpp | #include "stdafx.h"
DWORD WINAPI ThreadFuncForMsg(LPVOID lpParameter);
BOOL CheckSocketError(LPARAM lParam);
VOID WINAPI OnTimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
void OnCommand(WPARAM wParam, LPARAM lParam);
BOOL InitThread(LPTHREAD_START_ROUTINE lpRoutine);
extern SOCKET g_csock;
extern HWND g_hMainWnd;
extern HWND g_hStatusBar;
extern HWND g_hToolBar;
HANDLE g_hMsgThread = INVALID_HANDLE_VALUE;
CWHQueue g_xMsgQueue;
static char WorkBuff[8192];
static int nWorkBuffLen;
LPARAM OnClientSockMsg(WPARAM wParam, LPARAM lParam)
{
switch (WSAGETSELECTEVENT(lParam))
{
case FD_CONNECT:
{
DWORD dwThreadIDForMsg = 0;
if (CheckSocketError(lParam))
{
dwThreadIDForMsg = 0;
if (InitThread(ThreadFuncForMsg))
{
KillTimer(g_hMainWnd, _ID_TIMER_CONNECTSERVER);
SetTimer(g_hMainWnd, _ID_TIMER_KEEPALIVE, 5000, (TIMERPROC)OnTimerProc);
InsertLogMsg(IDS_CONNECT_LOGINSERVER);
SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(1, 0), (LPARAM)_TEXT("Connected"));
}
}
else
{
closesocket(g_csock);
g_csock = INVALID_SOCKET;
SetTimer(g_hMainWnd, _ID_TIMER_CONNECTSERVER, 10000, (TIMERPROC)OnTimerProc);
}
break;
}
case FD_CLOSE:
{
closesocket(g_csock);
g_csock = INVALID_SOCKET;
OnCommand(IDM_STOPSERVICE, 0);
break;
}
case FD_READ:
{
int nSocket = 0;
char *pszFirst = NULL, *pszEnd = NULL;
UINT nRecv = 0;
ioctlsocket((SOCKET)wParam, FIONREAD, (u_long *)&nRecv);
if (nRecv)
{
char *pszPacket = new char[nRecv + 1];
nRecv = recv((SOCKET)wParam, pszPacket, nRecv, 0);
pszPacket[nRecv] = '\0';
if (!(g_xMsgQueue.PushQ((BYTE *)pszPacket)))
InsertLogMsg(_TEXT("[INFO] Not enough queue(g_xMsgQueue) buffer."));
}
break;
}
}
return 0L;
}
void SendExToServer(char *pszPacket)
{
DWORD dwSendBytes;
WSABUF buf;
buf.len = memlen(pszPacket) - 1;
buf.buf = pszPacket;
if ( WSASend(g_csock, &buf, 1, &dwSendBytes, 0, NULL, NULL) == SOCKET_ERROR )
{
int nErr = WSAGetLastError();
}
}
| [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
] | [
[
[
1,
106
]
]
] |
cd652212f4819ac726219acecfc8101e5d2020c9 | 031009bf00a8d7cd564e0f768ff3649907bd5b65 | /atom.h | 767d00d06ea5e9e47502db07b310008b71df1f0c | [] | no_license | usertex/autov | 237ab3b655be2dffcb7292cd212fe2b6d95907a7 | b470a96072484afe73ab0ae6ab7096970e34d973 | refs/heads/master | 2020-04-19T02:45:34.548955 | 2006-07-03T01:37:24 | 2006-07-03T01:37:24 | 67,372,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,988 | h | //
// Copyright (C) 2003-2004 Trevor Hogan
//
#ifndef ATOM_H
#define ATOM_H
#include <stdio.h>
#include <time.h>
#include <map>
#include <string>
#include <vector>
#include <utility>
using namespace std;
#ifdef WIN32
typedef __int64 int64;
typedef unsigned __int64 uint64;
#else
typedef long long int64;
typedef unsigned long long uint64;
#endif
class CAtom
{
public:
virtual ~CAtom( ) { }
virtual bool isLong( ) { return false; }
virtual bool isList( ) { return false; }
virtual bool isDicti( ) { return false; }
virtual int EncodedLength( ) = 0;
virtual int Length( ) = 0;
virtual string toString( ) = 0;
};
class CAtomInt : public CAtom
{
public:
CAtomInt( );
CAtomInt( int iInt );
CAtomInt( const CAtomInt &c );
virtual ~CAtomInt( );
virtual int EncodedLength( );
virtual int Length( );
virtual string toString( );
int getValue( ) const;
void setValue( int iInt );
private:
int m_iInt;
};
class CAtomLong : public CAtom
{
public:
CAtomLong( );
CAtomLong( int64 iLong );
CAtomLong( const CAtomLong &c );
virtual ~CAtomLong( );
virtual bool isLong( ) { return true; }
virtual int EncodedLength( );
virtual int Length( );
virtual string toString( );
int64 getValue( ) const;
void setValue( int64 iLong );
private:
int64 m_iLong;
};
class CAtomString : public CAtom
{
public:
CAtomString( );
CAtomString( string strString );
CAtomString( const CAtomString &c );
virtual ~CAtomString( );
virtual int EncodedLength( );
virtual int Length( );
virtual string toString( );
string getValue( ) const;
void setValue( string strString );
private:
string m_strString;
};
class CAtomList : public CAtom
{
public:
CAtomList( );
CAtomList( vector<CAtom *> vecList );
CAtomList( const CAtomList &c );
virtual ~CAtomList( );
virtual bool isList( ) { return true; }
virtual int EncodedLength( );
virtual int Length( );
virtual string toString( );
virtual bool isEmpty( );
virtual void clear( );
virtual void Randomize( );
vector<CAtom *> getValue( ) const;
vector<CAtom *> *getValuePtr( ) const;
void setValue( vector<CAtom *> vecList );
void delItem( CAtom *atmItem );
void addItem( CAtom *atmItem );
private:
vector<CAtom *> m_vecList;
};
class CAtomDicti : public CAtom
{
public:
CAtomDicti( );
CAtomDicti( const CAtomDicti &c );
virtual ~CAtomDicti( );
virtual bool isDicti( ) { return true; }
virtual int EncodedLength( );
virtual int Length( );
virtual string toString( );
virtual bool isEmpty( );
virtual void clear( );
map<string, CAtom *> *getValuePtr( ) const;
void setValue( map<string, CAtom *> mapDicti );
void delItem( string strKey );
CAtom *getItem( string strKey );
CAtom *getItem( string strKey, CAtom *pReturn );
void setItem( string strKey, CAtom *pValue );
private:
map<string, CAtom *> m_mapDicti;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
156
]
]
] |
914cc5884b2a9d17be1e2849b3a22ad45b885e7f | d8ee6216089aa884589ca9175d3bc191dcc1ea12 | /PostEffectProgram/Include/Singleton.h | 688a65e77cfdfbc67541e988f4d892fe92ec3fc5 | [] | no_license | OtterOrder/posteffectprogram | a15035eb96a107ec220f834baeb4c4db2573fd56 | ff713b71ba72984e74fc62e9a1f7b1fb8fb43198 | refs/heads/master | 2016-09-05T09:06:20.138050 | 2009-06-30T07:21:43 | 2009-06-30T07:21:43 | 32,115,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | h | #pragma once
#include <stdlib.h>
template< typename T >
class Singleton
{
public:
static T* GetSingleton( void )
{
if( !m_Instance )
m_Instance = new T;
return m_Instance;
}
static void DestroySingleton( void )
{
if( m_Instance )
{
delete m_Instance;
m_Instance = NULL;
}
}
protected:
Singleton ( void ){}
virtual ~Singleton ( void ){}
private:
static T *m_Instance;
};
template< typename T >
T* Singleton< T >::m_Instance = NULL;
| [
"germain.mazac@7ea0d518-2368-11de-96a1-5542d1fc8aa6"
] | [
[
[
1,
44
]
]
] |
00f5236c9f622c24753a5500f3547be8f2f16c10 | 07c6ebde11637b991d691e17456cfc8d6389738b | /peng/peng/cclienttoaol30.cpp | 82b47bfe7a5f4c3a58dfb72254d25db10cfe42f9 | [] | no_license | fourks/penggy-mirror | 067b3133125eb1d945305d2386d760d4d445bf21 | f5a600b9801cea0607e69c3d0c1c37a258b34631 | refs/heads/master | 2020-06-24T11:34:16.502470 | 2003-05-16T15:28:45 | 2003-05-16T15:28:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,254 | cpp | #include "globals.h"
/***************************************************************************
cclienttoaol30.cpp - description
-------------------
begin : Sun Jun 10 2001
copyright : (C) 2001 by stephane (birdy57)
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "cclienttoaol30.h"
CClientToAol30::CClientToAol30()
{
AolHeader = new CAolHeader30;
Vjcompress = new CVjcompress;
}
CClientToAol30::~CClientToAol30()
{
}
/** client -> AOL */
void CClientToAol30::Main()
{
bool bTooBig = false;
bool bFirstTrame = false;
unsigned short nIpLen;
unsigned short nRestSize;
unsigned short nSendLon;
char ssTrame[MRUOut + 200];
char *sTrame = &ssTrame[0];
char ssBuffer[MRUOut + 200];
char *sBuffer = &ssBuffer[0];
unsigned short nLon;
unsigned short nSize;
unsigned short nMtu;
unsigned short nSeq;
bool bReady = false;
while (!m_CKernel->bStopTunneling) {
sTrame = &ssTrame[0];
// Lecture d'une trame
while ((nLon =
m_CKernel->m_cDriverOut->Read(sTrame,
(MRUOut + 150))) < 1);
// Teste si la compression est possible
nIpLen = nLon;
if (nLon > (MTUAOL - 8)) {
// nLon=Vjcompress->Compress(sTrame,nLon);
bTooBig = true;
nRestSize = nLon;
nMtu = (MTUAOL - 8);
nLon = nMtu;
}
else {
bTooBig = false;
}
bFirstTrame = true;
// Boucle en cas de trame trop longue
while (bTooBig || bFirstTrame) {
// Gere le header AOL
AolHeader->SetHeader(sBuffer);
AolHeader->SetStartByte(0x5a);
AolHeader->SetIpLen(nIpLen);
m_CKernel->m_nLastAolSeq += 1;
if (m_CKernel->m_nLastAolSeq > 0x7f)
m_CKernel->m_nLastAolSeq = 0x10;
if (!bReady)
m_CKernel->m_nLastAolSeq = m_CKernel->m_nFirstAolSeq + 1;
if (bFirstTrame)
nSeq = m_CKernel->m_nLastAolSeq;
else
nSeq += 1;
if (nSeq > 0x7f)
nSeq = 0x10;
AolHeader->SetSeq((unsigned char) m_CKernel->m_nLastAolSeq);
AolHeader->SetAck((unsigned char) m_CKernel->m_nLastAolAck);
AolHeader->SetTyp(0xa0);
if (!bTooBig || bFirstTrame) {
AolHeader->SetCode(0x7963);
AolHeader->SetNormal();
}
if (bTooBig && !bFirstTrame) {
AolHeader->SetCode(0x7964);
AolHeader->SetExtra();
}
AolHeader->SetInNum((unsigned char) m_CKernel->m_nLastAolInet++);
nSize = (AolHeader->GetPayload() - sBuffer) + nLon - 5;
AolHeader->SetTotalSize(nSize);
memcpy(AolHeader->GetPayload(), sTrame, nLon);
sBuffer[nSize + 5] = 0x0d;
// calcul le checksum
AolHeader->SetCheckSum(0);
AolHeader->CalculateChkSum();
nSendLon = nSize + 6;
if ((unsigned char) sBuffer[0] >= 0x80)
m_CKernel->m_cMsgIn->Printf("%DSend VJ Header !! \n");
m_CKernel->bIDLE = true;
m_CKernel->InputWrite(sBuffer, nSendLon);
m_CKernel->bNeedAck = true;
m_CKernel->m_nNeedSeq = m_CKernel->m_nLastAolSeq;
m_CKernel->m_nNeedAck = m_CKernel->m_nLastAolAck;
if (((nMtu < (MTUAOL - 5)) || (nRestSize == 0))
&& !bFirstTrame)
bTooBig = false;
bFirstTrame = false;
bReady = true;
if (bTooBig) {
sTrame += nMtu;
nRestSize -= nMtu;
if (nRestSize < (MTUAOL - 5)) {
nLon = nRestSize;
nMtu = nRestSize;
} else {
nLon = (MTUAOL - 5);
nMtu = nLon;
}
}
}
} // end while pricipal bStopTunneling
}
/** definition de l'appelant */
void CClientToAol30::SetHost(class Kernel30 * Kernel)
{
m_CKernel = Kernel;
}
| [
""
] | [
[
[
1,
144
]
]
] |
b84be00a3bc9ab13380b9a10249b1790ef4f9349 | f55dee0ea7c9d5ff1b48c20231bd256e8eeedbbb | /World Server/extrafunctions.cpp | 9f6ab400fe23079852402b8e6b7bfc21b6dbffda | [] | no_license | trebor57/osprose-official | e998c8625e8e96d96af02bf2f95a05d4d45021cc | afe0e7b9b32216c7d6423f964769acdc7a99f36a | refs/heads/master | 2020-04-04T19:26:22.231668 | 2010-05-16T10:58:32 | 2010-05-16T10:58:32 | 32,129,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,937 | cpp | /*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Build Item Head
unsigned CWorldServer::BuildItemHead( CItem thisitem )
{
if (thisitem.count==0) return 0;
return ( ( thisitem.itemnum & 0x7ffffff ) << 5 ) | ( thisitem.itemtype & 0x1f );
}
// Build Item Data
unsigned CWorldServer::BuildItemData( CItem thisitem )
{
if (thisitem.count==0) return 0;
if ( thisitem.itemtype >= 10 && thisitem.itemtype <= 13 )
{
return thisitem.count;
}
else
{
unsigned part1 = (thisitem.refine>>4) << 28;
unsigned part2 = (thisitem.appraised?1:0) << 27;
unsigned part3 = (thisitem.socketed?1:0) << 26;
unsigned part4 = (thisitem.lifespan*10) << 16;
unsigned part5 = thisitem.durability << 9;
unsigned part6 = thisitem.stats;
unsigned part7 = thisitem.gem;
if (!part7==0)part6=0;
return part1 | part2 | part3 | part4 | part5 | part6 | part7;
}
}
// Get Item By Head and Data (Coded by Caali)
CItem CWorldServer::GetItemByHeadAndData( unsigned head, unsigned data )
{
CItem thisitem;
//Get info from ItemHead
thisitem.itemnum = (head >> 5) & 0x7ffffff;
head ^= (thisitem.itemtype & 0x7ffffff) << 5;
thisitem.itemtype = head & 0x1f;
//Get info from ItemData
if( thisitem.itemtype >= 10 && thisitem.itemtype <= 13 ) //Stackable
{
thisitem.refine = 0;
thisitem.appraised = 0;
thisitem.socketed = 0;
thisitem.lifespan = 100;
thisitem.durability = 40;
thisitem.gem = 0;
thisitem.stats = 0;
thisitem.count = (int)data;
}
else //Non-stackable
{
thisitem.refine = (data >> 28) << 4;
data-=(thisitem.refine>>4) << 28;
thisitem.appraised = ((data >> 27)==1)?true:false;
data-=(thisitem.appraised?1:0) << 27;
thisitem.socketed = ((data >> 26)==1)?true:false;
data-=(thisitem.socketed?1:0) << 26;
thisitem.lifespan = (data >> 16) / 10;
data-=(thisitem.lifespan*10) << 16;
thisitem.durability = data >> 9;
data-=thisitem.durability << 9;
thisitem.gem = data;
data-=thisitem.gem;
thisitem.count = 1;
}
return thisitem;
}
//----Build Item Show
unsigned CWorldServer::BuildItemShow(CItem thisitem)
{
if (thisitem.gem == 0)
{
unsigned part1 = thisitem.refine*0x10000;
unsigned part2 = thisitem.itemnum;
return part2|part1;
}
else
{
unsigned part1 = thisitem.refine*0x10000;
unsigned part2 = thisitem.itemnum;
unsigned part3 = (0xd0000)+(((thisitem.gem-320)*0x400));
return part3|part2|part1;
}
}
//----Build Item refine
unsigned CWorldServer::BuildItemRefine(CItem thisitem)
{
if (thisitem.gem == 0)
return ((thisitem.refine)*256);
else
{
return (0xd00+(thisitem.gem-320)*4)+((thisitem.refine)*256);
}
}
// Send a packet too all connected clients
void CWorldServer::SendToAll( CPacket* pak )
{
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* otherclient = (CPlayer*) ClientList.at( i )->player;
if (otherclient->Session->inGame)
otherclient->client->SendPacketCpy( pak );
}
}
// Send a packet too all X who are visible
// -- CLIENT --
void CWorldServer::SendToVisible( CPacket* pak, CPlayer* thisclient, bool dothisclient )
{
for(unsigned j=0; j<thisclient->VisiblePlayers.size(); j++)
{
thisclient->VisiblePlayers.at( j )->client->SendPacketCpy( pak );
}
if(dothisclient)
thisclient->client->SendPacketCpy( pak );
}
void CWorldServer::SendToVisible( CPacket* pak, CPlayer* thisclient, CPlayer* xotherclient )
{
for(unsigned j=0; j<thisclient->VisiblePlayers.size(); j++)
{
CPlayer* otherclient = thisclient->VisiblePlayers.at( j );
if(otherclient==xotherclient)
continue;
otherclient->client->SendPacketCpy( pak );
}
}
// -- MONSTER --
void CWorldServer::SendToVisible( CPacket* pak, CMonster* thismon, CDrop* thisdrop )
{
CMap* map = MapList.Index[thismon->Position->Map];
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* otherclient = map->PlayerList.at(i);
if( IsVisible(otherclient, thismon) )
otherclient->client->SendPacketCpy( pak );
if(thisdrop!=NULL)
{
otherclient->VisibleDrops.push_back( thisdrop );
}
}
}
// -- CHARACTER --
void CWorldServer::SendToVisible( CPacket* pak, CCharacter* character, CDrop* thisdrop )
{
if(character->IsPlayer( ))
{
SendToVisible( pak, (CPlayer*)character );
}
else
if(character->IsMonster( ))
{
SendToVisible( pak, (CMonster*)character, thisdrop );
}
}
// -- DROP --
void CWorldServer::SendToVisible( CPacket* pak, CDrop* thisdrop )
{
CMap* map = MapList.Index[thisdrop->posMap];
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* otherclient = map->PlayerList.at(i);
if (otherclient->client == NULL) continue;
if (!otherclient->client->isActive) continue;
if( IsVisible(otherclient, thisdrop) )
otherclient->client->SendPacketCpy( pak );
}
}
// Send a packet too all clients on the specified map
void CWorldServer::SendToMap( CPacket* pak, int mapid )
{
CMap* map = MapList.Index[mapid];
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* otherclient = map->PlayerList.at(i);
if( otherclient->Session->inGame )
otherclient->client->SendPacketCpy( pak );
}
}
// -----------------------------------------------------------------------------------------
// Check if an object is visible to a client
// -----------------------------------------------------------------------------------------
// -- CLIENT --
bool CWorldServer::IsVisible( CPlayer* thisclient, CPlayer* otherclient )
{
for(unsigned j=0; j<thisclient->VisiblePlayers.size(); j++)
{
if (otherclient==thisclient->VisiblePlayers.at(j))
return true;
}
return false;
}
// -- MOB --
bool CWorldServer::IsVisible( CPlayer* thisclient, CMonster* thismon )
{
for(unsigned j=0; j<thisclient->VisibleMonsters.size(); j++)
{
if (thismon->clientid == thisclient->VisibleMonsters.at(j)) return true;
}
return false;
}
// -- DROP --
bool CWorldServer::IsVisible( CPlayer* thisclient, CDrop* thisdrop )
{
for(unsigned j=0; j<thisclient->VisibleDrops.size(); j++)
{
if (thisdrop == thisclient->VisibleDrops.at(j)) return true;
}
return false;
}
// -- NPC --
bool CWorldServer::IsVisible( CPlayer* thisclient, CNPC* thisnpc )
{
for(unsigned j=0; j<thisclient->VisibleNPCs.size(); j++)
{
if (thisnpc==thisclient->VisibleNPCs.at(j)) return true;
}
return false;
}
// This function gets a new clientID for a npc, monster or mob
unsigned CWorldServer::GetNewClientID( )
{
for (unsigned i=1; i<0xffff; i++)
{
if (ClientIDList[i]!=0 && time(NULL)-ClientIDList[i]>60)
{//Log( MSG_INFO, "lock id: %i",i);
ClientIDList[i] = 0;
return i;
}
}
return 0;
}
// This function will free our clientID
void CWorldServer::ClearClientID( unsigned int id )
{//Log( MSG_INFO, "free id: %i",id);
ClientIDList[id] = time(NULL);
}
// Search a drop by ID
CDrop* CWorldServer::GetDropByID( UINT id, UINT map )
{
if(map!=0)
return MapList.Index[map]->GetDropInMap( id );
for(unsigned j=0; j<MapList.Map.size(); j++)
{
CDrop* thisdrop = MapList.Map.at(j)->GetDropInMap( id );
if(thisdrop != NULL)
return thisdrop;
}
return NULL;
}
// Search a Monster by ID
CMonster* CWorldServer::GetMonsterByID( UINT id, UINT map )
{
if(map!=0)
return MapList.Index[map]->GetMonsterInMap( id );
for(UINT i=0;i<MapList.Map.size();i++)
{
CMonster* thismon = MapList.Map.at(i)->GetMonsterInMap( id );
if(thismon!=NULL)
return thismon;
}
return NULL;
}
// Search a Client by Username
CPlayer* CWorldServer::GetClientByUserName( char *username )
{
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* thisclient = (CPlayer*) ClientList.at(i)->player;
if (strcmp(thisclient->Session->username,username)==0)
return thisclient;
}
return NULL;
}
// Get Client By ID
CPlayer* CWorldServer::GetClientByID( UINT id, UINT map )
{
if(map!=0)
return MapList.Index[map]->GetPlayerInMap( id );
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* thisclient = (CPlayer*) ClientList.at(i)->player;
if (thisclient->clientid==id)
return thisclient;
}
return NULL;
}
// Search a Client by CharID
CPlayer* CWorldServer::GetClientByCID( UINT id, UINT map )
{
if(map!=0)
return MapList.Index[map]->GetCharIDInMap( id );
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* thisclient = (CPlayer*) ClientList.at(i)->player;
if (thisclient->CharInfo->charid==id)
return thisclient;
}
return NULL;
}
// Seach a client by Charname
CPlayer* CWorldServer::GetClientByCharName( char* name )
{
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* thisclient = (CPlayer*) ClientList.at(i)->player;
if (strncmp(thisclient->CharInfo->charname,name, 16)==0)
return thisclient;
}
return NULL;
}
// Get Spawn Area by ID
CSpawnArea* CWorldServer::GetSpawnArea( UINT id, UINT map )
{
if(map!=0)
{
for(unsigned j=0; j<MapList.Index[map]->MonsterSpawnList.size(); j++)
{
CSpawnArea* thisspawn = MapList.Index[map]->MonsterSpawnList.at(j);
if (thisspawn->id==id)
return thisspawn;
}
}
else
{
for(map=0;map<MapList.Map.size();map++)
{
for(unsigned j=0; j<MapList.Index[map]->MonsterSpawnList.size(); j++)
{
CSpawnArea* thisspawn = MapList.Index[map]->MonsterSpawnList.at(j);
if (thisspawn->id==id)
return thisspawn;
}
}
}
return NULL;
}
#ifdef USEIFO
CMobGroup* CWorldServer::GetMobGroup(UINT id, UINT map )
{
if (map != 0)
{
for (unsigned j = 0; j < MapList.Index[map]->MobGroupList.size(); j++)
{
CMobGroup* thisgroup = MapList.Index[map]->MobGroupList.at(j);
if (thisgroup->id == id)
return thisgroup;
}
}
else
{
for (map = 0; map < MapList.Map.size(); map++)
{
for (unsigned j = 0; j < MapList.Index[map]->MobGroupList.size(); j++)
{
CMobGroup* thisgroup = MapList.Index[map]->MobGroupList.at(j);
if (thisgroup->id == id)
return thisgroup;
}
}
}
return NULL;
}
#endif
// delete a spawn
bool CWorldServer::DeleteSpawn( CSpawnArea* spawn )
{
if(spawn==NULL)
return false;
for(UINT i=0;i<MapList.Index[spawn->map]->MonsterSpawnList.size();i++)
{
if(MapList.Index[spawn->map]->MonsterSpawnList.at(i)==spawn)
{
MapList.Index[spawn->map]->MonsterSpawnList.erase( MapList.Index[spawn->map]->MonsterSpawnList.begin()+i );
delete spawn;
return true;
}
}
return false;
}
// Search NPC by ID
CNPC* CWorldServer::GetNPCByID( UINT id, UINT map )
{
if(map!=0)
return MapList.Index[map]->GetNPCInMap( id );
for(unsigned j=0; j<MapList.Map.size(); j++)
{
CNPC* thisnpc = MapList.Map.at( j )->GetNPCInMap( id );
if (thisnpc!=0)
return thisnpc;
}
return NULL;
}
// Get Telegate by ID
CTeleGate* CWorldServer::GetTeleGateByID( unsigned int id )
{
for(unsigned j=0; j<TeleGateList.size(); j++)
{
CTeleGate* thisgate = TeleGateList.at(j);
if (thisgate->id == id) return thisgate;
}
// Hmm, shit, couldent find it
return NULL;
}
// Get Triangle Area
float CWorldServer::AreaOfTriangle( fPoint p1, fPoint p2, fPoint p3 )
{
return abs((int)((p2.x * p1.y - p1.x * p2.y) + (p3.x * p2.y - p2.x * p3.y) + (p1.x * p3.y - p2.x * p1.y))) / 2;
}
// Get a random point in triangle area
fPoint CWorldServer::RandInTriangle( fPoint p1, fPoint p2, fPoint p3 )
{
fPoint thispoint;
float a = 1.0;
float b = 1.0;
while (a+b>1) { a=(float)(rand()*1.0/RAND_MAX); b=(float)(rand()*1.0/RAND_MAX); }
float c = 1 - a - b;
thispoint.x = (p1.x*a)+(p2.x*b)+(p3.x*c);
thispoint.y = (p1.y*a)+(p2.y*b)+(p3.y*c);
return thispoint;
}
// Get random point in poly
fPoint CWorldServer::RandInPoly( fPoint p[], int pcount )
{
int tnum = 0;
float tval = 0;
float totalarea = 0;
float* areas = new float[pcount-1];
for(int i=0; i<pcount-2; i++) {
totalarea += AreaOfTriangle(p[0], p[i+1], p[i+2]);
areas[i+1] = totalarea;
}
tval = rand() * totalarea / RAND_MAX;
for (tnum=1; tnum<pcount-1; tnum++) { if(tval<=areas[tnum]&&tval>areas[tnum-1]) break; }
return RandInTriangle(p[0], p[tnum], p[tnum+1]);
}
// Get Random point in circle
fPoint CWorldServer::RandInCircle( fPoint center, float radius )
{
fPoint thispoint;
float angle = (float)(rand() * ( pi * 2 ) / RAND_MAX);
float distance = (float)sqrt( rand() * 1.0 / RAND_MAX ) * radius;
thispoint.x = cos(angle) * distance + center.x;
thispoint.y = sin(angle) * distance + center.y;
return thispoint;
}
// Check if a Monster is in a Circle around a Client with a specific range
bool CWorldServer::IsMonInCircle( CPlayer* thisclient, CMonster* thismon, float radius )
{
if ( thisclient->Position->Map!=thismon->Position->Map ) return false;
float dx = ( thisclient->Position->current.x - thismon->Position->current.x );
float dy = ( thisclient->Position->current.y - thismon->Position->current.y );
if ( sqrt( (dx * dx) + (dy * dy) ) <= radius )
{
return true;
}
else
{
return false;
}
}
// Check if a Monster is in a Circle around a point with a specific radius
bool CWorldServer::IsMonInCircle( fPoint center, fPoint position, float radius )
{
float dx = ( center.x - position.x );
float dy = ( center.y - position.y );
if ( sqrt( (dx * dx) + (dy * dy) ) <= radius )
{
return true;
}
else
{
return false;
}
}
// Check if a Player is in a Circle around a Client with a specific range
bool CWorldServer::IsPlayerInCircle( CPlayer* thisclient, CPlayer* otherclient, float radius )
{
if ( thisclient->Position->Map!=otherclient->Position->Map ) return false;
float dx = ( thisclient->Position->current.x - otherclient->Position->current.x );
float dy = ( thisclient->Position->current.y - otherclient->Position->current.y );
if ( sqrt( (dx * dx) + (dy * dy) ) <= radius )
{
return true;
}
else
{
return false;
}
}
// Search Respawn by ID
CRespawnPoint* CWorldServer::GetRespawnByID( unsigned id )
{
for(UINT i=0;i<MapList.Map.size();i++)
{
CMap* thismap = MapList.Map.at(i);
for(UINT j=0;j<thismap->RespawnList.size();j++)
{
CRespawnPoint* thisrespawn = thismap->RespawnList.at(j);
if(thisrespawn->id==id)
return thisrespawn;
}
}
return NULL;
}
// Search Respawn by Map
CRespawnPoint* CWorldServer::GetRespawnByMap( int map )
{
for(UINT j=0;j<MapList.Index[map]->RespawnList.size();j++)
{
if(MapList.Index[map]->RespawnList.at(j)->destMap==map)
return MapList.Index[map]->RespawnList.at(j);
}
return NULL;
}
// Search Skill By ID
CSkills* CWorldServer::GetSkillByID( unsigned int id )
{
unsigned int A=0,B=0,C=0;
for(A=0,B=SkillList.size()-1;A<=B;)
{
if(A==B)
{
CSkills* thisskill = (CSkills*) SkillList.at( A );
if( id = thisskill->id )// lol this function aint working correct
{
//Log(MSG_INFO,"skill returned id = %i", id );
return thisskill;
}
else
{
Log(MSG_WARNING,"SKILL NOT FOUNDED! %i", id );
return NULL;
}
}
C = (A+B)/2;
CSkills* thisskill = (CSkills*) SkillList.at( C );
if(thisskill->id == id)
{
//Log(MSG_INFO,"skill returned id = %i. C = %i", id,C );
return thisskill;
}
if(thisskill->id > id)
{
B=C-1;
}
else
{
A=C+1;
}
}
Log( MSG_WARNING,"SKILL NOT FOUNDED! %i", id );
return NULL;
}
// Search Status By ID
CStatus* CWorldServer::GetStatusByID( unsigned int id )
{
unsigned int A=0,B=0,C=0;
for(A=0,B=StatusList.size()-1;A<=B;)
{
if(A==B)
{
CStatus* thisstatus = (CStatus*) StatusList.at( A );
if( id = thisstatus->id )
return thisstatus;
else
{
Log(MSG_WARNING,"STATUS NOT FOUND! %i", id );
return NULL;
}
}
C = (A+B)/2;
CStatus* thisstatus = (CStatus*) StatusList.at( C );
if(thisstatus->id == id)
return thisstatus;
if(thisstatus->id > id)
B=C-1;
else
A=C+1;
}
Log( MSG_WARNING,"STATUS NOT FOUND! %i", id );
return NULL;
}
// Get Monster Drop By ID
CMDrops* CWorldServer::GetDropData( unsigned int id )
{
return NULL;
unsigned int A=0,B=0,C=0;
for(A=0,B=MDropList.size()-1;A<=B;)
{
if(A==B)
{
CMDrops* thismdrop = (CMDrops*) MDropList.at( A );
if( id == thismdrop->id ){return thismdrop;}
else
{
Log(MSG_WARNING,"DROP NOT FOUNDED! %i", id );
return 0;
}
}
C = (A+B)/2;
CMDrops* thismdrop = (CMDrops*) MDropList.at( C );
if(thismdrop->id == id){return thismdrop;}
if(thismdrop->id > id){B=C-1;}
else{A=C+1;}
}
Log(MSG_WARNING,"DROP NOT FOUNDED! %i", id );
return NULL;
}
// Get NPC Data by ID
CNPCData* CWorldServer::GetNPCDataByID( unsigned int id )
{
unsigned int A=0,B=0,C=0;
for(A=0,B=NPCData.size()-1;A<=B;)
{
if(A==B)
{
CNPCData* thisnpc = (CNPCData*) NPCData.at( A );
if( id == thisnpc->id ){return thisnpc;}
else
{
Log(MSG_WARNING,"NPC NOT FOUNDED! %i", id );
return 0;
}
}
C = (A+B)/2;
CNPCData* thisnpc = (CNPCData*) NPCData.at( C );
if(thisnpc->id == id){return thisnpc;}
if(thisnpc->id > id){B=C-1;}
else{A=C+1;}
}
Log(MSG_WARNING,"NPC NOT FOUNDED! %i", id );
return NULL;
}
// Get Consumible Item Info
CUseInfo* CWorldServer::GetUseItemInfo(CPlayer* thisclient, unsigned int slot )
{
if(thisclient->items[slot].count<1)
return NULL;
CUseInfo* useitem = new (nothrow) CUseInfo;
if(useitem==NULL)
{
Log(MSG_WARNING, "Error allocing memory GetUseItemInfo");
return useitem;
}
useitem->itemnum = 0;
useitem->itemtype = 0;
useitem->usescript = 0;
useitem->usetype = 0;
useitem->usevalue = 0;
unsigned int type = 0;
useitem->itemnum = thisclient->items[slot].itemnum;
useitem->itemtype = thisclient->items[slot].itemtype;
type = UseList.Index[useitem->itemnum]->type;
switch(type)
{
case 311://Medicine
case 312://Food
{
useitem->usescript = 1;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[0];
useitem->usevalue = UseList.Index[useitem->itemnum]->useeffect[1];
}
break;
case 313://Magic Item [scrolls/summons/fireworks/etc]
{
// scrolls [maxhp,attackpower up, ... ]
if((useitem->itemnum >= 301 && useitem->itemnum <= 323)|| (useitem->itemnum >= 961 && useitem->itemnum <= 964) ||(useitem->itemnum >= 331 && useitem->itemnum <= 340))
{
useitem->usescript = 7;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
useitem->usevalue = 0;
}
else//Return Scrolls
if(useitem->itemnum > 349 && useitem->itemnum < 367)
{
if( thisclient->Stats->MP < 33 ){delete useitem;}
thisclient->Stats->MP -= 32;
useitem->usescript = 2;
switch( useitem->itemnum )
{
//Adventure plain [credits to tomiz]
case 350:
useitem->usetype = 22;
useitem->usevalue = 51105310;
break;
//Zant
case 351:
useitem->usetype = 1;
useitem->usevalue = 52405192;
break;
//Junon
case 352:
useitem->usetype = 2;
useitem->usevalue = 55095283;
break;
//Eucar
case 353:
useitem->usetype = 51;
useitem->usevalue = 53665099;
break;
//Xita
case 354:
useitem->usetype = 61;
useitem->usevalue = 54344607;
break;
//Goblin cave
case 360:
useitem->usetype = 31;
useitem->usevalue = 55185444;
break;
//Desert of dead
case 361:
useitem->usetype = 29;
useitem->usevalue = 50825013;
break;
//El Verloon
case 362:
useitem->usetype = 24;
useitem->usevalue = 55275377;
break;
//George of Silence
case 363:
useitem->usetype = 28;
useitem->usevalue = 54674783;
break;
//Shady Jungle
case 364:
useitem->usetype = 62;
useitem->usevalue = 57515196;
break;
//Sunshine Beach
case 366:
useitem->usetype = 37;
useitem->usevalue = 50055382;
break;
}
}
else //Charm Scrolls
if( (useitem->itemnum>380 && useitem->itemnum<384) )
{
useitem->usescript = 3;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
thisclient->CharInfo->stamina -= 5000;
}
else //Dance Scroll
if( (useitem->itemnum>370 && useitem->itemnum<377) ||
(useitem->itemnum>389 && useitem->itemnum<398) )
{
useitem->usescript = 12; // should not be treated the same as firecrackers. this is a skill
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
}
else // Firecrackers
if( useitem->itemnum == 913 || (useitem->itemnum >= 921 && useitem->itemnum <= 929) ||
(useitem->itemnum >= 991 && useitem->itemnum <= 995) )
{
useitem->usescript = 13;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
//useitem->usevalue = UseList.Index[useitem->itemnum]->useeffect[1];
}
else // Emotions
if( (useitem->itemnum>970 && useitem->itemnum<979) )
{
useitem->usescript = 4;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[0];
useitem->usevalue = UseList.Index[useitem->itemnum]->useeffect[1];
}
else // Summons
if(useitem->itemnum > 400 && useitem->itemnum < 440)
{
if( thisclient->CharInfo->stamina < 100 )
return NULL;
thisclient->CharInfo->stamina -= 100;
useitem->usescript = 5;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
CSkills* skill = GetSkillByID(useitem->usetype);
if(skill == NULL)
{
Log(MSG_INFO,"Useitem returnd a NULL skill");
return NULL;
}
useitem->usevalue = skill->svalue1;
}
else // Summons 2. Special summons such as goodie bags
if(useitem->itemnum > 908 && useitem->itemnum < 918)
{
if( thisclient->CharInfo->stamina < 100 )
return NULL;
thisclient->CharInfo->stamina -= 100;
useitem->usescript = 5; // testing at 11 for a bit. Gives no owner to the summons.
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[1];
CSkills* skill = GetSkillByID(useitem->usetype);
if(skill == NULL)
{
Log(MSG_INFO,"Useitem returnd a NULL skill");
return NULL;
}
useitem->usevalue = skill->svalue1;
}
else // Snowball
if( useitem->itemnum == 326 )
{
useitem->usescript = 6;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[0];
useitem->usevalue = UseList.Index[useitem->itemnum]->useeffect[1];
}
else
{
Log( MSG_WARNING, "Unknown Item %i - Type %i",useitem->itemnum,type);
delete useitem;
return NULL;
}
}
break;
case 314://Skill Book
{
useitem->usescript = 10;
useitem->usetype = UseList.Index[useitem->itemnum]->useeffect[0];
useitem->usevalue = UseList.Index[useitem->itemnum]->useeffect[1];
}
break;
case 315://Repair Tool
delete useitem;
return NULL;
break;
case 316://Quest Scroll
delete useitem;
return NULL;
break;
case 317://Engine Fuel
delete useitem;
return NULL;
break;
case 320://Automatic Consumption
delete useitem;
return NULL;
break;
case 321://Time Coupon / shop coupon / storage expansion coupon
switch( useitem->itemnum )
{
case 954: //shop coupon A
{
delete useitem;
thisclient->Shop->ShopType = 1;
}
case 955: //shop coupon B
{
delete useitem;
thisclient->Shop->ShopType = 2;
}
case 956: //shop coupon C
{
delete useitem;
thisclient->Shop->ShopType = 3;
}
}
return NULL;
break;
default:
Log( MSG_WARNING, "Unknown use item type: %i",type);
return NULL;
break;
}
useitem->itemtype -= 1;
return useitem;
}
// Look if a skill target is friendly
bool CWorldServer::isSkillTargetFriendly( CSkills* thisskill )
{
switch(thisskill->target)
{ //Non-Hostile Target
case tYourself://yourself
case tPartyMember://party member
case tClanMember://clan member
case tAlly://ally
case tAllMembers://all members
case tAllCharacters: // All characters
case tFaintedAlly://Fainted
return true;
break; //Hostile Target
case tMonster: //monster
case tHostileCharacter: //hostile character
case tHostileTeamMember: //hostile team member
case tHostileMonster: //hostile monster
return false;
break;
default:
Log(MSG_WARNING,"Unknown skill target %i. Skill id = %i", thisskill->target, thisskill->id);
break;
}
return false;
}
// calc distance
float CWorldServer::distance( fPoint pos1, fPoint pos2 )
{
float distance = 0;
float dx = pos1.x - pos2.x;
float dy = pos1.y - pos2.y;
distance = sqrt( (dx*dx) + (dy*dy) );
return distance;
}
// Search client by userid
CPlayer* CWorldServer::GetClientByUserID( UINT userid )
{
for(UINT i=0;i<ClientList.size();i++)
{
CPlayer* thisclient = (CPlayer*)ClientList.at(i)->player;
if(thisclient->Session->userid==userid)
return thisclient;
};
return NULL;
}
// Check if a slot is valid (to prevent crash)
bool CWorldServer::CheckInventorySlot( CPlayer* thisclient, int slot )
{
if(slot>=MAX_INVENTORY || slot<0)
{
Log(MSG_HACK, "Invalid Inventory slot %i from %s", slot, thisclient->Session->username );
return false;
}
return true;
}
// Return a pseudo random number
UINT CWorldServer::RandNumber( UINT init, UINT range, UINT seed )
{
if(seed!=0)
srand(seed);
if(range>RAND_MAX)
{
UINT max = (UINT)GServer->round(sqrt((double)range));
UINT num1 = init+int(max*rand()/(RAND_MAX + 1.0));
UINT num2 = init+int(max*rand()/(RAND_MAX + 1.0));
UINT num3 = init+int(max*rand()/(RAND_MAX + 1.0));
UINT res = (num1 * num2)+num3;
return res>range?range:res;
}
else
{
UINT ranum = init+int(range*rand()/(RAND_MAX + 1.0));
return ranum;
}
}
// Check if is a valid item
bool CWorldServer::IsValidItem(UINT type, UINT id )
{
if(type==0 || id==0 )
return false;
if(type<10)
{
if(id>4999)
return false;
if(EquipList[type].Index[id]->id==0)
return false;
}
else
{
switch(type)
{
case 10:
if(id>1999)
return false;
if(UseList.Index[id]->id==0)
return false;
break;
case 11:
if(id>3999)
return false;
if(JemList.Index[id]->id==0)
return false;
break;
case 12:
if(id>999)
return false;
if(NaturalList.Index[id]->id==00)
return false;
break;
case 14:
if(id>999)
return false;
if(PatList.Index[id]->id==00)
return false;
break;
default:
return false;
}
}
return true;
}
int CWorldServer::GetIntValue( const char* s , void* var )
{
char *tmp = strtok( (char*)var, (const char*)s );
return atoi(tmp==NULL?0:tmp);
}
UINT CWorldServer::GetUIntValue( const char* s , void* var )
{
char *tmp = strtok( (char*)var, (const char*)s );
return atoi(tmp==NULL?0:tmp);
}
char* CWorldServer::GetStrValue( const char* s , void* var )
{
char *tmp = strtok( (char*)var, (const char*)s );
return tmp;
}
bool CWorldServer::AddParty( CParty* thisparty )
{
PartyList.push_back( thisparty );
return true;
}
bool CWorldServer::RemoveParty( CParty* thisparty )
{
for(UINT i=0;i<PartyList.size( );i++)
{
if(PartyList.at(i)==thisparty)
{
PartyList.erase(PartyList.begin( )+i );
return true;
}
}
return false;
}
// return fairy range for waiting time random
UINT CWorldServer::GetFairyRange( UINT part )
{
UINT Range1[] = { 5, 5, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
UINT Range2[] = { 10, 7, 7, 6, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 };
if (part == 0) return Range1[GServer->FairyList.size()];
if (part == 1) return Range2[GServer->FairyList.size()];
}
| [
"lmameps@3c0ee055-4d62-4915-5d54-7a338cdfeaf6"
] | [
[
[
1,
1115
]
]
] |
71bdb913b65b26a4310940bcfb4798f45d14ac12 | 51b4a73188ea00537dfd6ca3e757707cb45c5478 | /scripts/CRFpp/featureGenerator/mapper.h | 98f039b9b4cf333c9f6f39b5b5b62f667c4844c3 | [] | no_license | kanei/MoTag | 212c78990a09743138c0d18900d96780f970faf2 | 1226930de4734c14d7c51d2103429a5e5e08a2fb | refs/heads/master | 2016-09-05T21:46:11.883733 | 2011-06-15T17:23:10 | 2011-06-15T17:23:10 | 591,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | h | #ifndef Mapper_H
#define Mapper_H
#include <fstream>
#include <map>
#include <vector>
#include <iostream>
/*
* Objekt implementujici mapovani retezcu na cisla a zpet
*
*/
using namespace std;
class Mapper
{
private:
static bool instanceFlag; //singleton
static Mapper *single; //ziskani ukazatele na objekt
Mapper();
unsigned lastId;
map <string,unsigned> dict; //slovnik pro prevod ze stringu na unsigned
vector <string> undict; //pro prevod z unsigned na string
public:
Mapper* getInstance();
~Mapper();
unsigned nothing; //vrati identifikator pro nic
unsigned strToUns(string* input); //vrati identifikator pro dany retezec
string* unsToStr(unsigned input); //vrati retezec prirazeny k danemu identifikatoru a nebo NULL
};
#endif // Mapper_H
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
45f72377e15b749dfc3163ac3ad4f75e0be825ce | 68127d36b179fd5548a1e593e2c20791db6b48e3 | /programacaoC/a31-01.cpp | 789b1c6c16d9c7092208bdc2eebd733238052062 | [] | no_license | renatomb/engComp | fa50b962dbdf4f9387fd02a28b3dc130b683ed02 | b533c876b50427d44cfdb92c507a6e74b1b7fa79 | refs/heads/master | 2020-04-11T06:22:05.209022 | 2006-04-26T13:40:08 | 2018-12-13T04:25:08 | 161,578,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | #include <iostream.h>
int quadrado(int num);
void main() {
int num1=0,num2=0;
cout << "\nEntre com o primeiro e o segundo numeros: ";
cin >> num1 >> num2;
cout << "\nA soma do quadrado desses numeros eh: " << (quadrado(num1)+quadrado(num2));
}
int quadrado(int num){
return num*num;
}
| [
"[email protected]"
] | [
[
[
1,
14
]
]
] |
fe201ed2cf96d98dd93f95441904e14a9414885d | e2f961659b90ff605798134a0a512f9008c1575b | /Example-09/MODEL_INIT.INC | 54eef78b73acccab316361ae22f498e1679a0e01 | [] | 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 | 151 | inc | EQUIL
2200 240 2424 1* 2200 1* 1* 1* 1*
/
PBVD
2300 191
2500 191
/
| [
"[email protected]"
] | [
[
[
1,
7
]
]
] |
41c6cfcaef095c6dd3cb83450f65a140fabd6912 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/validators/datatype/AnySimpleTypeDatatypeValidator.hpp | 73a100034a17f844778ab245ee0538416676fd74 | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,066 | hpp | /*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: AnySimpleTypeDatatypeValidator.hpp,v 1.12 2004/09/08 13:56:52 peiyongz Exp $
*/
#if !defined(ANYSIMPLETYPEDATATYPEVALIDATOR_HPP)
#define ANYSIMPLETYPEDATATYPEVALIDATOR_HPP
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class VALIDATORS_EXPORT AnySimpleTypeDatatypeValidator : public DatatypeValidator
{
public:
// -----------------------------------------------------------------------
// Public Constructor
// -----------------------------------------------------------------------
/** @name Constructor */
//@{
AnySimpleTypeDatatypeValidator
(
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@}
// -----------------------------------------------------------------------
// Public Destructor
// -----------------------------------------------------------------------
/** @name Destructor. */
//@{
virtual ~AnySimpleTypeDatatypeValidator();
//@}
virtual const RefArrayVectorOf<XMLCh>* getEnumString() const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter Functions */
//@{
/**
* Returns whether the type is atomic or not
*/
virtual bool isAtomic() const;
//@}
// -----------------------------------------------------------------------
// Validation methods
// -----------------------------------------------------------------------
/** @name Validation Function */
//@{
/**
* Checks that the "content" string is valid datatype.
* If invalid, a Datatype validation exception is thrown.
*
* @param content A string containing the content to be validated
*
*/
virtual void validate
(
const XMLCh* const content
, ValidationContext* const context = 0
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
/**
* Checks whether a given type can be used as a substitute
*
* @param toCheck A datatype validator of the type to be used as a
* substitute
*
*/
bool isSubstitutableBy(const DatatypeValidator* const toCheck);
//@}
// -----------------------------------------------------------------------
// Compare methods
// -----------------------------------------------------------------------
/** @name Compare Function */
//@{
/**
* Compares content in the Domain value vs. lexical value.
*
* @param value1 string to compare
*
* @param value2 string to compare
*
*/
int compare(const XMLCh* const value1, const XMLCh* const value2
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@}
/**
* Returns an instance of the base datatype validator class
* Used by the DatatypeValidatorFactory.
*/
virtual DatatypeValidator* newInstance
(
RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const int finalSet
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(AnySimpleTypeDatatypeValidator)
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
AnySimpleTypeDatatypeValidator(const AnySimpleTypeDatatypeValidator&);
AnySimpleTypeDatatypeValidator& operator=(const AnySimpleTypeDatatypeValidator&);
};
// ---------------------------------------------------------------------------
// DatatypeValidator: Getters
// ---------------------------------------------------------------------------
inline bool AnySimpleTypeDatatypeValidator::isAtomic() const {
return false;
}
// ---------------------------------------------------------------------------
// DatatypeValidators: Compare methods
// ---------------------------------------------------------------------------
inline int AnySimpleTypeDatatypeValidator::compare(const XMLCh* const,
const XMLCh* const
, MemoryManager* const)
{
return -1;
}
// ---------------------------------------------------------------------------
// DatatypeValidators: Validation methods
// ---------------------------------------------------------------------------
inline bool
AnySimpleTypeDatatypeValidator::isSubstitutableBy(const DatatypeValidator* const)
{
return true;
}
inline void
AnySimpleTypeDatatypeValidator::validate(const XMLCh* const
, ValidationContext* const
, MemoryManager* const)
{
return;
}
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file AnySimpleTypeDatatypeValidator.hpp
*/
| [
"[email protected]"
] | [
[
[
1,
190
]
]
] |
b3c6eecf4be20afa3e500a9d94be4410b41506a3 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Renderer/D3D9Effect.cpp | 195f5b5cec1ef578b7e51b7a5cc4a8509ce412c5 | [] | no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,237 | cpp | #include "D3D9Effect.h"
#include "D3D9RenderWindow.h"
#include "D3D9Texture.h"
#include "D3D9VolumeTexture.h"
#include "D3D9CubeTexture.h"
#include "D3D9RenderTexture.h"
#include "D3D9RenderCubeTexture.h"
namespace Flagship
{
extern HINSTANCE g_hInstance;
D3D9Effect::D3D9Effect()
{
m_iClassType = Base::Resource_Effect;
m_pD3D9Effect = NULL;
}
D3D9Effect::~D3D9Effect()
{
SAFE_RELEASE( m_pD3D9Effect );
}
bool D3D9Effect::Cache()
{
if ( ! Effect::Cache() )
{
return false;
}
CreateFromMemory();
m_bReady = true;
return true;
}
void D3D9Effect::UnCache()
{
Effect::UnCache();
m_mParamHandleMap.clear();
m_mTechHandleMap.clear();
SAFE_RELEASE( m_pD3D9Effect );
}
bool D3D9Effect::CreateFromMemory()
{
// 获取D3D9设备指针
LPD3DXBUFFER pErrer;
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
HRESULT hr = D3DXCreateEffect( pD3D9Device, m_kFileBuffer.GetPointer(), m_kFileBuffer.GetSize()
, NULL, NULL, 0, NULL, &m_pD3D9Effect, &pErrer );
if ( FAILED( hr ) )
{
char szLog[10240];
char szFile[256];
wcstombs( szFile, GetKey().GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::CreateEffect() Fail! File:%s, %s", szFile, (char *)pErrer->GetBufferPointer() );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
void D3D9Effect::AddParamHandle( BYTE byType, Key& szName )
{
D3DXHANDLE hHandle;
char szTemp[256];
wcstombs( szTemp, szName.GetName().c_str(), 256 );
if ( byType == Param_Technique )
{
hHandle = m_pD3D9Effect->GetTechniqueByName( szTemp );
m_mTechHandleMap[ szName ] = hHandle;
}
else
{
hHandle = m_pD3D9Effect->GetParameterByName( NULL, szTemp );
m_mParamHandleMap[ szName ] = hHandle;
}
}
bool D3D9Effect::SetValue( Key& szParam, void * pValue, UINT uiSize )
{
HRESULT hr = m_pD3D9Effect->SetValue( m_mParamHandleMap[szParam], pValue, uiSize );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetValue() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetInt( Key& szParam, int * piValue )
{
HRESULT hr = m_pD3D9Effect->SetInt( m_mParamHandleMap[szParam], *piValue );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetInt() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetFloat( Key& szParam, float * pfValue )
{
HRESULT hr = m_pD3D9Effect->SetFloat( m_mParamHandleMap[szParam], *pfValue );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetFloat() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetVector( Key& szParam, Vector4f * pvValue )
{
D3DXVECTOR4 vVector( (*pvValue)[0], (*pvValue)[1], (*pvValue)[2], (*pvValue)[3] );
HRESULT hr = m_pD3D9Effect->SetVector( m_mParamHandleMap[szParam], &vVector );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetVector() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetVectorArray( Key& szParam, Vector4f * pvValue, UINT uiNum )
{
D3DXVECTOR4 * pvVector;
pvVector = new D3DXVECTOR4[uiNum];
for ( UINT i = 0; i < uiNum; i++ )
{
pvVector[i] = D3DXVECTOR4( (pvValue[i])[0], (pvValue[i])[1], (pvValue[i])[2], (pvValue[i])[3] );
}
HRESULT hr = m_pD3D9Effect->SetVectorArray( m_mParamHandleMap[szParam], pvVector, uiNum );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetVectorArray() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
SAFE_DELETE_ARRAY( pvVector );
return true;
}
bool D3D9Effect::SetMatrix( Key& szParam, Matrix4f * pmatValue )
{
Matrix4f matTemp = pmatValue->Transpose();
D3DXMATRIX matMatrix( matTemp[0][0], matTemp[0][1], matTemp[0][2], matTemp[0][3],
matTemp[1][0], matTemp[1][1], matTemp[1][2], matTemp[1][3],
matTemp[2][0], matTemp[2][1], matTemp[2][2], matTemp[2][3],
matTemp[3][0], matTemp[3][1], matTemp[3][2], matTemp[3][3] );
HRESULT hr = m_pD3D9Effect->SetMatrix( m_mParamHandleMap[szParam], &matMatrix );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetMatrix() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetMatrixArray( Key& szParam, Matrix4f * pmatValue, UINT uiNum )
{
D3DXMATRIX * pmatMatrix;
pmatMatrix = new D3DXMATRIX[uiNum];
for ( UINT i = 0; i < uiNum; i++ )
{
Matrix4f matTemp = pmatValue[i].Transpose();
pmatMatrix[i] = D3DXMATRIX( matTemp[0][0], matTemp[0][1], matTemp[0][2], matTemp[0][3],
matTemp[1][0], matTemp[1][1], matTemp[1][2], matTemp[1][3],
matTemp[2][0], matTemp[2][1], matTemp[2][2], matTemp[2][3],
matTemp[3][0], matTemp[3][1], matTemp[3][2], matTemp[3][3] );
}
HRESULT hr = m_pD3D9Effect->SetMatrixArray( m_mParamHandleMap[szParam], pmatMatrix, uiNum );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetMatrixArray() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
SAFE_DELETE_ARRAY( pmatMatrix );
return true;
}
bool D3D9Effect::SetTexture( Key& szParam, Texture * pTexture )
{
HRESULT hr;
int iTextureType = pTexture->GetClassType();
switch ( iTextureType )
{
case Base::Texture_General:
{
LPDIRECT3DTEXTURE9 pD3D9Texture = ( (D3D9Texture *) pTexture )->GetImpliment();
hr = m_pD3D9Effect->SetTexture( m_mParamHandleMap[szParam], pD3D9Texture );
break;
}
case Base::Texture_Volume:
{
LPDIRECT3DVOLUMETEXTURE9 pD3D9Texture = ( (D3D9VolumeTexture *) pTexture )->GetImpliment();
hr = m_pD3D9Effect->SetTexture( m_mParamHandleMap[szParam], pD3D9Texture );
break;
}
case Base::Texture_Cube:
{
LPDIRECT3DCUBETEXTURE9 pD3D9Texture = ( (D3D9CubeTexture *) pTexture )->GetImpliment();
hr = m_pD3D9Effect->SetTexture( m_mParamHandleMap[szParam], pD3D9Texture );
break;
}
}
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetTexture() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::SetTechnique( Key& szParam )
{
HRESULT hr = m_pD3D9Effect->SetTechnique( m_mTechHandleMap[szParam] );
if ( FAILED( hr ) )
{
char szLog[10240];
char szTemp[256];
wcstombs( szTemp, szParam.GetName().c_str(), 256 );
sprintf( szLog, "D3D9Effect::SetTechnique() Fail! Param:%s", szTemp );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::Begin( UINT * uiPassNum )
{
HRESULT hr = m_pD3D9Effect->Begin( uiPassNum, 0 );
if ( FAILED( hr ) )
{
char szLog[10240];
sprintf( szLog, "D3D9Effect::Begin() Fail!" );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::End()
{
HRESULT hr = m_pD3D9Effect->End();
if ( FAILED( hr ) )
{
char szLog[10240];
sprintf( szLog, "D3D9Effect::End() Fail!" );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::BeginPass( UINT uiPass )
{
HRESULT hr = m_pD3D9Effect->BeginPass( uiPass );
if ( FAILED( hr ) )
{
char szLog[10240];
sprintf( szLog, "D3D9Effect::BeginPass() Fail!" );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9Effect::EndPass()
{
HRESULT hr = m_pD3D9Effect->EndPass();
if ( FAILED( hr ) )
{
char szLog[10240];
sprintf( szLog, "D3D9Effect::EndPass() Fail!" );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
} | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
369
]
]
] |
dc19ae44b3cb18ee51748734da9bb914a4fc0aed | fbd2deaa66c52fc8c38baa90dd8f662aabf1f0dd | /totalFirePower/ta demo/code/Object.cpp | 239bc3b019b95f177e64009ce89cc96d9cde468c | [] | no_license | arlukin/dev | ea4f62f3a2f95e1bd451fb446409ab33e5c0d6e1 | b71fa9e9d8953e33f25c2ae7e5b3c8e0defd18e0 | refs/heads/master | 2021-01-15T11:29:03.247836 | 2011-02-24T23:27:03 | 2011-02-24T23:27:03 | 1,408,455 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cpp | // Object.cpp: implementation of the CObject class.
//
//////////////////////////////////////////////////////////////////////
#include "Object.h"
#include <windows.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CObject::~CObject()
{
std::list<CObject*>::iterator di;
for(di=listeners.begin();di!=listeners.end();di++){
(*di)->DependentDied(this);
(*di)->listening.remove(this);
}
for(di=listening.begin();di!=listening.end();di++){
(*di)->listeners.remove(this);
}
}
CObject::DependentDied(CObject* o)
{
// MessageBox(0,"wrong","ag",0);
}
void CObject::AddDeathDependence(CObject *o)
{
o->listeners.push_back(this);
listening.push_back(o);
}
void CObject::DeleteDeathDependence(CObject *o)
{
std::list<CObject*>::iterator di;
for(di=listening.begin();di!=listening.end();di++){
if((*di)==o){
listening.erase(di);
break;
}
}
for(di=o->listeners.begin();di!=o->listeners.end();di++){
if((*di)==this){
o->listeners.erase(di);
break;
}
}
}
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
400284ba6b9d00caaf42d118b2c3b4410f5c4493 | a9afa168fac234c3b838dd29af4a5966a6acb328 | /CppUTest/src/CppUTest/MemoryLeakDetector.cpp | 7834e291a8bb1cfa11fd1c7261f76bc8c4528b32 | [] | no_license | unclebob/tddrefcpp | 38a4170c38f612c180a8b9e5bdb2ec9f8971832e | 9124a6fad27349911658606392ba5730ff0d1e15 | refs/heads/master | 2021-01-25T07:34:57.626817 | 2010-05-10T20:01:39 | 2010-05-10T20:01:39 | 659,579 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 13,173 | cpp | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/MemoryLeakAllocator.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#define UNKNOWN ((char*)("<unknown>"))
SimpleStringBuffer::SimpleStringBuffer() :
positions_filled(0)
{
}
;
void SimpleStringBuffer::clear()
{
positions_filled = 0;
buffer[0] = '\0';
}
void SimpleStringBuffer::add(const char* format, ...)
{
int count = 0;
va_list arguments;
va_start(arguments, format);
count = PlatformSpecificVSNprintf(buffer + positions_filled,
SIMPLE_STRING_BUFFER_LEN - positions_filled, format, arguments);
if (count > 0) positions_filled += count;
va_end(arguments);
}
char* SimpleStringBuffer::toString()
{
return buffer;
}
///////////////////////
void MemoryLeakDetectorList::initNode(MemoryLeakDetectorNode* node,
MemoryLeakAllocator* allocator, size_t size, char* memory,
MemLeakPeriod period, const char* file, int line)
{
if (node) {
node->size = size;
node->memory = memory;
node->period = period;
node->file = file;
node->line = line;
node->allocator = allocator;
}
}
bool MemoryLeakDetectorList::isInPeriod(MemoryLeakDetectorNode* node,
MemLeakPeriod period)
{
return period == mem_leak_period_all || node->period == period
|| (node->period != mem_leak_period_disabled && period
== mem_leak_period_enabled);
}
void MemoryLeakDetectorList::clearAllAccounting(MemLeakPeriod period)
{
MemoryLeakDetectorNode* cur = head;
MemoryLeakDetectorNode* prev = 0;
while (cur) {
if (isInPeriod(cur, period)) {
if (prev) {
prev->next = cur->next;
cur = prev;
}
else {
head = cur->next;
cur = head;
continue;
}
}
prev = cur;
cur = cur->next;
}
}
void MemoryLeakDetectorList::addNewNode(MemoryLeakDetectorNode* node)
{
node->next = head;
head = node;
}
MemoryLeakDetectorNode* MemoryLeakDetectorList::removeNode(char* memory)
{
MemoryLeakDetectorNode* cur = head;
MemoryLeakDetectorNode* prev = 0;
while (cur) {
if (cur->memory == memory) {
if (prev) {
prev->next = cur->next;
return cur;
}
else {
head = cur->next;
return cur;
}
}
prev = cur;
cur = cur->next;
}
return 0;
}
MemoryLeakDetectorNode* MemoryLeakDetectorList::getLeakFrom(
MemoryLeakDetectorNode* node, MemLeakPeriod period)
{
for (MemoryLeakDetectorNode* cur = node; cur; cur = cur->next)
if (isInPeriod(cur, period)) return cur;
return 0;
}
MemoryLeakDetectorNode* MemoryLeakDetectorList::getFirstLeak(
MemLeakPeriod period)
{
return getLeakFrom(head, period);
}
MemoryLeakDetectorNode* MemoryLeakDetectorList::getNextLeak(
MemoryLeakDetectorNode* node, MemLeakPeriod period)
{
return getLeakFrom(node->next, period);
}
int MemoryLeakDetectorList::getTotalLeaks(MemLeakPeriod period)
{
int total_leaks = 0;
for (MemoryLeakDetectorNode* node = head; node; node = node->next) {
if (isInPeriod(node, period)) total_leaks++;
}
return total_leaks;
}
bool MemoryLeakDetectorList::hasLeaks(MemLeakPeriod period)
{
for (MemoryLeakDetectorNode* node = head; node; node = node->next)
if (isInPeriod(node, period)) return true;
return false;
}
/////////////////////////////////////////////////////////////
int MemoryLeakDetectorTable::hash(char* memory)
{
return ((size_t) memory) % hash_prime;
}
void MemoryLeakDetectorTable::clearAllAccounting(MemLeakPeriod period)
{
for (int i = 0; i < hash_prime; i++)
table[i].clearAllAccounting(period);
}
void MemoryLeakDetectorTable::addNewNode(MemoryLeakDetectorNode* node)
{
table[hash(node->memory)].addNewNode(node);
}
MemoryLeakDetectorNode* MemoryLeakDetectorTable::removeNode(char* memory)
{
return table[hash(memory)].removeNode(memory);
}
bool MemoryLeakDetectorTable::hasLeaks(MemLeakPeriod period)
{
for (int i = 0; i < hash_prime; i++)
if (table[i].hasLeaks(period)) return true;
return false;
}
int MemoryLeakDetectorTable::getTotalLeaks(MemLeakPeriod period)
{
int total_leaks = 0;
for (int i = 0; i < hash_prime; i++)
total_leaks += table[i].getTotalLeaks(period);
return total_leaks;
}
MemoryLeakDetectorNode* MemoryLeakDetectorTable::getFirstLeak(
MemLeakPeriod period)
{
for (int i = 0; i < hash_prime; i++) {
MemoryLeakDetectorNode* node = table[i].getFirstLeak(period);
if (node) return node;
}
return 0;
}
MemoryLeakDetectorNode* MemoryLeakDetectorTable::getNextLeak(
MemoryLeakDetectorNode* leak, MemLeakPeriod period)
{
int i = hash(leak->memory);
MemoryLeakDetectorNode* node = table[i].getNextLeak(leak, period);
if (node) return node;
for (++i; i < hash_prime; i++) {
node = table[i].getFirstLeak(period);
if (node) return node;
}
return 0;
}
/////////////////////////////////////////////////////////////
MemoryLeakDetector::MemoryLeakDetector()
{
}
void MemoryLeakDetector::init(MemoryLeakFailure* report)
{
doAllocationTypeChecking = true;
current_period = mem_leak_period_disabled;
reporter = report;
output_buffer = SimpleStringBuffer();
memoryTable = MemoryLeakDetectorTable();
}
void MemoryLeakDetector::clearAllAccounting(MemLeakPeriod period)
{
memoryTable.clearAllAccounting(period);
}
void MemoryLeakDetector::startChecking()
{
output_buffer.clear();
current_period = mem_leak_period_checking;
}
void MemoryLeakDetector::stopChecking()
{
current_period = mem_leak_period_enabled;
}
void MemoryLeakDetector::enable()
{
current_period = mem_leak_period_enabled;
}
void MemoryLeakDetector::disable()
{
current_period = mem_leak_period_disabled;
}
void MemoryLeakDetector::disableAllocationTypeChecking()
{
doAllocationTypeChecking = false;
}
void MemoryLeakDetector::enableAllocationTypeChecking()
{
doAllocationTypeChecking = true;
}
void MemoryLeakDetector::reportFailure(const char* message,
const char* allocFile, int allocLine, size_t allocSize,
MemoryLeakAllocator* allocAllocator, const char* freeFile,
int freeLine, MemoryLeakAllocator* freeAllocator)
{
output_buffer.add(message);
output_buffer.add(MEM_LEAK_ALLOC_LOCATION, allocFile, allocLine, allocSize,
allocAllocator->alloc_name());
output_buffer.add(MEM_LEAK_DEALLOC_LOCATION, freeFile, freeLine,
freeAllocator->free_name());
reporter->fail(output_buffer.toString());
}
int calculateIntAlignedSize(size_t size)
{
return (sizeof(int) - (size % sizeof(int))) + size;
}
MemoryLeakDetectorNode* MemoryLeakDetector::getNodeFromMemoryPointer(
char* memory, size_t memory_size)
{
return (MemoryLeakDetectorNode*) (memory + calculateIntAlignedSize(
memory_size + memory_corruption_buffer_size));
}
char* MemoryLeakDetector::allocateMemoryAndExtraInfo(
MemoryLeakAllocator* allocator, size_t size)
{
return allocator->alloc_memory(calculateIntAlignedSize(size
+ memory_corruption_buffer_size) + memory_corruption_buffer_size
+ sizeof(MemoryLeakDetectorNode));
}
char* MemoryLeakDetector::reallocateMemoryAndExtraInfo(char* memory,
size_t size)
{
return (char*) PlatformSpecificRealloc(memory, calculateIntAlignedSize(size
+ memory_corruption_buffer_size) + sizeof(MemoryLeakDetectorNode));
}
void MemoryLeakDetector::addMemoryCorruptionInformation(char* memory,
size_t size)
{
memory[size] = 'B';
memory[size + 1] = 'A';
memory[size + 2] = 'S';
}
void MemoryLeakDetector::checkForAllocMismatchOrCorruption(
MemoryLeakDetectorNode* node, const char* file, int line,
MemoryLeakAllocator* allocator)
{
if (node->allocator != allocator && doAllocationTypeChecking) {
if (!allocator->isOfEqualType(node->allocator)) reportFailure(
MEM_LEAK_ALLOC_DEALLOC_MISMATCH, node->file, node->line,
node->size, node->allocator, file, line, allocator);
}
else if (node->memory[node->size] != 'B' || node->memory[node->size + 1]
!= 'A' || node->memory[node->size + 2] != 'S') reportFailure(
MEM_LEAK_MEMORY_CORRUPTION, node->file, node->line, node->size,
node->allocator, file, line, allocator);
}
void MemoryLeakDetector::addMemoryLeakInfoAndCorruptionInfo(char* memory,
size_t size, const char* file, int line, MemoryLeakAllocator* allocator)
{
addMemoryCorruptionInformation(memory, size);
if (memory) {
MemoryLeakDetectorNode* node = getNodeFromMemoryPointer(memory, size);
MemoryLeakDetectorList::initNode(node, allocator, size, memory,
current_period, file, line);
memoryTable.addNewNode(node);
}
}
bool MemoryLeakDetector::removeMemoryLeakInfoAndCheckCorruption(char* memory,
const char* file, int line, MemoryLeakAllocator* allocator)
{
MemoryLeakDetectorNode* node = memoryTable.removeNode(memory);
if (node) {
checkForAllocMismatchOrCorruption(node, file, line, allocator);
return true;
}
reportFailure(MEM_LEAK_DEALLOC_NON_ALLOCATED, "<unknown>", 0, 0,
NullUnknownAllocator::defaultAllocator(), file, line, allocator);
return false;
}
char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator,
size_t size)
{
return allocMemory(allocator, size, UNKNOWN, 0);
}
char* MemoryLeakDetector::allocMemory(MemoryLeakAllocator* allocator,
size_t size, const char* file, int line)
{
char* mem = allocateMemoryAndExtraInfo(allocator, size);
if (mem)
addMemoryLeakInfoAndCorruptionInfo(mem, size, file, line, allocator);
return mem;
}
void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator,
void* memory, const char* file, int line)
{
if (memory == 0) return;
if (removeMemoryLeakInfoAndCheckCorruption((char*) memory, file, line,
allocator)) allocator->free_memory((char*) memory);
}
void MemoryLeakDetector::deallocMemory(MemoryLeakAllocator* allocator,
void* memory)
{
deallocMemory(allocator, (char*) memory, UNKNOWN, 0);
}
char* MemoryLeakDetector::reallocMemory(MemoryLeakAllocator* allocator,
char* memory, size_t size, const char* file, int line)
{
if (memory) removeMemoryLeakInfoAndCheckCorruption(memory, file, line,
allocator);
char* mem = reallocateMemoryAndExtraInfo(memory, size);
addMemoryCorruptionInformation(mem, size);
addMemoryLeakInfoAndCorruptionInfo(mem, size, file, line, allocator);
return mem;
}
void MemoryLeakDetector::ConstructMemoryLeakReport(MemLeakPeriod period)
{
MemoryLeakDetectorNode* leak = memoryTable.getFirstLeak(period);
int total_leaks = 0;
output_buffer.add(MEM_LEAK_HEADER);
while (leak) {
output_buffer.add(MEM_LEAK_LEAK, leak->size, leak->file, leak->line,
leak->allocator->alloc_name(), leak->memory);
total_leaks++;
leak = memoryTable.getNextLeak(leak, period);
}
output_buffer.add("%s %d", MEM_LEAK_FOOTER, total_leaks);
}
const char* MemoryLeakDetector::report(MemLeakPeriod period)
{
if (!memoryTable.hasLeaks(period)) return MEM_LEAK_NONE;
output_buffer.clear();
ConstructMemoryLeakReport(period);
return output_buffer.toString();
}
void MemoryLeakDetector::markCheckingPeriodLeaksAsNonCheckingPeriod()
{
MemoryLeakDetectorNode* leak = memoryTable.getFirstLeak(
mem_leak_period_checking);
while (leak) {
if (leak->period == mem_leak_period_checking) leak->period
= mem_leak_period_enabled;
leak = memoryTable.getNextLeak(leak, mem_leak_period_checking);
}
}
int MemoryLeakDetector::totalMemoryLeaks(MemLeakPeriod period)
{
return memoryTable.getTotalLeaks(period);
}
| [
"[email protected]"
] | [
[
[
1,
453
]
]
] |
663ba3909ff81c010e0da49621d8d5600e77eb57 | d67b01b820739ea2d63968389a83c36c4b0ff163 | /QuizBotWeb/QuizBotDLL/QuizBotDLL/code/main.cpp | 0481ca0b66a1b5aac97bc14c3c3f94458cd625b5 | [] | no_license | iamukasa/pookas | 114458dc7347c66844ff8cf3023ec75ce4c486b5 | bd5bf9178d2a2a37b3251a07eb3e6afa96f66c67 | refs/heads/master | 2021-01-13T02:08:54.947799 | 2009-11-04T00:52:06 | 2009-11-04T00:52:06 | 35,762,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,757 | cpp | /** \file main.cpp
Main file where the bot starts executing.
*/
#include "aw.h" //include Activeworld header file
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <Vector>
#include "Vect3D.h"
#include "ParticipantManager.h"
#include "QuizParticipant.h"
#include "QuizPage.h"
#include <windows.h>
void init();
void createBot( std::string botName, float x, float y, float z );
void createHUD( int session );
//event handlers
void onAvatarSpeak();
void onAvatarClick();
bool addPlayer( int speakerSession, std::string name, std::string message );
void quizRound();
void destroy();
/**
The QuizBot goes through these states throughout the whole lifetime of the program.
*/
enum BotState { QUIZBOT_IDLE, /**< Nobody has talked to the bot */
QUIZBOT_REGISTRATION, /**< Someone decided to start a quiz, and other players can join */
QUIZBOT_INPROGRESS /**< Quiz is in progress */
};
ParticipantManager users;
BotState quizState;
QuizPage quizPage;
std::vector <Vect3D*> panelPos;
bool contin = true;
/**
\fn int botStart (char *htmldata)
\brief Main bot function where execution starts and ends.
\param htmldata The string containing HTML format quiz data
Initialises and shuts down ActiveWorlds and the bot.
Sets the position of the answer panels.
Contains a main loop that triggers every second.
When the bot is IN_PROGRESS, this main loop calls quizRound().
*/
int botStart (char *htmldata)
{
//initialize quiz questions
quizPage.loadHTMLData(htmldata);
init();
createBot("Quiz Bot", 4750, 815, -518);
quizState = QUIZBOT_IDLE;
//set the positions for the answer panels
panelPos.push_back( new Vect3D(4200, 760, 82) ); //1
panelPos.push_back( new Vect3D(4150, 760, -1118) ); //2
panelPos.push_back( new Vect3D(5350, 760, -418) ); //3
while (contin) //main event loop triggers every second
{
switch ( quizState )
{
case QUIZBOT_IDLE:
{
break;
}
case QUIZBOT_INPROGRESS:
{
quizRound();
break;
}
}
aw_wait (1000);
}
destroy();
aw_destroy ();
aw_term ();
return 0;
}
/**
\fn void init()
\brief Initialises activeworlds api, registers event handlers
*/
void init()
{
int rc;
if (rc = aw_init (AW_BUILD))
{
printf ("Unable to initialize API (reason %d)\n", rc);
exit (1);
}
//register event handlers
aw_event_set(AW_EVENT_CHAT, onAvatarSpeak );
aw_event_set(AW_EVENT_AVATAR_CLICK, onAvatarClick);
}
/**
\fn void destroy()
\brief Shutdown function called when execution ends.
*/
void destroy()
{
for ( unsigned int i = 0; i < panelPos.size(); i++ )
{
delete panelPos.at(i);
}
users.destroy();
}
/**
\fn void onAvatarSpeak()
\brief Called when an avatar speaks to another.
Checks if the speaker is speaking to the bot.
IDLE - Add starting player, and move state to REGISTRATION.
REGISTRATION - Add other players to the quiz.
*/
void onAvatarSpeak()
{
int speakerSession = aw_int( AW_CHAT_SESSION );
if ( aw_int(AW_CHAT_TYPE) == AW_CHAT_WHISPER )
{
std::string message = aw_string(AW_CHAT_MESSAGE);
if ( message == "password" ) //shut down the bot
{
contin = false;
return;
}
switch ( quizState )
{
case QUIZBOT_IDLE: //nobody decided to start a quiz game yet
{
if ( addPlayer( speakerSession, aw_string(AW_AVATAR_NAME), message ) )
{
//delete everyone else in the list in case multiple people clicked but didn't reply y/n
users.removeAllUsers();
users.setUser( speakerSession, QUIZPLAYER_REGISTERED );
users.setPlayerName( speakerSession, aw_string(AW_AVATAR_NAME) );
users.setStartingPlayer( speakerSession );
ParticipantManager::whisper(speakerSession,
"You are the starting player. Click on me when you would like to begin the quiz for everyone." ,
0, 100, 0, 0, 0);
aw_say( "[Announcement] Join the quiz game starting now at Level 2!");
//advance the bot state to registration
quizState = QUIZBOT_REGISTRATION;
}
break;
}
case QUIZBOT_REGISTRATION:
{
// check if the player is the starting player
if ( speakerSession == users.getStartingPlayer() )
{
if (( message == "Y" || message == "y" ) &&
users.getState(users.getStartingPlayer()) == QUIZPLAYER_STARTER )
{
//remove all players with state QUIZPLAYER_CLICKED
users.removeAllWithState( QUIZPLAYER_CLICKED );
//start game
users.broadcast( "Game started!", 100, 0, 100, 1, 0 );
quizState = QUIZBOT_INPROGRESS;
}
else
{
users.setState( speakerSession, QUIZPLAYER_REGISTERED );
std::string str = "Please wait a moment while ";
str += aw_string (AW_AVATAR_NAME);
str += " gets the game started!";
users.broadcast( str, 0, 1, 0, 0, 1 );
}
}
else //not the starting player
{
//add the player
addPlayer( speakerSession, aw_string(AW_AVATAR_NAME), message );
}
break;
}
case QUIZBOT_INPROGRESS:
{
break;
}
}
}
}
/**
\fn bool addPlayer( int speakerSession, std::string name, std::string message )
\brief Adds player to the quiz.
\param speakerSession Session ID of the player who wants to join
\param name Name of the player who wants to join
\param message The player's whispered message to the bot.
Checks if the speaker is whispering "y/n" to the bot and adds the player accordingly.
*/
bool addPlayer( int speakerSession, std::string name, std::string message )
{
int userExists = users.userExists( speakerSession );
if ( userExists == -1 ) //if the user isn't on the list, he hasn't clicked the bot yet
return false;
if ( users.getState( speakerSession ) != QUIZPLAYER_CLICKED ) //the player is already registered
{
ParticipantManager::whisper(speakerSession , "Please wait for the game to start.", 0, 100, 0, 0, 0);
return false;
}
if ( message == "Y" || message == "y" )
{
std::cout << aw_string(AW_AVATAR_NAME) << " signed up \n";
ParticipantManager::whisper(speakerSession , "You have signed up for the quiz!", 0, 100, 0, 0, 0);
users.setUser( speakerSession, QUIZPLAYER_REGISTERED );
users.setPlayerName( speakerSession, name );
users.print();
//broadcast to everyone that the new player has joined.
std::string announce = name;
announce += " has joined the game!";
users.broadcast(announce, 0, 100, 0, 0, 0);
return true;
}
else if ( message == "N" || message == "n" )
{
users.removeUser( speakerSession );
ParticipantManager::whisper(speakerSession , "Alrighty then.", 0, 100, 0, 0, 0);
return false;
}
return false;
}
/**
\fn void onAvatarClick()
\brief Called when an avatar is clicked
Checks if the player clicked on the bot.
IDLE - Bot asks if the player wants to start a new quiz.
REGISTRATION - Bot asks if the player wants to join.
IN_PROGRESS - Notifies clicker that a quiz is in progress.
*/
void onAvatarClick()
{
int clicker = aw_int( AW_AVATAR_SESSION );
//bot got clicked on
if ( aw_int(AW_CLICKED_SESSION) == aw_session() )
{
//check if user exists in the participants list
int userExists = users.userExists( clicker );
switch (quizState)
{
case QUIZBOT_IDLE:
{
ParticipantManager::whisper(clicker , "Hello. Up for some quizzing today? (y/n)", 0, 100, 0, 1, 0);
users.setUser( clicker, QUIZPLAYER_CLICKED );
break;
}
case QUIZBOT_REGISTRATION:
{
if ( userExists == -1 ) //new player joins
{
ParticipantManager::whisper(clicker , "Hello. Would you like to join the quiz? (y/n)", 0, 100, 0, 1, 0);
users.setUser( clicker, QUIZPLAYER_CLICKED );
}
else if ( users.getState(clicker) == QUIZPLAYER_REGISTERED ) // the clicker is registered
{
if ( users.getStartingPlayer() == clicker )
{
ParticipantManager::whisper(clicker ,
"You are the starting player. Would you like to start the quiz now for everyone? (y/n)",
0, 100, 0, 0, 0);
users.setState( clicker, QUIZPLAYER_STARTER );
}
else
{
ParticipantManager::whisper(clicker, "Please wait for the game to start.", 0, 100, 0, 0, 0);
}
}
break;
}
case QUIZBOT_INPROGRESS:
{
ParticipantManager::whisper(clicker , "A quiz is in progress, please wait for the current game to finish.", 0, 100, 0, 1, 0);
break;
}
}
}
}
/**
\fn void createBot( std::string botName, float x, float y, float z )
\brief Called to create a bot.
\param botName Name of the bot
\param x x-coordinate
\param y y-coordinate
\param z z-coordinate
Creates a bot and connects to ActiveWorlds. Does not support multiple instances currently.
*/
void createBot( std::string botName, float x, float y, float z )
{
int rc;
/* create bot instance */
if (rc = aw_create ("155.69.101.53", 5552, 0))
{
//server to launch the bot, ip is 155.69.101.53, and port is 5552
printf ("Unable to create bot instance (reason %d)\n", rc);
}
/* log bot into the universe */
aw_int_set (AW_LOGIN_OWNER, 1); //citizen id of the administrator
aw_string_set (AW_LOGIN_PRIVILEGE_PASSWORD, "12345"); //privilege password of administrator
aw_string_set (AW_LOGIN_APPLICATION, "SDK Sample Application #1");
aw_string_set (AW_LOGIN_NAME, botName.c_str()); //set bot name
if (rc = aw_login ())
{ //login to uniserver
printf ("Unable to login (reason %d)\n", rc);
//exit (1);
}
/* log bot into the world called "beta" */
if (rc = aw_enter ("A_Pookas"))
{
printf ("Unable to enter world (reason %d)\n", rc);
}
/* announce our position in the world */
aw_int_set (AW_MY_X, (int)x); //w
aw_int_set (AW_MY_Y, (int)y);
aw_int_set (AW_MY_Z, (int)z); //n
aw_int_set (AW_MY_YAW, 900); //facing
aw_int_set (AW_MY_TYPE, 62 );
aw_int_set (AW_MY_GESTURE, 1);
if (rc = aw_state_change ())
{
//change bot state to let it appear in the world
printf ("Unable to change state (reason %d)\n", rc);
}
}
/**
\fn void createBot( std::string botName, float x, float y, float z )
\brief Defines each round of the quiz when the bot is IN_PROGRESS.
Called every tick when the bot is IN_PROGRESS.
Gets questions and answers each round, checks the answers when time is up, and increments player score accordingly.
Resets the quiz when all the questions are used.
*/
void quizRound()
{
//retrieve a question
QuizQuestion *q = quizPage.getNextQuestion();
if ( q != NULL )
{
users.broadcast( q->getQuestion(), 255, 0, 0, 1, 0 );
//get the answers for the question
std::vector <std::string>* a = q->getAnswers();
for ( unsigned int i = 0; i < a->size(); i++ )
{
users.broadcast( a->at(i), 0, 0, 0, 1, 0 );
}
//wait for 10 seconds for the players to answer
aw_wait(10000);
users.broadcast("Time's up!", 100, 0, 100, 0, 0 );
//check answers
users.checkAnswers( *panelPos.at( q->getCorrectAnswer() ) , 200);
//broadcast the correct answer
std::string correct = "The correct answer was ";
correct += q->getAnswers()->at( q->getCorrectAnswer() );
users.broadcast( correct, 0, 100, 0, 1, 0 );
}
else //no more questions
{
//broadcast the top scores
users.broadcastTopScores();
users.broadcast( "The quiz is over! Thank you for playing.", 100, 0, 100, 1, 0 );
//reset everything
quizPage.reset();
users.reset();
quizState = QUIZBOT_IDLE;
}
} | [
"lab4games@40cc54bc-b367-11de-8ef2-6d788aed22ac"
] | [
[
[
1,
431
]
]
] |
cb2cae48d30890ddea9efbee7236f7af91cf93f3 | f9d55548d2d1044dc344bb9685393f6e820d44df | /src/bullet/btHeightfieldTerrainShape.cpp | 97e2040d424ef2b96bbecbdc6d2e2f862e98c278 | [] | no_license | schweikm/3DJoust | 5709bed8e6ad5299faef576d4d754e8f15004fdb | d662b9379cd1afc8204535254343df42ff438b9d | refs/heads/master | 2020-12-24T05:24:09.774415 | 2011-10-08T03:47:29 | 2011-10-08T03:47:29 | 61,953,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,112 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btHeightfieldTerrainShape.h"
#include "btTransformUtil.h"
btHeightfieldTerrainShape::btHeightfieldTerrainShape
(
int heightStickWidth, int heightStickLength, void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight,int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges
)
{
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength,void* heightfieldData,btScalar maxHeight,int upAxis,bool useFloatData,bool flipQuadEdges)
{
// legacy constructor: support only float or unsigned char,
// and min height is zero
PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR;
btScalar minHeight = 0.0;
// previously, height = uchar * maxHeight / 65535.
// So to preserve legacy behavior, heightScale = maxHeight / 65535
btScalar heightScale = maxHeight / 65535;
initialize(heightStickWidth, heightStickLength, heightfieldData,
heightScale, minHeight, maxHeight, upAxis, hdt,
flipQuadEdges);
}
void btHeightfieldTerrainShape::initialize
(
int heightStickWidth, int heightStickLength, void* heightfieldData,
btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
PHY_ScalarType hdt, bool flipQuadEdges
)
{
// validation
btAssert(heightStickWidth > 1 && "bad width");
btAssert(heightStickLength > 1 && "bad length");
btAssert(heightfieldData && "null heightfield data");
// btAssert(heightScale) -- do we care? Trust caller here
btAssert(minHeight <= maxHeight && "bad min/max height");
btAssert(upAxis >= 0 && upAxis < 3 &&
"bad upAxis--should be in range [0,2]");
btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_SHORT &&
"Bad height data type enum");
// initialize member variables
m_shapeType = TERRAIN_SHAPE_PROXYTYPE;
m_heightStickWidth = heightStickWidth;
m_heightStickLength = heightStickLength;
m_minHeight = minHeight;
m_maxHeight = maxHeight;
m_width = (btScalar) (heightStickWidth - 1);
m_length = (btScalar) (heightStickLength - 1);
m_heightScale = heightScale;
m_heightfieldDataUnknown = heightfieldData;
m_heightDataType = hdt;
m_flipQuadEdges = flipQuadEdges;
m_useDiamondSubdivision = false;
m_upAxis = upAxis;
m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.));
// determine min/max axis-aligned bounding box (aabb) values
switch (m_upAxis)
{
case 0:
{
m_localAabbMin.setValue(m_minHeight, 0, 0);
m_localAabbMax.setValue(m_maxHeight, m_width, m_length);
break;
}
case 1:
{
m_localAabbMin.setValue(0, m_minHeight, 0);
m_localAabbMax.setValue(m_width, m_maxHeight, m_length);
break;
};
case 2:
{
m_localAabbMin.setValue(0, 0, m_minHeight);
m_localAabbMax.setValue(m_width, m_length, m_maxHeight);
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0 && "Bad m_upAxis");
}
}
// remember origin (defined as exact middle of aabb)
m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax);
}
btHeightfieldTerrainShape::~btHeightfieldTerrainShape()
{
}
void btHeightfieldTerrainShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
btVector3 halfExtents = (m_localAabbMax-m_localAabbMin)* m_localScaling * btScalar(0.5);
btVector3 localOrigin(0, 0, 0);
localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5);
localOrigin *= m_localScaling;
btMatrix3x3 abs_b = t.getBasis().absolute();
btVector3 center = t.getOrigin();
btVector3 extent = btVector3(abs_b[0].dot(halfExtents),
abs_b[1].dot(halfExtents),
abs_b[2].dot(halfExtents));
extent += btVector3(getMargin(),getMargin(),getMargin());
aabbMin = center - extent;
aabbMax = center + extent;
}
btScalar btHeightfieldTerrainShape::getHeightFieldValue(int x,int y) const
{
btScalar val = 0.f;
switch (m_heightDataType)
{
case PHY_FLOAT:
{
val = m_heightfieldDataFloat[(y*m_heightStickWidth)+x];
break;
}
case PHY_UCHAR:
{
unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y*m_heightStickWidth)+x];
val = heightFieldValue * m_heightScale;
break;
}
case PHY_SHORT:
{
short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x];
val = hfValue * m_heightScale;
break;
}
default:
{
btAssert(!"Bad m_heightDataType");
}
}
return val;
}
void btHeightfieldTerrainShape::getVertex(int x,int y,btVector3& vertex) const
{
btAssert(x>=0);
btAssert(y>=0);
btAssert(x<m_heightStickWidth);
btAssert(y<m_heightStickLength);
btScalar height = getHeightFieldValue(x,y);
switch (m_upAxis)
{
case 0:
{
vertex.setValue(
height,
(-m_width/btScalar(2.0)) + x,
(-m_length/btScalar(2.0) ) + y
);
break;
}
case 1:
{
vertex.setValue(
(-m_width/btScalar(2.0)) + x,
height,
(-m_length/btScalar(2.0)) + y
);
break;
};
case 2:
{
vertex.setValue(
(-m_width/btScalar(2.0)) + x,
(-m_length/btScalar(2.0)) + y,
height
);
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
vertex*=m_localScaling;
}
static inline int
getQuantized
(
float x
)
{
if (x < 0.0) {
return (int) (x - 0.5);
}
return (int) (x + 0.5);
}
/// given input vector, return quantized version
/**
This routine is basically determining the gridpoint indices for a given
input vector, answering the question: "which gridpoint is closest to the
provided point?".
"with clamp" means that we restrict the point to be in the heightfield's
axis-aligned bounding box.
*/
void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point,int /*isMax*/) const
{
btVector3 clampedPoint(point);
clampedPoint.setMax(m_localAabbMin);
clampedPoint.setMin(m_localAabbMax);
out[0] = getQuantized(clampedPoint.getX());
out[1] = getQuantized(clampedPoint.getY());
out[2] = getQuantized(clampedPoint.getZ());
}
/// process all triangles within the provided axis-aligned bounding box
/**
basic algorithm:
- convert input aabb to local coordinates (scale down and shift for local origin)
- convert input aabb to a range of heightfield grid points (quantize)
- iterate over all triangles in that subset of the grid
*/
void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const
{
// scale down the input aabb's so they are in local (non-scaled) coordinates
btVector3 localAabbMin = aabbMin*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
btVector3 localAabbMax = aabbMax*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
// account for local origin
localAabbMin += m_localOrigin;
localAabbMax += m_localOrigin;
//quantize the aabbMin and aabbMax, and adjust the start/end ranges
int quantizedAabbMin[3];
int quantizedAabbMax[3];
quantizeWithClamp(quantizedAabbMin, localAabbMin,0);
quantizeWithClamp(quantizedAabbMax, localAabbMax,1);
// expand the min/max quantized values
// this is to catch the case where the input aabb falls between grid points!
for (int i = 0; i < 3; ++i) {
quantizedAabbMin[i]--;
quantizedAabbMax[i]++;
}
int startX=0;
int endX=m_heightStickWidth-1;
int startJ=0;
int endJ=m_heightStickLength-1;
switch (m_upAxis)
{
case 0:
{
if (quantizedAabbMin[1]>startX)
startX = quantizedAabbMin[1];
if (quantizedAabbMax[1]<endX)
endX = quantizedAabbMax[1];
if (quantizedAabbMin[2]>startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2]<endJ)
endJ = quantizedAabbMax[2];
break;
}
case 1:
{
if (quantizedAabbMin[0]>startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0]<endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[2]>startJ)
startJ = quantizedAabbMin[2];
if (quantizedAabbMax[2]<endJ)
endJ = quantizedAabbMax[2];
break;
};
case 2:
{
if (quantizedAabbMin[0]>startX)
startX = quantizedAabbMin[0];
if (quantizedAabbMax[0]<endX)
endX = quantizedAabbMax[0];
if (quantizedAabbMin[1]>startJ)
startJ = quantizedAabbMin[1];
if (quantizedAabbMax[1]<endJ)
endJ = quantizedAabbMax[1];
break;
}
default:
{
//need to get valid m_upAxis
btAssert(0);
}
}
for(int j=startJ; j<endJ; j++)
{
for(int x=startX; x<endX; x++)
{
btVector3 vertices[3];
if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j+x) & 1)))
{
//first triangle
getVertex(x,j,vertices[0]);
getVertex(x+1,j,vertices[1]);
getVertex(x+1,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
//second triangle
getVertex(x,j,vertices[0]);
getVertex(x+1,j+1,vertices[1]);
getVertex(x,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
} else
{
//first triangle
getVertex(x,j,vertices[0]);
getVertex(x,j+1,vertices[1]);
getVertex(x+1,j,vertices[2]);
callback->processTriangle(vertices,x,j);
//second triangle
getVertex(x+1,j,vertices[0]);
getVertex(x,j+1,vertices[1]);
getVertex(x+1,j+1,vertices[2]);
callback->processTriangle(vertices,x,j);
}
}
}
}
void btHeightfieldTerrainShape::calculateLocalInertia(btScalar ,btVector3& inertia) const
{
//moving concave objects not supported
inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}
void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling)
{
m_localScaling = scaling;
}
const btVector3& btHeightfieldTerrainShape::getLocalScaling() const
{
return m_localScaling;
}
| [
"[email protected]"
] | [
[
[
1,
409
]
]
] |
516f560b76b251ffd6fcfca2baaac951edee3f59 | cde1dd6cf288c4ef62e980e4e208bc56703d4373 | /include/GUI/TextArea.hpp | eb3c1f70d3961c85a2d3b31b4b87d23ce4a1571b | [] | no_license | TheProjecter/simple-gui | 3c355834549292a9cd5bbd03b7ef2f3f24c58a15 | c00313dd1d4299e00b11369ae31c58b96e73eb4c | refs/heads/master | 2021-01-10T15:12:57.104734 | 2011-06-21T14:38:29 | 2011-06-21T14:38:29 | 45,961,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,920 | hpp | #pragma once
#include "Widget.hpp"
#include <vector>
namespace gui
{
struct Word {
float GetWidth() const;
std::string GetText() const;
void SetPos(int x, int y);
std::vector<sf::String> m_char;
};
struct Line {
Line(): m_align(ALIGN_LEFT) {}
enum LineAlignment {
ALIGN_LEFT,
ALIGN_RIGHT,
ALIGN_CENTER
};
float GetWidth() const;
std::string GetText() const;
void SetPos(const Rect& container,uint32 line_spacing);
uint32 GetLineSpacing() const;
std::vector<Word> m_words;
LineAlignment m_align;
};
//***********************************************************************
//* Text Area Specific Tags *
//***********************************************************************
// 1. <color> must be closed by a </color> *
// usage: *
// <color=x.x.x> The rgb components will be r=x, g=x, b=x *
// The default value for x is 0 in case it's not specified. *
// Example: <color=255> r=255,g=0,b=0 => red! *
// 2. <font size> must be closed by a </font size> *
// usage: *
// <font size=x> The size of the text will be x until you close *
// the tag *
// 3. <align=x> must be closed by a </align> *
// usage: *
// <align=left> Aligns text to the left. *
// <align=right> Aligns text to the right. *
// <align=center> Aligns text to the center. *
// Warning: *
// The current line on which you specified the alignement will *
// keep the alignment even if you close the tag on the same line! *
// 4. <b> must be closed by a </b> *
// Makes the text have a bold style until closed *
// usage: *
// <b>Some Bold Text</b> *
// 5. <i> must be closed by a </i> *
// Makes the text have an italic style until closed *
// usage: *
// <i>Some Italic Text</i> *
// 6. <u> must be closed by a </u> *
// Makes the text have a underlined style until closed *
// usage: *
// <u>Some Underlined Text</u> *
// *
//***********************************************************************
class TextArea : public Widget
{
public:
TextArea();
void SetText(const std::string& text);
std::string GetTextFromLine(uint32 line) const;
const std::string& GetText() const;
void Resize(int w, int h, bool save = true);
void SetPos(int x, int y, bool forceMove = false, bool save=true);
private:
std::string m_text;
std::vector<Line> m_lines;
uint32 m_viewableLines;
uint32 m_totalLines;
uint32 m_startingLine;
virtual void Draw() const;
virtual void InitGraphics();
virtual void ReloadSettings();
};
void Parse(std::stringstream& s,std::vector<Line>& text, const Rect& container);
} | [
"[email protected]"
] | [
[
[
1,
89
]
]
] |
f44029f19dd165a2963889ee801d67283bd5ab03 | 554a3b859473dc4dfebc6a31b16dfd14c84ffd09 | /sxsim/generic_sx_implementation.hpp | 4c0d47b64faf8bf362436d824846c88b708bff74 | [
"BSL-1.0"
] | permissive | DannyHavenith/sxsim | c0fbaf016fc7dcae7535e152ae9e33f3386d3792 | e3d5ad1f6f75157397d03c191b4b4b0af00ebb60 | refs/heads/master | 2021-01-19T11:22:20.615306 | 2011-05-30T22:11:18 | 2011-05-30T22:11:18 | 1,822,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,038 | hpp |
// Copyright Danny Havenith 2006 - 2009.
// 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)
// NOTE THAT THERE IS NO INCLUDE GUARD HERE!
// This include file is essentially a piece of text that facilitates
// creating generic implementations of sx instructions.
// This is typically used for situations where the implementation is
// almost the same for all instructions, as in
// for instance for a clock-cycle calculator, a 'disassembler', etc.
// USAGE:
// * define a macro GENERIC_SX_CLASS_HEADER with the name of your class
// and optionally a base class that you've implemented.
// * Then define the MACRO GENERIC_SX_IMPLEMENT_INSTRUCTION, that specifies
// how each function must be implemented.
// * include this file.
// * UNDEFine GENERIC_SX_CLASS_HEADER and GENERIC_SX_IMPLEMENT_INSTRUCTION
//
// see sx_print.hpp for an example.
//
struct GENERIC_SX_CLASS_HEADER
{
GENERIC_SX_IMPLEMENT_INSTRUCTION( add_w_fr, (const add_w_fr &, int arg_register), ( add_w_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( add_fr_w, (const add_fr_w &, int arg_register), ( add_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( and_w_lit, (const and_w_lit &, int arg_lit8), ( and_w_lit(), arg_lit8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( and_w_fr, (const and_w_fr &, int arg_register), ( and_w_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( and_fr_w, (const and_fr_w &, int arg_register), ( and_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( clrb_fr_bit, (const clrb_fr_bit &, int arg_register, int bit), ( clrb_fr_bit(), arg_register, bit))
GENERIC_SX_IMPLEMENT_INSTRUCTION( setb_fr_bit, (const setb_fr_bit &, int arg_register, int bit), ( setb_fr_bit(), arg_register, bit))
GENERIC_SX_IMPLEMENT_INSTRUCTION( snb_fr_bit, (const snb_fr_bit &, int arg_register, int bit), ( snb_fr_bit(), arg_register, bit))
GENERIC_SX_IMPLEMENT_INSTRUCTION( sb_fr_bit, (const sb_fr_bit &, int arg_register, int bit), ( sb_fr_bit(), arg_register, bit))
GENERIC_SX_IMPLEMENT_INSTRUCTION( call, (const call &, int arg_addr8), ( call(), arg_addr8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( clr_fr, (const clr_fr &, int arg_register), ( clr_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( clr_w, (const clr_w &), ( clr_w()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_not_fr, (const mov_w_not_fr &, int arg_register), ( mov_w_not_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( not_fr, (const not_fr &, int arg_register), ( not_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_dec_fr, (const mov_w_dec_fr &, int arg_register), ( mov_w_dec_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( dec_fr, (const dec_fr &, int arg_register), ( dec_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( movsz_w_dec_fr,(const movsz_w_dec_fr &, int arg_register), ( movsz_w_dec_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( decsz_fr, (const decsz_fr &, int arg_register), ( decsz_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( jmp, (const jmp &, int addr9_), ( jmp(), addr9_))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_inc_fr, (const mov_w_inc_fr &, int arg_register), ( mov_w_inc_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( inc_fr, (const inc_fr &, int arg_register), ( inc_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( movsz_w_inc_fr,(const movsz_w_inc_fr &, int arg_register), ( movsz_w_inc_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( incsz_fr, (const incsz_fr &, int arg_register), ( incsz_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( or_w_lit, (const or_w_lit &, int arg_lit8), ( or_w_lit(), arg_lit8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( or_w_fr, (const or_w_fr &, int arg_register), ( or_w_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( or_fr_w, (const or_fr_w &, int arg_register), ( or_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_fr, (const mov_w_fr &, int arg_register), ( mov_w_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( test_fr, (const test_fr &, int arg_register), ( test_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_lit, (const mov_w_lit &, int arg_lit8), ( mov_w_lit(), arg_lit8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_fr_w, (const mov_fr_w &, int arg_register), ( mov_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( retw, (const retw &, int arg_lit8), ( retw(), arg_lit8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_shiftleft_fr, (const mov_w_shiftleft_fr &, int arg_register), ( mov_w_shiftleft_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( rl_fr, (const rl_fr &, int arg_register), ( rl_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_shiftright_fr, (const mov_w_shiftright_fr &, int arg_register), ( mov_w_shiftright_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( rr_fr, (const rr_fr &, int arg_register), ( rr_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_fr_minus_w, (const mov_w_fr_minus_w &, int arg_register), ( mov_w_fr_minus_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( sub_fr_w, (const sub_fr_w &, int arg_register), ( sub_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_swap_fr,(const mov_w_swap_fr &, int arg_register), ( mov_w_swap_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( swap_fr, (const swap_fr &, int arg_register), ( swap_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_special_rx_w, (const mov_special_rx_w &, int arg_cregister), ( mov_special_rx_w(), arg_cregister))
GENERIC_SX_IMPLEMENT_INSTRUCTION( xor_w_lit, (const xor_w_lit &, int arg_lit8), ( xor_w_lit(), arg_lit8))
GENERIC_SX_IMPLEMENT_INSTRUCTION( xor_w_fr, (const xor_w_fr &, int arg_register), ( xor_w_fr(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( xor_fr_w, (const xor_fr_w &, int arg_register), ( xor_fr_w(), arg_register))
GENERIC_SX_IMPLEMENT_INSTRUCTION( ret, (const ret &), ( ret()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( retp, (const retp &), ( retp()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( reti, (const reti &), ( reti()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( retiw, (const retiw &), ( retiw()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( page, (const page &, int lit3), ( page(), lit3))
GENERIC_SX_IMPLEMENT_INSTRUCTION( bank, (const bank &, int lit3), ( bank(), lit3))
GENERIC_SX_IMPLEMENT_INSTRUCTION( iread, (const iread &), ( iread()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_w_m, (const mov_w_m &), ( mov_w_m()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_m_w, (const mov_m_w &), ( mov_m_w()))
GENERIC_SX_IMPLEMENT_INSTRUCTION( mov_m_lit, (const mov_m_lit &, int arg_lit4), ( mov_m_lit(), arg_lit4))
};
| [
"danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c",
"Danny@3a7aa2ed-2c50-d14e-a1b9-f07bebb4988c"
] | [
[
[
1,
6
],
[
27,
79
]
],
[
[
7,
26
],
[
80,
80
]
]
] |
b49562451b49c9b2b33bdaf76fec1859004f56c2 | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/qcommon/memheap.cpp | 3929659d716b3e341ac0554c27e610152dea0adb | [] | no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188,705 | cpp | #include"memheap.h"
#include<stdio.h>
#include<stdarg.h>
#include<stdlib.h>
#ifdef _WIN32_WCE
#define WIN32 1
#define ABORT { assert(0); exit(0); }
#endif
#undef DEBUG
#define USE_DL_PREFIX 1
#define MSPACES 1
#define ONLY_MSPACES 1
#ifdef WIN32
#include<windows.h>
#else
#include"unixdefs.h"
#include"string.h"
#endif
namespace DLMALLOC
{
/*
This is a version (aka dlmalloc) of malloc/free/realloc written by
Doug Lea and released to the public domain, as explained at
http://creativecommons.org/licenses/publicdomain. Send questions,
comments, complaints, performance data, etc to [email protected]
* Version 2.8.3 Thu Sep 22 11:16:15 2005 Doug Lea (dl at gee)
Note: There may be an updated version of this malloc obtainable at
ftp://gee.cs.oswego.edu/pub/misc/malloc.c
Check before installing!
* Quickstart
This library is all in one file to simplify the most common usage:
ftp it, compile it (-O3), and link it into another program. All of
the compile-time options default to reasonable values for use on
most platforms. You might later want to step through various
compile-time and dynamic tuning options.
For convenience, an include file for code using this malloc is at:
ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.3.h
You don't really need this .h file unless you call functions not
defined in your system include files. The .h file contains only the
excerpts from this file needed for using this malloc on ANSI C/C++
systems, so long as you haven't changed compile-time options about
naming and tuning parameters. If you do, then you can create your
own malloc.h that does include all settings by cutting at the point
indicated below. Note that you may already by default be using a C
library containing a malloc that is based on some version of this
malloc (for example in linux). You might still want to use the one
in this file to customize settings or to avoid overheads associated
with library versions.
* Vital statistics:
Supported pointer/size_t representation: 4 or 8 bytes
size_t MUST be an unsigned type of the same width as
pointers. (If you are using an ancient system that declares
size_t as a signed type, or need it to be a different width
than pointers, you can use a previous release of this malloc
(e.g. 2.7.2) supporting these.)
Alignment: 8 bytes (default)
This suffices for nearly all current machines and C compilers.
However, you can define MALLOC_ALIGNMENT to be wider than this
if necessary (up to 128bytes), at the expense of using more space.
Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
8 or 16 bytes (if 8byte sizes)
Each malloced chunk has a hidden word of overhead holding size
and status information, and additional cross-check word
if FOOTERS is defined.
Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
8-byte ptrs: 32 bytes (including overhead)
Even a request for zero bytes (i.e., malloc(0)) returns a
pointer to something of the minimum allocatable size.
The maximum overhead wastage (i.e., number of extra bytes
allocated than were requested in malloc) is less than or equal
to the minimum size, except for requests >= mmap_threshold that
are serviced via mmap(), where the worst case wastage is about
32 bytes plus the remainder from a system page (the minimal
mmap unit); typically 4096 or 8192 bytes.
Security: static-safe; optionally more or less
The "security" of malloc refers to the ability of malicious
code to accentuate the effects of errors (for example, freeing
space that is not currently malloc'ed or overwriting past the
ends of chunks) in code that calls malloc. This malloc
guarantees not to modify any memory locations below the base of
heap, i.e., static variables, even in the presence of usage
errors. The routines additionally detect most improper frees
and reallocs. All this holds as long as the static bookkeeping
for malloc itself is not corrupted by some other means. This
is only one aspect of security -- these checks do not, and
cannot, detect all possible programming errors.
If FOOTERS is defined nonzero, then each allocated chunk
carries an additional check word to verify that it was malloced
from its space. These check words are the same within each
execution of a program using malloc, but differ across
executions, so externally crafted fake chunks cannot be
freed. This improves security by rejecting frees/reallocs that
could corrupt heap memory, in addition to the checks preventing
writes to statics that are always on. This may further improve
security at the expense of time and space overhead. (Note that
FOOTERS may also be worth using with MSPACES.)
By default detected errors cause the program to abort (calling
"abort()"). You can override this to instead proceed past
errors by defining PROCEED_ON_ERROR. In this case, a bad free
has no effect, and a malloc that encounters a bad address
caused by user overwrites will ignore the bad address by
dropping pointers and indices to all known memory. This may
be appropriate for programs that should continue if at all
possible in the face of programming errors, although they may
run out of memory because dropped memory is never reclaimed.
If you don't like either of these options, you can define
CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
else. And if if you are sure that your program using malloc has
no errors or vulnerabilities, you can define INSECURE to 1,
which might (or might not) provide a small performance improvement.
Thread-safety: NOT thread-safe unless USE_LOCKS defined
When USE_LOCKS is defined, each public call to malloc, free,
etc is surrounded with either a pthread mutex or a win32
spinlock (depending on WIN32). This is not especially fast, and
can be a major bottleneck. It is designed only to provide
minimal protection in concurrent environments, and to provide a
basis for extensions. If you are using malloc in a concurrent
program, consider instead using ptmalloc, which is derived from
a version of this malloc. (See http://www.malloc.de).
System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
This malloc can use unix sbrk or any emulation (invoked using
the CALL_MORECORE macro) and/or mmap/munmap or any emulation
(invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
memory. On most unix systems, it tends to work best if both
MORECORE and MMAP are enabled. On Win32, it uses emulations
based on VirtualAlloc. It also uses common C library functions
like memset.
Compliance: I believe it is compliant with the Single Unix Specification
(See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
others as well.
* Overview of algorithms
This is not the fastest, most space-conserving, most portable, or
most tunable malloc ever written. However it is among the fastest
while also being among the most space-conserving, portable and
tunable. Consistent balance across these factors results in a good
general-purpose allocator for malloc-intensive programs.
In most ways, this malloc is a best-fit allocator. Generally, it
chooses the best-fitting existing chunk for a request, with ties
broken in approximately least-recently-used order. (This strategy
normally maintains low fragmentation.) However, for requests less
than 256bytes, it deviates from best-fit when there is not an
exactly fitting available chunk by preferring to use space adjacent
to that used for the previous small request, as well as by breaking
ties in approximately most-recently-used order. (These enhance
locality of series of small allocations.) And for very large requests
(>= 256Kb by default), it relies on system memory mapping
facilities, if supported. (This helps avoid carrying around and
possibly fragmenting memory used only for large chunks.)
All operations (except malloc_stats and mallinfo) have execution
times that are bounded by a constant factor of the number of bits in
a size_t, not counting any clearing in calloc or copying in realloc,
or actions surrounding MORECORE and MMAP that have times
proportional to the number of non-contiguous regions returned by
system allocation routines, which is often just 1.
The implementation is not very modular and seriously overuses
macros. Perhaps someday all C compilers will do as good a job
inlining modular code as can now be done by brute-force expansion,
but now, enough of them seem not to.
Some compilers issue a lot of warnings about code that is
dead/unreachable only on some platforms, and also about intentional
uses of negation on unsigned types. All known cases of each can be
ignored.
For a longer but out of date high-level description, see
http://gee.cs.oswego.edu/dl/html/malloc.html
* MSPACES
If MSPACES is defined, then in addition to malloc, free, etc.,
this file also defines mspace_malloc, mspace_free, etc. These
are versions of malloc routines that take an "mspace" argument
obtained using create_mspace, to control all internal bookkeeping.
If ONLY_MSPACES is defined, only these versions are compiled.
So if you would like to use this allocator for only some allocations,
and your system malloc for others, you can compile with
ONLY_MSPACES and then do something like...
static mspace mymspace = create_mspace(0,0); // for example
#define mymalloc(bytes) mspace_malloc(mymspace, bytes)
(Note: If you only need one instance of an mspace, you can instead
use "USE_DL_PREFIX" to relabel the global malloc.)
You can similarly create thread-local allocators by storing
mspaces as thread-locals. For example:
static __thread mspace tlms = 0;
void* tlmalloc(size_t bytes) {
if (tlms == 0) tlms = create_mspace(0, 0);
return mspace_malloc(tlms, bytes);
}
void tlfree(void* mem) { mspace_free(tlms, mem); }
Unless FOOTERS is defined, each mspace is completely independent.
You cannot allocate from one and free to another (although
conformance is only weakly checked, so usage errors are not always
caught). If FOOTERS is defined, then each chunk carries around a tag
indicating its originating mspace, and frees are directed to their
originating spaces.
------------------------- Compile-time options ---------------------------
Be careful in setting #define values for numerical constants of type
size_t. On some systems, literal values are not automatically extended
to size_t precision unless they are explicitly casted.
WIN32 default: defined if _WIN32 defined
Defining WIN32 sets up defaults for MS environment and compilers.
Otherwise defaults are for unix.
MALLOC_ALIGNMENT default: (size_t)8
Controls the minimum alignment for malloc'ed chunks. It must be a
power of two and at least 8, even on machines for which smaller
alignments would suffice. It may be defined as larger than this
though. Note however that code and data structures are optimized for
the case of 8-byte alignment.
MSPACES default: 0 (false)
If true, compile in support for independent allocation spaces.
This is only supported if HAVE_MMAP is true.
ONLY_MSPACES default: 0 (false)
If true, only compile in mspace versions, not regular versions.
USE_LOCKS default: 0 (false)
Causes each call to each public routine to be surrounded with
pthread or WIN32 mutex lock/unlock. (If set true, this can be
overridden on a per-mspace basis for mspace versions.)
FOOTERS default: 0
If true, provide extra checking and dispatching by placing
information in the footers of allocated chunks. This adds
space and time overhead.
INSECURE default: 0
If true, omit checks for usage errors and heap space overwrites.
USE_DL_PREFIX default: NOT defined
Causes compiler to prefix all public routines with the string 'dl'.
This can be useful when you only want to use this malloc in one part
of a program, using your regular system malloc elsewhere.
ABORT default: defined as abort()
Defines how to abort on failed checks. On most systems, a failed
check cannot die with an "assert" or even print an informative
message, because the underlying print routines in turn call malloc,
which will fail again. Generally, the best policy is to simply call
abort(). It's not very useful to do more than this because many
errors due to overwriting will show up as address faults (null, odd
addresses etc) rather than malloc-triggered checks, so will also
abort. Also, most compilers know that abort() does not return, so
can better optimize code conditionally calling it.
PROCEED_ON_ERROR default: defined as 0 (false)
Controls whether detected bad addresses cause them to bypassed
rather than aborting. If set, detected bad arguments to free and
realloc are ignored. And all bookkeeping information is zeroed out
upon a detected overwrite of freed heap space, thus losing the
ability to ever return it from malloc again, but enabling the
application to proceed. If PROCEED_ON_ERROR is defined, the
static variable malloc_corruption_error_count is compiled in
and can be examined to see if errors have occurred. This option
generates slower code than the default abort policy.
DEBUG default: NOT defined
The DEBUG setting is mainly intended for people trying to modify
this code or diagnose problems when porting to new platforms.
However, it may also be able to better isolate user errors than just
using runtime checks. The assertions in the check routines spell
out in more detail the assumptions and invariants underlying the
algorithms. The checking is fairly extensive, and will slow down
execution noticeably. Calling malloc_stats or mallinfo with DEBUG
set will attempt to check every non-mmapped allocated and free chunk
in the course of computing the summaries.
ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
Debugging assertion failures can be nearly impossible if your
version of the assert macro causes malloc to be called, which will
lead to a cascade of further failures, blowing the runtime stack.
ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
which will usually make debugging easier.
MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
The action to take before "return 0" when malloc fails to be able to
return memory because there is none available.
HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
True if this system supports sbrk or an emulation of it.
MORECORE default: sbrk
The name of the sbrk-style system routine to call to obtain more
memory. See below for guidance on writing custom MORECORE
functions. The type of the argument to sbrk/MORECORE varies across
systems. It cannot be size_t, because it supports negative
arguments, so it is normally the signed type of the same width as
size_t (sometimes declared as "intptr_t"). It doesn't much matter
though. Internally, we only call it with arguments less than half
the max value of a size_t, which should work across all reasonable
possibilities, although sometimes generating compiler warnings. See
near the end of this file for guidelines for creating a custom
version of MORECORE.
MORECORE_CONTIGUOUS default: 1 (true)
If true, take advantage of fact that consecutive calls to MORECORE
with positive arguments always return contiguous increasing
addresses. This is true of unix sbrk. It does not hurt too much to
set it true anyway, since malloc copes with non-contiguities.
Setting it false when definitely non-contiguous saves time
and possibly wasted space it would take to discover this though.
MORECORE_CANNOT_TRIM default: NOT defined
True if MORECORE cannot release space back to the system when given
negative arguments. This is generally necessary only if you are
using a hand-crafted MORECORE function that cannot handle negative
arguments.
HAVE_MMAP default: 1 (true)
True if this system supports mmap or an emulation of it. If so, and
HAVE_MORECORE is not true, MMAP is used for all system
allocation. If set and HAVE_MORECORE is true as well, MMAP is
primarily used to directly allocate very large blocks. It is also
used as a backup strategy in cases where MORECORE fails to provide
space from system. Note: A single call to MUNMAP is assumed to be
able to unmap memory that may have be allocated using multiple calls
to MMAP, so long as they are adjacent.
HAVE_MREMAP default: 1 on linux, else 0
If true realloc() uses mremap() to re-allocate large blocks and
extend or shrink allocation spaces.
MMAP_CLEARS default: 1 on unix
True if mmap clears memory so calloc doesn't need to. This is true
for standard unix mmap using /dev/zero.
USE_BUILTIN_FFS default: 0 (i.e., not used)
Causes malloc to use the builtin ffs() function to compute indices.
Some compilers may recognize and intrinsify ffs to be faster than the
supplied C version. Also, the case of x86 using gcc is special-cased
to an asm instruction, so is already as fast as it can be, and so
this setting has no effect. (On most x86s, the asm version is only
slightly faster than the C version.)
malloc_getpagesize default: derive from system includes, or 4096.
The system page size. To the extent possible, this malloc manages
memory from the system in page-size units. This may be (and
usually is) a function rather than a constant. This is ignored
if WIN32, where page size is determined using getSystemInfo during
initialization.
USE_DEV_RANDOM default: 0 (i.e., not used)
Causes malloc to use /dev/random to initialize secure magic seed for
stamping footers. Otherwise, the current time is used.
NO_MALLINFO default: 0
If defined, don't compile "mallinfo". This can be a simple way
of dealing with mismatches between system declarations and
those in this file.
MALLINFO_FIELD_TYPE default: size_t
The type of the fields in the mallinfo struct. This was originally
defined as "int" in SVID etc, but is more usefully defined as
size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
REALLOC_ZERO_BYTES_FREES default: not defined
This should be set if a call to realloc with zero bytes should
be the same as a call to free. Some people think it should. Otherwise,
since this malloc returns a unique pointer for malloc(0), so does
realloc(p, 0).
LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
LACKS_STDLIB_H default: NOT defined unless on WIN32
Define these if your system does not have these header files.
You might need to manually insert some of the declarations they provide.
DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
system_info.dwAllocationGranularity in WIN32,
otherwise 64K.
Also settable using mallopt(M_GRANULARITY, x)
The unit for allocating and deallocating memory from the system. On
most systems with contiguous MORECORE, there is no reason to
make this more than a page. However, systems with MMAP tend to
either require or encourage larger granularities. You can increase
this value to prevent system allocation functions to be called so
often, especially if they are slow. The value must be at least one
page and must be a power of two. Setting to 0 causes initialization
to either page size or win32 region size. (Note: In previous
versions of malloc, the equivalent of this option was called
"TOP_PAD")
DEFAULT_TRIM_THRESHOLD default: 2MB
Also settable using mallopt(M_TRIM_THRESHOLD, x)
The maximum amount of unused top-most memory to keep before
releasing via malloc_trim in free(). Automatic trimming is mainly
useful in long-lived programs using contiguous MORECORE. Because
trimming via sbrk can be slow on some systems, and can sometimes be
wasteful (in cases where programs immediately afterward allocate
more large chunks) the value should be high enough so that your
overall system performance would improve by releasing this much
memory. As a rough guide, you might set to a value close to the
average size of a process (program) running on your system.
Releasing this much memory would allow such a process to run in
memory. Generally, it is worth tuning trim thresholds when a
program undergoes phases where several large chunks are allocated
and released in ways that can reuse each other's storage, perhaps
mixed with phases where there are no such chunks at all. The trim
value must be greater than page size to have any useful effect. To
disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
some people use of mallocing a huge space and then freeing it at
program startup, in an attempt to reserve system memory, doesn't
have the intended effect under automatic trimming, since that memory
will immediately be returned to the system.
DEFAULT_MMAP_THRESHOLD default: 256K
Also settable using mallopt(M_MMAP_THRESHOLD, x)
The request size threshold for using MMAP to directly service a
request. Requests of at least this size that cannot be allocated
using already-existing space will be serviced via mmap. (If enough
normal freed space already exists it is used instead.) Using mmap
segregates relatively large chunks of memory so that they can be
individually obtained and released from the host system. A request
serviced through mmap is never reused by any other request (at least
not directly; the system may just so happen to remap successive
requests to the same locations). Segregating space in this way has
the benefits that: Mmapped space can always be individually released
back to the system, which helps keep the system level memory demands
of a long-lived program low. Also, mapped memory doesn't become
`locked' between other chunks, as can happen with normally allocated
chunks, which means that even trimming via malloc_trim would not
release them. However, it has the disadvantage that the space
cannot be reclaimed, consolidated, and then used to service later
requests, as happens with normal chunks. The advantages of mmap
nearly always outweigh disadvantages for "large" chunks, but the
value of "large" may vary across systems. The default is an
empirically derived value that works well in most systems. You can
disable mmap by setting to MAX_SIZE_T.
*/
#ifndef WIN32
#ifdef _WIN32
#define WIN32 1
#endif /* _WIN32 */
#endif /* WIN32 */
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define HAVE_MMAP 1
#define HAVE_MORECORE 0
#define LACKS_UNISTD_H
#define LACKS_SYS_PARAM_H
#define LACKS_SYS_MMAN_H
#define LACKS_STRING_H
#define LACKS_STRINGS_H
#define LACKS_SYS_TYPES_H
#define LACKS_ERRNO_H
#define LACKS_FCNTL_H
#define MALLOC_FAILURE_ACTION
#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
#endif /* WIN32 */
#if defined(DARWIN) || defined(_DARWIN)
/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
#ifndef HAVE_MORECORE
#define HAVE_MORECORE 0
#define HAVE_MMAP 1
#endif /* HAVE_MORECORE */
#endif /* DARWIN */
#ifndef LACKS_SYS_TYPES_H
#include <sys/types.h> /* For size_t */
#endif /* LACKS_SYS_TYPES_H */
/* The maximum possible size_t value has all bits set */
#define MAX_SIZE_T (~(size_t)0)
#ifndef ONLY_MSPACES
#define ONLY_MSPACES 0
#endif /* ONLY_MSPACES */
#ifndef MSPACES
#if ONLY_MSPACES
#define MSPACES 1
#else /* ONLY_MSPACES */
#define MSPACES 0
#endif /* ONLY_MSPACES */
#endif /* MSPACES */
#ifndef MALLOC_ALIGNMENT
#define MALLOC_ALIGNMENT ((size_t)8U)
#endif /* MALLOC_ALIGNMENT */
#ifndef FOOTERS
#define FOOTERS 0
#endif /* FOOTERS */
#ifndef ABORT
#define ABORT abort()
#endif /* ABORT */
#ifndef ABORT_ON_ASSERT_FAILURE
#define ABORT_ON_ASSERT_FAILURE 1
#endif /* ABORT_ON_ASSERT_FAILURE */
#ifndef PROCEED_ON_ERROR
#define PROCEED_ON_ERROR 0
#endif /* PROCEED_ON_ERROR */
#ifndef USE_LOCKS
#define USE_LOCKS 0
#endif /* USE_LOCKS */
#ifndef INSECURE
#define INSECURE 0
#endif /* INSECURE */
#ifndef HAVE_MMAP
#define HAVE_MMAP 1
#endif /* HAVE_MMAP */
#ifndef MMAP_CLEARS
#define MMAP_CLEARS 1
#endif /* MMAP_CLEARS */
#ifndef HAVE_MREMAP
#ifdef linux
#define HAVE_MREMAP 1
#else /* linux */
#define HAVE_MREMAP 0
#endif /* linux */
#endif /* HAVE_MREMAP */
#ifndef MALLOC_FAILURE_ACTION
#define MALLOC_FAILURE_ACTION errno = ENOMEM;
#endif /* MALLOC_FAILURE_ACTION */
#ifndef HAVE_MORECORE
#if ONLY_MSPACES
#define HAVE_MORECORE 0
#else /* ONLY_MSPACES */
#define HAVE_MORECORE 1
#endif /* ONLY_MSPACES */
#endif /* HAVE_MORECORE */
#if !HAVE_MORECORE
#define MORECORE_CONTIGUOUS 0
#else /* !HAVE_MORECORE */
#ifndef MORECORE
#define MORECORE sbrk
#endif /* MORECORE */
#ifndef MORECORE_CONTIGUOUS
#define MORECORE_CONTIGUOUS 1
#endif /* MORECORE_CONTIGUOUS */
#endif /* HAVE_MORECORE */
#ifndef DEFAULT_GRANULARITY
#if MORECORE_CONTIGUOUS
#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
#else /* MORECORE_CONTIGUOUS */
#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
#endif /* MORECORE_CONTIGUOUS */
#endif /* DEFAULT_GRANULARITY */
#ifndef DEFAULT_TRIM_THRESHOLD
#ifndef MORECORE_CANNOT_TRIM
#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
#else /* MORECORE_CANNOT_TRIM */
#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
#endif /* MORECORE_CANNOT_TRIM */
#endif /* DEFAULT_TRIM_THRESHOLD */
#ifndef DEFAULT_MMAP_THRESHOLD
#if HAVE_MMAP
#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
#else /* HAVE_MMAP */
#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
#endif /* HAVE_MMAP */
#endif /* DEFAULT_MMAP_THRESHOLD */
#ifndef USE_BUILTIN_FFS
#define USE_BUILTIN_FFS 0
#endif /* USE_BUILTIN_FFS */
#ifndef USE_DEV_RANDOM
#define USE_DEV_RANDOM 0
#endif /* USE_DEV_RANDOM */
#ifndef NO_MALLINFO
#define NO_MALLINFO 0
#endif /* NO_MALLINFO */
#ifndef MALLINFO_FIELD_TYPE
#define MALLINFO_FIELD_TYPE size_t
#endif /* MALLINFO_FIELD_TYPE */
/*
mallopt tuning options. SVID/XPG defines four standard parameter
numbers for mallopt, normally defined in malloc.h. None of these
are used in this malloc, so setting them has no effect. But this
malloc does support the following options.
*/
#define M_TRIM_THRESHOLD (-1)
#define M_GRANULARITY (-2)
#define M_MMAP_THRESHOLD (-3)
/* ------------------------ Mallinfo declarations ------------------------ */
#if !NO_MALLINFO
/*
This version of malloc supports the standard SVID/XPG mallinfo
routine that returns a struct containing usage properties and
statistics. It should work on any system that has a
/usr/include/malloc.h defining struct mallinfo. The main
declaration needed is the mallinfo struct that is returned (by-copy)
by mallinfo(). The malloinfo struct contains a bunch of fields that
are not even meaningful in this version of malloc. These fields are
are instead filled by mallinfo() with other numbers that might be of
interest.
HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
/usr/include/malloc.h file that includes a declaration of struct
mallinfo. If so, it is included; else a compliant version is
declared below. These must be precisely the same for mallinfo() to
work. The original SVID version of this struct, defined on most
systems with mallinfo, declares all fields as ints. But some others
define as unsigned long. If your system defines the fields using a
type of different width than listed here, you MUST #include your
system version and #define HAVE_USR_INCLUDE_MALLOC_H.
*/
/* #define HAVE_USR_INCLUDE_MALLOC_H */
#ifdef HAVE_USR_INCLUDE_MALLOC_H
#include "/usr/include/malloc.h"
#else /* HAVE_USR_INCLUDE_MALLOC_H */
struct mallinfo {
MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
MALLINFO_FIELD_TYPE smblks; /* always 0 */
MALLINFO_FIELD_TYPE hblks; /* always 0 */
MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
MALLINFO_FIELD_TYPE fordblks; /* total free space */
MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
};
#endif /* HAVE_USR_INCLUDE_MALLOC_H */
#endif /* NO_MALLINFO */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#if !ONLY_MSPACES
/* ------------------- Declarations of public routines ------------------- */
#ifndef USE_DL_PREFIX
#define dlcalloc calloc
#define dlfree free
#define dlmalloc malloc
#define dlmemalign memalign
#define dlrealloc realloc
#define dlvalloc valloc
#define dlpvalloc pvalloc
#define dlmallinfo mallinfo
#define dlmallopt mallopt
#define dlmalloc_trim malloc_trim
#define dlmalloc_stats malloc_stats
#define dlmalloc_usable_size malloc_usable_size
#define dlmalloc_footprint malloc_footprint
#define dlmalloc_max_footprint malloc_max_footprint
#define dlindependent_calloc independent_calloc
#define dlindependent_comalloc independent_comalloc
#endif /* USE_DL_PREFIX */
/*
malloc(size_t n)
Returns a pointer to a newly allocated chunk of at least n bytes, or
null if no space is available, in which case errno is set to ENOMEM
on ANSI C systems.
If n is zero, malloc returns a minimum-sized chunk. (The minimum
size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
systems.) Note that size_t is an unsigned type, so calls with
arguments that would be negative if signed are interpreted as
requests for huge amounts of space, which will often fail. The
maximum supported value of n differs across systems, but is in all
cases less than the maximum representable value of a size_t.
*/
void* dlmalloc(size_t);
/*
free(void* p)
Releases the chunk of memory pointed to by p, that had been previously
allocated using malloc or a related routine such as realloc.
It has no effect if p is null. If p was not malloced or already
freed, free(p) will by default cause the current program to abort.
*/
void dlfree(void*);
/*
calloc(size_t n_elements, size_t element_size);
Returns a pointer to n_elements * element_size bytes, with all locations
set to zero.
*/
void* dlcalloc(size_t, size_t);
/*
realloc(void* p, size_t n)
Returns a pointer to a chunk of size n that contains the same data
as does chunk p up to the minimum of (n, p's size) bytes, or null
if no space is available.
The returned pointer may or may not be the same as p. The algorithm
prefers extending p in most cases when possible, otherwise it
employs the equivalent of a malloc-copy-free sequence.
If p is null, realloc is equivalent to malloc.
If space is not available, realloc returns null, errno is set (if on
ANSI) and p is NOT freed.
if n is for fewer bytes than already held by p, the newly unused
space is lopped off and freed if possible. realloc with a size
argument of zero (re)allocates a minimum-sized chunk.
The old unix realloc convention of allowing the last-free'd chunk
to be used as an argument to realloc is not supported.
*/
void* dlrealloc(void*, size_t);
/*
memalign(size_t alignment, size_t n);
Returns a pointer to a newly allocated chunk of n bytes, aligned
in accord with the alignment argument.
The alignment argument should be a power of two. If the argument is
not a power of two, the nearest greater power is used.
8-byte alignment is guaranteed by normal malloc calls, so don't
bother calling memalign with an argument of 8 or less.
Overreliance on memalign is a sure way to fragment space.
*/
void* dlmemalign(size_t, size_t);
/*
valloc(size_t n);
Equivalent to memalign(pagesize, n), where pagesize is the page
size of the system. If the pagesize is unknown, 4096 is used.
*/
void* dlvalloc(size_t);
/*
mallopt(int parameter_number, int parameter_value)
Sets tunable parameters The format is to provide a
(parameter-number, parameter-value) pair. mallopt then sets the
corresponding parameter to the argument value if it can (i.e., so
long as the value is meaningful), and returns 1 if successful else
0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
normally defined in malloc.h. None of these are use in this malloc,
so setting them has no effect. But this malloc also supports other
options in mallopt. See below for details. Briefly, supported
parameters are as follows (listed defaults are for "typical"
configurations).
Symbol param # default allowed param values
M_TRIM_THRESHOLD -1 2*1024*1024 any (MAX_SIZE_T disables)
M_GRANULARITY -2 page size any power of 2 >= page size
M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
*/
int dlmallopt(int, int);
/*
malloc_footprint();
Returns the number of bytes obtained from the system. The total
number of bytes allocated by malloc, realloc etc., is less than this
value. Unlike mallinfo, this function returns only a precomputed
result, so can be called frequently to monitor memory consumption.
Even if locks are otherwise defined, this function does not use them,
so results might not be up to date.
*/
size_t dlmalloc_footprint(void);
/*
malloc_max_footprint();
Returns the maximum number of bytes obtained from the system. This
value will be greater than current footprint if deallocated space
has been reclaimed by the system. The peak number of bytes allocated
by malloc, realloc etc., is less than this value. Unlike mallinfo,
this function returns only a precomputed result, so can be called
frequently to monitor memory consumption. Even if locks are
otherwise defined, this function does not use them, so results might
not be up to date.
*/
size_t dlmalloc_max_footprint(void);
#if !NO_MALLINFO
/*
mallinfo()
Returns (by copy) a struct containing various summary statistics:
arena: current total non-mmapped bytes allocated from system
ordblks: the number of free chunks
smblks: always zero.
hblks: current number of mmapped regions
hblkhd: total bytes held in mmapped regions
usmblks: the maximum total allocated space. This will be greater
than current total if trimming has occurred.
fsmblks: always zero
uordblks: current total allocated space (normal or mmapped)
fordblks: total free space
keepcost: the maximum number of bytes that could ideally be released
back to system via malloc_trim. ("ideally" means that
it ignores page restrictions etc.)
Because these fields are ints, but internal bookkeeping may
be kept as longs, the reported values may wrap around zero and
thus be inaccurate.
*/
struct mallinfo dlmallinfo(void);
#endif /* NO_MALLINFO */
/*
independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
independent_calloc is similar to calloc, but instead of returning a
single cleared space, it returns an array of pointers to n_elements
independent elements that can hold contents of size elem_size, each
of which starts out cleared, and can be independently freed,
realloc'ed etc. The elements are guaranteed to be adjacently
allocated (this is not guaranteed to occur with multiple callocs or
mallocs), which may also improve cache locality in some
applications.
The "chunks" argument is optional (i.e., may be null, which is
probably the most typical usage). If it is null, the returned array
is itself dynamically allocated and should also be freed when it is
no longer needed. Otherwise, the chunks array must be of at least
n_elements in length. It is filled in with the pointers to the
chunks.
In either case, independent_calloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and "chunks"
is null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be individually freed when it is no longer
needed. If you'd like to instead be able to free all at once, you
should instead use regular calloc and assign pointers into this
space to represent elements. (In this case though, you cannot
independently free elements.)
independent_calloc simplifies and speeds up implementations of many
kinds of pools. It may also be useful when constructing large data
structures that initially have a fixed number of fixed-sized nodes,
but the number is not known at compile time, and some of the nodes
may later need to be freed. For example:
struct Node { int item; struct Node* next; };
struct Node* build_list() {
struct Node** pool;
int n = read_number_of_nodes_needed();
if (n <= 0) return 0;
pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
if (pool == 0) die();
// organize into a linked list...
struct Node* first = pool[0];
for (i = 0; i < n-1; ++i)
pool[i]->next = pool[i+1];
free(pool); // Can now free the array (or not, if it is needed later)
return first;
}
*/
void** dlindependent_calloc(size_t, size_t, void**);
/*
independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
independent_comalloc allocates, all at once, a set of n_elements
chunks with sizes indicated in the "sizes" array. It returns
an array of pointers to these elements, each of which can be
independently freed, realloc'ed etc. The elements are guaranteed to
be adjacently allocated (this is not guaranteed to occur with
multiple callocs or mallocs), which may also improve cache locality
in some applications.
The "chunks" argument is optional (i.e., may be null). If it is null
the returned array is itself dynamically allocated and should also
be freed when it is no longer needed. Otherwise, the chunks array
must be of at least n_elements in length. It is filled in with the
pointers to the chunks.
In either case, independent_comalloc returns this pointer array, or
null if the allocation failed. If n_elements is zero and chunks is
null, it returns a chunk representing an array with zero elements
(which should be freed if not wanted).
Each element must be individually freed when it is no longer
needed. If you'd like to instead be able to free all at once, you
should instead use a single regular malloc, and assign pointers at
particular offsets in the aggregate space. (In this case though, you
cannot independently free elements.)
independent_comallac differs from independent_calloc in that each
element may have a different size, and also that it does not
automatically clear elements.
independent_comalloc can be used to speed up allocation in cases
where several structs or objects must always be allocated at the
same time. For example:
struct Head { ... }
struct Foot { ... }
void send_message(char* msg) {
int msglen = strlen(msg);
size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
void* chunks[3];
if (independent_comalloc(3, sizes, chunks) == 0)
die();
struct Head* head = (struct Head*)(chunks[0]);
char* body = (char*)(chunks[1]);
struct Foot* foot = (struct Foot*)(chunks[2]);
// ...
}
In general though, independent_comalloc is worth using only for
larger values of n_elements. For small values, you probably won't
detect enough difference from series of malloc calls to bother.
Overuse of independent_comalloc can increase overall memory usage,
since it cannot reuse existing noncontiguous small chunks that
might be available for some of the elements.
*/
void** dlindependent_comalloc(size_t, size_t*, void**);
/*
pvalloc(size_t n);
Equivalent to valloc(minimum-page-that-holds(n)), that is,
round up n to nearest pagesize.
*/
void* dlpvalloc(size_t);
/*
malloc_trim(size_t pad);
If possible, gives memory back to the system (via negative arguments
to sbrk) if there is unused memory at the `high' end of the malloc
pool or in unused MMAP segments. You can call this after freeing
large blocks of memory to potentially reduce the system-level memory
requirements of a program. However, it cannot guarantee to reduce
memory. Under some allocation patterns, some large free blocks of
memory will be locked between two used chunks, so they cannot be
given back to the system.
The `pad' argument to malloc_trim represents the amount of free
trailing space to leave untrimmed. If this argument is zero, only
the minimum amount of memory to maintain internal data structures
will be left. Non-zero arguments can be supplied to maintain enough
trailing space to service future expected allocations without having
to re-obtain memory from the system.
Malloc_trim returns 1 if it actually released any memory, else 0.
*/
int dlmalloc_trim(size_t);
/*
malloc_usable_size(void* p);
Returns the number of bytes you can actually use in
an allocated chunk, which may be more than you requested (although
often not) due to alignment and minimum size constraints.
You can use this many bytes without worrying about
overwriting other allocated objects. This is not a particularly great
programming practice. malloc_usable_size can be more useful in
debugging and assertions, for example:
p = malloc(n);
assert(malloc_usable_size(p) >= 256);
*/
size_t dlmalloc_usable_size(void*);
/*
malloc_stats();
Prints on stderr the amount of space obtained from the system (both
via sbrk and mmap), the maximum amount (which may be more than
current if malloc_trim and/or munmap got called), and the current
number of bytes allocated via malloc (or realloc, etc) but not yet
freed. Note that this is the number of bytes allocated, not the
number requested. It will be larger than the number requested
because of alignment and bookkeeping overhead. Because it includes
alignment wastage as being in use, this figure may be greater than
zero even when no user-level chunks are allocated.
The reported current and maximum system memory can be inaccurate if
a program makes other calls to system memory allocation functions
(normally sbrk) outside of malloc.
malloc_stats prints only the most commonly interesting statistics.
More information can be obtained by calling mallinfo.
*/
void dlmalloc_stats(void);
#endif /* ONLY_MSPACES */
#if MSPACES
/*
mspace is an opaque type representing an independent
region of space that supports mspace_malloc, etc.
*/
typedef void* mspace;
/*
create_mspace creates and returns a new independent space with the
given initial capacity, or, if 0, the default granularity size. It
returns null if there is no system memory available to create the
space. If argument locked is non-zero, the space uses a separate
lock to control access. The capacity of the space will grow
dynamically as needed to service mspace_malloc requests. You can
control the sizes of incremental increases of this space by
compiling with a different DEFAULT_GRANULARITY or dynamically
setting with mallopt(M_GRANULARITY, value).
*/
mspace create_mspace(size_t capacity, int locked);
/*
destroy_mspace destroys the given space, and attempts to return all
of its memory back to the system, returning the total number of
bytes freed. After destruction, the results of access to all memory
used by the space become undefined.
*/
size_t destroy_mspace(mspace msp);
/*
create_mspace_with_base uses the memory supplied as the initial base
of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
space is used for bookkeeping, so the capacity must be at least this
large. (Otherwise 0 is returned.) When this initial space is
exhausted, additional memory will be obtained from the system.
Destroying this space will deallocate all additionally allocated
space (if possible) but not the initial base.
*/
mspace create_mspace_with_base(void* base, size_t capacity, int locked);
/*
mspace_malloc behaves as malloc, but operates within
the given space.
*/
void* mspace_malloc(mspace msp, size_t bytes);
/*
mspace_free behaves as free, but operates within
the given space.
If compiled with FOOTERS==1, mspace_free is not actually needed.
free may be called instead of mspace_free because freed chunks from
any space are handled by their originating spaces.
*/
void mspace_free(mspace msp, void* mem);
/*
mspace_realloc behaves as realloc, but operates within
the given space.
If compiled with FOOTERS==1, mspace_realloc is not actually
needed. realloc may be called instead of mspace_realloc because
realloced chunks from any space are handled by their originating
spaces.
*/
void* mspace_realloc(mspace msp, void* mem, size_t newsize);
/*
mspace_calloc behaves as calloc, but operates within
the given space.
*/
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
/*
mspace_memalign behaves as memalign, but operates within
the given space.
*/
void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
/*
mspace_independent_calloc behaves as independent_calloc, but
operates within the given space.
*/
void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]);
/*
mspace_independent_comalloc behaves as independent_comalloc, but
operates within the given space.
*/
void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]);
/*
mspace_footprint() returns the number of bytes obtained from the
system for this space.
*/
size_t mspace_footprint(mspace msp);
/*
mspace_max_footprint() returns the peak number of bytes obtained from the
system for this space.
*/
size_t mspace_max_footprint(mspace msp);
#if !NO_MALLINFO
/*
mspace_mallinfo behaves as mallinfo, but reports properties of
the given space.
*/
struct mallinfo mspace_mallinfo(mspace msp);
#endif /* NO_MALLINFO */
/*
mspace_malloc_stats behaves as malloc_stats, but reports
properties of the given space.
*/
void mspace_malloc_stats(mspace msp);
/*
mspace_trim behaves as malloc_trim, but
operates within the given space.
*/
int mspace_trim(mspace msp, size_t pad);
/*
An alias for mallopt.
*/
int mspace_mallopt(int, int);
#endif /* MSPACES */
#ifdef __cplusplus
}; /* end of extern "C" */
#endif /* __cplusplus */
/*
========================================================================
To make a fully customizable malloc.h header file, cut everything
above this line, put into file malloc.h, edit to suit, and #include it
on the next line, as well as in programs that use this malloc.
========================================================================
*/
/* #include "malloc.h" */
/*------------------------------ internal #includes ---------------------- */
#ifdef WIN32
#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
#endif /* WIN32 */
#include <stdio.h> /* for printing in malloc_stats */
#ifndef LACKS_ERRNO_H
#include <errno.h> /* for MALLOC_FAILURE_ACTION */
#endif /* LACKS_ERRNO_H */
#if FOOTERS
#include <time.h> /* for magic initialization */
#endif /* FOOTERS */
#ifndef LACKS_STDLIB_H
#include <stdlib.h> /* for abort() */
#endif /* LACKS_STDLIB_H */
#ifdef DEBUG
#if ABORT_ON_ASSERT_FAILURE
#define assert(x) if(!(x)) ABORT
#else /* ABORT_ON_ASSERT_FAILURE */
#include <assert.h>
#endif /* ABORT_ON_ASSERT_FAILURE */
#else /* DEBUG */
#define assert(x)
#endif /* DEBUG */
#ifndef LACKS_STRING_H
#include <string.h> /* for memset etc */
#endif /* LACKS_STRING_H */
#if USE_BUILTIN_FFS
#ifndef LACKS_STRINGS_H
#include <strings.h> /* for ffs */
#endif /* LACKS_STRINGS_H */
#endif /* USE_BUILTIN_FFS */
#if HAVE_MMAP
#ifndef LACKS_SYS_MMAN_H
#include <sys/mman.h> /* for mmap */
#endif /* LACKS_SYS_MMAN_H */
#ifndef LACKS_FCNTL_H
#include <fcntl.h>
#endif /* LACKS_FCNTL_H */
#endif /* HAVE_MMAP */
#if HAVE_MORECORE
#ifndef LACKS_UNISTD_H
#include <unistd.h> /* for sbrk */
#else /* LACKS_UNISTD_H */
#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
extern void* sbrk(ptrdiff_t);
#endif /* FreeBSD etc */
#endif /* LACKS_UNISTD_H */
#endif /* HAVE_MMAP */
#ifndef WIN32
#ifndef malloc_getpagesize
# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
# ifndef _SC_PAGE_SIZE
# define _SC_PAGE_SIZE _SC_PAGESIZE
# endif
# endif
# ifdef _SC_PAGE_SIZE
# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
# else
# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
extern size_t getpagesize();
# define malloc_getpagesize getpagesize()
# else
# ifdef WIN32 /* use supplied emulation of getpagesize */
# define malloc_getpagesize getpagesize()
# else
# ifndef LACKS_SYS_PARAM_H
# include <sys/param.h>
# endif
# ifdef EXEC_PAGESIZE
# define malloc_getpagesize EXEC_PAGESIZE
# else
# ifdef NBPG
# ifndef CLSIZE
# define malloc_getpagesize NBPG
# else
# define malloc_getpagesize (NBPG * CLSIZE)
# endif
# else
# ifdef NBPC
# define malloc_getpagesize NBPC
# else
# ifdef PAGESIZE
# define malloc_getpagesize PAGESIZE
# else /* just guess */
# define malloc_getpagesize ((size_t)4096U)
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
#endif
/* ------------------- size_t and alignment properties -------------------- */
/* The byte and bit size of a size_t */
#define SIZE_T_SIZE (sizeof(size_t))
#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
/* Some constants coerced to size_t */
/* Annoying but necessary to avoid errors on some plaftorms */
#define SIZE_T_ZERO ((size_t)0)
#define SIZE_T_ONE ((size_t)1)
#define SIZE_T_TWO ((size_t)2)
#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
/* The bit mask value corresponding to MALLOC_ALIGNMENT */
#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
/* True if address a has acceptable alignment */
#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
/* the number of bytes to offset an address to align it */
#define align_offset(A)\
((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
/* -------------------------- MMAP preliminaries ------------------------- */
/*
If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
checks to fail so compiler optimizer can delete code rather than
using so many "#if"s.
*/
/* MORECORE and MMAP must return MFAIL on failure */
#define MFAIL ((void*)(MAX_SIZE_T))
#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
#if !HAVE_MMAP
#define IS_MMAPPED_BIT (SIZE_T_ZERO)
#define USE_MMAP_BIT (SIZE_T_ZERO)
#define CALL_MMAP(s) MFAIL
#define CALL_MUNMAP(a, s) (-1)
#define DIRECT_MMAP(s) MFAIL
#else /* HAVE_MMAP */
#define IS_MMAPPED_BIT (SIZE_T_ONE)
#define USE_MMAP_BIT (SIZE_T_ONE)
#ifndef WIN32
#define CALL_MUNMAP(a, s) munmap((a), (s))
#define MMAP_PROT (PROT_READ|PROT_WRITE)
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif /* MAP_ANON */
#ifdef MAP_ANONYMOUS
#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
#else /* MAP_ANONYMOUS */
/*
Nearly all versions of mmap support MAP_ANONYMOUS, so the following
is unlikely to be needed, but is supplied just in case.
*/
#define MMAP_FLAGS (MAP_PRIVATE)
static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \
(dev_zero_fd = open("/dev/zero", O_RDWR), \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
#endif /* MAP_ANONYMOUS */
#define DIRECT_MMAP(s) CALL_MMAP(s)
#else /* WIN32 */
/* Win32 MMAP via VirtualAlloc */
static void* win32mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
static void* win32direct_mmap(size_t size) {
void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
PAGE_READWRITE);
return (ptr != 0)? ptr: MFAIL;
}
/* This function supports releasing coalesed segments */
static int win32munmap(void* ptr, size_t size) {
MEMORY_BASIC_INFORMATION minfo;
char* cptr = (char *)ptr;
while (size) {
if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
return -1;
if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
minfo.State != MEM_COMMIT || minfo.RegionSize > size)
return -1;
if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
return -1;
cptr += minfo.RegionSize;
size -= minfo.RegionSize;
}
return 0;
}
#define CALL_MMAP(s) win32mmap(s)
#define CALL_MUNMAP(a, s) win32munmap((a), (s))
#define DIRECT_MMAP(s) win32direct_mmap(s)
#endif /* WIN32 */
#endif /* HAVE_MMAP */
#if HAVE_MMAP && HAVE_MREMAP
#define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
#else /* HAVE_MMAP && HAVE_MREMAP */
#define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
#endif /* HAVE_MMAP && HAVE_MREMAP */
#if HAVE_MORECORE
#define CALL_MORECORE(S) MORECORE(S)
#else /* HAVE_MORECORE */
#define CALL_MORECORE(S) MFAIL
#endif /* HAVE_MORECORE */
/* mstate bit set if continguous morecore disabled or failed */
#define USE_NONCONTIGUOUS_BIT (4U)
/* segment bit set in create_mspace_with_base */
#define EXTERN_BIT (8U)
/* --------------------------- Lock preliminaries ------------------------ */
#if USE_LOCKS
/*
When locks are defined, there are up to two global locks:
* If HAVE_MORECORE, morecore_mutex protects sequences of calls to
MORECORE. In many cases sys_alloc requires two calls, that should
not be interleaved with calls by other threads. This does not
protect against direct calls to MORECORE by other threads not
using this lock, so there is still code to cope the best we can on
interference.
* magic_init_mutex ensures that mparams.magic and other
unique mparams values are initialized only once.
*/
#ifndef WIN32
/* By default use posix locks */
#include <pthread.h>
#define MLOCK_T pthread_mutex_t
#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL)
#define ACQUIRE_LOCK(l) pthread_mutex_lock(l)
#define RELEASE_LOCK(l) pthread_mutex_unlock(l)
#if HAVE_MORECORE
static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif /* HAVE_MORECORE */
static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER;
#else /* WIN32 */
/*
Because lock-protected regions have bounded times, and there
are no recursive lock calls, we can use simple spinlocks.
*/
#define MLOCK_T long
static int win32_acquire_lock (MLOCK_T *sl) {
for (;;) {
#ifdef InterlockedCompareExchangePointer
if (!InterlockedCompareExchange(sl, 1, 0))
return 0;
#else /* Use older void* version */
if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0))
return 0;
#endif /* InterlockedCompareExchangePointer */
Sleep (0);
}
}
static void win32_release_lock (MLOCK_T *sl) {
InterlockedExchange (sl, 0);
}
#define INITIAL_LOCK(l) *(l)=0
#define ACQUIRE_LOCK(l) win32_acquire_lock(l)
#define RELEASE_LOCK(l) win32_release_lock(l)
#if HAVE_MORECORE
static MLOCK_T morecore_mutex;
#endif /* HAVE_MORECORE */
static MLOCK_T magic_init_mutex;
#endif /* WIN32 */
#define USE_LOCK_BIT (2U)
#else /* USE_LOCKS */
#define USE_LOCK_BIT (0U)
#define INITIAL_LOCK(l)
#endif /* USE_LOCKS */
#if USE_LOCKS && HAVE_MORECORE
#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex);
#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex);
#else /* USE_LOCKS && HAVE_MORECORE */
#define ACQUIRE_MORECORE_LOCK()
#define RELEASE_MORECORE_LOCK()
#endif /* USE_LOCKS && HAVE_MORECORE */
#if USE_LOCKS
#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex);
#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex);
#else /* USE_LOCKS */
#define ACQUIRE_MAGIC_INIT_LOCK()
#define RELEASE_MAGIC_INIT_LOCK()
#endif /* USE_LOCKS */
/* ----------------------- Chunk representations ------------------------ */
/*
(The following includes lightly edited explanations by Colin Plumb.)
The malloc_chunk declaration below is misleading (but accurate and
necessary). It declares a "view" into memory allowing access to
necessary fields at known offsets from a given base.
Chunks of memory are maintained using a `boundary tag' method as
originally described by Knuth. (See the paper by Paul Wilson
ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
techniques.) Sizes of free chunks are stored both in the front of
each chunk and at the end. This makes consolidating fragmented
chunks into bigger chunks fast. The head fields also hold bits
representing whether chunks are free or in use.
Here are some pictures to make it clearer. They are "exploded" to
show that the state of a chunk can be thought of as extending from
the high 31 bits of the head field of its header through the
prev_foot and PINUSE_BIT bit of the following chunk header.
A chunk that's in use looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk (if P = 1) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 1| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- -+
| :
+- size - sizeof(size_t) available payload bytes -+
: |
chunk-> +- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
| Size of next chunk (may or may not be in use) | +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
And if it's free, it looks like this:
chunk-> +- -+
| User payload (must be in use, or we would have merged!) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
| Size of this chunk 0| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Prev pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- size - sizeof(struct chunk) unused bytes -+
: |
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
| Size of next chunk (must be in use, or we would have merged)| +-+
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| :
+- User payload -+
: |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|
+-+
Note that since we always merge adjacent free chunks, the chunks
adjacent to a free chunk must be in use.
Given a pointer to a chunk (which can be derived trivially from the
payload pointer) we can, in O(1) time, find out whether the adjacent
chunks are free, and if so, unlink them from the lists that they
are on and merge them with the current chunk.
Chunks always begin on even word boundaries, so the mem portion
(which is returned to the user) is also on an even word boundary, and
thus at least double-word aligned.
The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
chunk size (which is always a multiple of two words), is an in-use
bit for the *previous* chunk. If that bit is *clear*, then the
word before the current chunk size contains the previous chunk
size, and can be used to find the front of the previous chunk.
The very first chunk allocated always has this bit set, preventing
access to non-existent (or non-owned) memory. If pinuse is set for
any given chunk, then you CANNOT determine the size of the
previous chunk, and might even get a memory addressing fault when
trying to do so.
The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
the chunk size redundantly records whether the current chunk is
inuse. This redundancy enables usage checks within free and realloc,
and reduces indirection when freeing and consolidating chunks.
Each freshly allocated chunk must have both cinuse and pinuse set.
That is, each allocated chunk borders either a previously allocated
and still in-use chunk, or the base of its memory arena. This is
ensured by making all allocations from the the `lowest' part of any
found chunk. Further, no free chunk physically borders another one,
so each free chunk is known to be preceded and followed by either
inuse chunks or the ends of memory.
Note that the `foot' of the current chunk is actually represented
as the prev_foot of the NEXT chunk. This makes it easier to
deal with alignments etc but can be very confusing when trying
to extend or adapt this code.
The exceptions to all this are
1. The special chunk `top' is the top-most available chunk (i.e.,
the one bordering the end of available memory). It is treated
specially. Top is never included in any bin, is used only if
no other chunk is available, and is released back to the
system if it is very large (see M_TRIM_THRESHOLD). In effect,
the top chunk is treated as larger (and thus less well
fitting) than any other available chunk. The top chunk
doesn't update its trailing size field since there is no next
contiguous chunk that would have to index off it. However,
space is still allocated for it (TOP_FOOT_SIZE) to enable
separation or merging when space is extended.
3. Chunks allocated via mmap, which have the lowest-order bit
(IS_MMAPPED_BIT) set in their prev_foot fields, and do not set
PINUSE_BIT in their head fields. Because they are allocated
one-by-one, each must carry its own prev_foot field, which is
also used to hold the offset this chunk has within its mmapped
region, which is needed to preserve alignment. Each mmapped
chunk is trailed by the first two fields of a fake next-chunk
for sake of usage checks.
*/
struct malloc_chunk {
size_t prev_foot; /* Size of previous chunk (if free). */
size_t head; /* Size and inuse bits. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
};
typedef struct malloc_chunk mchunk;
typedef struct malloc_chunk* mchunkptr;
typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
typedef unsigned int bindex_t; /* Described below */
typedef unsigned int binmap_t; /* Described below */
typedef unsigned int flag_t; /* The type of various bit flag sets */
/* ------------------- Chunks sizes and alignments ----------------------- */
#define MCHUNK_SIZE (sizeof(mchunk))
#if FOOTERS
#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
#else /* FOOTERS */
#define CHUNK_OVERHEAD (SIZE_T_SIZE)
#endif /* FOOTERS */
/* MMapped chunks need a second word of overhead ... */
#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
/* ... and additional padding for fake next-chunk at foot */
#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
/* The smallest size we can malloc is an aligned minimal chunk */
#define MIN_CHUNK_SIZE\
((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
/* chunk associated with aligned address A */
#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
/* Bounds on request (not chunk) sizes. */
#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
/* pad request bytes into a usable size */
#define pad_request(req) \
(((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
/* pad request, checking for minimum (but not maximum) */
#define request2size(req) \
(((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
/* ------------------ Operations on head and foot fields ----------------- */
/*
The head field of a chunk is or'ed with PINUSE_BIT when previous
adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
use. If the chunk was obtained with mmap, the prev_foot field has
IS_MMAPPED_BIT set, otherwise holding the offset of the base of the
mmapped region to the base of the chunk.
*/
#define PINUSE_BIT (SIZE_T_ONE)
#define CINUSE_BIT (SIZE_T_TWO)
#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
/* Head value for fenceposts */
#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
/* extraction of fields from head words */
#define cinuse(p) ((p)->head & CINUSE_BIT)
#define pinuse(p) ((p)->head & PINUSE_BIT)
#define chunksize(p) ((p)->head & ~(INUSE_BITS))
#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT)
/* Treat space at ptr +/- offset as a chunk */
#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
/* Ptr to next or previous physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS)))
#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
/* extract next chunk's pinuse bit */
#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
/* Get/set size at footer */
#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
/* Set size, pinuse bit, and foot */
#define set_size_and_pinuse_of_free_chunk(p, s)\
((p)->head = (s|PINUSE_BIT), set_foot(p, s))
/* Set size, pinuse bit, foot, and clear next pinuse */
#define set_free_with_pinuse(p, s, n)\
(clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
#define is_mmapped(p)\
(!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT))
/* Get the internal overhead associated with chunk p */
#define overhead_for(p)\
(is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
/* Return true if malloced space is not necessarily cleared */
#if MMAP_CLEARS
#define calloc_must_clear(p) (!is_mmapped(p))
#else /* MMAP_CLEARS */
#define calloc_must_clear(p) (1)
#endif /* MMAP_CLEARS */
/* ---------------------- Overlaid data structures ----------------------- */
/*
When chunks are not in use, they are treated as nodes of either
lists or trees.
"Small" chunks are stored in circular doubly-linked lists, and look
like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Larger chunks are kept in a form of bitwise digital trees (aka
tries) keyed on chunksizes. Because malloc_tree_chunks are only for
free chunks greater than 256 bytes, their size doesn't impose any
constraints on user chunk sizes. Each node looks like:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk of same size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to left child (child[0]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to right child (child[1]) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer to parent |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| bin index of this chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Each tree holding treenodes is a tree of unique chunk sizes. Chunks
of the same size are arranged in a circularly-linked list, with only
the oldest chunk (the next to be used, in our FIFO ordering)
actually in the tree. (Tree members are distinguished by a non-null
parent pointer.) If a chunk with the same size an an existing node
is inserted, it is linked off the existing node using pointers that
work in the same way as fd/bk pointers of small chunks.
Each tree contains a power of 2 sized range of chunk sizes (the
smallest is 0x100 <= x < 0x180), which is is divided in half at each
tree level, with the chunks in the smaller half of the range (0x100
<= x < 0x140 for the top nose) in the left subtree and the larger
half (0x140 <= x < 0x180) in the right subtree. This is, of course,
done by inspecting individual bits.
Using these rules, each node's left subtree contains all smaller
sizes than its right subtree. However, the node at the root of each
subtree has no particular ordering relationship to either. (The
dividing line between the subtree sizes is based on trie relation.)
If we remove the last chunk of a given size from the interior of the
tree, we need to replace it with a leaf node. The tree ordering
rules permit a node to be replaced by any leaf below it.
The smallest chunk in a tree (a common operation in a best-fit
allocator) can be found by walking a path to the leftmost leaf in
the tree. Unlike a usual binary tree, where we follow left child
pointers until we reach a null, here we follow the right child
pointer any time the left one is null, until we reach a leaf with
both child pointers null. The smallest chunk in the tree will be
somewhere along that path.
The worst case number of steps to add, find, or remove a node is
bounded by the number of bits differentiating chunks within
bins. Under current bin calculations, this ranges from 6 up to 21
(for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
is of course much better.
*/
struct malloc_tree_chunk {
/* The first four fields must be compatible with malloc_chunk */
size_t prev_foot;
size_t head;
struct malloc_tree_chunk* fd;
struct malloc_tree_chunk* bk;
struct malloc_tree_chunk* child[2];
struct malloc_tree_chunk* parent;
bindex_t index;
};
typedef struct malloc_tree_chunk tchunk;
typedef struct malloc_tree_chunk* tchunkptr;
typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
/* A little helper macro for trees */
#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
/* ----------------------------- Segments -------------------------------- */
/*
Each malloc space may include non-contiguous segments, held in a
list headed by an embedded malloc_segment record representing the
top-most space. Segments also include flags holding properties of
the space. Large chunks that are directly allocated by mmap are not
included in this list. They are instead independently created and
destroyed without otherwise keeping track of them.
Segment management mainly comes into play for spaces allocated by
MMAP. Any call to MMAP might or might not return memory that is
adjacent to an existing segment. MORECORE normally contiguously
extends the current space, so this space is almost always adjacent,
which is simpler and faster to deal with. (This is why MORECORE is
used preferentially to MMAP when both are available -- see
sys_alloc.) When allocating using MMAP, we don't use any of the
hinting mechanisms (inconsistently) supported in various
implementations of unix mmap, or distinguish reserving from
committing memory. Instead, we just ask for space, and exploit
contiguity when we get it. It is probably possible to do
better than this on some systems, but no general scheme seems
to be significantly better.
Management entails a simpler variant of the consolidation scheme
used for chunks to reduce fragmentation -- new adjacent memory is
normally prepended or appended to an existing segment. However,
there are limitations compared to chunk consolidation that mostly
reflect the fact that segment processing is relatively infrequent
(occurring only when getting memory from system) and that we
don't expect to have huge numbers of segments:
* Segments are not indexed, so traversal requires linear scans. (It
would be possible to index these, but is not worth the extra
overhead and complexity for most programs on most platforms.)
* New segments are only appended to old ones when holding top-most
memory; if they cannot be prepended to others, they are held in
different segments.
Except for the top-most segment of an mstate, each segment record
is kept at the tail of its segment. Segments are added by pushing
segment records onto the list headed by &mstate.seg for the
containing mstate.
Segment flags control allocation/merge/deallocation policies:
* If EXTERN_BIT set, then we did not allocate this segment,
and so should not try to deallocate or merge with others.
(This currently holds only for the initial segment passed
into create_mspace_with_base.)
* If IS_MMAPPED_BIT set, the segment may be merged with
other surrounding mmapped segments and trimmed/de-allocated
using munmap.
* If neither bit is set, then the segment was obtained using
MORECORE so can be merged with surrounding MORECORE'd segments
and deallocated/trimmed using MORECORE with negative arguments.
*/
struct malloc_segment {
char* base; /* base address */
size_t size; /* allocated size */
struct malloc_segment* next; /* ptr to next segment */
flag_t sflags; /* mmap and extern flag */
};
#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT)
#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
typedef struct malloc_segment msegment;
typedef struct malloc_segment* msegmentptr;
/* ---------------------------- malloc_state ----------------------------- */
/*
A malloc_state holds all of the bookkeeping for a space.
The main fields are:
Top
The topmost chunk of the currently active segment. Its size is
cached in topsize. The actual size of topmost space is
topsize+TOP_FOOT_SIZE, which includes space reserved for adding
fenceposts and segment records if necessary when getting more
space from the system. The size at which to autotrim top is
cached from mparams in trim_check, except that it is disabled if
an autotrim fails.
Designated victim (dv)
This is the preferred chunk for servicing small requests that
don't have exact fits. It is normally the chunk split off most
recently to service another small request. Its size is cached in
dvsize. The link fields of this chunk are not maintained since it
is not kept in a bin.
SmallBins
An array of bin headers for free chunks. These bins hold chunks
with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
chunks of all the same size, spaced 8 bytes apart. To simplify
use in double-linked lists, each bin header acts as a malloc_chunk
pointing to the real first node, if it exists (else pointing to
itself). This avoids special-casing for headers. But to avoid
waste, we allocate only the fd/bk pointers of bins, and then use
repositioning tricks to treat these as the fields of a chunk.
TreeBins
Treebins are pointers to the roots of trees holding a range of
sizes. There are 2 equally spaced treebins for each power of two
from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
larger.
Bin maps
There is one bit map for small bins ("smallmap") and one for
treebins ("treemap). Each bin sets its bit when non-empty, and
clears the bit when empty. Bit operations are then used to avoid
bin-by-bin searching -- nearly all "search" is done without ever
looking at bins that won't be selected. The bit maps
conservatively use 32 bits per map word, even if on 64bit system.
For a good description of some of the bit-based techniques used
here, see Henry S. Warren Jr's book "Hacker's Delight" (and
supplement at http://hackersdelight.org/). Many of these are
intended to reduce the branchiness of paths through malloc etc, as
well as to reduce the number of memory locations read or written.
Segments
A list of segments headed by an embedded malloc_segment record
representing the initial space.
Address check support
The least_addr field is the least address ever obtained from
MORECORE or MMAP. Attempted frees and reallocs of any address less
than this are trapped (unless INSECURE is defined).
Magic tag
A cross-check field that should always hold same value as mparams.magic.
Flags
Bits recording whether to use MMAP, locks, or contiguous MORECORE
Statistics
Each space keeps track of current and maximum system memory
obtained via MORECORE or MMAP.
Locking
If USE_LOCKS is defined, the "mutex" lock is acquired and released
around every public call using this mspace.
*/
/* Bin types, widths and sizes */
#define NSMALLBINS (32U)
#define NTREEBINS (32U)
#define SMALLBIN_SHIFT (3U)
#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
#define TREEBIN_SHIFT (8U)
#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
struct malloc_state {
binmap_t smallmap;
binmap_t treemap;
size_t dvsize;
size_t topsize;
char* least_addr;
mchunkptr dv;
mchunkptr top;
size_t trim_check;
size_t magic;
mchunkptr smallbins[(NSMALLBINS+1)*2];
tbinptr treebins[NTREEBINS];
size_t footprint;
size_t max_footprint;
flag_t mflags;
#if USE_LOCKS
MLOCK_T mutex; /* locate lock among fields that rarely change */
#endif /* USE_LOCKS */
msegment seg;
};
typedef struct malloc_state* mstate;
/* ------------- Global malloc_state and malloc_params ------------------- */
/*
malloc_params holds global properties, including those that can be
dynamically set using mallopt. There is a single instance, mparams,
initialized in init_mparams.
*/
struct malloc_params {
size_t magic;
size_t page_size;
size_t granularity;
size_t mmap_threshold;
size_t trim_threshold;
flag_t default_mflags;
};
static struct malloc_params mparams;
/* The global malloc_state used for all non-"mspace" calls */
static struct malloc_state _gm_;
#define gm (&_gm_)
#define is_global(M) ((M) == &_gm_)
#define is_initialized(M) ((M)->top != 0)
/* -------------------------- system alloc setup ------------------------- */
/* Operations on mflags */
#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
#define set_lock(M,L)\
((M)->mflags = (L)?\
((M)->mflags | USE_LOCK_BIT) :\
((M)->mflags & ~USE_LOCK_BIT))
/* page-align a size */
#define page_align(S)\
(((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE))
/* granularity-align a size */
#define granularity_align(S)\
(((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE))
#define is_page_aligned(S)\
(((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
#define is_granularity_aligned(S)\
(((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
/* True if segment S holds address A */
#define segment_holds(S, A)\
((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
/* Return segment holding given address */
static msegmentptr segment_holding(mstate m, char* addr) {
msegmentptr sp = &m->seg;
for (;;) {
if (addr >= sp->base && addr < sp->base + sp->size)
return sp;
if ((sp = sp->next) == 0)
return 0;
}
}
/* Return true if segment contains a segment link */
static int has_segment_link(mstate m, msegmentptr ss) {
msegmentptr sp = &m->seg;
for (;;) {
if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
return 1;
if ((sp = sp->next) == 0)
return 0;
}
}
#ifndef MORECORE_CANNOT_TRIM
#define should_trim(M,s) ((s) > (M)->trim_check)
#else /* MORECORE_CANNOT_TRIM */
#define should_trim(M,s) (0)
#endif /* MORECORE_CANNOT_TRIM */
/*
TOP_FOOT_SIZE is padding at the end of a segment, including space
that may be needed to place segment records and fenceposts when new
noncontiguous segments are added.
*/
#define TOP_FOOT_SIZE\
(align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
/* ------------------------------- Hooks -------------------------------- */
/*
PREACTION should be defined to return 0 on success, and nonzero on
failure. If you are not using locking, you can redefine these to do
anything you like.
*/
#if USE_LOCKS
/* Ensure locks are initialized */
#define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams())
#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
#else /* USE_LOCKS */
#ifndef PREACTION
#define PREACTION(M) (0)
#endif /* PREACTION */
#ifndef POSTACTION
#define POSTACTION(M)
#endif /* POSTACTION */
#endif /* USE_LOCKS */
/*
CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
USAGE_ERROR_ACTION is triggered on detected bad frees and
reallocs. The argument p is an address that might have triggered the
fault. It is ignored by the two predefined actions, but might be
useful in custom actions that try to help diagnose errors.
*/
#if PROCEED_ON_ERROR
/* A count of the number of corruption errors causing resets */
int malloc_corruption_error_count;
/* default corruption action */
static void reset_on_error(mstate m);
#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
#define USAGE_ERROR_ACTION(m, p)
#else /* PROCEED_ON_ERROR */
#ifndef CORRUPTION_ERROR_ACTION
#define CORRUPTION_ERROR_ACTION(m) ABORT
#endif /* CORRUPTION_ERROR_ACTION */
#ifndef USAGE_ERROR_ACTION
#define USAGE_ERROR_ACTION(m,p) ABORT
#endif /* USAGE_ERROR_ACTION */
#endif /* PROCEED_ON_ERROR */
/* -------------------------- Debugging setup ---------------------------- */
#if ! DEBUG
#define check_free_chunk(M,P)
#define check_inuse_chunk(M,P)
#define check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P)
#define check_malloc_state(M)
#define check_top_chunk(M,P)
#else /* DEBUG */
#define check_free_chunk(M,P) do_check_free_chunk(M,P)
#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
#define check_top_chunk(M,P) do_check_top_chunk(M,P)
#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
#define check_malloc_state(M) do_check_malloc_state(M)
static void do_check_any_chunk(mstate m, mchunkptr p);
static void do_check_top_chunk(mstate m, mchunkptr p);
static void do_check_mmapped_chunk(mstate m, mchunkptr p);
static void do_check_inuse_chunk(mstate m, mchunkptr p);
static void do_check_free_chunk(mstate m, mchunkptr p);
static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
static void do_check_tree(mstate m, tchunkptr t);
static void do_check_treebin(mstate m, bindex_t i);
static void do_check_smallbin(mstate m, bindex_t i);
static void do_check_malloc_state(mstate m);
static int bin_find(mstate m, mchunkptr x);
static size_t traverse_and_check(mstate m);
#endif /* DEBUG */
/* ---------------------------- Indexing Bins ---------------------------- */
#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
#define small_index(s) ((s) >> SMALLBIN_SHIFT)
#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
/* addressing by index. See above about smallbin repositioning */
#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
#define treebin_at(M,i) (&((M)->treebins[i]))
/* assign tree index for size S to variable I */
#if defined(__GNUC__) && defined(i386)
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int K;\
__asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\
I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
}\
}
#else /* GNUC */
#define compute_tree_index(S, I)\
{\
size_t X = S >> TREEBIN_SHIFT;\
if (X == 0)\
I = 0;\
else if (X > 0xFFFF)\
I = NTREEBINS-1;\
else {\
unsigned int Y = (unsigned int)X;\
unsigned int N = ((Y - 0x100) >> 16) & 8;\
unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
N += K;\
N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
K = 14 - N + ((Y <<= K) >> 15);\
I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
}\
}
#endif /* GNUC */
/* Bit representing maximum resolved size in a treebin at i */
#define bit_for_tree_index(i) \
(i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
/* Shift placing maximum resolved bit in a treebin at i as sign bit */
#define leftshift_for_tree_index(i) \
((i == NTREEBINS-1)? 0 : \
((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
/* The size of the smallest chunk held in bin with index i */
#define minsize_for_tree_index(i) \
((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
(((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
/* ------------------------ Operations on bin maps ----------------------- */
/* bit corresponding to given index */
#define idx2bit(i) ((binmap_t)(1) << (i))
/* Mark/Clear bits with given index */
#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
/* index corresponding to given bit */
#if defined(__GNUC__) && defined(i386)
#define compute_bit2idx(X, I)\
{\
unsigned int J;\
__asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\
I = (bindex_t)J;\
}
#else /* GNUC */
#if USE_BUILTIN_FFS
#define compute_bit2idx(X, I) I = ffs(X)-1
#else /* USE_BUILTIN_FFS */
#define compute_bit2idx(X, I)\
{\
unsigned int Y = X - 1;\
unsigned int K = Y >> (16-4) & 16;\
unsigned int N = K; Y >>= K;\
N += K = Y >> (8-3) & 8; Y >>= K;\
N += K = Y >> (4-2) & 4; Y >>= K;\
N += K = Y >> (2-1) & 2; Y >>= K;\
N += K = Y >> (1-0) & 1; Y >>= K;\
I = (bindex_t)(N + Y);\
}
#endif /* USE_BUILTIN_FFS */
#endif /* GNUC */
/* isolate the least set bit of a bitmap */
#define least_bit(x) ((x) & -(x))
/* mask with all bits to left of least bit of x on */
#define left_bits(x) ((x<<1) | -(x<<1))
/* mask with all bits to left of or equal to least bit of x on */
#define same_or_left_bits(x) ((x) | -(x))
/* ----------------------- Runtime Check Support ------------------------- */
/*
For security, the main invariant is that malloc/free/etc never
writes to a static address other than malloc_state, unless static
malloc_state itself has been corrupted, which cannot occur via
malloc (because of these checks). In essence this means that we
believe all pointers, sizes, maps etc held in malloc_state, but
check all of those linked or offsetted from other embedded data
structures. These checks are interspersed with main code in a way
that tends to minimize their run-time cost.
When FOOTERS is defined, in addition to range checking, we also
verify footer fields of inuse chunks, which can be used guarantee
that the mstate controlling malloc/free is intact. This is a
streamlined version of the approach described by William Robertson
et al in "Run-time Detection of Heap-based Overflows" LISA'03
http://www.usenix.org/events/lisa03/tech/robertson.html The footer
of an inuse chunk holds the xor of its mstate and a random seed,
that is checked upon calls to free() and realloc(). This is
(probablistically) unguessable from outside the program, but can be
computed by any code successfully malloc'ing any chunk, so does not
itself provide protection against code that has already broken
security through some other means. Unlike Robertson et al, we
always dynamically check addresses of all offset chunks (previous,
next, etc). This turns out to be cheaper than relying on hashes.
*/
#if !INSECURE
/* Check if address a is at least as high as any from MORECORE or MMAP */
#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
/* Check if address of next chunk n is higher than base chunk p */
#define ok_next(p, n) ((char*)(p) < (char*)(n))
/* Check if p has its cinuse bit on */
#define ok_cinuse(p) cinuse(p)
/* Check if p has its pinuse bit on */
#define ok_pinuse(p) pinuse(p)
#else /* !INSECURE */
#define ok_address(M, a) (1)
#define ok_next(b, n) (1)
#define ok_cinuse(p) (1)
#define ok_pinuse(p) (1)
#endif /* !INSECURE */
#if (FOOTERS && !INSECURE)
/* Check if (alleged) mstate m has expected magic field */
#define ok_magic(M) ((M)->magic == mparams.magic)
#else /* (FOOTERS && !INSECURE) */
#define ok_magic(M) (1)
#endif /* (FOOTERS && !INSECURE) */
/* In gcc, use __builtin_expect to minimize impact of checks */
#if !INSECURE
#if defined(__GNUC__) && __GNUC__ >= 3
#define RTCHECK(e) __builtin_expect(e, 1)
#else /* GNUC */
#define RTCHECK(e) (e)
#endif /* GNUC */
#else /* !INSECURE */
#define RTCHECK(e) (1)
#endif /* !INSECURE */
/* macros to set up inuse chunks with or without footers */
#if !FOOTERS
#define mark_inuse_foot(M,p,s)
/* Set cinuse bit and pinuse bit of next chunk */
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
/* Set size, cinuse and pinuse bit of this chunk */
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
#else /* FOOTERS */
/* Set foot of inuse chunk to be xor of mstate and seed */
#define mark_inuse_foot(M,p,s)\
(((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
#define get_mstate_for(p)\
((mstate)(((mchunkptr)((char*)(p) +\
(chunksize(p))))->prev_foot ^ mparams.magic))
#define set_inuse(M,p,s)\
((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
mark_inuse_foot(M,p,s))
#define set_inuse_and_pinuse(M,p,s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
(((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
mark_inuse_foot(M,p,s))
#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
mark_inuse_foot(M, p, s))
#endif /* !FOOTERS */
/* ---------------------------- setting mparams -------------------------- */
/* Initialize mparams */
static int init_mparams(void) {
if (mparams.page_size == 0) {
size_t s;
mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
#if MORECORE_CONTIGUOUS
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
#else /* MORECORE_CONTIGUOUS */
mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
#endif /* MORECORE_CONTIGUOUS */
#if (FOOTERS && !INSECURE)
{
#if USE_DEV_RANDOM
int fd;
unsigned char buf[sizeof(size_t)];
/* Try to use /dev/urandom, else fall back on using time */
if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
read(fd, buf, sizeof(buf)) == sizeof(buf)) {
s = *((size_t *) buf);
close(fd);
}
else
#endif /* USE_DEV_RANDOM */
s = (size_t)(time(0) ^ (size_t)0x55555555U);
s |= (size_t)8U; /* ensure nonzero */
s &= ~(size_t)7U; /* improve chances of fault for bad values */
}
#else /* (FOOTERS && !INSECURE) */
s = (size_t)0x58585858U;
#endif /* (FOOTERS && !INSECURE) */
ACQUIRE_MAGIC_INIT_LOCK();
if (mparams.magic == 0) {
mparams.magic = s;
/* Set up lock for main malloc area */
INITIAL_LOCK(&gm->mutex);
gm->mflags = mparams.default_mflags;
}
RELEASE_MAGIC_INIT_LOCK();
#ifndef WIN32
mparams.page_size = malloc_getpagesize;
mparams.granularity = ((DEFAULT_GRANULARITY != 0)?
DEFAULT_GRANULARITY : mparams.page_size);
#else /* WIN32 */
{
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
mparams.page_size = system_info.dwPageSize;
mparams.granularity = system_info.dwAllocationGranularity;
}
#endif /* WIN32 */
/* Sanity-check configuration:
size_t must be unsigned and as wide as pointer type.
ints must be at least 4 bytes.
alignment must be at least 8.
Alignment, min chunk size, and page size must all be powers of 2.
*/
if ((sizeof(size_t) != sizeof(char*)) ||
(MAX_SIZE_T < MIN_CHUNK_SIZE) ||
(sizeof(int) < 4) ||
(MALLOC_ALIGNMENT < (size_t)8U) ||
((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) ||
((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0))
ABORT;
}
return 0;
}
/* support for mallopt */
static int change_mparam(int param_number, int value) {
size_t val = (size_t)value;
init_mparams();
switch(param_number) {
case M_TRIM_THRESHOLD:
mparams.trim_threshold = val;
return 1;
case M_GRANULARITY:
if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
mparams.granularity = val;
return 1;
}
else
return 0;
case M_MMAP_THRESHOLD:
mparams.mmap_threshold = val;
return 1;
default:
return 0;
}
}
#if DEBUG
/* ------------------------- Debugging Support --------------------------- */
/* Check properties of any chunk, whether free, inuse, mmapped etc */
static void do_check_any_chunk(mstate m, mchunkptr p) {
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
}
/* Check properties of top chunk */
static void do_check_top_chunk(mstate m, mchunkptr p) {
msegmentptr sp = segment_holding(m, (char*)p);
size_t sz = chunksize(p);
assert(sp != 0);
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(sz == m->topsize);
assert(sz > 0);
assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
assert(pinuse(p));
assert(!next_pinuse(p));
}
/* Check properties of (inuse) mmapped chunks */
static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
size_t sz = chunksize(p);
size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD);
assert(is_mmapped(p));
assert(use_mmap(m));
assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
assert(ok_address(m, p));
assert(!is_small(sz));
assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
}
/* Check properties of inuse chunks */
static void do_check_inuse_chunk(mstate m, mchunkptr p) {
do_check_any_chunk(m, p);
assert(cinuse(p));
assert(next_pinuse(p));
/* If not pinuse and not mmapped, previous chunk has OK offset */
assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
if (is_mmapped(p))
do_check_mmapped_chunk(m, p);
}
/* Check properties of free chunks */
static void do_check_free_chunk(mstate m, mchunkptr p) {
size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
mchunkptr next = chunk_plus_offset(p, sz);
do_check_any_chunk(m, p);
assert(!cinuse(p));
assert(!next_pinuse(p));
assert (!is_mmapped(p));
if (p != m->dv && p != m->top) {
if (sz >= MIN_CHUNK_SIZE) {
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(is_aligned(chunk2mem(p)));
assert(next->prev_foot == sz);
assert(pinuse(p));
assert (next == m->top || cinuse(next));
assert(p->fd->bk == p);
assert(p->bk->fd == p);
}
else /* markers are always of size SIZE_T_SIZE */
assert(sz == SIZE_T_SIZE);
}
}
/* Check properties of malloced chunks at the point they are malloced */
static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT);
do_check_inuse_chunk(m, p);
assert((sz & CHUNK_ALIGN_MASK) == 0);
assert(sz >= MIN_CHUNK_SIZE);
assert(sz >= s);
/* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
}
}
/* Check a tree and its subtrees. */
static void do_check_tree(mstate m, tchunkptr t) {
tchunkptr head = 0;
tchunkptr u = t;
bindex_t tindex = t->index;
size_t tsize = chunksize(t);
bindex_t idx;
compute_tree_index(tsize, idx);
assert(tindex == idx);
assert(tsize >= MIN_LARGE_SIZE);
assert(tsize >= minsize_for_tree_index(idx));
assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
do { /* traverse through chain of same-sized nodes */
do_check_any_chunk(m, ((mchunkptr)u));
assert(u->index == tindex);
assert(chunksize(u) == tsize);
assert(!cinuse(u));
assert(!next_pinuse(u));
assert(u->fd->bk == u);
assert(u->bk->fd == u);
if (u->parent == 0) {
assert(u->child[0] == 0);
assert(u->child[1] == 0);
}
else {
assert(head == 0); /* only one node on chain has parent */
head = u;
assert(u->parent != u);
assert (u->parent->child[0] == u ||
u->parent->child[1] == u ||
*((tbinptr*)(u->parent)) == u);
if (u->child[0] != 0) {
assert(u->child[0]->parent == u);
assert(u->child[0] != u);
do_check_tree(m, u->child[0]);
}
if (u->child[1] != 0) {
assert(u->child[1]->parent == u);
assert(u->child[1] != u);
do_check_tree(m, u->child[1]);
}
if (u->child[0] != 0 && u->child[1] != 0) {
assert(chunksize(u->child[0]) < chunksize(u->child[1]));
}
}
u = u->fd;
} while (u != t);
assert(head != 0);
}
/* Check all the chunks in a treebin. */
static void do_check_treebin(mstate m, bindex_t i) {
tbinptr* tb = treebin_at(m, i);
tchunkptr t = *tb;
int empty = (m->treemap & (1U << i)) == 0;
if (t == 0)
assert(empty);
if (!empty)
do_check_tree(m, t);
}
/* Check all the chunks in a smallbin. */
static void do_check_smallbin(mstate m, bindex_t i) {
sbinptr b = smallbin_at(m, i);
mchunkptr p = b->bk;
unsigned int empty = (m->smallmap & (1U << i)) == 0;
if (p == b)
assert(empty);
if (!empty) {
for (; p != b; p = p->bk) {
size_t size = chunksize(p);
mchunkptr q;
/* each chunk claims to be free */
do_check_free_chunk(m, p);
/* chunk belongs in bin */
assert(small_index(size) == i);
assert(p->bk == b || chunksize(p->bk) == chunksize(p));
/* chunk is followed by an inuse chunk */
q = next_chunk(p);
if (q->head != FENCEPOST_HEAD)
do_check_inuse_chunk(m, q);
}
}
}
/* Find x in a bin. Used in other check functions. */
static int bin_find(mstate m, mchunkptr x) {
size_t size = chunksize(x);
if (is_small(size)) {
bindex_t sidx = small_index(size);
sbinptr b = smallbin_at(m, sidx);
if (smallmap_is_marked(m, sidx)) {
mchunkptr p = b;
do {
if (p == x)
return 1;
} while ((p = p->fd) != b);
}
}
else {
bindex_t tidx;
compute_tree_index(size, tidx);
if (treemap_is_marked(m, tidx)) {
tchunkptr t = *treebin_at(m, tidx);
size_t sizebits = size << leftshift_for_tree_index(tidx);
while (t != 0 && chunksize(t) != size) {
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
sizebits <<= 1;
}
if (t != 0) {
tchunkptr u = t;
do {
if (u == (tchunkptr)x)
return 1;
} while ((u = u->fd) != t);
}
}
}
return 0;
}
/* Traverse each chunk and check it; return total */
static size_t traverse_and_check(mstate m) {
size_t sum = 0;
if (is_initialized(m)) {
msegmentptr s = &m->seg;
sum += m->topsize + TOP_FOOT_SIZE;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
mchunkptr lastq = 0;
assert(pinuse(q));
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
sum += chunksize(q);
if (cinuse(q)) {
assert(!bin_find(m, q));
do_check_inuse_chunk(m, q);
}
else {
assert(q == m->dv || bin_find(m, q));
assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */
do_check_free_chunk(m, q);
}
lastq = q;
q = next_chunk(q);
}
s = s->next;
}
}
return sum;
}
/* Check all properties of malloc_state. */
static void do_check_malloc_state(mstate m) {
bindex_t i;
size_t total;
/* check bins */
for (i = 0; i < NSMALLBINS; ++i)
do_check_smallbin(m, i);
for (i = 0; i < NTREEBINS; ++i)
do_check_treebin(m, i);
if (m->dvsize != 0) { /* check dv chunk */
do_check_any_chunk(m, m->dv);
assert(m->dvsize == chunksize(m->dv));
assert(m->dvsize >= MIN_CHUNK_SIZE);
assert(bin_find(m, m->dv) == 0);
}
if (m->top != 0) { /* check top chunk */
do_check_top_chunk(m, m->top);
assert(m->topsize == chunksize(m->top));
assert(m->topsize > 0);
assert(bin_find(m, m->top) == 0);
}
total = traverse_and_check(m);
assert(total <= m->footprint);
assert(m->footprint <= m->max_footprint);
}
#endif /* DEBUG */
/* ----------------------------- statistics ------------------------------ */
#if !NO_MALLINFO
static struct mallinfo internal_mallinfo(mstate m) {
struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
if (!PREACTION(m)) {
check_malloc_state(m);
if (is_initialized(m)) {
size_t nfree = SIZE_T_ONE; /* top always free */
size_t mfree = m->topsize + TOP_FOOT_SIZE;
size_t sum = mfree;
msegmentptr s = &m->seg;
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
size_t sz = chunksize(q);
sum += sz;
if (!cinuse(q)) {
mfree += sz;
++nfree;
}
q = next_chunk(q);
}
s = s->next;
}
nm.arena = sum;
nm.ordblks = nfree;
nm.hblkhd = m->footprint - sum;
nm.usmblks = m->max_footprint;
nm.uordblks = m->footprint - mfree;
nm.fordblks = mfree;
nm.keepcost = m->topsize;
}
POSTACTION(m);
}
return nm;
}
#endif /* !NO_MALLINFO */
static void internal_malloc_stats(mstate m) {
if (!PREACTION(m)) {
size_t maxfp = 0;
size_t fp = 0;
size_t used = 0;
check_malloc_state(m);
if (is_initialized(m)) {
msegmentptr s = &m->seg;
maxfp = m->max_footprint;
fp = m->footprint;
used = fp - (m->topsize + TOP_FOOT_SIZE);
while (s != 0) {
mchunkptr q = align_as_chunk(s->base);
while (segment_holds(s, q) &&
q != m->top && q->head != FENCEPOST_HEAD) {
if (!cinuse(q))
used -= chunksize(q);
q = next_chunk(q);
}
s = s->next;
}
}
fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));
fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));
POSTACTION(m);
}
}
/* ----------------------- Operations on smallbins ----------------------- */
/*
Various forms of linking and unlinking are defined as macros. Even
the ones for trees, which are very long but have very short typical
paths. This is ugly but reduces reliance on inlining support of
compilers.
*/
/* Link a free chunk into a smallbin */
#define insert_small_chunk(M, P, S) {\
bindex_t I = small_index(S);\
mchunkptr B = smallbin_at(M, I);\
mchunkptr F = B;\
assert(S >= MIN_CHUNK_SIZE);\
if (!smallmap_is_marked(M, I))\
mark_smallmap(M, I);\
else if (RTCHECK(ok_address(M, B->fd)))\
F = B->fd;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
B->fd = P;\
F->bk = P;\
P->fd = F;\
P->bk = B;\
}
/* Unlink a chunk from a smallbin */
#define unlink_small_chunk(M, P, S) {\
mchunkptr F = P->fd;\
mchunkptr B = P->bk;\
bindex_t I = small_index(S);\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (F == B)\
clear_smallmap(M, I);\
else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\
(B == smallbin_at(M,I) || ok_address(M, B)))) {\
F->bk = B;\
B->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Unlink the first chunk from a smallbin */
#define unlink_first_small_chunk(M, B, P, I) {\
mchunkptr F = P->fd;\
assert(P != B);\
assert(P != F);\
assert(chunksize(P) == small_index2size(I));\
if (B == F)\
clear_smallmap(M, I);\
else if (RTCHECK(ok_address(M, F))) {\
B->fd = F;\
F->bk = B;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}
/* Replace dv node, binning the old one */
/* Used only when dvsize known to be small */
#define replace_dv(M, P, S) {\
size_t DVS = M->dvsize;\
if (DVS != 0) {\
mchunkptr DV = M->dv;\
assert(is_small(DVS));\
insert_small_chunk(M, DV, DVS);\
}\
M->dvsize = S;\
M->dv = P;\
}
/* ------------------------- Operations on trees ------------------------- */
/* Insert chunk into tree */
#define insert_large_chunk(M, X, S) {\
tbinptr* H;\
bindex_t I;\
compute_tree_index(S, I);\
H = treebin_at(M, I);\
X->index = I;\
X->child[0] = X->child[1] = 0;\
if (!treemap_is_marked(M, I)) {\
mark_treemap(M, I);\
*H = X;\
X->parent = (tchunkptr)H;\
X->fd = X->bk = X;\
}\
else {\
tchunkptr T = *H;\
size_t K = S << leftshift_for_tree_index(I);\
for (;;) {\
if (chunksize(T) != S) {\
tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
K <<= 1;\
if (*C != 0)\
T = *C;\
else if (RTCHECK(ok_address(M, C))) {\
*C = X;\
X->parent = T;\
X->fd = X->bk = X;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
else {\
tchunkptr F = T->fd;\
if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
T->fd = F->bk = X;\
X->fd = F;\
X->bk = T;\
X->parent = 0;\
break;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
break;\
}\
}\
}\
}\
}
/*
Unlink steps:
1. If x is a chained node, unlink it from its same-sized fd/bk links
and choose its bk node as its replacement.
2. If x was the last node of its size, but not a leaf node, it must
be replaced with a leaf node (not merely one with an open left or
right), to make sure that lefts and rights of descendents
correspond properly to bit masks. We use the rightmost descendent
of x. We could use any other leaf, but this is easy to locate and
tends to counteract removal of leftmosts elsewhere, and so keeps
paths shorter than minimally guaranteed. This doesn't loop much
because on average a node in a tree is near the bottom.
3. If x is the base of a chain (i.e., has parent links) relink
x's parent and children to x's replacement (or null if none).
*/
#define unlink_large_chunk(M, X) {\
tchunkptr XP = X->parent;\
tchunkptr R;\
if (X->bk != X) {\
tchunkptr F = X->fd;\
R = X->bk;\
if (RTCHECK(ok_address(M, F))) {\
F->bk = R;\
R->fd = F;\
}\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else {\
tchunkptr* RP;\
if (((R = *(RP = &(X->child[1]))) != 0) ||\
((R = *(RP = &(X->child[0]))) != 0)) {\
tchunkptr* CP;\
while ((*(CP = &(R->child[1])) != 0) ||\
(*(CP = &(R->child[0])) != 0)) {\
R = *(RP = CP);\
}\
if (RTCHECK(ok_address(M, RP)))\
*RP = 0;\
else {\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}\
if (XP != 0) {\
tbinptr* H = treebin_at(M, X->index);\
if (X == *H) {\
if ((*H = R) == 0) \
clear_treemap(M, X->index);\
}\
else if (RTCHECK(ok_address(M, XP))) {\
if (XP->child[0] == X) \
XP->child[0] = R;\
else \
XP->child[1] = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
if (R != 0) {\
if (RTCHECK(ok_address(M, R))) {\
tchunkptr C0, C1;\
R->parent = XP;\
if ((C0 = X->child[0]) != 0) {\
if (RTCHECK(ok_address(M, C0))) {\
R->child[0] = C0;\
C0->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
if ((C1 = X->child[1]) != 0) {\
if (RTCHECK(ok_address(M, C1))) {\
R->child[1] = C1;\
C1->parent = R;\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
else\
CORRUPTION_ERROR_ACTION(M);\
}\
}\
}
/* Relays to large vs small bin operations */
#define insert_chunk(M, P, S)\
if (is_small(S)) insert_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
#define unlink_chunk(M, P, S)\
if (is_small(S)) unlink_small_chunk(M, P, S)\
else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
/* Relays to internal calls to malloc/free from realloc, memalign etc */
#if ONLY_MSPACES
#define internal_malloc(m, b) mspace_malloc(m, b)
#define internal_free(m, mem) mspace_free(m,mem);
#else /* ONLY_MSPACES */
#if MSPACES
#define internal_malloc(m, b)\
(m == gm)? dlmalloc(b) : mspace_malloc(m, b)
#define internal_free(m, mem)\
if (m == gm) dlfree(mem); else mspace_free(m,mem);
#else /* MSPACES */
#define internal_malloc(m, b) dlmalloc(b)
#define internal_free(m, mem) dlfree(mem)
#endif /* MSPACES */
#endif /* ONLY_MSPACES */
/* ----------------------- Direct-mmapping chunks ----------------------- */
/*
Directly mmapped chunks are set up with an offset to the start of
the mmapped region stored in the prev_foot field of the chunk. This
allows reconstruction of the required argument to MUNMAP when freed,
and also allows adjustment of the returned chunk to meet alignment
requirements (especially in memalign). There is also enough space
allocated to hold a fake next chunk of size SIZE_T_SIZE to maintain
the PINUSE bit so frees can be checked.
*/
/* Malloc using mmap */
static void* mmap_alloc(mstate m, size_t nb) {
size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
if (mmsize > nb) { /* Check for wrap around 0 */
char* mm = (char*)(DIRECT_MMAP(mmsize));
if (mm != CMFAIL) {
size_t offset = align_offset(chunk2mem(mm));
size_t psize = mmsize - offset - MMAP_FOOT_PAD;
mchunkptr p = (mchunkptr)(mm + offset);
p->prev_foot = offset | IS_MMAPPED_BIT;
(p)->head = (psize|CINUSE_BIT);
mark_inuse_foot(m, p, psize);
chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
if (mm < m->least_addr)
m->least_addr = mm;
if ((m->footprint += mmsize) > m->max_footprint)
m->max_footprint = m->footprint;
assert(is_aligned(chunk2mem(p)));
check_mmapped_chunk(m, p);
return chunk2mem(p);
}
}
return 0;
}
/* Realloc using mmap */
static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
size_t oldsize = chunksize(oldp);
if (is_small(nb)) /* Can't shrink mmap regions below small size */
return 0;
/* Keep old chunk if big enough but not too big */
if (oldsize >= nb + SIZE_T_SIZE &&
(oldsize - nb) <= (mparams.granularity << 1))
return oldp;
else {
size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT;
size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES +
CHUNK_ALIGN_MASK);
char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
oldmmsize, newmmsize, 1);
if (cp != CMFAIL) {
mchunkptr newp = (mchunkptr)(cp + offset);
size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
newp->head = (psize|CINUSE_BIT);
mark_inuse_foot(m, newp, psize);
chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
if (cp < m->least_addr)
m->least_addr = cp;
if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
m->max_footprint = m->footprint;
check_mmapped_chunk(m, newp);
return newp;
}
}
return 0;
}
/* -------------------------- mspace management -------------------------- */
/* Initialize top chunk and its size */
static void init_top(mstate m, mchunkptr p, size_t psize) {
/* Ensure alignment */
size_t offset = align_offset(chunk2mem(p));
p = (mchunkptr)((char*)p + offset);
psize -= offset;
m->top = p;
m->topsize = psize;
p->head = psize | PINUSE_BIT;
/* set size of fake trailing chunk holding overhead space only once */
chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
m->trim_check = mparams.trim_threshold; /* reset on each update */
}
/* Initialize bins for a new mstate that is otherwise zeroed out */
static void init_bins(mstate m) {
/* Establish circular links for smallbins */
bindex_t i;
for (i = 0; i < NSMALLBINS; ++i) {
sbinptr bin = smallbin_at(m,i);
bin->fd = bin->bk = bin;
}
}
#if PROCEED_ON_ERROR
/* default corruption action */
static void reset_on_error(mstate m) {
int i;
++malloc_corruption_error_count;
/* Reinitialize fields to forget about all memory */
m->smallbins = m->treebins = 0;
m->dvsize = m->topsize = 0;
m->seg.base = 0;
m->seg.size = 0;
m->seg.next = 0;
m->top = m->dv = 0;
for (i = 0; i < NTREEBINS; ++i)
*treebin_at(m, i) = 0;
init_bins(m);
}
#endif /* PROCEED_ON_ERROR */
/* Allocate chunk and prepend remainder with chunk in successor base. */
static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
size_t nb) {
mchunkptr p = align_as_chunk(newbase);
mchunkptr oldfirst = align_as_chunk(oldbase);
size_t psize = (char*)oldfirst - (char*)p;
mchunkptr q = chunk_plus_offset(p, nb);
size_t qsize = psize - nb;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
assert((char*)oldfirst > (char*)q);
assert(pinuse(oldfirst));
assert(qsize >= MIN_CHUNK_SIZE);
/* consolidate remainder with first chunk of old base */
if (oldfirst == m->top) {
size_t tsize = m->topsize += qsize;
m->top = q;
q->head = tsize | PINUSE_BIT;
check_top_chunk(m, q);
}
else if (oldfirst == m->dv) {
size_t dsize = m->dvsize += qsize;
m->dv = q;
set_size_and_pinuse_of_free_chunk(q, dsize);
}
else {
if (!cinuse(oldfirst)) {
size_t nsize = chunksize(oldfirst);
unlink_chunk(m, oldfirst, nsize);
oldfirst = chunk_plus_offset(oldfirst, nsize);
qsize += nsize;
}
set_free_with_pinuse(q, qsize, oldfirst);
insert_chunk(m, q, qsize);
check_free_chunk(m, q);
}
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
/* Add a segment to hold a new noncontiguous region */
static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
/* Determine locations and sizes of segment, fenceposts, old top */
char* old_top = (char*)m->top;
msegmentptr oldsp = segment_holding(m, old_top);
char* old_end = oldsp->base + oldsp->size;
size_t ssize = pad_request(sizeof(struct malloc_segment));
char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
size_t offset = align_offset(chunk2mem(rawsp));
char* asp = rawsp + offset;
char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
mchunkptr sp = (mchunkptr)csp;
msegmentptr ss = (msegmentptr)(chunk2mem(sp));
mchunkptr tnext = chunk_plus_offset(sp, ssize);
mchunkptr p = tnext;
int nfences = 0;
/* reset top to new space */
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
/* Set up segment record */
assert(is_aligned(ss));
set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
*ss = m->seg; /* Push current record */
m->seg.base = tbase;
m->seg.size = tsize;
m->seg.sflags = mmapped;
m->seg.next = ss;
/* Insert trailing fenceposts */
for (;;) {
mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
p->head = FENCEPOST_HEAD;
++nfences;
if ((char*)(&(nextp->head)) < old_end)
p = nextp;
else
break;
}
assert(nfences >= 2);
/* Insert the rest of old top into a bin as an ordinary free chunk */
if (csp != old_top) {
mchunkptr q = (mchunkptr)old_top;
size_t psize = csp - old_top;
mchunkptr tn = chunk_plus_offset(q, psize);
set_free_with_pinuse(q, psize, tn);
insert_chunk(m, q, psize);
}
check_top_chunk(m, m->top);
}
/* -------------------------- System allocation -------------------------- */
/* Get memory from system using MORECORE or MMAP */
static void* sys_alloc(mstate m, size_t nb) {
char* tbase = CMFAIL;
size_t tsize = 0;
flag_t mmap_flag = 0;
init_mparams();
/* Directly map large chunks */
if (use_mmap(m) && nb >= mparams.mmap_threshold) {
void* mem = mmap_alloc(m, nb);
if (mem != 0)
return mem;
}
/*
Try getting memory in any of three ways (in most-preferred to
least-preferred order):
1. A call to MORECORE that can normally contiguously extend memory.
(disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
or main space is mmapped or a previous contiguous call failed)
2. A call to MMAP new space (disabled if not HAVE_MMAP).
Note that under the default settings, if MORECORE is unable to
fulfill a request, and HAVE_MMAP is true, then mmap is
used as a noncontiguous system allocator. This is a useful backup
strategy for systems with holes in address spaces -- in this case
sbrk cannot contiguously expand the heap, but mmap may be able to
find space.
3. A call to MORECORE that cannot usually contiguously extend memory.
(disabled if not HAVE_MORECORE)
*/
if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
char* br = CMFAIL;
msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
size_t asize = 0;
ACQUIRE_MORECORE_LOCK();
if (ss == 0) { /* First time through or recovery */
char* base = (char*)CALL_MORECORE(0);
if (base != CMFAIL) {
asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
/* Adjust to end on a page boundary */
if (!is_page_aligned(base))
asize += (page_align((size_t)base) - (size_t)base);
/* Can't call MORECORE if size is negative when treated as signed */
if (asize < HALF_MAX_SIZE_T &&
(br = (char*)(CALL_MORECORE(asize))) == base) {
tbase = base;
tsize = asize;
}
}
}
else {
/* Subtract out existing available top space from MORECORE request. */
asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE);
/* Use mem here only if it did continuously extend old space */
if (asize < HALF_MAX_SIZE_T &&
(br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) {
tbase = br;
tsize = asize;
}
}
if (tbase == CMFAIL) { /* Cope with partial failure */
if (br != CMFAIL) { /* Try to use/extend the space we did get */
if (asize < HALF_MAX_SIZE_T &&
asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) {
size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize);
if (esize < HALF_MAX_SIZE_T) {
char* end = (char*)CALL_MORECORE(esize);
if (end != CMFAIL)
asize += esize;
else { /* Can't use; try to release */
CALL_MORECORE(-asize);
br = CMFAIL;
}
}
}
}
if (br != CMFAIL) { /* Use the space we did get */
tbase = br;
tsize = asize;
}
else
disable_contiguous(m); /* Don't try contiguous path in the future */
}
RELEASE_MORECORE_LOCK();
}
if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE;
size_t rsize = granularity_align(req);
if (rsize > nb) { /* Fail if wraps around zero */
char* mp = (char*)(CALL_MMAP(rsize));
if (mp != CMFAIL) {
tbase = mp;
tsize = rsize;
mmap_flag = IS_MMAPPED_BIT;
}
}
}
if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE);
if (asize < HALF_MAX_SIZE_T) {
char* br = CMFAIL;
char* end = CMFAIL;
ACQUIRE_MORECORE_LOCK();
br = (char*)(CALL_MORECORE(asize));
end = (char*)(CALL_MORECORE(0));
RELEASE_MORECORE_LOCK();
if (br != CMFAIL && end != CMFAIL && br < end) {
size_t ssize = end - br;
if (ssize > nb + TOP_FOOT_SIZE) {
tbase = br;
tsize = ssize;
}
}
}
}
if (tbase != CMFAIL) {
if ((m->footprint += tsize) > m->max_footprint)
m->max_footprint = m->footprint;
if (!is_initialized(m)) { /* first-time initialization */
m->seg.base = m->least_addr = tbase;
m->seg.size = tsize;
m->seg.sflags = mmap_flag;
m->magic = mparams.magic;
init_bins(m);
if (is_global(m))
init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
else {
/* Offset top by embedded malloc_state */
mchunkptr mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
}
}
else {
/* Try to merge with an existing segment */
msegmentptr sp = &m->seg;
while (sp != 0 && tbase != sp->base + sp->size)
sp = sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & IS_MMAPPED_BIT) == mmap_flag &&
segment_holds(sp, m->top)) { /* append */
sp->size += tsize;
init_top(m, m->top, m->topsize + tsize);
}
else {
if (tbase < m->least_addr)
m->least_addr = tbase;
sp = &m->seg;
while (sp != 0 && sp->base != tbase + tsize)
sp = sp->next;
if (sp != 0 &&
!is_extern_segment(sp) &&
(sp->sflags & IS_MMAPPED_BIT) == mmap_flag) {
char* oldbase = sp->base;
sp->base = tbase;
sp->size += tsize;
return prepend_alloc(m, tbase, oldbase, nb);
}
else
add_segment(m, tbase, tsize, mmap_flag);
}
}
if (nb < m->topsize) { /* Allocate from new or extended top space */
size_t rsize = m->topsize -= nb;
mchunkptr p = m->top;
mchunkptr r = m->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(m, p, nb);
check_top_chunk(m, m->top);
check_malloced_chunk(m, chunk2mem(p), nb);
return chunk2mem(p);
}
}
MALLOC_FAILURE_ACTION;
return 0;
}
/* ----------------------- system deallocation -------------------------- */
/* Unmap and unlink any mmapped segments that don't contain used chunks */
static size_t release_unused_segments(mstate m) {
size_t released = 0;
msegmentptr pred = &m->seg;
msegmentptr sp = pred->next;
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
msegmentptr next = sp->next;
if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
mchunkptr p = align_as_chunk(base);
size_t psize = chunksize(p);
/* Can unmap if first chunk holds entire segment and not pinned */
if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
tchunkptr tp = (tchunkptr)p;
assert(segment_holds(sp, (char*)sp));
if (p == m->dv) {
m->dv = 0;
m->dvsize = 0;
}
else {
unlink_large_chunk(m, tp);
}
if (CALL_MUNMAP(base, size) == 0) {
released += size;
m->footprint -= size;
/* unlink obsoleted record */
sp = pred;
sp->next = next;
}
else { /* back out if cannot unmap */
insert_large_chunk(m, tp, psize);
}
}
}
pred = sp;
sp = next;
}
return released;
}
static int sys_trim(mstate m, size_t pad) {
size_t released = 0;
if (pad < MAX_REQUEST && is_initialized(m)) {
pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
if (m->topsize > pad) {
/* Shrink top space in granularity-size units, keeping at least one */
size_t unit = mparams.granularity;
size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
SIZE_T_ONE) * unit;
msegmentptr sp = segment_holding(m, (char*)m->top);
if (!is_extern_segment(sp)) {
if (is_mmapped_segment(sp)) {
if (HAVE_MMAP &&
sp->size >= extra &&
!has_segment_link(m, sp)) { /* can't shrink if pinned */
size_t newsize = sp->size - extra;
/* Prefer mremap, fall back to munmap */
if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
(CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
released = extra;
}
}
}
else if (HAVE_MORECORE) {
if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
ACQUIRE_MORECORE_LOCK();
{
/* Make sure end of memory is where we last set it. */
char* old_br = (char*)(CALL_MORECORE(0));
if (old_br == sp->base + sp->size) {
char* rel_br = (char*)(CALL_MORECORE(-extra));
char* new_br = (char*)(CALL_MORECORE(0));
if (rel_br != CMFAIL && new_br < old_br)
released = old_br - new_br;
}
}
RELEASE_MORECORE_LOCK();
}
}
if (released != 0) {
sp->size -= released;
m->footprint -= released;
init_top(m, m->top, m->topsize - released);
check_top_chunk(m, m->top);
}
}
/* Unmap any unused mmapped segments */
if (HAVE_MMAP)
released += release_unused_segments(m);
/* On failure, disable autotrim to avoid repeated failed future calls */
if (released == 0)
m->trim_check = MAX_SIZE_T;
}
return (released != 0)? 1 : 0;
}
/* ---------------------------- malloc support --------------------------- */
/* allocate a large request from the best fitting chunk in a treebin */
static void* tmalloc_large(mstate m, size_t nb) {
tchunkptr v = 0;
size_t rsize = -nb; /* Unsigned negation */
tchunkptr t;
bindex_t idx;
compute_tree_index(nb, idx);
if ((t = *treebin_at(m, idx)) != 0) {
/* Traverse tree for this bin looking for node with size == nb */
size_t sizebits = nb << leftshift_for_tree_index(idx);
tchunkptr rst = 0; /* The deepest untaken right subtree */
for (;;) {
tchunkptr rt;
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
v = t;
if ((rsize = trem) == 0)
break;
}
rt = t->child[1];
t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
if (rt != 0 && rt != t)
rst = rt;
if (t == 0) {
t = rst; /* set t to least subtree holding sizes > nb */
break;
}
sizebits <<= 1;
}
}
if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
if (leftbits != 0) {
bindex_t i;
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
t = *treebin_at(m, i);
}
}
while (t != 0) { /* find smallest of tree or subtree */
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
t = leftmost_child(t);
}
/* If dv is a better fit, return 0 so malloc will use it */
if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
if (RTCHECK(ok_address(m, v))) { /* split */
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
insert_chunk(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
}
return 0;
}
/* allocate a small request from the best fitting chunk in a treebin */
static void* tmalloc_small(mstate m, size_t nb) {
tchunkptr t, v;
size_t rsize;
bindex_t i;
binmap_t leastbit = least_bit(m->treemap);
compute_bit2idx(leastbit, i);
v = t = *treebin_at(m, i);
rsize = chunksize(t) - nb;
while ((t = leftmost_child(t)) != 0) {
size_t trem = chunksize(t) - nb;
if (trem < rsize) {
rsize = trem;
v = t;
}
}
if (RTCHECK(ok_address(m, v))) {
mchunkptr r = chunk_plus_offset(v, nb);
assert(chunksize(v) == rsize + nb);
if (RTCHECK(ok_next(v, r))) {
unlink_large_chunk(m, v);
if (rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(m, v, (rsize + nb));
else {
set_size_and_pinuse_of_inuse_chunk(m, v, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(m, r, rsize);
}
return chunk2mem(v);
}
}
CORRUPTION_ERROR_ACTION(m);
return 0;
}
/* --------------------------- realloc support --------------------------- */
static void* internal_realloc(mstate m, void* oldmem, size_t bytes) {
if (bytes >= MAX_REQUEST) {
MALLOC_FAILURE_ACTION;
return 0;
}
if (!PREACTION(m)) {
mchunkptr oldp = mem2chunk(oldmem);
size_t oldsize = chunksize(oldp);
mchunkptr next = chunk_plus_offset(oldp, oldsize);
mchunkptr newp = 0;
void* extra = 0;
/* Try to either shrink or extend into top. Else malloc-copy-free */
if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) &&
ok_next(oldp, next) && ok_pinuse(next))) {
size_t nb = request2size(bytes);
if (is_mmapped(oldp))
newp = mmap_resize(m, oldp, nb);
else if (oldsize >= nb) { /* already big enough */
size_t rsize = oldsize - nb;
newp = oldp;
if (rsize >= MIN_CHUNK_SIZE) {
mchunkptr remainder = chunk_plus_offset(newp, nb);
set_inuse(m, newp, nb);
set_inuse(m, remainder, rsize);
extra = chunk2mem(remainder);
}
}
else if (next == m->top && oldsize + m->topsize > nb) {
/* Expand into top */
size_t newsize = oldsize + m->topsize;
size_t newtopsize = newsize - nb;
mchunkptr newtop = chunk_plus_offset(oldp, nb);
set_inuse(m, oldp, nb);
newtop->head = newtopsize |PINUSE_BIT;
m->top = newtop;
m->topsize = newtopsize;
newp = oldp;
}
}
else {
USAGE_ERROR_ACTION(m, oldmem);
POSTACTION(m);
return 0;
}
POSTACTION(m);
if (newp != 0) {
if (extra != 0) {
internal_free(m, extra);
}
check_inuse_chunk(m, newp);
return chunk2mem(newp);
}
else {
void* newmem = internal_malloc(m, bytes);
if (newmem != 0) {
size_t oc = oldsize - overhead_for(oldp);
memcpy(newmem, oldmem, (oc < bytes)? oc : bytes);
internal_free(m, oldmem);
}
return newmem;
}
}
return 0;
}
/* --------------------------- memalign support -------------------------- */
static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */
return internal_malloc(m, bytes);
if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
alignment = MIN_CHUNK_SIZE;
if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
size_t a = MALLOC_ALIGNMENT << 1;
while (a < alignment) a <<= 1;
alignment = a;
}
if (bytes >= MAX_REQUEST - alignment) {
if (m != 0) { /* Test isn't needed but avoids compiler warning */
MALLOC_FAILURE_ACTION;
}
}
else {
size_t nb = request2size(bytes);
size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
char* mem = (char*)internal_malloc(m, req);
if (mem != 0) {
void* leader = 0;
void* trailer = 0;
mchunkptr p = mem2chunk(mem);
if (PREACTION(m)) return 0;
if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */
/*
Find an aligned spot inside chunk. Since we need to give
back leading space in a chunk of at least MIN_CHUNK_SIZE, if
the first calculation places us at a spot with less than
MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
We've allocated enough total room so that this is always
possible.
*/
char* br = (char*)mem2chunk((size_t)(((size_t)(mem +
alignment -
SIZE_T_ONE)) &
-alignment));
char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
br : br+alignment;
mchunkptr newp = (mchunkptr)pos;
size_t leadsize = pos - (char*)(p);
size_t newsize = chunksize(p) - leadsize;
if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
newp->prev_foot = p->prev_foot + leadsize;
newp->head = (newsize|CINUSE_BIT);
}
else { /* Otherwise, give back leader, use the rest */
set_inuse(m, newp, newsize);
set_inuse(m, p, leadsize);
leader = chunk2mem(p);
}
p = newp;
}
/* Give back spare room at the end */
if (!is_mmapped(p)) {
size_t size = chunksize(p);
if (size > nb + MIN_CHUNK_SIZE) {
size_t remainder_size = size - nb;
mchunkptr remainder = chunk_plus_offset(p, nb);
set_inuse(m, p, nb);
set_inuse(m, remainder, remainder_size);
trailer = chunk2mem(remainder);
}
}
assert (chunksize(p) >= nb);
assert((((size_t)(chunk2mem(p))) % alignment) == 0);
check_inuse_chunk(m, p);
POSTACTION(m);
if (leader != 0) {
internal_free(m, leader);
}
if (trailer != 0) {
internal_free(m, trailer);
}
return chunk2mem(p);
}
}
return 0;
}
/* ------------------------ comalloc/coalloc support --------------------- */
static void** ialloc(mstate m,
size_t n_elements,
size_t* sizes,
int opts,
void* chunks[]) {
/*
This provides common support for independent_X routines, handling
all of the combinations that can result.
The opts arg has:
bit 0 set if all elements are same size (using sizes[0])
bit 1 set if elements should be zeroed
*/
size_t element_size; /* chunksize of each element, if all same */
size_t contents_size; /* total size of elements */
size_t array_size; /* request size of pointer array */
void* mem; /* malloced aggregate space */
mchunkptr p; /* corresponding chunk */
size_t remainder_size; /* remaining bytes while splitting */
void** marray; /* either "chunks" or malloced ptr array */
mchunkptr array_chunk; /* chunk for malloced ptr array */
flag_t was_enabled; /* to disable mmap */
size_t size;
size_t i;
/* compute array length, if needed */
if (chunks != 0) {
if (n_elements == 0)
return chunks; /* nothing to do */
marray = chunks;
array_size = 0;
}
else {
/* if empty req, must still return chunk representing empty array */
if (n_elements == 0)
return (void**)internal_malloc(m, 0);
marray = 0;
array_size = request2size(n_elements * (sizeof(void*)));
}
/* compute total element size */
if (opts & 0x1) { /* all-same-size */
element_size = request2size(*sizes);
contents_size = n_elements * element_size;
}
else { /* add up all the sizes */
element_size = 0;
contents_size = 0;
for (i = 0; i != n_elements; ++i)
contents_size += request2size(sizes[i]);
}
size = contents_size + array_size;
/*
Allocate the aggregate chunk. First disable direct-mmapping so
malloc won't use it, since we would not be able to later
free/realloc space internal to a segregated mmap region.
*/
was_enabled = use_mmap(m);
disable_mmap(m);
mem = internal_malloc(m, size - CHUNK_OVERHEAD);
if (was_enabled)
enable_mmap(m);
if (mem == 0)
return 0;
if (PREACTION(m)) return 0;
p = mem2chunk(mem);
remainder_size = chunksize(p);
assert(!is_mmapped(p));
if (opts & 0x2) { /* optionally clear the elements */
memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
}
/* If not provided, allocate the pointer array as final part of chunk */
if (marray == 0) {
size_t array_chunk_size;
array_chunk = chunk_plus_offset(p, contents_size);
array_chunk_size = remainder_size - contents_size;
marray = (void**) (chunk2mem(array_chunk));
set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
remainder_size = contents_size;
}
/* split out elements */
for (i = 0; ; ++i) {
marray[i] = chunk2mem(p);
if (i != n_elements-1) {
if (element_size != 0)
size = element_size;
else
size = request2size(sizes[i]);
remainder_size -= size;
set_size_and_pinuse_of_inuse_chunk(m, p, size);
p = chunk_plus_offset(p, size);
}
else { /* the final element absorbs any overallocation slop */
set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
break;
}
}
#if DEBUG
if (marray != chunks) {
/* final element must have exactly exhausted chunk */
if (element_size != 0) {
assert(remainder_size == element_size);
}
else {
assert(remainder_size == request2size(sizes[i]));
}
check_inuse_chunk(m, mem2chunk(marray));
}
for (i = 0; i != n_elements; ++i)
check_inuse_chunk(m, mem2chunk(marray[i]));
#endif /* DEBUG */
POSTACTION(m);
return marray;
}
/* -------------------------- public routines ---------------------------- */
#if !ONLY_MSPACES
void* dlmalloc(size_t bytes) {
/*
Basic algorithm:
If a small request (< 256 bytes minus per-chunk overhead):
1. If one exists, use a remainderless chunk in associated smallbin.
(Remainderless means that there are too few excess bytes to
represent as a chunk.)
2. If it is big enough, use the dv chunk, which is normally the
chunk adjacent to the one used for the most recent small request.
3. If one exists, split the smallest available chunk in a bin,
saving remainder in dv.
4. If it is big enough, use the top chunk.
5. If available, get memory from system and use it
Otherwise, for a large request:
1. Find the smallest available binned chunk that fits, and use it
if it is better fitting than dv chunk, splitting if necessary.
2. If better fitting than any binned chunk, use the dv chunk.
3. If it is big enough, use the top chunk.
4. If request size >= mmap threshold, try to directly mmap this chunk.
5. If available, get memory from system and use it
The ugly goto's here ensure that postaction occurs along all paths.
*/
if (!PREACTION(gm)) {
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = gm->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(gm, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(gm, b, p, idx);
set_inuse_and_pinuse(gm, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb > gm->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(gm, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(gm, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(gm, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(gm, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
}
if (nb <= gm->dvsize) {
size_t rsize = gm->dvsize - nb;
mchunkptr p = gm->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
gm->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
}
else { /* exhaust dv */
size_t dvs = gm->dvsize;
gm->dvsize = 0;
gm->dv = 0;
set_inuse_and_pinuse(gm, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
else if (nb < gm->topsize) { /* Split top */
size_t rsize = gm->topsize -= nb;
mchunkptr p = gm->top;
mchunkptr r = gm->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
mem = chunk2mem(p);
check_top_chunk(gm, gm->top);
check_malloced_chunk(gm, mem, nb);
goto postaction;
}
mem = sys_alloc(gm, nb);
postaction:
POSTACTION(gm);
return mem;
}
return 0;
}
void dlfree(void* mem) {
/*
Consolidate freed chunks with preceeding or succeeding bordering
free chunks, if they exist, and then place in a bin. Intermixed
with special cases for top, dv, mmapped chunks, and usage errors.
*/
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
#if FOOTERS
mstate fm = get_mstate_for(p);
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
#else /* FOOTERS */
#define fm gm
#endif /* FOOTERS */
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if ((prevsize & IS_MMAPPED_BIT) != 0) {
prevsize &= ~IS_MMAPPED_BIT;
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
insert_chunk(fm, p, psize);
check_free_chunk(fm, p);
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
#if !FOOTERS
#undef fm
#endif /* FOOTERS */
}
void* dlcalloc(size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = dlmalloc(req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
void* dlrealloc(void* oldmem, size_t bytes) {
if (oldmem == 0)
return dlmalloc(bytes);
#ifdef REALLOC_ZERO_BYTES_FREES
if (bytes == 0) {
dlfree(oldmem);
return 0;
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
#if ! FOOTERS
mstate m = gm;
#else /* FOOTERS */
mstate m = get_mstate_for(mem2chunk(oldmem));
if (!ok_magic(m)) {
USAGE_ERROR_ACTION(m, oldmem);
return 0;
}
#endif /* FOOTERS */
return internal_realloc(m, oldmem, bytes);
}
}
void* dlmemalign(size_t alignment, size_t bytes) {
return internal_memalign(gm, alignment, bytes);
}
void** dlindependent_calloc(size_t n_elements, size_t elem_size,
void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
return ialloc(gm, n_elements, &sz, 3, chunks);
}
void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
void* chunks[]) {
return ialloc(gm, n_elements, sizes, 0, chunks);
}
void* dlvalloc(size_t bytes) {
size_t pagesz;
init_mparams();
pagesz = mparams.page_size;
return dlmemalign(pagesz, bytes);
}
void* dlpvalloc(size_t bytes) {
size_t pagesz;
init_mparams();
pagesz = mparams.page_size;
return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
}
int dlmalloc_trim(size_t pad) {
int result = 0;
if (!PREACTION(gm)) {
result = sys_trim(gm, pad);
POSTACTION(gm);
}
return result;
}
size_t dlmalloc_footprint(void) {
return gm->footprint;
}
size_t dlmalloc_max_footprint(void) {
return gm->max_footprint;
}
#if !NO_MALLINFO
struct mallinfo dlmallinfo(void) {
return internal_mallinfo(gm);
}
#endif /* NO_MALLINFO */
void dlmalloc_stats() {
internal_malloc_stats(gm);
}
size_t dlmalloc_usable_size(void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
if (cinuse(p))
return chunksize(p) - overhead_for(p);
}
return 0;
}
int dlmallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
#endif /* !ONLY_MSPACES */
/* ----------------------------- user mspaces ---------------------------- */
#if MSPACES
static mstate init_user_mstate(char* tbase, size_t tsize) {
size_t msize = pad_request(sizeof(struct malloc_state));
mchunkptr mn;
mchunkptr msp = align_as_chunk(tbase);
mstate m = (mstate)(chunk2mem(msp));
memset(m, 0, msize);
INITIAL_LOCK(&m->mutex);
msp->head = (msize|PINUSE_BIT|CINUSE_BIT);
m->seg.base = m->least_addr = tbase;
m->seg.size = m->footprint = m->max_footprint = tsize;
m->magic = mparams.magic;
m->mflags = mparams.default_mflags;
disable_contiguous(m);
init_bins(m);
mn = next_chunk(mem2chunk(m));
init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
check_top_chunk(m, m->top);
return m;
}
mspace create_mspace(size_t capacity, int locked) {
mstate m = 0;
size_t msize = pad_request(sizeof(struct malloc_state));
init_mparams(); /* Ensure pagesize etc initialized */
if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
size_t rs = ((capacity == 0)? mparams.granularity :
(capacity + TOP_FOOT_SIZE + msize));
size_t tsize = granularity_align(rs);
char* tbase = (char*)(CALL_MMAP(tsize));
if (tbase != CMFAIL) {
m = init_user_mstate(tbase, tsize);
m->seg.sflags = IS_MMAPPED_BIT;
set_lock(m, locked);
}
}
return (mspace)m;
}
mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
mstate m = 0;
size_t msize = pad_request(sizeof(struct malloc_state));
init_mparams(); /* Ensure pagesize etc initialized */
if (capacity > msize + TOP_FOOT_SIZE &&
capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
m = init_user_mstate((char*)base, capacity);
m->seg.sflags = EXTERN_BIT;
set_lock(m, locked);
}
return (mspace)m;
}
size_t destroy_mspace(mspace msp) {
size_t freed = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
msegmentptr sp = &ms->seg;
while (sp != 0) {
char* base = sp->base;
size_t size = sp->size;
flag_t flag = sp->sflags;
sp = sp->next;
if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) &&
CALL_MUNMAP(base, size) == 0)
freed += size;
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return freed;
}
/*
mspace versions of routines are near-clones of the global
versions. This is not so nice but better than the alternatives.
*/
void* mspace_malloc(mspace msp, size_t bytes) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (!PREACTION(ms)) {
void* mem;
size_t nb;
if (bytes <= MAX_SMALL_REQUEST) {
bindex_t idx;
binmap_t smallbits;
nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
idx = small_index(nb);
smallbits = ms->smallmap >> idx;
if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
mchunkptr b, p;
idx += ~smallbits & 1; /* Uses next bin if idx empty */
b = smallbin_at(ms, idx);
p = b->fd;
assert(chunksize(p) == small_index2size(idx));
unlink_first_small_chunk(ms, b, p, idx);
set_inuse_and_pinuse(ms, p, small_index2size(idx));
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb > ms->dvsize) {
if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
mchunkptr b, p, r;
size_t rsize;
bindex_t i;
binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
binmap_t leastbit = least_bit(leftbits);
compute_bit2idx(leastbit, i);
b = smallbin_at(ms, i);
p = b->fd;
assert(chunksize(p) == small_index2size(i));
unlink_first_small_chunk(ms, b, p, i);
rsize = small_index2size(i) - nb;
/* Fit here cannot be remainderless if 4byte sizes */
if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
set_inuse_and_pinuse(ms, p, small_index2size(i));
else {
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
r = chunk_plus_offset(p, nb);
set_size_and_pinuse_of_free_chunk(r, rsize);
replace_dv(ms, r, rsize);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
}
else if (bytes >= MAX_REQUEST)
nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
else {
nb = pad_request(bytes);
if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
}
if (nb <= ms->dvsize) {
size_t rsize = ms->dvsize - nb;
mchunkptr p = ms->dv;
if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
ms->dvsize = rsize;
set_size_and_pinuse_of_free_chunk(r, rsize);
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
}
else { /* exhaust dv */
size_t dvs = ms->dvsize;
ms->dvsize = 0;
ms->dv = 0;
set_inuse_and_pinuse(ms, p, dvs);
}
mem = chunk2mem(p);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
else if (nb < ms->topsize) { /* Split top */
size_t rsize = ms->topsize -= nb;
mchunkptr p = ms->top;
mchunkptr r = ms->top = chunk_plus_offset(p, nb);
r->head = rsize | PINUSE_BIT;
set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
mem = chunk2mem(p);
check_top_chunk(ms, ms->top);
check_malloced_chunk(ms, mem, nb);
goto postaction;
}
mem = sys_alloc(ms, nb);
postaction:
POSTACTION(ms);
return mem;
}
return 0;
}
void mspace_free(mspace msp, void* mem) {
if (mem != 0) {
mchunkptr p = mem2chunk(mem);
#if FOOTERS
mstate fm = get_mstate_for(p);
#else /* FOOTERS */
mstate fm = (mstate)msp;
#endif /* FOOTERS */
if (!ok_magic(fm)) {
USAGE_ERROR_ACTION(fm, p);
return;
}
if (!PREACTION(fm)) {
check_inuse_chunk(fm, p);
if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) {
size_t psize = chunksize(p);
mchunkptr next = chunk_plus_offset(p, psize);
if (!pinuse(p)) {
size_t prevsize = p->prev_foot;
if ((prevsize & IS_MMAPPED_BIT) != 0) {
prevsize &= ~IS_MMAPPED_BIT;
psize += prevsize + MMAP_FOOT_PAD;
if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
fm->footprint -= psize;
goto postaction;
}
else {
mchunkptr prev = chunk_minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
if (p != fm->dv) {
unlink_chunk(fm, p, prevsize);
}
else if ((next->head & INUSE_BITS) == INUSE_BITS) {
fm->dvsize = psize;
set_free_with_pinuse(p, psize, next);
goto postaction;
}
}
else
goto erroraction;
}
}
if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
if (!cinuse(next)) { /* consolidate forward */
if (next == fm->top) {
size_t tsize = fm->topsize += psize;
fm->top = p;
p->head = tsize | PINUSE_BIT;
if (p == fm->dv) {
fm->dv = 0;
fm->dvsize = 0;
}
if (should_trim(fm, tsize))
sys_trim(fm, 0);
goto postaction;
}
else if (next == fm->dv) {
size_t dsize = fm->dvsize += psize;
fm->dv = p;
set_size_and_pinuse_of_free_chunk(p, dsize);
goto postaction;
}
else {
size_t nsize = chunksize(next);
psize += nsize;
unlink_chunk(fm, next, nsize);
set_size_and_pinuse_of_free_chunk(p, psize);
if (p == fm->dv) {
fm->dvsize = psize;
goto postaction;
}
}
}
else
set_free_with_pinuse(p, psize, next);
insert_chunk(fm, p, psize);
check_free_chunk(fm, p);
goto postaction;
}
}
erroraction:
USAGE_ERROR_ACTION(fm, p);
postaction:
POSTACTION(fm);
}
}
}
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
void* mem;
size_t req = 0;
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
if (n_elements != 0) {
req = n_elements * elem_size;
if (((n_elements | elem_size) & ~(size_t)0xffff) &&
(req / n_elements != elem_size))
req = MAX_SIZE_T; /* force downstream failure on overflow */
}
mem = internal_malloc(ms, req);
if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
memset(mem, 0, req);
return mem;
}
void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
if (oldmem == 0)
return mspace_malloc(msp, bytes);
#ifdef REALLOC_ZERO_BYTES_FREES
if (bytes == 0) {
mspace_free(msp, oldmem);
return 0;
}
#endif /* REALLOC_ZERO_BYTES_FREES */
else {
#if FOOTERS
mchunkptr p = mem2chunk(oldmem);
mstate ms = get_mstate_for(p);
#else /* FOOTERS */
mstate ms = (mstate)msp;
#endif /* FOOTERS */
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return internal_realloc(ms, oldmem, bytes);
}
}
void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return internal_memalign(ms, alignment, bytes);
}
void** mspace_independent_calloc(mspace msp, size_t n_elements,
size_t elem_size, void* chunks[]) {
size_t sz = elem_size; /* serves as 1-element array */
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, &sz, 3, chunks);
}
void** mspace_independent_comalloc(mspace msp, size_t n_elements,
size_t sizes[], void* chunks[]) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
return 0;
}
return ialloc(ms, n_elements, sizes, 0, chunks);
}
int mspace_trim(mspace msp, size_t pad) {
int result = 0;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
if (!PREACTION(ms)) {
result = sys_trim(ms, pad);
POSTACTION(ms);
}
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
return result;
}
void mspace_malloc_stats(mspace msp) {
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
internal_malloc_stats(ms);
}
else {
USAGE_ERROR_ACTION(ms,ms);
}
}
size_t mspace_footprint(mspace msp) {
size_t result;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->footprint;
}
USAGE_ERROR_ACTION(ms,ms);
return result;
}
size_t mspace_max_footprint(mspace msp) {
size_t result;
mstate ms = (mstate)msp;
if (ok_magic(ms)) {
result = ms->max_footprint;
}
USAGE_ERROR_ACTION(ms,ms);
return result;
}
#if !NO_MALLINFO
struct mallinfo mspace_mallinfo(mspace msp) {
mstate ms = (mstate)msp;
if (!ok_magic(ms)) {
USAGE_ERROR_ACTION(ms,ms);
}
return internal_mallinfo(ms);
}
#endif /* NO_MALLINFO */
int mspace_mallopt(int param_number, int value) {
return change_mparam(param_number, value);
}
#endif /* MSPACES */
/* -------------------- Alternative MORECORE functions ------------------- */
/*
Guidelines for creating a custom version of MORECORE:
* For best performance, MORECORE should allocate in multiples of pagesize.
* MORECORE may allocate more memory than requested. (Or even less,
but this will usually result in a malloc failure.)
* MORECORE must not allocate memory when given argument zero, but
instead return one past the end address of memory from previous
nonzero call.
* For best performance, consecutive calls to MORECORE with positive
arguments should return increasing addresses, indicating that
space has been contiguously extended.
* Even though consecutive calls to MORECORE need not return contiguous
addresses, it must be OK for malloc'ed chunks to span multiple
regions in those cases where they do happen to be contiguous.
* MORECORE need not handle negative arguments -- it may instead
just return MFAIL when given negative arguments.
Negative arguments are always multiples of pagesize. MORECORE
must not misinterpret negative args as large positive unsigned
args. You can suppress all such calls from even occurring by defining
MORECORE_CANNOT_TRIM,
As an example alternative MORECORE, here is a custom allocator
kindly contributed for pre-OSX macOS. It uses virtually but not
necessarily physically contiguous non-paged memory (locked in,
present and won't get swapped out). You can use it by uncommenting
this section, adding some #includes, and setting up the appropriate
defines above:
#define MORECORE osMoreCore
There is also a shutdown routine that should somehow be called for
cleanup upon program exit.
#define MAX_POOL_ENTRIES 100
#define MINIMUM_MORECORE_SIZE (64 * 1024U)
static int next_os_pool;
void *our_os_pools[MAX_POOL_ENTRIES];
void *osMoreCore(int size)
{
void *ptr = 0;
static void *sbrk_top = 0;
if (size > 0)
{
if (size < MINIMUM_MORECORE_SIZE)
size = MINIMUM_MORECORE_SIZE;
if (CurrentExecutionLevel() == kTaskLevel)
ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
if (ptr == 0)
{
return (void *) MFAIL;
}
// save ptrs so they can be freed during cleanup
our_os_pools[next_os_pool] = ptr;
next_os_pool++;
ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
sbrk_top = (char *) ptr + size;
return ptr;
}
else if (size < 0)
{
// we don't currently support shrink behavior
return (void *) MFAIL;
}
else
{
return sbrk_top;
}
}
// cleanup any allocated memory pools
// called as last thing before shutting down driver
void osCleanupMem(void)
{
void **ptr;
for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
if (*ptr)
{
PoolDeallocate(*ptr);
*ptr = 0;
}
}
*/
/* -----------------------------------------------------------------------
History:
V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
* Add max_footprint functions
* Ensure all appropriate literals are size_t
* Fix conditional compilation problem for some #define settings
* Avoid concatenating segments with the one provided
in create_mspace_with_base
* Rename some variables to avoid compiler shadowing warnings
* Use explicit lock initialization.
* Better handling of sbrk interference.
* Simplify and fix segment insertion, trimming and mspace_destroy
* Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
* Thanks especially to Dennis Flanagan for help on these.
V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
* Fix memalign brace error.
V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
* Fix improper #endif nesting in C++
* Add explicit casts needed for C++
V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
* Use trees for large bins
* Support mspaces
* Use segments to unify sbrk-based and mmap-based system allocation,
removing need for emulation on most platforms without sbrk.
* Default safety checks
* Optional footer checks. Thanks to William Robertson for the idea.
* Internal code refactoring
* Incorporate suggestions and platform-specific changes.
Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
Aaron Bachmann, Emery Berger, and others.
* Speed up non-fastbin processing enough to remove fastbins.
* Remove useless cfree() to avoid conflicts with other apps.
* Remove internal memcpy, memset. Compilers handle builtins better.
* Remove some options that no one ever used and rename others.
V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
* Fix malloc_state bitmap array misdeclaration
V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
* Allow tuning of FIRST_SORTED_BIN_SIZE
* Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
* Better detection and support for non-contiguousness of MORECORE.
Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
* Bypass most of malloc if no frees. Thanks To Emery Berger.
* Fix freeing of old top non-contiguous chunk im sysmalloc.
* Raised default trim and map thresholds to 256K.
* Fix mmap-related #defines. Thanks to Lubos Lunak.
* Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
* Branch-free bin calculation
* Default trim and mmap thresholds now 256K.
V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
* Introduce independent_comalloc and independent_calloc.
Thanks to Michael Pachos for motivation and help.
* Make optional .h file available
* Allow > 2GB requests on 32bit systems.
* new WIN32 sbrk, mmap, munmap, lock code from <[email protected]>.
Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
and Anonymous.
* Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
helping test this.)
* memalign: check alignment arg
* realloc: don't try to shift chunks backwards, since this
leads to more fragmentation in some programs and doesn't
seem to help in any others.
* Collect all cases in malloc requiring system memory into sysmalloc
* Use mmap as backup to sbrk
* Place all internal state in malloc_state
* Introduce fastbins (although similar to 2.5.1)
* Many minor tunings and cosmetic improvements
* Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
* Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
Thanks to Tony E. Bennett <[email protected]> and others.
* Include errno.h to support default failure action.
V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
* return null for negative arguments
* Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
* Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
(e.g. WIN32 platforms)
* Cleanup header file inclusion for WIN32 platforms
* Cleanup code to avoid Microsoft Visual C++ compiler complaints
* Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
memory allocation routines
* Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
* Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
usage of 'assert' in non-WIN32 code
* Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
avoid infinite loop
* Always call 'fREe()' rather than 'free()'
V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
* Fixed ordering problem with boundary-stamping
V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
* Added pvalloc, as recommended by H.J. Liu
* Added 64bit pointer support mainly from Wolfram Gloger
* Added anonymously donated WIN32 sbrk emulation
* Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
* malloc_extend_top: fix mask error that caused wastage after
foreign sbrks
* Add linux mremap support code from HJ Liu
V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
* Integrated most documentation with the code.
* Add support for mmap, with help from
Wolfram Gloger ([email protected]).
* Use last_remainder in more cases.
* Pack bins using idea from [email protected]
* Use ordered bins instead of best-fit threshhold
* Eliminate block-local decls to simplify tracing and debugging.
* Support another case of realloc via move into top
* Fix error occuring when initial sbrk_base not word-aligned.
* Rely on page size for units instead of SBRK_UNIT to
avoid surprises about sbrk alignment conventions.
* Add mallinfo, mallopt. Thanks to Raymond Nijssen
([email protected]) for the suggestion.
* Add `pad' argument to malloc_trim and top_pad mallopt parameter.
* More precautions for cases where other routines call sbrk,
courtesy of Wolfram Gloger ([email protected]).
* Added macros etc., allowing use in linux libc from
H.J. Lu ([email protected])
* Inverted this history list
V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
* Re-tuned and fixed to behave more nicely with V2.6.0 changes.
* Removed all preallocation code since under current scheme
the work required to undo bad preallocations exceeds
the work saved in good cases for most test programs.
* No longer use return list or unconsolidated bins since
no scheme using them consistently outperforms those that don't
given above changes.
* Use best fit for very large chunks to prevent some worst-cases.
* Added some support for debugging
V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
* Removed footers when chunks are in use. Thanks to
Paul Wilson ([email protected]) for the suggestion.
V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
* Added malloc_trim, with help from Wolfram Gloger
([email protected]).
V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
* realloc: try to expand in both directions
* malloc: swap order of clean-bin strategy;
* realloc: only conditionally expand backwards
* Try not to scavenge used bins
* Use bin counts as a guide to preallocation
* Occasionally bin return list chunks in first scan
* Add a few optimizations from [email protected]
V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
* faster bin computation & slightly different binning
* merged all consolidations to one part of malloc proper
(eliminating old malloc_find_space & malloc_clean_bin)
* Scan 2 returns chunks (not just 1)
* Propagate failure in realloc if malloc returns 0
* Add stuff to allow compilation on non-ANSI compilers
from [email protected]
V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
* removed potential for odd address access in prev_chunk
* removed dependency on getpagesize.h
* misc cosmetics and a bit more internal documentation
* anticosmetics: mangled names in macros to evade debugger strangeness
* tested on sparc, hp-700, dec-mips, rs6000
with gcc & native cc (hp, dec only) allowing
Detlefs & Zorn comparison study (in SIGPLAN Notices.)
Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
* Based loosely on libg++-1.2X malloc. (It retains some of the overall
structure of old version, but most details differ.)
*/
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#undef assert
#include<assert.h>
#if defined(WIN32) || defined(_WIN32_WCE)
inline void DPRINT(const char *str,...)
{
va_list args;
va_start(args,str);
char outstr[4096];
wchar_t outstrw[4096];
_vsnprintf(outstr,4096,str,args);
outstr[4095]='\0';
mbstowcs(outstrw,outstr,4096);
OutputDebugString(outstrw);
}
#else
inline void DPRINT(const char *str,...)
{
va_list args;
va_start(args,str);
vfprintf(stderr,str,args);
}
#endif
CMemHeap::CMemHeap()
{
m_pBuffer=NULL;
m_nBufferLength=0;
m_pSpace=NULL;
}
CMemHeap::CMemHeap(void *mem, size_t len)
{
m_pBuffer=NULL;
m_nBufferLength=0;
m_pSpace=NULL;
Create(mem,len);
}
CMemHeap::~CMemHeap()
{
Destroy();
}
bool CMemHeap::Create(void *mem, size_t len)
{
if(m_pBuffer)
{
return false;
}
m_pBuffer=mem;
m_nBufferLength=len;
m_pSpace=DLMALLOC::create_mspace_with_base(mem,len,0);
if(!m_pSpace)
{
m_pBuffer=NULL;
m_nBufferLength=0;
return false;
}
return true;
}
bool CMemHeap::Destroy(void)
{
if(!m_pBuffer)
{
return false;
}
DLMALLOC::destroy_mspace(m_pSpace);
m_pBuffer=NULL;
m_nBufferLength=0;
m_pSpace=NULL;
return true;
}
void *CMemHeap::Alloc(size_t len, bool bFill, unsigned char fillvalue)
{
if(!m_pBuffer)
{
ASSERT(0);
return NULL;
}
void *ptr=DLMALLOC::mspace_malloc(m_pSpace,len);
if(!ptr)
{
return NULL;
}
if(bFill)
{
memset(ptr,(int)(unsigned int)fillvalue,len);
}
return ptr;
}
void CMemHeap::Free(void *mem)
{
if(!m_pBuffer)
{
ASSERT(0);
return;
}
DLMALLOC::mspace_free(m_pSpace,mem);
}
void *CMemHeap::Realloc(void *mem, size_t newlen)
{
if(!m_pBuffer)
{
ASSERT(0);
return NULL;
}
return DLMALLOC::mspace_realloc(m_pSpace,mem,newlen);
}
size_t CMemHeap::GetSize(void *mem)
{
if(!m_pBuffer)
{
ASSERT(0);
return 0;
}
return *(((size_t *)mem)-1);
}
size_t CMemHeap::GetTotalSize(void)
{
if(!m_pBuffer)
{
ASSERT(0);
return 0;
}
DLMALLOC::mallinfo mi=DLMALLOC::mspace_mallinfo(m_pSpace);
return mi.usmblks;
}
size_t CMemHeap::GetUsedSize(void)
{
if(!m_pBuffer)
{
ASSERT(0);
return 0;
}
DLMALLOC::mallinfo mi=DLMALLOC::mspace_mallinfo(m_pSpace);
return mi.uordblks;
}
size_t CMemHeap::GetFreeSize(void)
{
if(!m_pBuffer)
{
ASSERT(0);
return 0;
}
DLMALLOC::mallinfo mi=DLMALLOC::mspace_mallinfo(m_pSpace);
return mi.fordblks;
}
void CMemHeap::Dump(void)
{
DPRINT("CMemHeap Status\n");
DPRINT("---------------\n");
DPRINT("Initialized: ");
if(!m_pBuffer)
{
DPRINT("NO\n");
return;
}
DPRINT("YES\n");
DPRINT("Buffer Pointer: 0x%p\n",m_pBuffer);
DPRINT("Buffer Length: 0x%p\n",m_nBufferLength);
DPRINT("Maximum Size: 0x%p\n",GetTotalSize());
DPRINT("Free Size: 0x%p\n",GetFreeSize());
DPRINT("Used Size: 0x%p\n",GetFreeSize());
}
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac",
"crioux@684fc592-8442-0410-8ea1-df6b371289ac"
] | [
[
[
1,
17
],
[
21,
5121
],
[
5123,
5298
]
],
[
[
18,
20
],
[
5122,
5122
]
]
] |
a768f2e87e690f8eaf72fba95355b14502c04e49 | 6b570e095f8eea42c8114ef6be1ee62cd4ec3c8f | /thu-remap/main.cxx | 98eb8a3f5461ead562eeb845975122de862f61ff | [] | no_license | pinewall/RemapTest | 6a89cf96640a52b9e3accb13eead76976ba77f38 | 0ca05f95b183cc5a556c0e607980257644e46392 | refs/heads/master | 2016-09-02T09:33:09.348387 | 2011-07-31T02:28:04 | 2011-07-31T02:28:04 | 2,070,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,134 | cxx | /*
??????????
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "dist_remap.h"
#include "grid.h"
#include "grid_func.h"
#include "data_func.h"
#include "io.h"
#include "remap_func.h"
#include "remap_cfg.h"
#include <sys/time.h>
#include <string.h>
#include "models_cfg.h"
// modified by ssq
#include <netcdf.h>
#include <math.h>
void wtime(double *t)
{
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (__timezone_ptr_t)0);
if (sec < 0)
sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec;
}
void Print_Dst_To_File(char* str, int npts_dst_para, double* lon_coords_dst_para, double* lat_coords_dst_para, double* data_dst_para)
{
FILE* out;
if ((out = fopen(str, "a+")) == NULL)
{
printf("Cannot open file!\n");
}
else
{
int count = 0;
while (count < npts_dst_para)
{
char out1[20] , out2[20] , out3[20];
const char* out4 = ",";
const char* out5 = ":";
const char* out6 = "\n";
sprintf(out1 , "res-%d: %lf" , count, lon_coords_dst_para[count]);
sprintf(out2 , "%lf" , lat_coords_dst_para[count]);
sprintf(out3 , "%lf" , data_dst_para[count]);
fputs((const char*)out1, out);
fputs(out4 , out);
fputs((const char*)out2 , out);
fputs(out5 , out);
fputs((const char*)out3 , out);
fputs(out6 , out);
count++;
}
}
fclose(out);
}
int main (int argc, char **argv)
{
int i, j;
int read_size;
double * data_src_array; // the src grid_2D data to be remapped
int size_input_data_file;
double * data_dst_array; // the dst grid_2D data after remapping
double * data_dst_remap;
double * data_dst_error;
FILE *fp_data_src;
FILE *fp_data_dst;
grid *grid_src, *grid_dst;
char *name_data_field = data_remaps_cfg[0].name_data_field;
char *grid_name1 = data_remaps_cfg[0].name_grid_src;
char *grid_name2 = data_remaps_cfg[0].name_grid_dst;
double time1, time2;
if (argc < 5) {
printf("usage <grid1> <grid2> <test_case:[1-3]> <algorithm>\n");
exit(0);
}
strcpy(atm_model_set.models_cfg[0].grid_2D.name_file, argv[1]);
strcpy(ocn_model_set.models_cfg[0].grid_2D.name_file, argv[2]);
strcpy(data_remaps_cfg[0].name_remap_alg, argv[4]);
generate_all_cpl_grids();
grid_src = cpl_grids->get_grid(grid_name1);
grid_dst = cpl_grids->get_grid(grid_name2);
wtime(&time1);
generate_remap_operators();
wtime(&time2);
printf("initialize_time %f\n", time2 - time1);
data_src_array = new double [grid_src->get_num_points()];
data_dst_array = new double [grid_dst->get_num_points()];
data_dst_remap = new double [grid_dst->get_num_points()];
data_dst_error = new double [grid_dst->get_num_points()];
memset(data_src_array, 0, sizeof(double) * grid_src->get_num_points());
memset(data_dst_array, 0, sizeof(double) * grid_dst->get_num_points());
memset(data_dst_remap, 0, sizeof(double) * grid_dst->get_num_points());
memset(data_dst_error, 0, sizeof(double) * grid_dst->get_num_points());
if (strcmp(argv[3], "1") == 0)
{
double length = 0.1 * 2 * 3.14159265359;
double grid_tmp;
for (int i = 0; i < grid_src->get_num_points(); i++)
{
data_src_array[i] = cos(grid_src->get_lat_coords()[i] * PI / 180)
* cos(grid_src->get_lon_coords()[i] * PI / 180);
grid_tmp = acos(-data_src_array[i]) / length;
if (grid_tmp <= 1.0)
{
data_src_array[i] = 2.0 + cos(3.14159265359 * grid_tmp);
}
else
{
data_src_array[i] = 1.0;
}
if (! grid_src->get_mymask()[i])
{
data_src_array[i] = 0.0;
}
}
for (int i = 0; i < grid_dst->get_num_points(); i++)
{
data_dst_array[i] = cos(grid_dst->get_lat_coords()[i] * PI / 180)
* cos(grid_dst->get_lon_coords()[i] * PI / 180);
grid_tmp = acos(-data_dst_array[i]) / length;
if (grid_tmp <= 1.0)
{
data_dst_array[i] = 2.0 + cos(3.14159265359 * grid_tmp);
}
else
{
data_dst_array[i] = 1.0;
}
if (! grid_dst->get_mymask()[i])
{
data_dst_array[i] = 0.0;
}
}
}
else if (strcmp(argv[3], "2") == 0)
{
for (int i = 0; i < grid_src->get_num_points(); i++)
{
if (grid_src->get_mymask()[i])
{
data_src_array[i] = 2.0 + cos(grid_src->get_lat_coords()[i] * PI / 180)* cos(grid_src->get_lat_coords()[i] * PI / 180) * cos(2.0 * grid_src->get_lon_coords()[i] * PI / 180);
}
else
{
data_src_array[i] = 0.0;
}
}
for (int i = 0; i < grid_dst->get_num_points(); i++)
{
if (grid_dst->get_mymask()[i])
{
data_dst_array[i] = 2.0 + cos(grid_dst->get_lat_coords()[i] * PI / 180)* cos(grid_dst->get_lat_coords()[i] * PI / 180) * cos(2.0 * grid_dst->get_lon_coords()[i] * PI / 180);
}
else
{
data_dst_array[i] = 0.0;
}
}
}
else if (strcmp(argv[3], "3") == 0)
{
for (int i = 0; i < grid_src->get_num_points(); i++)
{
if (grid_src->get_mymask()[i])
{
data_src_array[i] = 2.0 + pow(cos(grid_src->get_lat_coords()[i] * PI / 180),16) * cos(16 * grid_src->get_lon_coords()[i] * PI / 180);
}
else
{
data_src_array[i] = 0;
}
}
for (int i = 0; i < grid_dst->get_num_points(); i++)
{
if (grid_dst->get_mymask()[i])
{
data_dst_array[i] = 2.0 + pow(cos(grid_dst->get_lat_coords()[i] * PI / 180),16) * cos(16 * grid_dst->get_lon_coords()[i] * PI / 180);
}
else
{
data_dst_array[i] = 0;
}
}
}
else
{
printf("Unknown Test Case\n");
printf("\t[1]: cosine hill at lon=pi,lat=0\n");
printf("\t[2]: pseudo-spherical harmonic l=2, m=2\n");
printf("\t[3]: pseudo-spherical harmonic l=32, m=16\n");
return -1;
}
for (i = 0; i < grid_src->get_num_points(); i += grid_src->get_num_points()) {
wtime(&time1);
do_remap(name_data_field, grid_name1, grid_name2, data_src_array + i, data_dst_remap);
//do_remap(name_data_field, grid_name2, grid_name1, data_dst, data_src + i / sizeof(double));
wtime(&time2);
printf("remap_time %f\n", time2 - time1);
//Print_Dst_To_File("data_dst1", grid_dst->get_num_points(), grid_dst->get_lon_coords(), grid_dst->get_lat_coords(), data_dst);
}
// modified by ssq
int ncid;
int status;
// variable ID
int nc_srcgrdcntrlat_id, nc_srcgrdcntrlon_id;
int nc_dstgrdcntrlat_id, nc_dstgrdcntrlon_id;
int nc_srcgrdimask_id, nc_dstgrdimask_id;
int nc_srcgrdarea_id, nc_dstgrdarea_id;
int nc_srcgrdfrac_id, nc_dstgrdfrac_id;
int nc_srcarray_id, nc_dstarray_id;
int nc_srcgradlat_id, nc_srcgradlon_id;
int nc_dstremap1_id, nc_dstremap2_id;
int nc_dsterror1_id, nc_dsterror2_id;
status = nc_create ("THUoutput.nc", NC_CLOBBER, &ncid);
char remap_name[1024];
strcpy(remap_name, grid_src->get_grid_name());
strcat(remap_name, " --> ");
strcat(remap_name, grid_dst->get_grid_name());
status = nc_put_att_text (ncid, NC_GLOBAL, "title", strlen(remap_name), remap_name);
// define grid size dimensions
int nc_grid1size_id[2];
int nc_grid2size_id[2];
status = nc_def_dim (ncid, "grid1_dim1", grid_src->get_num_lats(), &(nc_grid1size_id[0]));
status = nc_def_dim (ncid, "grid1_dim2", grid_src->get_num_lons(), &(nc_grid1size_id[1]));
status = nc_def_dim (ncid, "grid2_dim1", grid_dst->get_num_lats(), &(nc_grid2size_id[0]));
status = nc_def_dim (ncid, "grid2_dim2", grid_dst->get_num_lons(), &(nc_grid2size_id[1]));
// define grid center latitude array
status = nc_def_var (ncid, "src_grid_center_lat", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgrdcntrlat_id);
status = nc_put_att_text (ncid, nc_srcgrdcntrlat_id, "units", 7, "radians");
status = nc_def_var (ncid, "dst_grid_center_lat", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstgrdcntrlat_id);
status = nc_put_att_text (ncid, nc_dstgrdcntrlat_id, "units", 7, "radians");
// define grid center longitude array
status = nc_def_var (ncid, "src_grid_center_lon", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgrdcntrlon_id);
status = nc_put_att_text (ncid, nc_srcgrdcntrlon_id, "units", 7, "radians");
status = nc_def_var (ncid, "dst_grid_center_lon", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstgrdcntrlon_id);
status = nc_put_att_text (ncid, nc_dstgrdcntrlon_id, "units", 7, "radians");
// define grid mask
status = nc_def_var (ncid, "src_grid_imask", NC_INT, 2, nc_grid1size_id, &nc_srcgrdimask_id);
status = nc_put_att_text (ncid, nc_srcgrdimask_id, "units", 8, "unitless");
status = nc_def_var (ncid, "dst_grid_imask", NC_INT, 2, nc_grid2size_id, &nc_dstgrdimask_id);
status = nc_put_att_text (ncid, nc_dstgrdimask_id, "units", 8, "unitless");
// define grid area
status = nc_def_var (ncid, "src_grid_area", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgrdarea_id);
status = nc_def_var (ncid, "dst_grid_area", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstgrdarea_id);
// define grid frac
status = nc_def_var (ncid, "src_grid_frac", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgrdfrac_id);
status = nc_def_var (ncid, "dst_grid_frac", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstgrdfrac_id);
// define source arrays
status = nc_def_var (ncid, "src_array", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcarray_id);
status = nc_def_var (ncid, "src_grad_lat", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgradlat_id);
status = nc_def_var (ncid, "src_grad_lon", NC_DOUBLE, 2, nc_grid1size_id, &nc_srcgradlon_id);
// define destination arrays
status = nc_def_var (ncid, "dst_array", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstarray_id);
status = nc_def_var (ncid, "dst_remap1", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstremap1_id);
status = nc_def_var (ncid, "dst_remap2", NC_DOUBLE, 2, nc_grid2size_id, &nc_dstremap2_id);
// define error arrays
status = nc_def_var (ncid, "dst_error1", NC_DOUBLE, 2, nc_grid2size_id, &nc_dsterror1_id);
status = nc_def_var (ncid, "dst_error2", NC_DOUBLE, 2, nc_grid2size_id, &nc_dsterror2_id);
// end definination stage
status = nc_enddef(ncid);
/* write some grid info */
// write grid center latitude array
status = nc_put_var_double (ncid, nc_srcgrdcntrlat_id, grid_src->get_lat_coords());
status = nc_put_var_double (ncid, nc_dstgrdcntrlat_id, grid_dst->get_lat_coords());
// write grid center longitude array
status = nc_put_var_double (ncid, nc_srcgrdcntrlon_id, grid_src->get_lon_coords());
status = nc_put_var_double (ncid, nc_dstgrdcntrlon_id, grid_src->get_lon_coords());
// write grid mask
int * grid1_imask = new int [grid_src->get_num_points()];
int * grid2_imask = new int [grid_dst->get_num_points()];
for (int i = 0; i < grid_src->get_num_points(); i++)
grid1_imask[i] = (grid_src->get_mymask()[i]) ? 1 : 0;
for (int i = 0; i < grid_dst->get_num_points(); i++)
grid2_imask[i] = (grid_dst->get_mymask()[i]) ? 1 : 0;
status = nc_put_var_int (ncid, nc_srcgrdimask_id, grid1_imask);
status = nc_put_var_int (ncid, nc_dstgrdimask_id, grid2_imask);
delete [] grid1_imask;
delete [] grid2_imask;
// write grid area
status = nc_put_var_double (ncid, nc_srcgrdarea_id, grid_src->get_cell_area());
status = nc_put_var_double (ncid, nc_dstgrdarea_id, grid_dst->get_cell_area());
// write grid frac [added later]
// write source and destination grids
status = nc_put_var_double (ncid, nc_srcarray_id, data_src_array);
status = nc_put_var_double (ncid, nc_dstarray_id, data_dst_array);
status = nc_put_var_double (ncid, nc_dstremap1_id, data_dst_remap);
status = nc_put_var_double (ncid, nc_dstremap2_id, data_dst_remap);
// write errors
for (int i = 0; i < grid_dst->get_num_points(); i++)
{
if (grid_dst->get_mymask()[i])
data_dst_error[i] = data_dst_remap[i] - data_dst_array[i];
else
data_dst_error[i] = 0.0;
}
status = nc_put_var_double (ncid, nc_dsterror1_id, data_dst_error);
status = nc_put_var_double (ncid, nc_dsterror2_id, data_dst_error);
// close file
status = nc_close(ncid);
finalize_all_cpl_grids();
finalize_remap_operators();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
357
]
]
] |
805745874a321193fd21a6aeca8acc45fc7c1901 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/uavobjects/positionactual.cpp | 5beca6b9719a5d7b81907e2723b9eb2af0f72bbe | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,555 | cpp | /**
******************************************************************************
*
* @file positionactual.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @see The GNU Public License (GPL) Version 3
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup UAVObjectsPlugin UAVObjects Plugin
* @{
*
* @note Object definition file: positionactual.xml.
* This is an automatically generated file.
* DO NOT modify manually.
*
* @brief The UAVUObjects GCS plugin
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "positionactual.h"
#include "uavobjectfield.h"
const QString PositionActual::NAME = QString("PositionActual");
/**
* Constructor
*/
PositionActual::PositionActual(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME)
{
// Create fields
QList<UAVObjectField*> fields;
QStringList NorthElemNames;
NorthElemNames.append("0");
fields.append( new UAVObjectField(QString("North"), QString("cm"), UAVObjectField::INT32, NorthElemNames, QStringList()) );
QStringList EastElemNames;
EastElemNames.append("0");
fields.append( new UAVObjectField(QString("East"), QString("cm"), UAVObjectField::INT32, EastElemNames, QStringList()) );
QStringList DownElemNames;
DownElemNames.append("0");
fields.append( new UAVObjectField(QString("Down"), QString("cm"), UAVObjectField::INT32, DownElemNames, QStringList()) );
// Initialize object
initializeFields(fields, (quint8*)&data, NUMBYTES);
// Set the default field values
setDefaultFieldValues();
}
/**
* Get the default metadata for this object
*/
UAVObject::Metadata PositionActual::getDefaultMetadata()
{
UAVObject::Metadata metadata;
metadata.flightAccess = ACCESS_READWRITE;
metadata.gcsAccess = ACCESS_READWRITE;
metadata.gcsTelemetryAcked = 0;
metadata.gcsTelemetryUpdateMode = UAVObject::UPDATEMODE_MANUAL;
metadata.gcsTelemetryUpdatePeriod = 0;
metadata.flightTelemetryAcked = 0;
metadata.flightTelemetryUpdateMode = UAVObject::UPDATEMODE_PERIODIC;
metadata.flightTelemetryUpdatePeriod = 1000;
metadata.loggingUpdateMode = UAVObject::UPDATEMODE_PERIODIC;
metadata.loggingUpdatePeriod = 1000;
return metadata;
}
/**
* Initialize object fields with the default values.
* If a default value is not specified the object fields
* will be initialized to zero.
*/
void PositionActual::setDefaultFieldValues()
{
}
/**
* Get the object data fields
*/
PositionActual::DataFields PositionActual::getData()
{
QMutexLocker locker(mutex);
return data;
}
/**
* Set the object data fields
*/
void PositionActual::setData(const DataFields& data)
{
QMutexLocker locker(mutex);
// Get metadata
Metadata mdata = getMetadata();
// Update object if the access mode permits
if ( mdata.gcsAccess == ACCESS_READWRITE )
{
this->data = data;
emit objectUpdatedAuto(this); // trigger object updated event
emit objectUpdated(this);
}
}
/**
* Create a clone of this object, a new instance ID must be specified.
* Do not use this function directly to create new instances, the
* UAVObjectManager should be used instead.
*/
UAVDataObject* PositionActual::clone(quint32 instID)
{
PositionActual* obj = new PositionActual();
obj->initialize(instID, this->getMetaObject());
return obj;
}
/**
* Static function to retrieve an instance of the object.
*/
PositionActual* PositionActual::GetInstance(UAVObjectManager* objMngr, quint32 instID)
{
return dynamic_cast<PositionActual*>(objMngr->getObject(PositionActual::OBJID, instID));
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
134
]
]
] |
fdce681ecf5f49d7c6a7668be3d1bf234ccbb2c7 | 88f4b257863d50044212e6036dd09a25ec65a1ff | /src/jingxian/protocol/proxy/AbstractCredentialPolicy.h | e4a88060003826cc2a1be9ff376803f1d1fb46ad | [] | no_license | mei-rune/jx-proxy | bb1ee92f6b76fb21fdf2f4d8a907823efd05e17b | d24117ab62b10410f2ad05769165130a9f591bfb | refs/heads/master | 2022-08-20T08:56:54.222821 | 2009-11-14T07:01:08 | 2009-11-14T07:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | h |
#ifndef _AbstractCredentialPolicy_H_
#define _AbstractCredentialPolicy_H_
#include "jingxian/config.h"
#if !defined (JINGXIAN_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* JINGXIAN_LACKS_PRAGMA_ONCE */
// Include files
# include "jingxian/protocol/proxy/ICredentialPolicy.h"
# include "jingxian/protocol/proxy/config/Credential.h"
_jingxian_begin
namespace proxy
{
class Proxy;
class AbstractCredentialPolicy : public ICredentialPolicy
{
public:
AbstractCredentialPolicy(Proxy* server, const config::Credential& credential)
: _server(server)
, _credential(credential)
, _complete(false)
{
}
AbstractCredentialPolicy(Proxy* server)
: _server(server)
, _complete(false)
{
}
virtual ~AbstractCredentialPolicy()
{
}
virtual int authenticationType() const
{
return _credential.AuthenticationType;
}
virtual bool isComplete()
{
return _complete;
}
protected:
Proxy* _server;
config::Credential _credential;
bool _complete;
};
}
_jingxian_end
#endif // _AbstractCredentialPolicy_H_
| [
"[email protected]@53e742d2-d0ea-11de-97bf-6350044336de"
] | [
[
[
1,
60
]
]
] |
05adc76258283b3931571c8dde791e4a007edb23 | 09ea547305ed8be9f8aa0dc6a9d74752d660d05d | /smf/smfservermodule/smfclient/smfclient.cpp | 62af0996c2c40d4ca360d8dc51823bd38c6eac23 | [] | no_license | SymbianSource/oss.FCL.sf.mw.socialmobilefw | 3c49e1d1ae2db8703e7c6b79a4c951216c9c5019 | 7020b195cf8d1aad30732868c2ed177e5459b8a8 | refs/heads/master | 2021-01-13T13:17:24.426946 | 2010-10-12T09:53:52 | 2010-10-12T09:53:52 | 72,676,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,835 | cpp | /**
* Copyright (c) 2010 Sasken Communication Technologies Ltd.
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the "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:
* Chandradeep Gandhi, Sasken Communication Technologies Ltd - Initial contribution
*
* Contributors:
* Manasij Roy, Nalina Hariharan
*
* Description:
* The SmfClient class provides a set of APIs to get list of service provider
* who implement the given interface. Calling GetServices of the instance of this
* class is mandatory before using any other interface.
*
*/
#include <qdebug.h>
#include <smfcredmgrclient.h>
#include "smfclient.h"
#include "smfclient_p.h"
SmfClient::SmfClient()
{
//Create instance of the private wrapper
m_private = new SmfClientPrivate(this);
m_providerList = NULL;
m_authAppProcess = NULL;
}
SmfClient::~SmfClient()
{
if(m_private)
{
delete m_private;
m_private = NULL;
}
if(m_authAppProcess)
delete m_authAppProcess;
}
QList<SmfProvider>* SmfClient::GetServices(const QString& serviceName)
{
qDebug()<<"Inside SmfClient::GetServices()";
//if serviceName is not empty
if(serviceName.size())
{
if(m_providerList)
{
delete m_providerList;
m_providerList = NULL;
}
//Getting the data synchronously
m_providerList = m_private->GetServices(serviceName);
qDebug()<<"After m_private->GetServices";
return m_providerList;
}
else
return NULL;
}
SMFProviderAuthorizationStatus SmfClient::checkAuthorization(const SmfProvider& provider)
{
SMFProviderAuthorizationStatus status = SMFProviderAuthStatusUnknown;
if(!provider.authenticationAppId().isEmpty())
{
SmfCredMgrClient csmClient;
QString authAppId = provider.authenticationAppId();
if(csmClient.CheckServiceAuthorization(authAppId))
status = SMFProviderAuthStatusAuthorised;
else
status = SMFProviderAuthStatusUnauthorised;
}
return status;
}
SmfError SmfClient::loginToService(SmfProvider* provider)
{
if(!m_authAppProcess)
m_authAppProcess = new QProcess();
connect(m_authAppProcess, SIGNAL(started()), this, SLOT(started()));
connect(m_authAppProcess, SIGNAL(stateChanged(QProcess::ProcessState)),
this, SLOT(stateChanged(QProcess::ProcessState)));
connect(m_authAppProcess, SIGNAL(error ( QProcess::ProcessError)),
this, SLOT(error ( QProcess::ProcessError)));
connect(m_authAppProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(finished(int, QProcess::ExitStatus)));
m_authAppProcess->start(provider->authenticationAppName());
m_authAppProcess->waitForFinished(-1);
return SmfNoError;
}
SmfError SmfClient::logoutOfService(SmfProvider* provider)
{
if(!m_authAppProcess)
m_authAppProcess = new QProcess();
connect(m_authAppProcess, SIGNAL(started()), this, SLOT(started()));
connect(m_authAppProcess, SIGNAL(stateChanged(QProcess::ProcessState)),
this, SLOT(stateChanged(QProcess::ProcessState)));
connect(m_authAppProcess, SIGNAL(error ( QProcess::ProcessError)),
this, SLOT(error ( QProcess::ProcessError)));
connect(m_authAppProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(finished(int, QProcess::ExitStatus)));
m_authAppProcess->start(provider->authenticationAppName());
m_authAppProcess->waitForFinished(-1);
return SmfNoError;
}
void SmfClient::started()
{
qDebug()<<"Inside SmfClient::started()";
}
void SmfClient::stateChanged(QProcess::ProcessState newState)
{
qDebug()<<"Inside SmfClient::stateChanged(), state = "<<newState;
}
void SmfClient::error(QProcess::ProcessError error)
{
qDebug()<<"Inside SmfClient::error(), error = "<<error;
}
void SmfClient::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug()<<"Inside SmfClient::finished()";
qDebug()<<"exitcode = "<<exitCode;
qDebug()<<"exitStatus = "<<exitStatus;
}
/**
* This method returns the error message for the mentioned argument error code
* @param aErrorCode The SmfError code for which the error string is required
* @returns a QString object containing the required error message
*/
QString SmfClient::errorString ( const SmfError &aErrorCode ) const
{
QString str;
str.clear();
switch(aErrorCode)
{
case SmfNoError: //0
str.append("No Error");
break;
case SmfInvalidInterface: //1
str.append("Smf Error : Invalid interface name");
break;
case SmfNoAuthorizedPlugin: //2
str.append("Smf Error : No Authorised plugins are available");
break;
case SmfClientAuthFailed: //3
str.append("Smf Error : Smf Client authorisation failed");
break;
case SmfPMPluginNotFound: //4
str.append("Smf Error : Plugin not found");
break;
case SmfPMPluginNotLoaded: //5
str.append("Smf Error : Plugin could not be loaded");
break;
case SmfPMPluginLoadError: //6
str.append("Smf Error : Plugin Load failed");
break;
case SmfPMPluginNotAuthorised: //7
str.append("Smf Error : Plugin not authorised");
break;
case SmfPMPluginRequestCreationFailed: //8
str.append("Smf Error : Plugin request creation failed");
break;
case SmfPMPluginUnknownPluginService: //9
str.append("Smf Error : Requested Plugin service not supported");
break;
case SmfPMPluginUnknownHttpService: //10
str.append("Smf Error : Unknown http service requested by plugin");
break;
case SmfPMPluginRequestSendingFailed: //11
str.append("Smf Error : Request created by plugin could not be send");
break;
case SmfPMPluginSOPCheckFailed: //12
str.append("Smf Error : Same Origin Policy violation by plugin");
break;
case SmfPMPluginSendRequestAgain: //13
str.append("Smf Error : Send request again");
break;
case SmfPluginErrorTooManyRequest: //14
str.append("Plugin Error: Too many requests");
break;
case SmfPluginErrorRequestQuotaExceeded: //15
str.append("Plugin Error: Request Quota Exceeded");
break;
case SmfPluginErrorInvalidRequest: //16
str.append("Plugin Error: Invalid Request");
break;
case SmfPluginErrorUserNotLoggedIn: //17
str.append("Plugin Error: User not logged in");
break;
case SmfPluginErrorAuthenticationExpired: //18
str.append("Plugin Error: Authentication Expired");
break;
case SmfPluginErrorPermissionDenied: //19
str.append("Plugin Error: Permission denied");
break;
case SmfPluginErrorInvalidApplication: //20
str.append("Plugin Error: Request Quota Exceeded");
break;
case SmfPluginErrorServiceUnavailable: //21
str.append("Plugin Error: Service unavailable");
break;
case SmfPluginErrorServiceTemporaryUnavailable: //22
str.append("Plugin Error: Service temporarily unavailable");
break;
case SmfPluginErrorFormatNotSupported: //23
str.append("Plugin Error: Format not supported");
break;
case SmfPluginErrorDataSizeExceeded : //24
str.append("Plugin Error: Data Size exceeded");
break;
case SmfPluginErrorInvalidArguments: //25
str.append("Plugin Error: Invalid request arguments");
break;
case SmfPluginErrorParsingFailed: //26
str.append("Plugin Error: Parsing failed");
break;
case SmfPluginErrorNetworkError: //27
str.append("Plugin Error: Network Error");
break;
case SmfPluginErrorCancelComplete: //28
str.append("Smf : Operation Cancelled");
break;
case SmfTMConnectionRefusedError: //29
str.append("Network Error: Connection Refused");
break;
case SmfTMRemoteHostClosedError: //30
str.append("Network Error: Remote Host Closed");
break;
case SmfTMHostNotFoundError: //31
str.append("Network Error: Host Not Found");
break;
case SmfTMTimeoutError: //32
str.append("Network Error: Time Out");
break;
case SmfTMOperationCanceledError: //33
str.append("Network Error: Operation cancelled");
break;
case SmfTMSslHandshakeFailedError: //34
str.append("Network Error: Handshake Failed");
break;
case SmfTMProxyConnectionRefusedError: //35
str.append("Network Error: Proxy Connection Refused");
break;
case SmfTMProxyConnectionClosedError: //36
str.append("Network Error: Proxy Connection Closed");
break;
case SmfTMProxyNotFoundError: //37
str.append("Network Error: Proxy Not Found");
break;
case SmfTMProxyTimeoutError: //38
str.append("Network Error: Proxy Timeout");
break;
case SmfTMProxyAuthenticationRequiredError: //39
str.append("Network Error: Proxy Authentication Required");
break;
case SmfTMContentAccessDenied: //40
str.append("Network Error: Content Access Denied");
break;
case SmfTMContentOperationNotPermittedError: //41
str.append("Network Error: Content Operation Not Permitted");
break;
case SmfTMContentNotFoundError: //42
str.append("Network Error: Content Not Found");
break;
case SmfTMAuthenticationRequiredError: //43
str.append("Network Error: Remote Server Required Authentication");
break;
case SmfTMContentReSendError: //44
str.append("Network Error: Content Resend Error");
break;
case SmfTMProtocolUnknownError: //45
str.append("Network Error: Protocol Unknown");
break;
case SmfTMProtocolInvalidOperationError: //46
str.append("Network Error: Protocol Invalid Operation");
break;
case SmfTMUnknownNetworkError: //47
str.append("Network Error: Unknown Network Error");
break;
case SmfTMUnknownProxyError: //48
str.append("Network Error: Unknown Proxy Error");
break;
case SmfTMUnknownContentError: //49
str.append("Network Error: Unknown Content Error");
break;
case SmfTMProtocolFailure: //50
str.append("Network Error: Protocol Failure");
break;
case SmfTMUnknownError: //51
str.append("Network Error: Unknown Error");
break;
case SmfTMIAPChanged: //52
str.append("Network Error: IAP Changed");
break;
case SmfTMCancelled: //53
str.append("Network Error: Cancelled");
break;
case SmfTMUnsupportedContentEncodingFormat: //54
str.append("Smf Error: Unsupported Content Encoding Format");
break;
case SmfTMInitNetworkNotAvailable : //55
str.append("Smf Error: Network Not Available");
break;
case SmfTMInitRoamingNetworkUsageNotEnabled: //56
str.append("Smf Error: Network Usage While Roaming is Disabled");
break;
case SmfTMGzipMemoryError: //57
str.append("Smf Error: Gzip Memory Error");
break;
case SmfTMGzipStreamError: //58
str.append("Smf Error: Gzip Stream Error");
break;
case SmfTMGzipDataError: //59
str.append("Smf Error: Gzip Data Error");
break;
case SmfMemoryAllocationFailure: //60
str.append("Smf Error: Memory failed");
break;
case SmfDbOpeningError: //61
str.append("Smf Database Error: Opening Error");
break;
case SmfDbQueryExecutonError: //61
str.append("Smf Database Error: Query Error");
break;
case SmfDbContactNotExist: //63
str.append("Smf Database Error: No contacts in Database");
break;
case SmfErrItemNotInRelation: //64
str.append("Smf Error: Item not in relation");
break;
case SmfErrInvalidRelation: //65
str.append("Smf Error: Invalid relation");
break;
case SmfInvalidGuid: //66
str.append("Smf Error: Invalid Guid");
break;
case SmfInvalidContactUrl: //67
str.append("Smf Error: Invalid ContactUrl");
break;
case SmfInvalidLocalId: //68
str.append("Smf Error: Invalid LocalId");
break;
case SmfContactExists: //69
str.append("Smf Error: Contact Already Exists");
break;
case SmfUnknownError: //70
default:
str.append("Smf Error: Unknown Error");
}
return str;
}
| [
"none@none"
] | [
[
[
1,
442
]
]
] |
5bb384c1715e8f0472c2e843fe95076831e85c3c | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swWxGuiTesting/VtkWxGuiTesting/CppGuiTest/swCRVtkCaptureTest.cpp | b16462ec4ae53d2e42f46e1ff913362dca843386 | [] | no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 36,842 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: swWxGuiTesting/VtkWxGuiTesting/CppTest/swCRVtkCaptureTest.cpp
// Author: Reinhold Füreder
// Created: 2004
// Copyright: (c) 2005 Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "swCRVtkCaptureTest.h"
#endif
#include "swCRVtkCaptureTest.h"
#include <stack>
#include "wx/xrc/xmlres.h"
#include "wx/frame.h"
#include "wx/treectrl.h"
#include "wx/statline.h"
#include "vtkXMLPolyDataReader.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkCamera.h"
#include "swWxGuiTestHelper.h"
#include "swWxGuiTestEventSimulationHelper.h"
#include "swWxGuiTestTimedDialogEnder.h"
#include "swWxGuiTestTempInteractive.h"
#include "swCRVtkCapture.h"
#include "swVtkWxGuiTestHelper.h"
#include "swWxVtkInteractorEventRecorder.h"
#include "swConfigManager.h"
#include "swConfig.h"
#include "swSpinCtrlDouble.h"
#include "wxVTKRenderWindowInteractor.h"
namespace swTst {
// Register test suite with special name in order to be identifiable as test
// which must be run after GUI part of wxWidgets library is initialised:
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CRVtkCaptureTest, "WxGuiTest" );
CRVtkCaptureTest::CRVtkCaptureTest ()
{
m_iren1 = NULL;
m_iren2 = NULL;
}
void CRVtkCaptureTest::setUp ()
{
char *vtkFilename = "../../../../TestData/vtk/hipStl.vtp";
wxXmlResource::Get()->InitAllHandlers();
wxXmlResource::Get()->Load ("../../../../Cxx/swWxGuiTesting/CppGuiTest/EvtSimHlpTest_wdr.xrc");
wxFrame *frame = new wxFrame (NULL, -1, "EvtSimHlpFrame");
wxMenuBar *menuBar = wxXmlResource::Get ()->LoadMenuBar (wxT("MenuBar"));
wxASSERT (menuBar != NULL);
frame->SetMenuBar (menuBar);
wxBoxSizer *topsizer = new wxBoxSizer (wxHORIZONTAL);
wxPanel *panel = wxXmlResource::Get ()->LoadPanel (frame, "EvtSimHlpTestPanel");
wxASSERT (panel != NULL);
// Include the unknown double spin control:
sw::SpinCtrlDouble *spinCtrl = new sw::SpinCtrlDouble (frame,
-1,
"",
wxDefaultPosition,
wxSize (80, 21),
wxNO_BORDER,
0.00000,
9999.99999,
0.5,
0.1);
spinCtrl->SetDigits (5, false);
wxXmlResource::Get ()->AttachUnknownControl ("SpinCtrlDbl", spinCtrl, frame);
wxTreeCtrl *treeCtrl = XRCCTRL (*frame, "TreeCtrl", wxTreeCtrl);
wxTreeItemId root = treeCtrl->AddRoot ("Root");
wxTreeItemId item = treeCtrl->AppendItem (root, "item");
wxTreeItemId item2 = treeCtrl->AppendItem (root, "item2");
// VTK stuff:
vtkXMLPolyDataReader *reader = vtkXMLPolyDataReader::New ();
reader->SetFileName (vtkFilename);
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New ();
mapper->SetInput (reader->GetOutput ());
reader->Delete ();
vtkActor *actor = vtkActor::New ();
actor->SetMapper (mapper);
mapper->Delete ();
m_iren1 = new wxVTKRenderWindowInteractor (frame, -1);
m_iren1->UseCaptureMouseOn ();
VtkWxGuiTestHelper::GetInstance ()->RegisterForRecording (m_iren1, "Multi",
"iren1");
m_iren2 = new wxVTKRenderWindowInteractor (frame, -1);
m_iren2->UseCaptureMouseOn ();
VtkWxGuiTestHelper::GetInstance ()->RegisterForRecording (m_iren2, "Multi",
"iren2");
vtkRenderer *renderer1 = vtkRenderer::New ();
vtkRenderer *renderer2 = vtkRenderer::New ();
renderer1->AddActor (actor);
renderer2->AddActor (actor);
actor->Delete ();
m_iren1->GetRenderWindow ()->AddRenderer (renderer1);
m_iren2->GetRenderWindow ()->AddRenderer (renderer2);
renderer1->Delete ();
renderer2->Delete ();
// End VTK stuff
topsizer->Add (panel, 1, wxGROW | wxADJUST_MINSIZE, 0);
topsizer->Add (m_iren1, 1, wxGROW | wxADJUST_MINSIZE, 0);
topsizer->Add (new wxStaticLine (frame, -1, wxDefaultPosition, wxDefaultSize,
wxLI_VERTICAL), 0, wxALIGN_CENTRE | wxALL | wxGROW);
topsizer->Add (m_iren2, 1, wxGROW | wxADJUST_MINSIZE, 0);
topsizer->SetSizeHints (frame);
frame->SetSizer (topsizer);
frame->Show ();
wxTheApp->SetTopWindow (frame);
WxGuiTestHelper::Show (frame, true, false);
WxGuiTestHelper::FlushEventQueue ();
}
void CRVtkCaptureTest::tearDown ()
{
wxWindow *topWdw = wxTheApp->GetTopWindow ();
wxTheApp->SetTopWindow (NULL);
//topWdw->Destroy ();
//WxGuiTestHelper::FlushEventQueue ();
topWdw->Hide ();
swTst::VtkWxGuiTestHelper::Destroy ();
sw::ConfigManager::Destroy ();
m_iren1->Delete ();
m_iren2->Delete ();
}
void CRVtkCaptureTest::testVtkCapture ()
{
wxString xrcDir = "../../../../TestData/xrc/CaptureTest/";
sw::Config *configInit = new sw::Config ();
configInit->SetResourceDir (xrcDir);
sw::ConfigManager::SetInstance (configInit);
sw::ConfigInterface *config = sw::ConfigManager::GetInstance ();
wxASSERT (config != NULL);
wxString resDir;
bool ret = config->GetResourceDir (resDir);
// Testing event capturing Cpp code emitting:
#define TESTCREMITTING
#ifdef TESTCREMITTING
{
wxApp *app = wxTheApp;
wxASSERT (app != NULL);
WxGuiTestApp *guiTestApp = dynamic_cast< WxGuiTestApp * >(app);
wxASSERT (guiTestApp != NULL);
guiTestApp->SetEventFilter (CREventCaptureManager::GetInstance ());
CRCppEmitter::GetInstance ()->SetTestCaseFileContext (__FILE__);
CREventCaptureManager::GetInstance ()->On ();
try {
// Put here the emitted code:
swTst::WxVtkInteractorEventRecorder *multiRecorder = swTst::
VtkWxGuiTestHelper::GetInstance ()->GetWxVtkRecorder ("Multi");
std::stack< wxWindow *, std::list< wxWindow * > > wdwStack;
wxWindow *wdw = NULL;
wxVTKRenderWindowInteractor * iren1WxVtkRwi = multiRecorder->GetInteractor
("iren1");
wxWindow *iren1Wdw = iren1WxVtkRwi;
wdw = iren1Wdw;
wdwStack.push (wdw);
while (wdw->GetParent () != NULL) {
wdw = wdw->GetParent ();
wdwStack.push (wdw);
}
wdw->Move (30, 25);
wdwStack.top ()->SetSize (1036, 631);
wdwStack.pop ();
wdwStack.top ()->SetSize (342, 585);
wdwStack.pop ();
wxASSERT (wdwStack.empty ());
vtkRendererCollection *renderers = iren1WxVtkRwi->GetRenderWindow ()->
GetRenderers ();
wxASSERT_MSG (renderers->GetNumberOfItems () == 1, "Currently only one "
"renderer per render window interactor is supported");
vtkCamera *camera = renderers->GetFirstRenderer ()->GetActiveCamera ();
camera->SetParallelScale (87.6875);
camera->SetViewAngle (30);
camera->SetClippingRange (279.701, 414.007);
camera->SetFocalPoint (-371.244, 252.214, 0);
camera->SetPosition (-453.827, 190.15, 322.665);
camera->SetViewUp (0.949353, 0.155696, 0.272924);
wxVTKRenderWindowInteractor * iren2WxVtkRwi = multiRecorder->GetInteractor
("iren2");
wxWindow *iren2Wdw = iren2WxVtkRwi;
wdw = iren2Wdw;
wdwStack.push (wdw);
while (wdw->GetParent () != NULL) {
wdw = wdw->GetParent ();
wdwStack.push (wdw);
}
wdw->Move (30, 25);
wdwStack.top ()->SetSize (1036, 631);
wdwStack.pop ();
wdwStack.top ()->SetSize (342, 585);
wdwStack.pop ();
wxASSERT (wdwStack.empty ());
vtkRendererCollection *renderers1 = iren2WxVtkRwi->GetRenderWindow ()->
GetRenderers ();
wxASSERT_MSG (renderers1->GetNumberOfItems () == 1, "Currently only one "
"renderer per render window interactor is supported");
vtkCamera *camera1 = renderers1->GetFirstRenderer ()->GetActiveCamera ();
camera1->SetParallelScale (87.6875);
camera1->SetViewAngle (30);
camera1->SetClippingRange (260.477, 438.206);
camera1->SetFocalPoint (-371.244, 252.214, 0);
camera1->SetPosition (-42.745, 286.958, 75.2683);
camera1->SetViewUp (-0.113197, 0.992931, 0.0356974);
multiRecorder->ReadFromInputStringOn ();
multiRecorder->SetInputString (
"# StreamVersion 2\n"
"EnterEvent 11 42 0 0 0 0 i iren2\n"
"MouseMoveEvent 11 42 0 0 0 0 i iren2\n"
"MouseMoveEvent 22 105 0 0 0 0 i iren2\n"
"MouseMoveEvent 28 135 0 0 0 0 i iren2\n"
"MouseMoveEvent 34 162 0 0 0 0 i iren2\n"
"MouseMoveEvent 49 186 0 0 0 0 i iren2\n"
"MouseMoveEvent 55 213 0 0 0 0 i iren2\n"
"MouseMoveEvent 61 231 0 0 0 0 i iren2\n"
"MouseMoveEvent 76 252 0 0 0 0 i iren2\n"
"MouseMoveEvent 80 267 0 0 0 0 i iren2\n"
"MouseMoveEvent 83 273 0 0 0 0 i iren2\n"
"MouseMoveEvent 83 278 0 0 0 0 i iren2\n"
"MouseMoveEvent 83 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 83 282 0 0 0 0 i iren2\n"
"MouseMoveEvent 81 284 0 0 0 0 i iren2\n"
"MouseMoveEvent 79 285 0 0 0 0 i iren2\n"
"MouseMoveEvent 79 287 0 0 0 0 i iren2\n"
"MouseMoveEvent 78 288 0 0 0 0 i iren2\n"
"MouseMoveEvent 79 288 0 0 0 0 i iren2\n"
"MouseMoveEvent 80 290 0 0 0 0 i iren2\n"
"MouseMoveEvent 83 291 0 0 0 0 i iren2\n"
"MouseMoveEvent 86 294 0 0 0 0 i iren2\n"
"MouseMoveEvent 89 297 0 0 0 0 i iren2\n"
"MouseMoveEvent 92 299 0 0 0 0 i iren2\n"
"MouseMoveEvent 95 300 0 0 0 0 i iren2\n"
"MouseMoveEvent 98 303 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 306 0 0 0 0 i iren2\n"
"MouseMoveEvent 107 308 0 0 0 0 i iren2\n"
"MouseMoveEvent 110 311 0 0 0 0 i iren2\n"
"MouseMoveEvent 115 312 0 0 0 0 i iren2\n"
"MouseMoveEvent 118 315 0 0 0 0 i iren2\n"
"MouseMoveEvent 119 317 0 0 0 0 i iren2\n"
"MouseMoveEvent 122 317 0 0 0 0 i iren2\n"
"MouseMoveEvent 122 318 0 0 0 0 i iren2\n"
"MouseMoveEvent 124 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 123 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 123 321 0 0 0 0 i iren2\n"
"MouseMoveEvent 121 321 0 0 0 0 i iren2\n"
"MouseMoveEvent 120 321 0 0 0 0 i iren2\n"
"MouseMoveEvent 118 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 117 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 115 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 114 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 112 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 111 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 111 324 0 0 0 0 i iren2\n"
"MouseMoveEvent 109 324 0 0 0 0 i iren2\n"
"MouseMoveEvent 108 324 0 0 0 0 i iren2\n"
"MouseMoveEvent 108 326 0 0 0 0 i iren2\n"
"MouseMoveEvent 106 326 0 0 0 0 i iren2\n"
"LeftButtonPressEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"TimerEvent 106 326 0 0 0 0 i iren2\n"
"MouseMoveEvent 107 326 0 0 0 0 i iren2\n"
"TimerEvent 107 326 0 0 0 0 i iren2\n"
"MouseMoveEvent 109 326 0 0 0 0 i iren2\n"
"TimerEvent 109 326 0 0 0 0 i iren2\n"
"MouseMoveEvent 110 326 0 0 0 0 i iren2\n"
"TimerEvent 110 326 0 0 0 0 i iren2\n"
"MouseMoveEvent 110 325 0 0 0 0 i iren2\n"
"TimerEvent 110 325 0 0 0 0 i iren2\n"
"MouseMoveEvent 112 325 0 0 0 0 i iren2\n"
"TimerEvent 112 325 0 0 0 0 i iren2\n"
"MouseMoveEvent 113 325 0 0 0 0 i iren2\n"
"TimerEvent 113 325 0 0 0 0 i iren2\n"
"TimerEvent 113 325 0 0 0 0 i iren2\n"
"MouseMoveEvent 115 325 0 0 0 0 i iren2\n"
"TimerEvent 115 325 0 0 0 0 i iren2\n"
"MouseMoveEvent 116 325 0 0 0 0 i iren2\n"
"TimerEvent 116 325 0 0 0 0 i iren2\n"
"MouseMoveEvent 116 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 118 323 0 0 0 0 i iren2\n"
"TimerEvent 118 323 0 0 0 0 i iren2\n"
"TimerEvent 118 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 119 323 0 0 0 0 i iren2\n"
"TimerEvent 119 323 0 0 0 0 i iren2\n"
"TimerEvent 119 323 0 0 0 0 i iren2\n"
"TimerEvent 119 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 121 323 0 0 0 0 i iren2\n"
"TimerEvent 121 323 0 0 0 0 i iren2\n"
"TimerEvent 121 323 0 0 0 0 i iren2\n"
"MouseMoveEvent 121 322 0 0 0 0 i iren2\n"
"TimerEvent 121 322 0 0 0 0 i iren2\n"
"MouseMoveEvent 122 322 0 0 0 0 i iren2\n"
"MouseMoveEvent 124 322 0 0 0 0 i iren2\n"
"TimerEvent 124 322 0 0 0 0 i iren2\n"
"MouseMoveEvent 125 322 0 0 0 0 i iren2\n"
"MouseMoveEvent 125 320 0 0 0 0 i iren2\n"
"TimerEvent 125 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 127 320 0 0 0 0 i iren2\n"
"TimerEvent 127 320 0 0 0 0 i iren2\n"
"TimerEvent 127 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"TimerEvent 128 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 130 320 0 0 0 0 i iren2\n"
"TimerEvent 130 320 0 0 0 0 i iren2\n"
"TimerEvent 130 320 0 0 0 0 i iren2\n"
"TimerEvent 130 320 0 0 0 0 i iren2\n"
"TimerEvent 130 320 0 0 0 0 i iren2\n"
"TimerEvent 130 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 131 320 0 0 0 0 i iren2\n"
"TimerEvent 131 320 0 0 0 0 i iren2\n"
"MouseMoveEvent 131 319 0 0 0 0 i iren2\n"
"TimerEvent 131 319 0 0 0 0 i iren2\n"
"MouseMoveEvent 133 319 0 0 0 0 i iren2\n"
"TimerEvent 133 319 0 0 0 0 i iren2\n"
"MouseMoveEvent 133 317 0 0 0 0 i iren2\n"
"MouseMoveEvent 134 317 0 0 0 0 i iren2\n"
"TimerEvent 134 317 0 0 0 0 i iren2\n"
"TimerEvent 134 317 0 0 0 0 i iren2\n"
"MouseMoveEvent 134 316 0 0 0 0 i iren2\n"
"MouseMoveEvent 136 316 0 0 0 0 i iren2\n"
"TimerEvent 136 316 0 0 0 0 i iren2\n"
"MouseMoveEvent 136 314 0 0 0 0 i iren2\n"
"TimerEvent 136 314 0 0 0 0 i iren2\n"
"TimerEvent 136 314 0 0 0 0 i iren2\n"
"MouseMoveEvent 136 313 0 0 0 0 i iren2\n"
"TimerEvent 136 313 0 0 0 0 i iren2\n"
"TimerEvent 136 313 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 313 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 311 0 0 0 0 i iren2\n"
"TimerEvent 137 311 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 310 0 0 0 0 i iren2\n"
"TimerEvent 137 310 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 308 0 0 0 0 i iren2\n"
"TimerEvent 137 308 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 307 0 0 0 0 i iren2\n"
"TimerEvent 137 307 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 305 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 304 0 0 0 0 i iren2\n"
"TimerEvent 137 304 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 302 0 0 0 0 i iren2\n"
"TimerEvent 137 302 0 0 0 0 i iren2\n"
"MouseMoveEvent 137 301 0 0 0 0 i iren2\n"
"TimerEvent 137 301 0 0 0 0 i iren2\n"
"MouseMoveEvent 139 301 0 0 0 0 i iren2\n"
"MouseMoveEvent 139 299 0 0 0 0 i iren2\n"
"TimerEvent 139 299 0 0 0 0 i iren2\n"
"MouseMoveEvent 139 298 0 0 0 0 i iren2\n"
"MouseMoveEvent 139 296 0 0 0 0 i iren2\n"
"TimerEvent 139 296 0 0 0 0 i iren2\n"
"MouseMoveEvent 140 296 0 0 0 0 i iren2\n"
"MouseMoveEvent 140 295 0 0 0 0 i iren2\n"
"TimerEvent 140 295 0 0 0 0 i iren2\n"
"MouseMoveEvent 140 293 0 0 0 0 i iren2\n"
"TimerEvent 140 293 0 0 0 0 i iren2\n"
"MouseMoveEvent 142 293 0 0 0 0 i iren2\n"
"MouseMoveEvent 142 292 0 0 0 0 i iren2\n"
"TimerEvent 142 292 0 0 0 0 i iren2\n"
"MouseMoveEvent 142 290 0 0 0 0 i iren2\n"
"MouseMoveEvent 142 289 0 0 0 0 i iren2\n"
"TimerEvent 142 289 0 0 0 0 i iren2\n"
"MouseMoveEvent 143 289 0 0 0 0 i iren2\n"
"MouseMoveEvent 143 287 0 0 0 0 i iren2\n"
"TimerEvent 143 287 0 0 0 0 i iren2\n"
"MouseMoveEvent 145 286 0 0 0 0 i iren2\n"
"MouseMoveEvent 145 284 0 0 0 0 i iren2\n"
"TimerEvent 145 284 0 0 0 0 i iren2\n"
"MouseMoveEvent 145 283 0 0 0 0 i iren2\n"
"TimerEvent 145 283 0 0 0 0 i iren2\n"
"TimerEvent 145 283 0 0 0 0 i iren2\n"
"MouseMoveEvent 146 283 0 0 0 0 i iren2\n"
"MouseMoveEvent 146 281 0 0 0 0 i iren2\n"
"TimerEvent 146 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 146 280 0 0 0 0 i iren2\n"
"TimerEvent 146 280 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 280 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 278 0 0 0 0 i iren2\n"
"TimerEvent 148 278 0 0 0 0 i iren2\n"
"TimerEvent 148 278 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 277 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 277 0 0 0 0 i iren2\n"
"TimerEvent 149 277 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 275 0 0 0 0 i iren2\n"
"TimerEvent 149 275 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 274 0 0 0 0 i iren2\n"
"TimerEvent 149 274 0 0 0 0 i iren2\n"
"MouseMoveEvent 151 274 0 0 0 0 i iren2\n"
"TimerEvent 151 274 0 0 0 0 i iren2\n"
"MouseMoveEvent 151 272 0 0 0 0 i iren2\n"
"TimerEvent 151 272 0 0 0 0 i iren2\n"
"TimerEvent 151 272 0 0 0 0 i iren2\n"
"MouseMoveEvent 152 272 0 0 0 0 i iren2\n"
"TimerEvent 152 272 0 0 0 0 i iren2\n"
"MouseMoveEvent 152 271 0 0 0 0 i iren2\n"
"TimerEvent 152 271 0 0 0 0 i iren2\n"
"TimerEvent 152 271 0 0 0 0 i iren2\n"
"MouseMoveEvent 152 269 0 0 0 0 i iren2\n"
"TimerEvent 152 269 0 0 0 0 i iren2\n"
"MouseMoveEvent 154 269 0 0 0 0 i iren2\n"
"TimerEvent 154 269 0 0 0 0 i iren2\n"
"TimerEvent 154 269 0 0 0 0 i iren2\n"
"MouseMoveEvent 154 268 0 0 0 0 i iren2\n"
"TimerEvent 154 268 0 0 0 0 i iren2\n"
"TimerEvent 154 268 0 0 0 0 i iren2\n"
"TimerEvent 154 268 0 0 0 0 i iren2\n"
"TimerEvent 154 268 0 0 0 0 i iren2\n"
"MouseMoveEvent 154 266 0 0 0 0 i iren2\n"
"MouseMoveEvent 155 266 0 0 0 0 i iren2\n"
"TimerEvent 155 266 0 0 0 0 i iren2\n"
"TimerEvent 155 266 0 0 0 0 i iren2\n"
"MouseMoveEvent 155 265 0 0 0 0 i iren2\n"
"TimerEvent 155 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"TimerEvent 157 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 158 265 0 0 0 0 i iren2\n"
"TimerEvent 158 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 160 265 0 0 0 0 i iren2\n"
"TimerEvent 160 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 161 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 163 265 0 0 0 0 i iren2\n"
"TimerEvent 163 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 164 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 166 265 0 0 0 0 i iren2\n"
"TimerEvent 166 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 169 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 170 265 0 0 0 0 i iren2\n"
"TimerEvent 170 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 172 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 173 265 0 0 0 0 i iren2\n"
"TimerEvent 173 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 175 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 176 265 0 0 0 0 i iren2\n"
"TimerEvent 176 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 179 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 181 265 0 0 0 0 i iren2\n"
"TimerEvent 181 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 182 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 184 265 0 0 0 0 i iren2\n"
"TimerEvent 184 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 185 265 0 0 0 0 i iren2\n"
"TimerEvent 185 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 187 265 0 0 0 0 i iren2\n"
"TimerEvent 187 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 188 265 0 0 0 0 i iren2\n"
"TimerEvent 188 265 0 0 0 0 i iren2\n"
"TimerEvent 188 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 190 265 0 0 0 0 i iren2\n"
"TimerEvent 190 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"TimerEvent 191 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 191 263 0 0 0 0 i iren2\n"
"MouseMoveEvent 190 263 0 0 0 0 i iren2\n"
"TimerEvent 190 263 0 0 0 0 i iren2\n"
"MouseMoveEvent 189 263 0 0 0 0 i iren2\n"
"TimerEvent 189 263 0 0 0 0 i iren2\n"
"MouseMoveEvent 187 262 0 0 0 0 i iren2\n"
"TimerEvent 187 262 0 0 0 0 i iren2\n"
"MouseMoveEvent 186 262 0 0 0 0 i iren2\n"
"TimerEvent 186 262 0 0 0 0 i iren2\n"
"MouseMoveEvent 184 262 0 0 0 0 i iren2\n"
"TimerEvent 184 262 0 0 0 0 i iren2\n"
"MouseMoveEvent 183 260 0 0 0 0 i iren2\n"
"TimerEvent 183 260 0 0 0 0 i iren2\n"
"TimerEvent 183 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 181 260 0 0 0 0 i iren2\n"
"TimerEvent 181 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 180 260 0 0 0 0 i iren2\n"
"TimerEvent 180 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 178 260 0 0 0 0 i iren2\n"
"TimerEvent 178 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 177 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 175 260 0 0 0 0 i iren2\n"
"TimerEvent 175 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 174 260 0 0 0 0 i iren2\n"
"TimerEvent 174 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 172 260 0 0 0 0 i iren2\n"
"TimerEvent 172 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 171 260 0 0 0 0 i iren2\n"
"TimerEvent 171 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 169 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 168 260 0 0 0 0 i iren2\n"
"TimerEvent 168 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 166 260 0 0 0 0 i iren2\n"
"TimerEvent 166 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 165 259 0 0 0 0 i iren2\n"
"TimerEvent 165 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 163 259 0 0 0 0 i iren2\n"
"TimerEvent 163 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 162 259 0 0 0 0 i iren2\n"
"TimerEvent 162 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 160 259 0 0 0 0 i iren2\n"
"TimerEvent 160 259 0 0 0 0 i iren2\n"
"TimerEvent 160 259 0 0 0 0 i iren2\n"
"TimerEvent 160 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 159 259 0 0 0 0 i iren2\n"
"TimerEvent 159 259 0 0 0 0 i iren2\n"
"TimerEvent 159 259 0 0 0 0 i iren2\n"
"TimerEvent 159 259 0 0 0 0 i iren2\n"
"TimerEvent 159 259 0 0 0 0 i iren2\n"
"TimerEvent 159 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"TimerEvent 157 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 156 259 0 0 0 0 i iren2\n"
"TimerEvent 156 259 0 0 0 0 i iren2\n"
"TimerEvent 156 259 0 0 0 0 i iren2\n"
"TimerEvent 156 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 154 259 0 0 0 0 i iren2\n"
"TimerEvent 154 259 0 0 0 0 i iren2\n"
"TimerEvent 154 259 0 0 0 0 i iren2\n"
"TimerEvent 154 259 0 0 0 0 i iren2\n"
"MouseMoveEvent 154 260 0 0 0 0 i iren2\n"
"TimerEvent 154 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 153 260 0 0 0 0 i iren2\n"
"TimerEvent 153 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 153 261 0 0 0 0 i iren2\n"
"MouseMoveEvent 151 261 0 0 0 0 i iren2\n"
"TimerEvent 151 261 0 0 0 0 i iren2\n"
"MouseMoveEvent 151 263 0 0 0 0 i iren2\n"
"TimerEvent 151 263 0 0 0 0 i iren2\n"
"MouseMoveEvent 150 263 0 0 0 0 i iren2\n"
"TimerEvent 150 263 0 0 0 0 i iren2\n"
"TimerEvent 150 263 0 0 0 0 i iren2\n"
"TimerEvent 150 263 0 0 0 0 i iren2\n"
"MouseMoveEvent 150 264 0 0 0 0 i iren2\n"
"TimerEvent 150 264 0 0 0 0 i iren2\n"
"TimerEvent 150 264 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 264 0 0 0 0 i iren2\n"
"TimerEvent 148 264 0 0 0 0 i iren2\n"
"TimerEvent 148 264 0 0 0 0 i iren2\n"
"TimerEvent 148 264 0 0 0 0 i iren2\n"
"TimerEvent 148 264 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 266 0 0 0 0 i iren2\n"
"TimerEvent 148 266 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 266 0 0 0 0 i iren2\n"
"TimerEvent 147 266 0 0 0 0 i iren2\n"
"TimerEvent 147 266 0 0 0 0 i iren2\n"
"TimerEvent 147 266 0 0 0 0 i iren2\n"
"TimerEvent 147 266 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 267 0 0 0 0 i iren2\n"
"TimerEvent 147 267 0 0 0 0 i iren2\n"
"TimerEvent 147 267 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 269 0 0 0 0 i iren2\n"
"TimerEvent 147 269 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 270 0 0 0 0 i iren2\n"
"TimerEvent 147 270 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 272 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 273 0 0 0 0 i iren2\n"
"TimerEvent 147 273 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 275 0 0 0 0 i iren2\n"
"TimerEvent 147 275 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 276 0 0 0 0 i iren2\n"
"TimerEvent 148 276 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 278 0 0 0 0 i iren2\n"
"TimerEvent 148 278 0 0 0 0 i iren2\n"
"TimerEvent 148 278 0 0 0 0 i iren2\n"
"TimerEvent 148 278 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 279 0 0 0 0 i iren2\n"
"TimerEvent 148 279 0 0 0 0 i iren2\n"
"TimerEvent 148 279 0 0 0 0 i iren2\n"
"TimerEvent 148 279 0 0 0 0 i iren2\n"
"TimerEvent 148 279 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"TimerEvent 148 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"LeftButtonReleaseEvent 149 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 281 0 0 0 0 i iren2\n"
"TimerEvent 149 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 149 282 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 282 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 281 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 278 0 0 0 0 i iren2\n"
"MouseMoveEvent 148 277 0 0 0 0 i iren2\n"
"MouseMoveEvent 147 272 0 0 0 0 i iren2\n"
"MouseMoveEvent 145 269 0 0 0 0 i iren2\n"
"MouseMoveEvent 142 265 0 0 0 0 i iren2\n"
"MouseMoveEvent 141 260 0 0 0 0 i iren2\n"
"MouseMoveEvent 138 256 0 0 0 0 i iren2\n"
"MouseMoveEvent 136 251 0 0 0 0 i iren2\n"
"MouseMoveEvent 133 245 0 0 0 0 i iren2\n"
"MouseMoveEvent 132 239 0 0 0 0 i iren2\n"
"MouseMoveEvent 129 224 0 0 0 0 i iren2\n"
"MouseMoveEvent 124 209 0 0 0 0 i iren2\n"
"MouseMoveEvent 121 203 0 0 0 0 i iren2\n"
"MouseMoveEvent 118 185 0 0 0 0 i iren2\n"
"MouseMoveEvent 115 179 0 0 0 0 i iren2\n"
"MouseMoveEvent 112 173 0 0 0 0 i iren2\n"
"MouseMoveEvent 109 155 0 0 0 0 i iren2\n"
"MouseMoveEvent 106 149 0 0 0 0 i iren2\n"
"MouseMoveEvent 106 131 0 0 0 0 i iren2\n"
"MouseMoveEvent 105 125 0 0 0 0 i iren2\n"
"MouseMoveEvent 105 119 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 98 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 83 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 68 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 53 0 0 0 0 i iren2\n"
"MouseMoveEvent 103 38 0 0 0 0 i iren2\n"
"MouseMoveEvent 104 32 0 0 0 0 i iren2\n"
"MouseMoveEvent 104 26 0 0 0 0 i iren2\n"
"MouseMoveEvent 104 20 0 0 0 0 i iren2\n"
"LeaveEvent 106 16 0 0 0 0 i iren2\n"
);
multiRecorder->Play ();
// End
} catch (...) {
guiTestApp->SetEventFilter (NULL);
throw;
}
guiTestApp->SetEventFilter (NULL);
CRCppEmitter::Destroy ();
}
#endif
// Do bootstrap capturing:
/*
{
wxApp *app = wxTheApp;
wxASSERT (app != NULL);
swTst::WxGuiTestApp *guiTestApp = dynamic_cast< swTst::WxGuiTestApp * >(app);
wxASSERT (guiTestApp != NULL);
guiTestApp->SetEventFilter (swTst::CREventCaptureManager::GetInstance ());
swTst::CRCapture *capture = new swTst::CRCapture ();
try {
capture->Capture (__FILE__, __LINE__);
} catch (...) {
guiTestApp->SetEventFilter (NULL);
throw;
}
guiTestApp->SetEventFilter (NULL);
delete capture;
swTst::CRCppEmitter::Destroy ();
}
*/
// Or use easier macro:
VTK_CAPTURE
swTst::WxGuiTestTempInteractive interactive;
interactive.ShowCurrentGui ();
// Using the {...} notation we can have several VTK_CAPTUREs in one method:
//VTK_CAPTURE
sw::ConfigManager::SetInstance (NULL);
}
} // End namespace swTst
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
] | [
[
[
1,
795
]
]
] |
855905b5d641a8298ce1e90918c4259d3c3580cd | d6dbf57842d0b5121b3ece85f7b8ffc195519d51 | /OgreMax/OgreMaxScene.hpp | 85027003a88f36e53ab5c8d269af4ddcbb070f7a | [] | no_license | tunnuz/cel-language | 3f0baddaa04a51afa10cf2fed4a47f4c93bb28a8 | afaa3f201d56c33099e7787b1613daeab21cf027 | refs/heads/master | 2020-05-18T12:55:56.785687 | 2010-07-06T12:51:15 | 2010-07-06T12:51:15 | 32,117,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,942 | hpp | /*
* OgreMaxViewer - An Ogre 3D-based viewer for .scene and .mesh files
* Copyright 2008 Derek Nedelman
*
* This code is available under the OgreMax Free License:
* -You may use this code for any purpose, commercial or non-commercial.
* -If distributing derived works (that use this source code) in binary or source code form,
* you must give the following credit in your work's end-user documentation:
* "Portions of this work provided by OgreMax (www.ogremax.com)"
*
* Derek Nedelman assumes no responsibility for any harm caused by using this code.
*
* OgreMaxViewer was written by Derek Nedelman and released at www.ogremax.com
*/
#ifndef OgreMax_OgreMaxScene_INCLUDED
#define OgreMax_OgreMaxScene_INCLUDED
//Includes---------------------------------------------------------------------
#include <OgreRenderTargetListener.h>
#include <OgreInstancedGeometry.h>
#include <OgreStaticGeometry.h>
#include "OgreMaxPlatform.hpp"
#include "ProgressCalculator.hpp"
#include "Version.hpp"
#include "OgreMaxModel.hpp"
#include "OgreMaxRenderWindowIterator.hpp"
//Classes----------------------------------------------------------------------
namespace OgreMax
{
class OgreMaxSceneCallback;
/**
* Manages the loading of a OgreMax .scene file.
* This class is very lightwight in the sense that doesn't maintain a lot of
* internal state. Instead, wherever possible, most of the data is put into the
* Ogre scene manager. As such, when deleting an OgreMaxScene, keep in mind that
* the scene manager and all of resources that were loaded as a result of loading
* the scene are NOT destroyed. You will need to destroy those manually.
*/
class _OgreMaxExport OgreMaxScene : public Ogre::RenderTargetListener
{
public:
OgreMaxScene();
virtual ~OgreMaxScene();
/**
* Options that may be passed to Load()
*/
typedef int LoadOptions;
enum
{
NO_OPTIONS = 0,
/** Skips the environment settings in the file. Skipping the environment also skips shadows */
SKIP_ENVIRONMENT = 0x1,
/** Skips the shadow settings in the file */
SKIP_SHADOWS = 0x2,
/** Skips the sky settings in the file */
SKIP_SKY = 0x4,
/** Skips the nodes in the file */
SKIP_NODES = 0x8,
/** Skips the externals in the file */
SKIP_EXTERNALS = 0x10,
/** Skips the terrain in the file */
SKIP_TERRAIN = 0x20,
/** Skips the octree in the file */
SKIP_OCTREE = 0x40,
/** Skips scene level (non-node) lights in the file */
SKIP_SCENE_LIGHT = 0x80,
/** Skips scene level (non-node) cameras in the file */
SKIP_SCENE_CAMERA = 0x100,
/** Skips scene level query flags in the file */
SKIP_QUERY_FLAG_ALIASES = 0x200,
/** Skips scene level visibility flags in the file */
SKIP_VISIBILITY_FLAG_ALIASES = 0x400,
/** Skips scene level resource locations in the file */
SKIP_RESOURCE_LOCATIONS = 0x800,
/** Indicates animation states should not be created for node animation tracks */
NO_ANIMATION_STATES = 0x1000,
/**
* Indicates scene 'externals' should not be stored. They will, however, still
* be loaded and the CreatedExternal() scene callback will be called
*/
NO_EXTERNALS = 0x2000,
/**
* By default, the OgreMaxScene::Load() checks to see if the file that was passed
* in exists in the file system (outside of the configured resource locations).
* This flag disables that logic
*/
NO_FILE_SYSTEM_CHECK = 0x4000,
/**
* Indicates that a light should be created if the loaded scene doesn't contain a light
* Any lights created as a result of setting the default lighting are not passed to
* the scene callback
*/
SET_DEFAULT_LIGHTING = 0x8000,
/**
* Indicates that the 'fileNameOrContent' parameter in Load() should be treated as the
* scene XML. In other words, no file is loaded from Ogre's file system.
*/
FILE_NAME_CONTAINS_CONTENT = 0x10000
};
/**
* Loads a scene from the specified file.
* @param fileNameOrContent [in] - The name of the file to load. This file name can contain a directory path
* or be a base name that exists within Ogre's resource manager. If the file contains a directory path,
* the directory will be added to Ogre's resource manager as a resource location and the directory will be
* set as a base resource location. If the file doesn't contain a directory path, and assuming
* If the FILE_NAME_CONTAINS_CONTENT flag is specified as a load option, this parameter is treated
* as though it is the scene file itself. That is, the string contains the scene file XML.
* SetBaseResourceLocation() hasn't already been called elsewhere, no resource location configuration
* will occur during the load
* @param renderWindow [in] - The render window in use
* @param loadOptions [in] - Options used to specify the loading behavior. Optional.
* @param sceneManager [in] - The scene manager into which the scene is loaded. Optional. If not specified,
* the scene manager specified in the scene file will be used to create a new scene manager
* @param rootNode [in] - Root node under which all loaded scene nodes will be created. If specified,
* this should be a scene node in the specified scene manager
* @param callback [in] - Pointer to a callback object. Optional.
* @param defaultResourceGroupName [in] - The resource group name that is used by default when
* creating new resources. Optional.
*/
void Load
(
const Ogre::String& fileNameOrContent,
Ogre::RenderWindow* renderWindow,
LoadOptions loadOptions = NO_OPTIONS,
Ogre::SceneManager* sceneManager = 0,
Ogre::SceneNode* rootNode = 0,
OgreMaxSceneCallback* callback = 0,
const Ogre::String& defaultResourceGroupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
);
void Load
(
const Ogre::String& fileName,
OgreMaxRenderWindowIterator& renderWindows,
LoadOptions loadOptions = NO_OPTIONS,
Ogre::SceneManager* sceneManager = 0,
Ogre::SceneNode* rootNode = 0,
OgreMaxSceneCallback* callback = 0,
const Ogre::String& defaultResourceGroupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
);
/**
* Destroys the internal OgreMaxScene objects
* Note that this does not affect the scene manager or any resources.
* Those must be destroyed manually
*/
void Destroy();
/** Flags that define which name prefixes to set */
typedef int WhichNamePrefix;
enum
{
OBJECT_NAME_PREFIX = 0x1,
NODE_NAME_PREFIX = 0x2,
NODE_ANIMATION_NAME_PREFIX = 0x4,
ALL_NAME_PREFIXES = OBJECT_NAME_PREFIX | NODE_NAME_PREFIX | NODE_ANIMATION_NAME_PREFIX
};
/**
* Sets one or more name prefixes. This should be called before Load() is called
* @param name [in] - The prefix. This may be null
* @param prefixes [in] - Flags indicating which prefixes to set
*/
void SetNamePrefix(const Ogre::String& name, WhichNamePrefix prefixes = ALL_NAME_PREFIXES);
void Update(Ogre::Real elapsedTime);
/** Gets the base resource location */
const Ogre::String& GetBaseResourceLocation() const;
/**
* Sets the base resource location, a directory, which all other resource locations
* are considered to be relative to.
* @param directory [in] - The base directory. If this is an empty string, resource
* locations loaded from the scene file are not added to the Ogre resource group manager
*/
void SetBaseResourceLocation(const Ogre::String& directory);
//Various getters
Ogre::SceneManager* GetSceneManager();
Ogre::SceneNode* GetRootNode();
/**
* Gets the scene node with the specified name, optionally prepending the scene node name prefix
* @param name [in] - The name of the scene node to get
* @param nameIncludesPrefix [in] - Indicates whether the name already includes the prefix. If false,
* the scene node name prefix is used with the node name.
* @return The scene node with the specified name is returned
*/
Ogre::SceneNode* GetSceneNode(const Ogre::String& name, bool nameIncludesPrefix);
/** Gets the up axis type */
Types::UpAxis GetUpAxis() const;
/** Gets the up axis vector */
const Ogre::Vector3& GetUpVector() const;
/**
* Gets the scene scaling - in units per meter.
* This will be zero if the setting was not defined in the scene file
*/
Ogre::Real GetUnitsPerMeter();
/**
* Gets the scene's unit type (meters, feet, and so on).
* This is a descriptive string that may contain an additional divide factor
*/
const Ogre::String GetUnitType();
/** Gets the extra data associated with the scene */
const Types::ObjectExtraData& GetSceneExtraData() const;
/** Gets the extra data associated with the terrain */
const Types::ObjectExtraData& GetTerrainExtraData() const;
/** Gets the extra data associated with the sky box */
const Types::ObjectExtraData& GetSkyBoxExtraData() const;
/** Gets the extra data associated with the sky dome */
const Types::ObjectExtraData& GetSkyDomeExtraData() const;
/** Gets the extra data associated with the sky plane */
const Types::ObjectExtraData& GetSkyPlaneExtraData() const;
typedef std::list<Types::ExternalItem> ExternalItemList;
/** Gets the list of external items */
const ExternalItemList& GetExternalItems() const;
/** Gets the background color */
const Ogre::ColourValue& GetBackgroundColor() const;
/** Gets the environment near range */
Ogre::Real GetEnvironmentNear() const;
/** Gets the environment far range */
Ogre::Real GetEnvironmentFar() const;
/** Gets the loaded fog settings */
const Types::FogParameters& GetFogParameters() const;
/** Gets plane object used as the current shadow optimal plane */
Ogre::MovablePlane* GetShadowOptimalPlane();
/** Gets the plane object with the specified name */
Ogre::MovablePlane* GetMovablePlane(const Ogre::String& name);
typedef std::map<const Ogre::String, Ogre::AnimationState*> AnimationStates;
/** Gets all the animation states created by the scene */
AnimationStates& GetAnimationStates();
/** Gets the animation state created by the scene with the specified name */
Ogre::AnimationState* GetAnimationState(const Ogre::String& animationName);
typedef std::map<const Ogre::MovableObject*, Types::ObjectExtraDataPtr> ObjectExtraDataMap;
/** Gets the collection of extra data for all Ogre::MovableObjects */
ObjectExtraDataMap& GetAllObjectExtraData();
typedef std::map<const Ogre::Node*, Types::ObjectExtraDataPtr> NodeObjectExtraDataMap;
/** Gets the collection of extra data for all Ogre::Nodes */
NodeObjectExtraDataMap& GetAllNodeObjectExtraData();
typedef std::map<const Ogre::String, OgreMaxModel*> ModelMap;
/** Gets the collection of all model templates, each of which is keyed by file name */
const ModelMap& GetModelMap() const;
/** Gets the model template with the specified file name, loading it if it isn't already loaded */
OgreMaxModel* GetModel(const Ogre::String& fileName);
/** Gets the collection of scene query flag aliases */
const Types::FlagAliases& GetQueryFlagAliases() const;
/** Gets the collection of scene visibility flag aliases */
const Types::FlagAliases& GetVisibilityFlagAliases() const;
/** A single resource location */
class ResourceLocation
{
public:
ResourceLocation()
{
this->recursive = false;
this->initialized = false;
}
ResourceLocation
(
const Ogre::String& name,
const Ogre::String& type,
bool recursive = false
)
{
this->name = name;
this->type = type;
this->recursive = recursive;
this->initialized = false;
}
bool operator < (const ResourceLocation& other) const
{
return this->name < other.name;
}
Ogre::String name;
Ogre::String type;
bool recursive;
private:
friend class OgreMaxScene;
bool initialized;
};
/**
* Adds a new resource location.
* The new resource location isn't visible to Ogre until CommitResourceLocations() is called
*/
bool AddResourceLocation(const ResourceLocation& resourceLocation);
/** Adds new resource locations to Ogre3D's resource group manager */
void CommitResourceLocations();
typedef std::set<ResourceLocation> ResourceLocations;
/** Gets the resource locations that were configured through the scene */
const ResourceLocations& GetResourceLocations() const;
/** Gets the extra data, if any, for the specified object */
Types::ObjectExtraData* GetObjectExtraData(const Ogre::MovableObject* object) const;
/**
* Gets the extra data, if any, for the specified node
* This only works for nodes that were exported as 'empty'
*/
Types::ObjectExtraData* GetObjectExtraData(const Ogre::Node* node) const;
/** For internal use only */
void HandleNewObjectExtraData(Types::ObjectExtraDataPtr objectExtraData);
/** This is to be called if you manually destroy a scene node */
void DestroyedSceneNode(const Ogre::SceneNode* node);
/** This is to be called if you manually destroy a movable object (entity, light, camera, etc.)*/
void DestroyedObject(const Ogre::MovableObject* object);
protected:
/**
* Loads a scene from the specified XML element
* @param objectElement [in] - The 'scene' XML element
*/
void Load
(
TiXmlElement* objectElement,
OgreMaxRenderWindowIterator& renderWindows,
LoadOptions loadOptions = NO_OPTIONS,
Ogre::SceneManager* sceneManager = 0,
Ogre::SceneNode* rootNode = 0,
OgreMaxSceneCallback* callback = 0,
const Ogre::String& defaultResourceGroupName = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
);
//Ogre::RenderTargetListener methods
void preRenderTargetUpdate(const Ogre::RenderTargetEvent& e);
void postRenderTargetUpdate(const Ogre::RenderTargetEvent& e);
/**
* Determines the name of an object stored in an XML element. The name is
* presumed to be for a new object, so if the name is not unique an exception is thrown
* @param objectElement [in] - The XML element that contains the object
* @param node [in] - The scene node that will contain the object once it's
* parsed from the XML element.
* @return If the XML element contains the 'name' attribute, that attribute's value is returned.
* Otherwise the parent node's name is returned
*/
Ogre::String GetNewObjectName(const TiXmlElement* objectElement, Ogre::SceneNode* node);
/** Updates the progress for the specified progress calculator. */
void UpdateLoadProgress(ProgressCalculator* calculator, Ogre::Real amount);
void LoadScene(const TiXmlElement* objectElement);
void FinishLoadingLookAndTrackTargets();
bool LoadResourceLocations(const TiXmlElement* objectElement);
void LoadInstancedGeometries(const TiXmlElement* objectElement);
void LoadInstancedGeometry(const TiXmlElement* objectElement);
void LoadInstancedGeometryEntity(const TiXmlElement* objectElement, Ogre::InstancedGeometry* instancedGeometry);
void LoadStaticGeometries(const TiXmlElement* objectElement);
void LoadStaticGeometry(const TiXmlElement* objectElement);
void LoadStaticGeometryEntity(const TiXmlElement* objectElement, Ogre::StaticGeometry* staticGeometry);
void LoadPortalConnectedZones(const TiXmlElement* objectElement);
void LoadNodes(const TiXmlElement* objectElement);
void LoadQueryFlagAliases(const TiXmlElement* objectElement);
void LoadVisibilityFlagAliases(const TiXmlElement* objectElement);
void LoadExternals(const TiXmlElement* objectElement);
void LoadEnvironment(const TiXmlElement* objectElement);
void LoadRenderTextures(const TiXmlElement* objectElement);
void FinishLoadingRenderTextures();
void GetRenderTextureObjects(Types::LoadedRenderTexture* loadedRenderTexture);
void LoadTerrain(const TiXmlElement* objectElement);
void LoadOctree(const TiXmlElement* objectElement);
void LoadNode(const TiXmlElement* objectElement, Ogre::SceneNode* parentNode);
void LoadFog(const TiXmlElement* objectElement);
void LoadSkyBox(const TiXmlElement* objectElement);
void LoadSkyDome(const TiXmlElement* objectElement);
void LoadSkyPlane(const TiXmlElement* objectElement);
void LoadClipping(const TiXmlElement* objectElement, Ogre::Real& nearClip, Ogre::Real& farClip);
void LoadShadows(const TiXmlElement* objectElement);
void LoadExternalItem(const TiXmlElement* objectElement);
void LoadEntity(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadLight(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadCamera(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadParticleSystem(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadBillboardSet(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadPlane(const TiXmlElement* objectElement, const Types::MovableObjectOwner& owner);
void LoadBoneAttachments(const TiXmlElement* objectElement, Ogre::Entity* entity);
void LoadBoneAttachment(const TiXmlElement* objectElement, Ogre::Entity* entity);
void LoadLookTarget(const TiXmlElement* objectElement, Ogre::SceneNode* node, Ogre::Camera* camera);
void LoadTrackTarget(const TiXmlElement* objectElement, Ogre::SceneNode* node, Ogre::Camera* camera);
void LoadBillboard(const TiXmlElement* objectElement, Ogre::BillboardSet* billboardSet);
void LoadLightRange(const TiXmlElement* objectElement, Ogre::Light* light);
void LoadLightAttenuation(const TiXmlElement* objectElement, Ogre::Light* light);
void LoadNodeAnimations(const TiXmlElement* objectElement, Ogre::SceneNode* node);
void LoadNodeAnimation(const TiXmlElement* objectElement, Ogre::SceneNode* node);
void LoadNodeAnimationKeyFrame(const TiXmlElement* objectElement, Ogre::NodeAnimationTrack* animationTrack);
void LoadObjectNames(const TiXmlElement* objectElement, const Ogre::String& elementName, std::vector<Ogre::String>& names);
void LoadRenderTextureMaterials
(
const TiXmlElement* childElement,
std::vector<Types::RenderTextureParameters::Material>& materials
);
Ogre::ShadowCameraSetup* ParseShadowCameraSetup(const Ogre::String& type, Ogre::Plane optimalPlane);
protected:
LoadOptions loadOptions;
OgreMaxRenderWindowIterator* renderWindows;
Ogre::SceneManager* sceneManager;
Ogre::SceneNode* rootNode;
OgreMaxSceneCallback* callback;
Ogre::String defaultResourceGroupName;
Ogre::String baseResourceLocation;
bool loadedFromFileSystem;
Types::ObjectExtraData sceneExtraData;
Version formatVersion;
Version minOgreVersion;
Ogre::String author;
Types::UpAxis upAxis;
Ogre::Real unitsPerMeter;
Ogre::String unitType;
Types::ObjectExtraData terrainExtraData;
Types::ObjectExtraData skyBoxExtraData;
Types::ObjectExtraData skyDomeExtraData;
Types::ObjectExtraData skyPlaneExtraData;
ExternalItemList externalItems;
Ogre::ColourValue backgroundColor;
Ogre::Real environmentNear;
Ogre::Real environmentFar;
Types::FogParameters fogParameters;
Ogre::MovablePlane* shadowOptimalPlane;
/** Movable planes that were created when loading Ogre plane objects */
typedef std::map<Ogre::String, Ogre::MovablePlane*> MovablePlanesMap;
MovablePlanesMap movablePlanes;
/** The objects that were explicitly loaded from the scene file */
std::map<Ogre::String, Ogre::MovableObject*> loadedObjects;
/** Tracks scene loading progress. */
class LoadSceneProgressCalculator : public ProgressCalculator
{
public:
LoadSceneProgressCalculator()
{
this->nodes = AddCalculator("nodes");
this->externals = AddCalculator("externals");
}
public:
//Child calculators
ProgressCalculator* nodes;
ProgressCalculator* externals;
};
LoadSceneProgressCalculator loadProgress;
/** Look target information, encountered during the loading of a scene */
typedef std::list<Types::LookTarget> LookTargetList;
LookTargetList lookTargets;
/** Track target information, encountered during the loading of a scene */
typedef std::list<Types::TrackTarget> TrackTargetList;
TrackTargetList trackTargets;
/** The created animation states */
AnimationStates animationStates;
/**
* A lookup table for all the ObjectExtraData created for each object
* This will be destroyed when the OgreMaxScene is destroyed, so if you
* would like to keep this data, it should be 'stolen' by calling
* GetAllObjectExtraData(), copying the values, then clearing the values
* that are contained in the OgreMaxScene
*/
ObjectExtraDataMap allObjectExtraData;
/**
* A lookup table for all the ObjectExtraData created for each object
*/
NodeObjectExtraDataMap allNodeObjectExtraData;
/**
* A lookup table for all the models that have been loaded
*/
ModelMap modelMap;
/**
* The index into the first unused element in loadedRenderTextures
* Used during the loading process
*/
size_t currentRenderTextureIndex;
/** All the render textures */
std::vector<Types::LoadedRenderTexture*> loadedRenderTextures;
/**
* All the render textures, keyed by the corresponding render targets
* The pointers reference the entries in loadedRenderTextures
*/
typedef std::map<Ogre::RenderTarget*, Types::LoadedRenderTexture*> RenderTargetMap;
RenderTargetMap renderTargets;
/** The query flag aliases */
Types::FlagAliases queryFlags;
/** The visibility flag aliases */
Types::FlagAliases visibilityFlags;
/** The active scheme, saved before a render texture update and restored after */
Ogre::String previousActiveScheme;
//Various name prefixes
Ogre::String objectNamePrefix;
Ogre::String nodeNamePrefix;
Ogre::String nodeAnimationNamePrefix;
/** Loaded resource locations */
ResourceLocations resourceLocations;
};
/** A interface that receives notifications during the loading of the scene */
class OgreMaxSceneCallback
{
public:
virtual ~OgreMaxSceneCallback() {}
/** Called before a scene is to be loaded. */
virtual void StartedLoad(const OgreMaxScene* scene) {}
virtual void CreatedSceneManager(const OgreMaxScene* scene, Ogre::SceneManager* sceneManager) {}
virtual void CreatedExternal(const OgreMaxScene* scene, const OgreMax::Types::ExternalItem& item) {}
//Called when scene (not per-object) user data is loaded. Will only be called if there is user data
virtual void LoadedUserData(const OgreMaxScene* scene, const Ogre::String& userDataReference, const Ogre::String& userData) {}
//Called when resource locations are loaded. Will only be called if there are resource locations
virtual void LoadingResourceLocations(const OgreMaxScene* scene) {}
virtual void LoadedResourceLocations(const OgreMaxScene* scene, const OgreMaxScene::ResourceLocations& resourceLocations) {}
//Resource-based callbacks, called before a resource is created
//The main purpose of these callbacks is to get the resource group name for the
//resource being loaded, though other parameters may be modified as well
virtual void LoadingRenderTexture(const OgreMaxScene* scene, OgreMax::Types::RenderTextureParameters& renderTextureParameters) {}
virtual void LoadingSceneFile(const OgreMaxScene* scene, const Ogre::String& fileName, Ogre::String& resourceGroupName) {}
virtual void LoadingSkyBox(const OgreMaxScene* scene, OgreMax::Types::SkyBoxParameters& skyBoxParameters) {}
virtual void LoadingSkyDome(const OgreMaxScene* scene, OgreMax::Types::SkyDomeParameters& skyDomeParameters) {}
virtual void LoadingSkyPlane(const OgreMaxScene* scene, OgreMax::Types::SkyPlaneParameters& skyPlaneParameters) {}
virtual void LoadingEntity(const OgreMaxScene* scene, OgreMax::Types::EntityParameters& parameters) {}
virtual void LoadingPlane(const OgreMaxScene* scene, OgreMax::Types::PlaneParameters& parameters) {}
/**
* Called right before an Ogre animation is created. The parameters may be modified.
* In particular modifying the length is useful in cases where there are multiple node animation
* tracks on the animation, each of which starts and ends at different times.
*/
virtual void LoadingNodeAnimation(const OgreMaxScene* scene, Types::NodeAnimationParameters& parameters) {}
//MovableObject-creation callbacks, called after an object has been created
//These are called after the object was attached to its parent node, if there is a parent node
virtual void CreatedLight(const OgreMaxScene* scene, Ogre::Light* light) {CreatedMovableObject(scene, light);}
virtual void CreatedCamera(const OgreMaxScene* scene, Ogre::Camera* camera) {CreatedMovableObject(scene, camera);}
virtual void CreatedMesh(const OgreMaxScene* scene, Ogre::Mesh* mesh) {}
virtual void CreatedEntity(const OgreMaxScene* scene, Ogre::Entity* entity) {CreatedMovableObject(scene, entity);}
virtual void CreatedParticleSystem(const OgreMaxScene* scene, Ogre::ParticleSystem* particleSystem) {CreatedMovableObject(scene, particleSystem);}
virtual void CreatedBillboardSet(const OgreMaxScene* scene, Ogre::BillboardSet* billboardSet) {CreatedMovableObject(scene, billboardSet);}
virtual void CreatedPlane(const OgreMaxScene* scene, const Ogre::Plane& plane, Ogre::Entity* entity) {CreatedMovableObject(scene, entity);}
virtual void CreatedMovableObject(const OgreMaxScene* scene, Ogre::MovableObject* object) {}
virtual void CreatedNodeAnimation(const OgreMaxScene* scene, Ogre::SceneNode* Node, Ogre::Animation* animation) {}
virtual void CreatedNodeAnimationTrack(const OgreMaxScene* scene, Ogre::SceneNode* node, Ogre::AnimationTrack* animationTrack, bool enabled, bool looping) {}
virtual void CreatedNodeAnimationState(const OgreMaxScene* scene, Ogre::SceneNode* node, Ogre::AnimationState* animationState) {}
//Render texture creation callbacks
virtual Ogre::Camera* GetRenderTextureCamera(const OgreMaxScene* scene, const OgreMax::Types::RenderTextureParameters& renderTextureParameters) {return 0;}
virtual void CreatedRenderTexture(const OgreMaxScene* scene, const OgreMax::Types::LoadedRenderTexture* renderTexture) {}
/** Called after a node is created, but before its entities or any child nodes have been created */
virtual void StartedCreatingNode(const OgreMaxScene* scene, Ogre::SceneNode* node) {}
/** Called after the node and all its entities and child nodes have been created */
virtual void FinishedCreatingNode(const OgreMaxScene* scene, Ogre::SceneNode* node) {}
virtual void CreatedTerrain(const OgreMaxScene* scene, const Ogre::String& dataFile) {}
virtual void HandleObjectExtraData(Types::ObjectExtraDataPtr objectExtraData) {}
//Progress callback
virtual void UpdatedLoadProgress(const OgreMaxScene* scene, Ogre::Real progress) {}
/**
* Called after a scene is loaded.
* @param scene [in] - The scene that was loaded
* @param success [in] - Indicates whether the scene was successfully loaded. False
* indicates an error occurred.
*/
virtual void FinishedLoad(const OgreMaxScene* scene, bool success) {}
/**
* Notifies the caller that shadow textures are about to be created
* @param scene [in] - The scene that was loaded
* @param parameters [in/out] - The shadow parameters that are in effect. Any of the texture-related
* parameters can be modified. The most typical one to be modified is the texture pixel format.
*/
virtual void CreatingShadowTextures(const OgreMaxScene* scene, Types::ShadowParameters& shadowParameters) {}
};
}
#endif
| [
"tunnuz@5541800f-1273-12b8-a6ef-86c1fc29b7c3"
] | [
[
[
1,
683
]
]
] |
f91628f167a103f98b252ad8a9119a0bfc48ca26 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/windows/com/itypeinfo.hpp | 7340a57c97e15c3761ad5812301092275966e6a3 | [
"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,851 | 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_WINDOWS_COM_ITYPEINFO_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_WINDOWS_COM_ITYPEINFO_HPP_INCLUDED
#include <cbear.berlios.de/windows/com/pointer.hpp>
#include <cbear.berlios.de/windows/com/exception.hpp>
namespace cbear_berlios_de
{
namespace windows
{
namespace com
{
typedef pointer< ::ITypeInfo> itypeinfo;
template<class T>
class library_info;
template<class T>
class scoped_type_info
{
public:
scoped_type_info()
{
Value = library_info<T>::type::typelib().gettypeinfoofguid<T>();
}
static const itypeinfo &typeinfo() { return Value; }
private:
static itypeinfo Value;
};
template<class T>
itypeinfo scoped_type_info<T>::Value;
}
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
61
]
]
] |
a554b9ba0bdcffad8abd75d14354eb3d18450b01 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/web/favourites_api/src/FavouritesDbIncrementalTestCases.cpp | 05e30755b3a671511f3d94f910d9e1ea9445a41e | [] | 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 | 6,443 | cpp | /*
* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*
*/
// INCLUDE FILES
#include <e32math.h>
#include "FavouritesBCTest.h"
// EXTERNAL DATA STRUCTURES
// None
// EXTERNAL FUNCTION PROTOTYPES
// None
// CONSTANTS
// None
// MACROS
// None
// LOCAL CONSTANTS AND MACROS
// None
// MODULE DATA STRUCTURES
// None
// LOCAL FUNCTION PROTOTYPES
// None
// FORWARD DECLARATIONS
// None
// ==================== LOCAL FUNCTIONS =======================================
// ============================ MEMBER FUNCTIONS ===============================
/*
-------------------------------------------------------------------------------
Class: CFavouritesBCTest
Method: DbIncRecoverTestL
Description: Test the RFavouritesDbIncremental Recover method.
Parameters: TTestResult& aErrorDescription: out:
Test result and on error case a short description of error
Return Values: TInt: Always KErrNone to indicate that test was valid
Errors/Exceptions: None
Status: Approved
-------------------------------------------------------------------------------
*/
TInt CFavouritesBCTest::DbIncRecoverTestL( TTestResult& aResult )
{
/* Simple server connect */
_LIT( KDefinition ,"State" );
_LIT( KData ,"Test the RFavouritesDbIncremental Recover method" );
TestModuleIf().Printf( 0, KDefinition, KData );
TInt tempResult = iFavouritesDb.Open( iFavouritesSession, KTestDbName );
tempResult = tempResult;
CleanupClosePushL<RFavouritesDb>( iFavouritesDb );
CreatePopulatedDbL();
TInt step;
RFavouritesDbIncremental incremental;
TInt result = incremental.Recover( iFavouritesDb, step );
CleanupClosePushL<RFavouritesDbIncremental>( incremental );
_LIT( KData2 ,"Finished" );
TestModuleIf().Printf( 0, KDefinition, KData2 );
if( result == KErrNone )
{
_LIT( KDescription , "Test case passed" );
aResult.SetResult( KErrNone, KDescription );
}
else
{
_LIT( KDescription , "Test case failed" );
aResult.SetResult( KErrGeneral, KDescription );
}
CleanupStack::PopAndDestroy(2); // iFavouritesDb, incremental
iFavouritesSession.DeleteDatabase( KTestDbName );
// Case was executed
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Class: CFavouritesBCTest
Method: DbIncCompactTestL
Description: Test the RFavouritesDbIncremental Compact method.
Parameters: TTestResult& aErrorDescription: out:
Test result and on error case a short description of error
Return Values: TInt: Always KErrNone to indicate that test was valid
Errors/Exceptions: None
Status: Approved
-------------------------------------------------------------------------------
*/
TInt CFavouritesBCTest::DbIncCompactTestL( TTestResult& aResult )
{
/* Simple server connect */
_LIT( KDefinition ,"State" );
_LIT( KData ,"Test the RFavouritesDbIncremental Compact method" );
TestModuleIf().Printf( 0, KDefinition, KData );
TInt tempResult = iFavouritesDb.Open( iFavouritesSession, KTestDbName );
tempResult = tempResult;
CleanupClosePushL<RFavouritesDb>( iFavouritesDb );
CreatePopulatedDbL();
TInt step;
RFavouritesDbIncremental incremental;
TInt result = incremental.Compact( iFavouritesDb, step );
CleanupClosePushL<RFavouritesDbIncremental>( incremental );
_LIT( KData2 ,"Finished" );
TestModuleIf().Printf( 0, KDefinition, KData2 );
if( result == KErrNone )
{
_LIT( KDescription , "Test case passed" );
aResult.SetResult( KErrNone, KDescription );
}
else
{
_LIT( KDescription , "Test case failed" );
aResult.SetResult( KErrGeneral, KDescription );
}
CleanupStack::PopAndDestroy(2); // iFavouritesDb, incremental
iFavouritesSession.DeleteDatabase( KTestDbName );
// Case was executed
return KErrNone;
}
/*
-------------------------------------------------------------------------------
Class: CFavouritesBCTest
Method: DbIncNextTestL
Description: Test the RFavouritesDbIncremental Next method.
Parameters: TTestResult& aErrorDescription: out:
Test result and on error case a short description of error
Return Values: TInt: Always KErrNone to indicate that test was valid
Errors/Exceptions: None
Status: Approved
-------------------------------------------------------------------------------
*/
TInt CFavouritesBCTest::DbIncNextTestL( TTestResult& aResult )
{
/* Simple server connect */
_LIT( KDefinition ,"State" );
_LIT( KData ,"Test the RFavouritesDbIncremental Next method" );
TestModuleIf().Printf( 0, KDefinition, KData );
TInt tempResult = iFavouritesDb.Open( iFavouritesSession, KTestDbName );
tempResult = tempResult;
CleanupClosePushL<RFavouritesDb>( iFavouritesDb );
CreatePopulatedDbL();
TInt step;
RFavouritesDbIncremental incremental;
incremental.Compact( iFavouritesDb, step );
CleanupClosePushL<RFavouritesDbIncremental>( incremental );
TInt result = incremental.Next( step );
_LIT( KData2 ,"Finished" );
TestModuleIf().Printf( 0, KDefinition, KData2 );
if( result == KErrNone )
{
_LIT( KDescription , "Test case passed" );
aResult.SetResult( KErrNone, KDescription );
}
else
{
_LIT( KDescription , "Test case failed" );
aResult.SetResult( KErrGeneral, KDescription );
}
CleanupStack::PopAndDestroy(2); // iFavouritesDb, incremental
iFavouritesSession.DeleteDatabase( KTestDbName );
// Case was executed
return KErrNone;
}
// ================= OTHER EXPORTED FUNCTIONS =================================
// End of File
| [
"none@none"
] | [
[
[
1,
238
]
]
] |
9febc817b05235c209cd0a01138355d308901d39 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkMILVideoSource.h | 4c3ac3bf37554c7c97a9b10508cc39e1a834f5be | [
"BSD-3-Clause"
] | permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,624 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMILVideoSource.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkMILVideoSource - Matrox Imaging Library frame grabbers
// .SECTION Description
// vtkMILVideoSource provides an interface to Matrox Meteor, MeteorII
// and Corona video digitizers through the Matrox Imaging Library
// interface. In order to use this class, you must link VTK with mil.lib,
// MIL version 5.0 or higher is required.
// .SECTION Caveats
// With some capture cards, if this class is leaked and ReleaseSystemResources
// is not called, you may have to reboot before you can capture again.
// vtkVideoSource used to keep a global list and delete the video sources
// if your program leaked, due to exit crashes that was removed.
// .SECTION See Also
// vtkWin32VideoSource vtkVideoSource
#ifndef __vtkMILVideoSource_h
#define __vtkMILVideoSource_h
#include "vtkVideoSource.h"
// digitizer hardware
#define VTK_MIL_DEFAULT 0
#define VTK_MIL_METEOR "M_SYSTEM_METEOR"
#define VTK_MIL_METEOR_II "M_SYSTEM_METEOR_II"
#define VTK_MIL_METEOR_II_DIG "M_SYSTEM_METEOR_II_DIG"
#define VTK_MIL_METEOR_II_CL "M_SYSTEM_METEOR_II_CL"
#define VTK_MIL_METEOR_II_1394 "M_SYSTEM_METEOR_II_1394"
#define VTK_MIL_CORONA "M_SYSTEM_CORONA"
#define VTK_MIL_CORONA_II "M_SYSTEM_CORONA_II"
#define VTK_MIL_PULSAR "M_SYSTEM_PULSAR"
#define VTK_MIL_GENESIS "M_SYSTEM_GENESIS"
#define VTK_MIL_GENESIS_PLUS "M_SYSTEM_GENESIS_PLUS"
#define VTK_MIL_ORION "M_SYSTEM_ORION"
#define VTK_MIL_CRONOS "M_SYSTEM_CRONOS"
#define VTK_MIL_ODYSSEY "M_SYSTEM_ODYSSEY"
// video inputs:
#define VTK_MIL_MONO 0
#define VTK_MIL_COMPOSITE 1
#define VTK_MIL_YC 2
#define VTK_MIL_RGB 3
#define VTK_MIL_DIGITAL 4
// video formats:
#define VTK_MIL_RS170 0
#define VTK_MIL_NTSC 1
#define VTK_MIL_CCIR 2
#define VTK_MIL_PAL 3
#define VTK_MIL_SECAM 4
#define VTK_MIL_NONSTANDARD 5
class VTK_HYBRID_EXPORT vtkMILVideoSource : public vtkVideoSource
{
public:
static vtkMILVideoSource *New();
vtkTypeMacro(vtkMILVideoSource,vtkVideoSource);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Standard VCR functionality: Record incoming video.
void Record();
// Description:
// Standard VCR functionality: Play recorded video.
void Play();
// Description:
// Standard VCR functionality: Stop recording or playing.
void Stop();
// Description:
// Grab a single video frame.
void Grab();
// Description:
// Request a particular frame size (set the third value to 1).
void SetFrameSize(int x, int y, int z);
// Description:
// Request a particular output format (default: VTK_RGB).
void SetOutputFormat(int format);
// Description:
// Set/Get the video channel
virtual void SetVideoChannel(int channel);
vtkGetMacro(VideoChannel, int);
// Description:
// Set/Get the video format
virtual void SetVideoFormat(int format);
void SetVideoFormatToNTSC() { this->SetVideoFormat(VTK_MIL_NTSC); };
void SetVideoFormatToPAL() { this->SetVideoFormat(VTK_MIL_PAL); };
void SetVideoFormatToSECAM() { this->SetVideoFormat(VTK_MIL_SECAM); };
void SetVideoFormatToRS170() { this->SetVideoFormat(VTK_MIL_RS170); };
void SetVideoFormatToCCIR() { this->SetVideoFormat(VTK_MIL_CCIR); };
void SetVideoFormatToNonStandard() {
this->SetVideoFormat(VTK_MIL_NONSTANDARD); };
vtkGetMacro(VideoFormat,int);
// Description:
// Set/Get the video input
virtual void SetVideoInput(int input);
void SetVideoInputToMono() { this->SetVideoInput(VTK_MIL_MONO); };
void SetVideoInputToComposite() {this->SetVideoInput(VTK_MIL_COMPOSITE);};
void SetVideoInputToYC() { this->SetVideoInput(VTK_MIL_YC); };
void SetVideoInputToRGB() { this->SetVideoInput(VTK_MIL_RGB); };
void SetVideoInputToDigital() { this->SetVideoInput(VTK_MIL_DIGITAL); };
vtkGetMacro(VideoInput,int);
// Description:
// Set/Get the video levels for composite/SVideo: the valid ranges are:
// Contrast [0.0,2.0]
// Brighness [0.0,255.0]
// Hue [-0.5,0.5]
// Saturation [0.0,2.0]
virtual void SetContrastLevel(float contrast);
vtkGetMacro(ContrastLevel,float);
virtual void SetBrightnessLevel(float brightness);
vtkGetMacro(BrightnessLevel,float);
virtual void SetHueLevel(float hue);
vtkGetMacro(HueLevel,float);
virtual void SetSaturationLevel(float saturation);
vtkGetMacro(SaturationLevel,float);
// Description:
// Set/Get the video levels for monochrome/RGB: valid values are
// between 0.0 and 255.0.
virtual void SetBlackLevel(float value);
virtual float GetBlackLevel() {
return this->BlackLevel; };
virtual void SetWhiteLevel(float value);
virtual float GetWhiteLevel() {
return this->WhiteLevel; };
// Description:
// Set the system which you want use. If you don't specify a system,
// then your primary digitizer will be autodetected.
vtkSetStringMacro(MILSystemType);
vtkGetStringMacro(MILSystemType);
void SetMILSystemTypeToMeteor() { this->SetMILSystemType(VTK_MIL_METEOR); };
void SetMILSystemTypeToMeteorII() { this->SetMILSystemType(VTK_MIL_METEOR_II); };
void SetMILSystemTypeToMeteorIIDig() { this->SetMILSystemType(VTK_MIL_METEOR_II_DIG); };
void SetMILSystemTypeToMeteorIICL() { this->SetMILSystemType(VTK_MIL_METEOR_II_CL); };
void SetMILSystemTypeToMeteorII1394() { this->SetMILSystemType(VTK_MIL_METEOR_II_1394); };
void SetMILSystemTypeToCorona() { this->SetMILSystemType(VTK_MIL_CORONA); };
void SetMILSystemTypeToCoronaII() { this->SetMILSystemType(VTK_MIL_CORONA_II); };
void SetMILSystemTypeToPulsar() { this->SetMILSystemType(VTK_MIL_PULSAR); };
void SetMILSystemTypeToGenesis() { this->SetMILSystemType(VTK_MIL_GENESIS); };
void SetMILSystemTypeToGenesisPlus() { this->SetMILSystemType(VTK_MIL_GENESIS_PLUS); };
void SetMILSystemTypeToOrion() { this->SetMILSystemType(VTK_MIL_ORION); };
void SetMILSystemTypeToCronos() { this->SetMILSystemType(VTK_MIL_CRONOS); };
void SetMILSystemTypeToOdyssey() { this->SetMILSystemType(VTK_MIL_ODYSSEY); };
// Description:
// Set the system number if you have multiple systems of the same type
vtkSetMacro(MILSystemNumber,int);
vtkGetMacro(MILSystemNumber,int);
// Description:
// Set the DCF filename for non-standard video formats
vtkSetStringMacro(MILDigitizerDCF);
vtkGetStringMacro(MILDigitizerDCF);
// Description:
// Set the digitizer number for systems with multiple digitizers
vtkSetMacro(MILDigitizerNumber,int);
vtkGetMacro(MILDigitizerNumber,int);
// Description:
// Set whether to display MIL error messages (default on)
virtual void SetMILErrorMessages(int yesno);
vtkBooleanMacro(MILErrorMessages,int);
vtkGetMacro(MILErrorMessages,int);
// Description:
// Allows fine-grained control
vtkSetMacro(MILAppID,long);
vtkGetMacro(MILAppID,long);
vtkSetMacro(MILSysID,long);
vtkGetMacro(MILSysID,long);
vtkGetMacro(MILDigID,long);
vtkGetMacro(MILBufID,long);
// Description:
// Initialize the driver (this is called automatically when the
// first grab is done).
void Initialize();
// Description:
// Free the driver (this is called automatically inside the
// destructor).
void ReleaseSystemResources();
// Description:
// For internal use only
void *OldHookFunction;
void *OldUserDataPtr;
int FrameCounter;
int ForceGrab;
void InternalGrab();
protected:
vtkMILVideoSource();
~vtkMILVideoSource();
virtual void AllocateMILDigitizer();
virtual void AllocateMILBuffer();
virtual char *MILInterpreterForSystem(const char *system);
char *MILInterpreterDLL;
int VideoChannel;
int VideoInput;
int VideoInputForColor;
int VideoFormat;
float ContrastLevel;
float BrightnessLevel;
float HueLevel;
float SaturationLevel;
float BlackLevel;
float WhiteLevel;
int FrameMaxSize[2];
long MILAppID;
long MILSysID;
long MILDigID;
long MILBufID;
// long MILDispBufID;
// long MILDispID;
char *MILSystemType;
int MILSystemNumber;
int MILDigitizerNumber;
char *MILDigitizerDCF;
int MILErrorMessages;
int MILAppInternallyAllocated;
int MILSysInternallyAllocated;
int FatalMILError;
// Description:
// Method for updating the virtual clock that accurately times the
// arrival of each frame, more accurately than is possible with
// the system clock alone because the virtual clock averages out the
// jitter.
double CreateTimeStampForFrame(unsigned long frame);
double LastTimeStamp;
unsigned long LastFrameCount;
double EstimatedFramePeriod;
double NextFramePeriod;
private:
vtkMILVideoSource(const vtkMILVideoSource&); // Not implemented.
void operator=(const vtkMILVideoSource&); // Not implemented.
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
] | [
[
[
1,
276
]
]
] |
69aa467414289989ee1198b2d91cdf578bf518dc | 508bfb3220be28811600a2cbf0aabae382f78775 | /AcademicCrawler-sdk/Qt/Qt-4.6.2/include/Qt/qscriptcontextinfo.h | 0d69ce804e4bea4b8c98af9bff8dfb2b9be7dd0a | [] | no_license | darkbtf/academic-crawler | 295f3bd74b18e700402bc2be59f15694d6195471 | 5dfcb0f1b88b93aa7545ef233344a41570011532 | refs/heads/master | 2021-01-01T19:21:00.162442 | 2011-03-10T16:29:25 | 2011-03-10T16:29:25 | 42,468,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,997 | h | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtScript module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL-ONLY$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSCRIPTCONTEXTINFO_H
#define QSCRIPTCONTEXTINFO_H
#include <QtCore/qobjectdefs.h>
#include <QtCore/qlist.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qsharedpointer.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Script)
class QScriptContext;
#ifndef QT_NO_DATASTREAM
class QDataStream;
#endif
class QScriptContextInfoPrivate;
class Q_SCRIPT_EXPORT QScriptContextInfo
{
public:
#ifndef QT_NO_DATASTREAM
friend Q_SCRIPT_EXPORT QDataStream &operator<<(QDataStream &, const QScriptContextInfo &);
friend Q_SCRIPT_EXPORT QDataStream &operator>>(QDataStream &, QScriptContextInfo &);
#endif
enum FunctionType {
ScriptFunction,
QtFunction,
QtPropertyFunction,
NativeFunction
};
QScriptContextInfo(const QScriptContext *context);
QScriptContextInfo(const QScriptContextInfo &other);
QScriptContextInfo();
~QScriptContextInfo();
QScriptContextInfo &operator=(const QScriptContextInfo &other);
bool isNull() const;
qint64 scriptId() const;
QString fileName() const;
int lineNumber() const;
int columnNumber() const;
QString functionName() const;
FunctionType functionType() const;
QStringList functionParameterNames() const;
int functionStartLineNumber() const;
int functionEndLineNumber() const;
int functionMetaIndex() const;
bool operator==(const QScriptContextInfo &other) const;
bool operator!=(const QScriptContextInfo &other) const;
private:
QExplicitlySharedDataPointer<QScriptContextInfoPrivate> d_ptr;
Q_DECLARE_PRIVATE(QScriptContextInfo)
};
typedef QList<QScriptContextInfo> QScriptContextInfoList;
#ifndef QT_NO_DATASTREAM
Q_SCRIPT_EXPORT QDataStream &operator<<(QDataStream &, const QScriptContextInfo &);
Q_SCRIPT_EXPORT QDataStream &operator>>(QDataStream &, QScriptContextInfo &);
#endif
QT_END_NAMESPACE
QT_END_HEADER
#endif
| [
"ulmonkey1987@7c5ce3f8-edad-37de-be84-b98c484540b5"
] | [
[
[
1,
104
]
]
] |
104a175bb2c4cf6bd3e5a35bce116e363cc81615 | 2c5d9e1a28490dce3a19a3fd97a1a478e90f4b9a | /Artifacts/Attic/QtDSP/main.cpp | 9c3cc676fc6a284b3978c5050d6502ccc562f32b | [] | no_license | QtWorks/cp2 | 25602bb6ecb9e276e57568b5076b09a551e7eaef | 871344f4f7ee4bb9f05ed35dcfb4ba62b1555dd4 | refs/heads/master | 2021-01-11T04:06:32.283135 | 2009-10-15T16:21:17 | 2009-10-15T16:21:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | #include "qtdsp.h"
#include <qapplication.h>
#include <qstring.h>
#include <iostream>
#include <qtimer.h>
#include <qcheckbox.h>
#include <qcheckbox.h>
int main( int argc, char ** argv )
{
QApplication app( argc, argv );
// a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
// create our test dialog. It may contain a ScopePlot sometime, and
// other buttons etc.
QtDSP dsp;
// if we don't show() the test dialog, nothing appears!
dsp.show();
// This tells qt to stop running when scopeTestDialog
// closes.
app.setMainWidget(&dsp);
return app.exec();
}
| [
"martinc@e5e72e4b-7c09-0410-958a-85c34e28b278"
] | [
[
[
1,
27
]
]
] |
79308795ed8f984c99a39e06aaccc5af5080d60b | eb5e73b39b6cca6590e6c7e2a86dbce48d03e031 | /windows/libSO.cpp | f41e900cdd8d6c588dad3abea3bfde539242a811 | [] | no_license | alejopelaez/practica-operativos | 8f9381d31de6737c8539dae3e6e4cc8e6ffe8cc2 | d4b1ff82c16ce4583ffa9ca1615b39d7008e5234 | refs/heads/master | 2021-01-22T11:59:19.890999 | 2010-11-28T21:06:42 | 2010-11-28T21:06:42 | 1,095,087 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,102 | cpp | #define _WIN32_WINNT 0x0501
#ifdef BUILDING_DLL
#define DLLIMPORT __declspec (dllexport)
#else
# define DLLIMPORT __declspec (dllimport)
#endif
#include <windows.h>
#include <winbase.h>
#include <psapi.h>
#ifdef __cplusplus
extern "C" {
#endif
ULARGE_INTEGER lasti, lastk, lastu;
DLLIMPORT int *GetProcessList(int *nroProcesos){
DWORD *processes = new DWORD[1024];
DWORD pBytesReturned;
EnumProcesses(processes, DWORD(1024), &pBytesReturned);
*nroProcesos = (int)(pBytesReturned/sizeof(DWORD));
//Conversión from DWORD to int
int *ans = new int[*nroProcesos];
for(int i = 0; i < *nroProcesos; ++i)
ans[i] = (int)processes[i];
return ans;
}
DLLIMPORT float CpuUsage(){
FILETIME i, k, u;
GetSystemTimes(&i, &k, &u);
//Que horrible esto :S, mas casteos pa donde
ULARGE_INTEGER ut, kt, it;
ULONGLONG du, dk, di;
ut.LowPart = u.dwLowDateTime;
ut.HighPart = u.dwHighDateTime;
kt.LowPart = k.dwLowDateTime;
kt.HighPart = k.dwHighDateTime;
it.LowPart = i.dwLowDateTime;
it.HighPart = i.dwHighDateTime;
du = ut.QuadPart-lastu.QuadPart;
dk = kt.QuadPart-lastk.QuadPart;
di = it.QuadPart-lasti.QuadPart;
lasti = it, lastu = ut, lastk = kt;
return float((float)(du+dk)/(float)(du+dk+di));
}
BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ ,
DWORD reason /* Reason this function is being called. */ ,
LPVOID reserved /* Not used. */ )
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
/* Returns TRUE on success, FALSE on failure */
return TRUE;
}
#ifdef __cplusplus
}
#endif
| [
"[email protected]"
] | [
[
[
1,
80
]
]
] |
6ed5eeb23dabdb502ac62c98b3c5a31d0abe1a20 | eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5 | /WinEditionWithJRE/browser-lcc/jscc/src/v8/v8/src/x64/lithium-x64.h | 7c18533c318b7d74283013e26ea6e26fbfba49b0 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"Artistic-1.0",
"LicenseRef-scancode-public-domain",
"Artistic-2.0"
] | permissive | baxtree/OKBuzzer | c46c7f271a26be13adcf874d77a7a6762a8dc6be | a16e2baad145f5c65052cdc7c767e78cdfee1181 | refs/heads/master | 2021-01-02T22:17:34.168564 | 2011-06-15T02:29:56 | 2011-06-15T02:29:56 | 1,790,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,021 | h | // Copyright 2011 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_X64_LITHIUM_X64_H_
#define V8_X64_LITHIUM_X64_H_
#include "hydrogen.h"
#include "lithium-allocator.h"
#include "lithium.h"
#include "safepoint-table.h"
namespace v8 {
namespace internal {
// Forward declarations.
class LCodeGen;
#define LITHIUM_ALL_INSTRUCTION_LIST(V) \
V(ControlInstruction) \
V(Call) \
LITHIUM_CONCRETE_INSTRUCTION_LIST(V)
#define LITHIUM_CONCRETE_INSTRUCTION_LIST(V) \
V(AccessArgumentsAt) \
V(AddI) \
V(ApplyArguments) \
V(ArgumentsElements) \
V(ArgumentsLength) \
V(ArithmeticD) \
V(ArithmeticT) \
V(ArrayLiteral) \
V(BitI) \
V(BitNotI) \
V(BoundsCheck) \
V(Branch) \
V(CallConstantFunction) \
V(CallFunction) \
V(CallGlobal) \
V(CallKeyed) \
V(CallKnownGlobal) \
V(CallNamed) \
V(CallNew) \
V(CallRuntime) \
V(CallStub) \
V(CheckFunction) \
V(CheckInstanceType) \
V(CheckMap) \
V(CheckNonSmi) \
V(CheckPrototypeMaps) \
V(CheckSmi) \
V(ClassOfTest) \
V(ClassOfTestAndBranch) \
V(CmpID) \
V(CmpIDAndBranch) \
V(CmpJSObjectEq) \
V(CmpJSObjectEqAndBranch) \
V(CmpMapAndBranch) \
V(CmpT) \
V(CmpTAndBranch) \
V(ConstantD) \
V(ConstantI) \
V(ConstantT) \
V(Context) \
V(DeleteProperty) \
V(Deoptimize) \
V(DivI) \
V(DoubleToI) \
V(ExternalArrayLength) \
V(FixedArrayLength) \
V(FunctionLiteral) \
V(GetCachedArrayIndex) \
V(GlobalObject) \
V(GlobalReceiver) \
V(Goto) \
V(HasCachedArrayIndex) \
V(HasCachedArrayIndexAndBranch) \
V(HasInstanceType) \
V(HasInstanceTypeAndBranch) \
V(In) \
V(InstanceOf) \
V(InstanceOfAndBranch) \
V(InstanceOfKnownGlobal) \
V(InstructionGap) \
V(Integer32ToDouble) \
V(InvokeFunction) \
V(IsNull) \
V(IsNullAndBranch) \
V(IsObject) \
V(IsObjectAndBranch) \
V(IsSmi) \
V(IsSmiAndBranch) \
V(JSArrayLength) \
V(Label) \
V(LazyBailout) \
V(LoadContextSlot) \
V(LoadElements) \
V(LoadExternalArrayPointer) \
V(LoadGlobalCell) \
V(LoadGlobalGeneric) \
V(LoadKeyedFastElement) \
V(LoadKeyedGeneric) \
V(LoadKeyedSpecializedArrayElement) \
V(LoadNamedField) \
V(LoadNamedFieldPolymorphic) \
V(LoadNamedGeneric) \
V(LoadFunctionPrototype) \
V(ModI) \
V(MulI) \
V(NumberTagD) \
V(NumberTagI) \
V(NumberUntagD) \
V(ObjectLiteral) \
V(OsrEntry) \
V(OuterContext) \
V(Parameter) \
V(Power) \
V(PushArgument) \
V(RegExpLiteral) \
V(Return) \
V(ShiftI) \
V(SmiTag) \
V(SmiUntag) \
V(StackCheck) \
V(StoreContextSlot) \
V(StoreGlobalCell) \
V(StoreGlobalGeneric) \
V(StoreKeyedFastElement) \
V(StoreKeyedGeneric) \
V(StoreKeyedSpecializedArrayElement) \
V(StoreNamedField) \
V(StoreNamedGeneric) \
V(StringAdd) \
V(StringCharCodeAt) \
V(StringCharFromCode) \
V(StringLength) \
V(SubI) \
V(TaggedToI) \
V(ToFastProperties) \
V(Throw) \
V(Typeof) \
V(TypeofIs) \
V(TypeofIsAndBranch) \
V(IsConstructCall) \
V(IsConstructCallAndBranch) \
V(UnaryMathOperation) \
V(UnknownOSRValue) \
V(ValueOf)
#define DECLARE_CONCRETE_INSTRUCTION(type, mnemonic) \
virtual Opcode opcode() const { return LInstruction::k##type; } \
virtual void CompileToNative(LCodeGen* generator); \
virtual const char* Mnemonic() const { return mnemonic; } \
static L##type* cast(LInstruction* instr) { \
ASSERT(instr->Is##type()); \
return reinterpret_cast<L##type*>(instr); \
}
#define DECLARE_HYDROGEN_ACCESSOR(type) \
H##type* hydrogen() const { \
return H##type::cast(hydrogen_value()); \
}
class LInstruction: public ZoneObject {
public:
LInstruction()
: environment_(NULL),
hydrogen_value_(NULL),
is_call_(false),
is_save_doubles_(false) { }
virtual ~LInstruction() { }
virtual void CompileToNative(LCodeGen* generator) = 0;
virtual const char* Mnemonic() const = 0;
virtual void PrintTo(StringStream* stream);
virtual void PrintDataTo(StringStream* stream) = 0;
virtual void PrintOutputOperandTo(StringStream* stream) = 0;
enum Opcode {
// Declare a unique enum value for each instruction.
#define DECLARE_OPCODE(type) k##type,
LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_OPCODE)
kNumberOfInstructions
#undef DECLARE_OPCODE
};
virtual Opcode opcode() const = 0;
// Declare non-virtual type testers for all leaf IR classes.
#define DECLARE_PREDICATE(type) \
bool Is##type() const { return opcode() == k##type; }
LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_PREDICATE)
#undef DECLARE_PREDICATE
// Declare virtual predicates for instructions that don't have
// an opcode.
virtual bool IsGap() const { return false; }
virtual bool IsControl() const { return false; }
virtual void SetBranchTargets(int true_block_id, int false_block_id) { }
void set_environment(LEnvironment* env) { environment_ = env; }
LEnvironment* environment() const { return environment_; }
bool HasEnvironment() const { return environment_ != NULL; }
void set_pointer_map(LPointerMap* p) { pointer_map_.set(p); }
LPointerMap* pointer_map() const { return pointer_map_.get(); }
bool HasPointerMap() const { return pointer_map_.is_set(); }
void set_hydrogen_value(HValue* value) { hydrogen_value_ = value; }
HValue* hydrogen_value() const { return hydrogen_value_; }
void set_deoptimization_environment(LEnvironment* env) {
deoptimization_environment_.set(env);
}
LEnvironment* deoptimization_environment() const {
return deoptimization_environment_.get();
}
bool HasDeoptimizationEnvironment() const {
return deoptimization_environment_.is_set();
}
void MarkAsCall() { is_call_ = true; }
void MarkAsSaveDoubles() { is_save_doubles_ = true; }
// Interface to the register allocator and iterators.
bool IsMarkedAsCall() const { return is_call_; }
bool IsMarkedAsSaveDoubles() const { return is_save_doubles_; }
virtual bool HasResult() const = 0;
virtual LOperand* result() = 0;
virtual int InputCount() = 0;
virtual LOperand* InputAt(int i) = 0;
virtual int TempCount() = 0;
virtual LOperand* TempAt(int i) = 0;
LOperand* FirstInput() { return InputAt(0); }
LOperand* Output() { return HasResult() ? result() : NULL; }
#ifdef DEBUG
void VerifyCall();
#endif
private:
LEnvironment* environment_;
SetOncePointer<LPointerMap> pointer_map_;
HValue* hydrogen_value_;
SetOncePointer<LEnvironment> deoptimization_environment_;
bool is_call_;
bool is_save_doubles_;
};
template<typename ElementType, int NumElements>
class OperandContainer {
public:
OperandContainer() {
for (int i = 0; i < NumElements; i++) elems_[i] = NULL;
}
int length() { return NumElements; }
ElementType& operator[](int i) {
ASSERT(i < length());
return elems_[i];
}
void PrintOperandsTo(StringStream* stream);
private:
ElementType elems_[NumElements];
};
template<typename ElementType>
class OperandContainer<ElementType, 0> {
public:
int length() { return 0; }
void PrintOperandsTo(StringStream* stream) { }
ElementType& operator[](int i) {
UNREACHABLE();
static ElementType t = 0;
return t;
}
};
// R = number of result operands (0 or 1).
// I = number of input operands.
// T = number of temporary operands.
template<int R, int I, int T>
class LTemplateInstruction: public LInstruction {
public:
// Allow 0 or 1 output operands.
STATIC_ASSERT(R == 0 || R == 1);
virtual bool HasResult() const { return R != 0; }
void set_result(LOperand* operand) { results_[0] = operand; }
LOperand* result() { return results_[0]; }
int InputCount() { return I; }
LOperand* InputAt(int i) { return inputs_[i]; }
int TempCount() { return T; }
LOperand* TempAt(int i) { return temps_[i]; }
virtual void PrintDataTo(StringStream* stream);
virtual void PrintOutputOperandTo(StringStream* stream);
protected:
OperandContainer<LOperand*, R> results_;
OperandContainer<LOperand*, I> inputs_;
OperandContainer<LOperand*, T> temps_;
};
class LGap: public LTemplateInstruction<0, 0, 0> {
public:
explicit LGap(HBasicBlock* block)
: block_(block) {
parallel_moves_[BEFORE] = NULL;
parallel_moves_[START] = NULL;
parallel_moves_[END] = NULL;
parallel_moves_[AFTER] = NULL;
}
// Can't use the DECLARE-macro here because of sub-classes.
virtual bool IsGap() const { return true; }
virtual void PrintDataTo(StringStream* stream);
static LGap* cast(LInstruction* instr) {
ASSERT(instr->IsGap());
return reinterpret_cast<LGap*>(instr);
}
bool IsRedundant() const;
HBasicBlock* block() const { return block_; }
enum InnerPosition {
BEFORE,
START,
END,
AFTER,
FIRST_INNER_POSITION = BEFORE,
LAST_INNER_POSITION = AFTER
};
LParallelMove* GetOrCreateParallelMove(InnerPosition pos) {
if (parallel_moves_[pos] == NULL) parallel_moves_[pos] = new LParallelMove;
return parallel_moves_[pos];
}
LParallelMove* GetParallelMove(InnerPosition pos) {
return parallel_moves_[pos];
}
private:
LParallelMove* parallel_moves_[LAST_INNER_POSITION + 1];
HBasicBlock* block_;
};
class LInstructionGap: public LGap {
public:
explicit LInstructionGap(HBasicBlock* block) : LGap(block) { }
DECLARE_CONCRETE_INSTRUCTION(InstructionGap, "gap")
};
class LGoto: public LTemplateInstruction<0, 0, 0> {
public:
LGoto(int block_id, bool include_stack_check = false)
: block_id_(block_id), include_stack_check_(include_stack_check) { }
DECLARE_CONCRETE_INSTRUCTION(Goto, "goto")
virtual void PrintDataTo(StringStream* stream);
virtual bool IsControl() const { return true; }
int block_id() const { return block_id_; }
bool include_stack_check() const { return include_stack_check_; }
private:
int block_id_;
bool include_stack_check_;
};
class LLazyBailout: public LTemplateInstruction<0, 0, 0> {
public:
LLazyBailout() : gap_instructions_size_(0) { }
DECLARE_CONCRETE_INSTRUCTION(LazyBailout, "lazy-bailout")
void set_gap_instructions_size(int gap_instructions_size) {
gap_instructions_size_ = gap_instructions_size;
}
int gap_instructions_size() { return gap_instructions_size_; }
private:
int gap_instructions_size_;
};
class LDeoptimize: public LTemplateInstruction<0, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(Deoptimize, "deoptimize")
};
class LLabel: public LGap {
public:
explicit LLabel(HBasicBlock* block)
: LGap(block), replacement_(NULL) { }
DECLARE_CONCRETE_INSTRUCTION(Label, "label")
virtual void PrintDataTo(StringStream* stream);
int block_id() const { return block()->block_id(); }
bool is_loop_header() const { return block()->IsLoopHeader(); }
Label* label() { return &label_; }
LLabel* replacement() const { return replacement_; }
void set_replacement(LLabel* label) { replacement_ = label; }
bool HasReplacement() const { return replacement_ != NULL; }
private:
Label label_;
LLabel* replacement_;
};
class LParameter: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(Parameter, "parameter")
};
class LCallStub: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallStub, "call-stub")
DECLARE_HYDROGEN_ACCESSOR(CallStub)
TranscendentalCache::Type transcendental_type() {
return hydrogen()->transcendental_type();
}
};
class LUnknownOSRValue: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(UnknownOSRValue, "unknown-osr-value")
};
template<int I, int T>
class LControlInstruction: public LTemplateInstruction<0, I, T> {
public:
virtual bool IsControl() const { return true; }
int true_block_id() const { return true_block_id_; }
int false_block_id() const { return false_block_id_; }
void SetBranchTargets(int true_block_id, int false_block_id) {
true_block_id_ = true_block_id;
false_block_id_ = false_block_id;
}
private:
int true_block_id_;
int false_block_id_;
};
class LApplyArguments: public LTemplateInstruction<1, 4, 0> {
public:
LApplyArguments(LOperand* function,
LOperand* receiver,
LOperand* length,
LOperand* elements) {
inputs_[0] = function;
inputs_[1] = receiver;
inputs_[2] = length;
inputs_[3] = elements;
}
DECLARE_CONCRETE_INSTRUCTION(ApplyArguments, "apply-arguments")
LOperand* function() { return inputs_[0]; }
LOperand* receiver() { return inputs_[1]; }
LOperand* length() { return inputs_[2]; }
LOperand* elements() { return inputs_[3]; }
};
class LAccessArgumentsAt: public LTemplateInstruction<1, 3, 0> {
public:
LAccessArgumentsAt(LOperand* arguments, LOperand* length, LOperand* index) {
inputs_[0] = arguments;
inputs_[1] = length;
inputs_[2] = index;
}
DECLARE_CONCRETE_INSTRUCTION(AccessArgumentsAt, "access-arguments-at")
LOperand* arguments() { return inputs_[0]; }
LOperand* length() { return inputs_[1]; }
LOperand* index() { return inputs_[2]; }
virtual void PrintDataTo(StringStream* stream);
};
class LArgumentsLength: public LTemplateInstruction<1, 1, 0> {
public:
explicit LArgumentsLength(LOperand* elements) {
inputs_[0] = elements;
}
DECLARE_CONCRETE_INSTRUCTION(ArgumentsLength, "arguments-length")
};
class LArgumentsElements: public LTemplateInstruction<1, 0, 0> {
public:
LArgumentsElements() { }
DECLARE_CONCRETE_INSTRUCTION(ArgumentsElements, "arguments-elements")
};
class LModI: public LTemplateInstruction<1, 2, 1> {
public:
LModI(LOperand* left, LOperand* right, LOperand* temp) {
inputs_[0] = left;
inputs_[1] = right;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(ModI, "mod-i")
DECLARE_HYDROGEN_ACCESSOR(Mod)
};
class LDivI: public LTemplateInstruction<1, 2, 1> {
public:
LDivI(LOperand* left, LOperand* right, LOperand* temp) {
inputs_[0] = left;
inputs_[1] = right;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(DivI, "div-i")
DECLARE_HYDROGEN_ACCESSOR(Div)
};
class LMulI: public LTemplateInstruction<1, 2, 0> {
public:
LMulI(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(MulI, "mul-i")
DECLARE_HYDROGEN_ACCESSOR(Mul)
};
class LCmpID: public LTemplateInstruction<1, 2, 0> {
public:
LCmpID(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpID, "cmp-id")
DECLARE_HYDROGEN_ACCESSOR(Compare)
Token::Value op() const { return hydrogen()->token(); }
bool is_double() const {
return hydrogen()->GetInputRepresentation().IsDouble();
}
};
class LCmpIDAndBranch: public LControlInstruction<2, 0> {
public:
LCmpIDAndBranch(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpIDAndBranch, "cmp-id-and-branch")
DECLARE_HYDROGEN_ACCESSOR(Compare)
Token::Value op() const { return hydrogen()->token(); }
bool is_double() const {
return hydrogen()->GetInputRepresentation().IsDouble();
}
virtual void PrintDataTo(StringStream* stream);
};
class LUnaryMathOperation: public LTemplateInstruction<1, 1, 0> {
public:
explicit LUnaryMathOperation(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(UnaryMathOperation, "unary-math-operation")
DECLARE_HYDROGEN_ACCESSOR(UnaryMathOperation)
virtual void PrintDataTo(StringStream* stream);
BuiltinFunctionId op() const { return hydrogen()->op(); }
};
class LCmpJSObjectEq: public LTemplateInstruction<1, 2, 0> {
public:
LCmpJSObjectEq(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpJSObjectEq, "cmp-jsobject-eq")
};
class LCmpJSObjectEqAndBranch: public LControlInstruction<2, 0> {
public:
LCmpJSObjectEqAndBranch(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpJSObjectEqAndBranch,
"cmp-jsobject-eq-and-branch")
};
class LIsNull: public LTemplateInstruction<1, 1, 0> {
public:
explicit LIsNull(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(IsNull, "is-null")
DECLARE_HYDROGEN_ACCESSOR(IsNull)
bool is_strict() const { return hydrogen()->is_strict(); }
};
class LIsNullAndBranch: public LControlInstruction<1, 1> {
public:
LIsNullAndBranch(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(IsNullAndBranch, "is-null-and-branch")
DECLARE_HYDROGEN_ACCESSOR(IsNull)
bool is_strict() const { return hydrogen()->is_strict(); }
virtual void PrintDataTo(StringStream* stream);
};
class LIsObject: public LTemplateInstruction<1, 1, 0> {
public:
explicit LIsObject(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(IsObject, "is-object")
};
class LIsObjectAndBranch: public LControlInstruction<1, 0> {
public:
explicit LIsObjectAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(IsObjectAndBranch, "is-object-and-branch")
virtual void PrintDataTo(StringStream* stream);
};
class LIsSmi: public LTemplateInstruction<1, 1, 0> {
public:
explicit LIsSmi(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(IsSmi, "is-smi")
DECLARE_HYDROGEN_ACCESSOR(IsSmi)
};
class LIsSmiAndBranch: public LControlInstruction<1, 0> {
public:
explicit LIsSmiAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(IsSmiAndBranch, "is-smi-and-branch")
virtual void PrintDataTo(StringStream* stream);
};
class LHasInstanceType: public LTemplateInstruction<1, 1, 0> {
public:
explicit LHasInstanceType(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(HasInstanceType, "has-instance-type")
DECLARE_HYDROGEN_ACCESSOR(HasInstanceType)
};
class LHasInstanceTypeAndBranch: public LControlInstruction<1, 0> {
public:
explicit LHasInstanceTypeAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(HasInstanceTypeAndBranch,
"has-instance-type-and-branch")
DECLARE_HYDROGEN_ACCESSOR(HasInstanceType)
virtual void PrintDataTo(StringStream* stream);
};
class LGetCachedArrayIndex: public LTemplateInstruction<1, 1, 0> {
public:
explicit LGetCachedArrayIndex(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(GetCachedArrayIndex, "get-cached-array-index")
DECLARE_HYDROGEN_ACCESSOR(GetCachedArrayIndex)
};
class LHasCachedArrayIndex: public LTemplateInstruction<1, 1, 0> {
public:
explicit LHasCachedArrayIndex(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(HasCachedArrayIndex, "has-cached-array-index")
DECLARE_HYDROGEN_ACCESSOR(HasCachedArrayIndex)
};
class LHasCachedArrayIndexAndBranch: public LControlInstruction<1, 0> {
public:
explicit LHasCachedArrayIndexAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(HasCachedArrayIndexAndBranch,
"has-cached-array-index-and-branch")
virtual void PrintDataTo(StringStream* stream);
};
class LClassOfTest: public LTemplateInstruction<1, 1, 1> {
public:
LClassOfTest(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(ClassOfTest, "class-of-test")
DECLARE_HYDROGEN_ACCESSOR(ClassOfTest)
virtual void PrintDataTo(StringStream* stream);
};
class LClassOfTestAndBranch: public LControlInstruction<1, 1> {
public:
LClassOfTestAndBranch(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(ClassOfTestAndBranch,
"class-of-test-and-branch")
DECLARE_HYDROGEN_ACCESSOR(ClassOfTest)
virtual void PrintDataTo(StringStream* stream);
};
class LCmpT: public LTemplateInstruction<1, 2, 0> {
public:
LCmpT(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpT, "cmp-t")
DECLARE_HYDROGEN_ACCESSOR(Compare)
Token::Value op() const { return hydrogen()->token(); }
};
class LCmpTAndBranch: public LControlInstruction<2, 0> {
public:
LCmpTAndBranch(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(CmpTAndBranch, "cmp-t-and-branch")
DECLARE_HYDROGEN_ACCESSOR(Compare)
Token::Value op() const { return hydrogen()->token(); }
};
class LIn: public LTemplateInstruction<1, 2, 0> {
public:
LIn(LOperand* key, LOperand* object) {
inputs_[0] = key;
inputs_[1] = object;
}
LOperand* key() { return inputs_[0]; }
LOperand* object() { return inputs_[1]; }
DECLARE_CONCRETE_INSTRUCTION(In, "in")
};
class LInstanceOf: public LTemplateInstruction<1, 2, 0> {
public:
LInstanceOf(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(InstanceOf, "instance-of")
};
class LInstanceOfAndBranch: public LControlInstruction<2, 0> {
public:
LInstanceOfAndBranch(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(InstanceOfAndBranch, "instance-of-and-branch")
};
class LInstanceOfKnownGlobal: public LTemplateInstruction<1, 1, 1> {
public:
LInstanceOfKnownGlobal(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(InstanceOfKnownGlobal,
"instance-of-known-global")
DECLARE_HYDROGEN_ACCESSOR(InstanceOfKnownGlobal)
Handle<JSFunction> function() const { return hydrogen()->function(); }
};
class LBoundsCheck: public LTemplateInstruction<0, 2, 0> {
public:
LBoundsCheck(LOperand* index, LOperand* length) {
inputs_[0] = index;
inputs_[1] = length;
}
LOperand* index() { return inputs_[0]; }
LOperand* length() { return inputs_[1]; }
DECLARE_CONCRETE_INSTRUCTION(BoundsCheck, "bounds-check")
};
class LBitI: public LTemplateInstruction<1, 2, 0> {
public:
LBitI(Token::Value op, LOperand* left, LOperand* right)
: op_(op) {
inputs_[0] = left;
inputs_[1] = right;
}
Token::Value op() const { return op_; }
DECLARE_CONCRETE_INSTRUCTION(BitI, "bit-i")
private:
Token::Value op_;
};
class LShiftI: public LTemplateInstruction<1, 2, 0> {
public:
LShiftI(Token::Value op, LOperand* left, LOperand* right, bool can_deopt)
: op_(op), can_deopt_(can_deopt) {
inputs_[0] = left;
inputs_[1] = right;
}
Token::Value op() const { return op_; }
bool can_deopt() const { return can_deopt_; }
DECLARE_CONCRETE_INSTRUCTION(ShiftI, "shift-i")
private:
Token::Value op_;
bool can_deopt_;
};
class LSubI: public LTemplateInstruction<1, 2, 0> {
public:
LSubI(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(SubI, "sub-i")
DECLARE_HYDROGEN_ACCESSOR(Sub)
};
class LConstantI: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(ConstantI, "constant-i")
DECLARE_HYDROGEN_ACCESSOR(Constant)
int32_t value() const { return hydrogen()->Integer32Value(); }
};
class LConstantD: public LTemplateInstruction<1, 0, 1> {
public:
explicit LConstantD(LOperand* temp) {
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(ConstantD, "constant-d")
DECLARE_HYDROGEN_ACCESSOR(Constant)
double value() const { return hydrogen()->DoubleValue(); }
};
class LConstantT: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(ConstantT, "constant-t")
DECLARE_HYDROGEN_ACCESSOR(Constant)
Handle<Object> value() const { return hydrogen()->handle(); }
};
class LBranch: public LControlInstruction<1, 0> {
public:
explicit LBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(Branch, "branch")
DECLARE_HYDROGEN_ACCESSOR(Value)
virtual void PrintDataTo(StringStream* stream);
};
class LCmpMapAndBranch: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCmpMapAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CmpMapAndBranch, "cmp-map-and-branch")
DECLARE_HYDROGEN_ACCESSOR(CompareMap)
virtual bool IsControl() const { return true; }
Handle<Map> map() const { return hydrogen()->map(); }
int true_block_id() const {
return hydrogen()->FirstSuccessor()->block_id();
}
int false_block_id() const {
return hydrogen()->SecondSuccessor()->block_id();
}
};
class LJSArrayLength: public LTemplateInstruction<1, 1, 0> {
public:
explicit LJSArrayLength(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(JSArrayLength, "js-array-length")
DECLARE_HYDROGEN_ACCESSOR(JSArrayLength)
};
class LExternalArrayLength: public LTemplateInstruction<1, 1, 0> {
public:
explicit LExternalArrayLength(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(ExternalArrayLength, "external-array-length")
DECLARE_HYDROGEN_ACCESSOR(ExternalArrayLength)
};
class LFixedArrayLength: public LTemplateInstruction<1, 1, 0> {
public:
explicit LFixedArrayLength(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(FixedArrayLength, "fixed-array-length")
DECLARE_HYDROGEN_ACCESSOR(FixedArrayLength)
};
class LValueOf: public LTemplateInstruction<1, 1, 0> {
public:
explicit LValueOf(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(ValueOf, "value-of")
DECLARE_HYDROGEN_ACCESSOR(ValueOf)
};
class LThrow: public LTemplateInstruction<0, 1, 0> {
public:
explicit LThrow(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(Throw, "throw")
};
class LBitNotI: public LTemplateInstruction<1, 1, 0> {
public:
explicit LBitNotI(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(BitNotI, "bit-not-i")
};
class LAddI: public LTemplateInstruction<1, 2, 0> {
public:
LAddI(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(AddI, "add-i")
DECLARE_HYDROGEN_ACCESSOR(Add)
};
class LPower: public LTemplateInstruction<1, 2, 0> {
public:
LPower(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(Power, "power")
DECLARE_HYDROGEN_ACCESSOR(Power)
};
class LArithmeticD: public LTemplateInstruction<1, 2, 0> {
public:
LArithmeticD(Token::Value op, LOperand* left, LOperand* right)
: op_(op) {
inputs_[0] = left;
inputs_[1] = right;
}
Token::Value op() const { return op_; }
virtual Opcode opcode() const { return LInstruction::kArithmeticD; }
virtual void CompileToNative(LCodeGen* generator);
virtual const char* Mnemonic() const;
private:
Token::Value op_;
};
class LArithmeticT: public LTemplateInstruction<1, 2, 0> {
public:
LArithmeticT(Token::Value op, LOperand* left, LOperand* right)
: op_(op) {
inputs_[0] = left;
inputs_[1] = right;
}
virtual Opcode opcode() const { return LInstruction::kArithmeticT; }
virtual void CompileToNative(LCodeGen* generator);
virtual const char* Mnemonic() const;
Token::Value op() const { return op_; }
private:
Token::Value op_;
};
class LReturn: public LTemplateInstruction<0, 1, 0> {
public:
explicit LReturn(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(Return, "return")
};
class LLoadNamedField: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadNamedField(LOperand* object) {
inputs_[0] = object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadNamedField, "load-named-field")
DECLARE_HYDROGEN_ACCESSOR(LoadNamedField)
};
class LLoadNamedFieldPolymorphic: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadNamedFieldPolymorphic(LOperand* object) {
inputs_[0] = object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadNamedField, "load-named-field-polymorphic")
DECLARE_HYDROGEN_ACCESSOR(LoadNamedFieldPolymorphic)
LOperand* object() { return inputs_[0]; }
};
class LLoadNamedGeneric: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadNamedGeneric(LOperand* object) {
inputs_[0] = object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadNamedGeneric, "load-named-generic")
DECLARE_HYDROGEN_ACCESSOR(LoadNamedGeneric)
LOperand* object() { return inputs_[0]; }
Handle<Object> name() const { return hydrogen()->name(); }
};
class LLoadFunctionPrototype: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadFunctionPrototype(LOperand* function) {
inputs_[0] = function;
}
DECLARE_CONCRETE_INSTRUCTION(LoadFunctionPrototype, "load-function-prototype")
DECLARE_HYDROGEN_ACCESSOR(LoadFunctionPrototype)
LOperand* function() { return inputs_[0]; }
};
class LLoadElements: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadElements(LOperand* object) {
inputs_[0] = object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadElements, "load-elements")
};
class LLoadExternalArrayPointer: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadExternalArrayPointer(LOperand* object) {
inputs_[0] = object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadExternalArrayPointer,
"load-external-array-pointer")
};
class LLoadKeyedFastElement: public LTemplateInstruction<1, 2, 0> {
public:
LLoadKeyedFastElement(LOperand* elements, LOperand* key) {
inputs_[0] = elements;
inputs_[1] = key;
}
DECLARE_CONCRETE_INSTRUCTION(LoadKeyedFastElement, "load-keyed-fast-element")
DECLARE_HYDROGEN_ACCESSOR(LoadKeyedFastElement)
LOperand* elements() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
};
class LLoadKeyedSpecializedArrayElement: public LTemplateInstruction<1, 2, 0> {
public:
LLoadKeyedSpecializedArrayElement(LOperand* external_pointer,
LOperand* key) {
inputs_[0] = external_pointer;
inputs_[1] = key;
}
DECLARE_CONCRETE_INSTRUCTION(LoadKeyedSpecializedArrayElement,
"load-keyed-specialized-array-element")
DECLARE_HYDROGEN_ACCESSOR(LoadKeyedSpecializedArrayElement)
LOperand* external_pointer() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
ExternalArrayType array_type() const {
return hydrogen()->array_type();
}
};
class LLoadKeyedGeneric: public LTemplateInstruction<1, 2, 0> {
public:
LLoadKeyedGeneric(LOperand* obj, LOperand* key) {
inputs_[0] = obj;
inputs_[1] = key;
}
DECLARE_CONCRETE_INSTRUCTION(LoadKeyedGeneric, "load-keyed-generic")
LOperand* object() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
};
class LLoadGlobalCell: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(LoadGlobalCell, "load-global-cell")
DECLARE_HYDROGEN_ACCESSOR(LoadGlobalCell)
};
class LLoadGlobalGeneric: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadGlobalGeneric(LOperand* global_object) {
inputs_[0] = global_object;
}
DECLARE_CONCRETE_INSTRUCTION(LoadGlobalGeneric, "load-global-generic")
DECLARE_HYDROGEN_ACCESSOR(LoadGlobalGeneric)
LOperand* global_object() { return inputs_[0]; }
Handle<Object> name() const { return hydrogen()->name(); }
bool for_typeof() const { return hydrogen()->for_typeof(); }
};
class LStoreGlobalCell: public LTemplateInstruction<0, 1, 1> {
public:
explicit LStoreGlobalCell(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(StoreGlobalCell, "store-global-cell")
DECLARE_HYDROGEN_ACCESSOR(StoreGlobalCell)
};
class LStoreGlobalGeneric: public LTemplateInstruction<0, 2, 0> {
public:
explicit LStoreGlobalGeneric(LOperand* global_object,
LOperand* value) {
inputs_[0] = global_object;
inputs_[1] = value;
}
DECLARE_CONCRETE_INSTRUCTION(StoreGlobalGeneric, "store-global-generic")
DECLARE_HYDROGEN_ACCESSOR(StoreGlobalGeneric)
LOperand* global_object() { return InputAt(0); }
Handle<Object> name() const { return hydrogen()->name(); }
LOperand* value() { return InputAt(1); }
bool strict_mode() { return hydrogen()->strict_mode(); }
};
class LLoadContextSlot: public LTemplateInstruction<1, 1, 0> {
public:
explicit LLoadContextSlot(LOperand* context) {
inputs_[0] = context;
}
DECLARE_CONCRETE_INSTRUCTION(LoadContextSlot, "load-context-slot")
DECLARE_HYDROGEN_ACCESSOR(LoadContextSlot)
LOperand* context() { return InputAt(0); }
int slot_index() { return hydrogen()->slot_index(); }
virtual void PrintDataTo(StringStream* stream);
};
class LStoreContextSlot: public LTemplateInstruction<0, 2, 1> {
public:
LStoreContextSlot(LOperand* context, LOperand* value, LOperand* temp) {
inputs_[0] = context;
inputs_[1] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(StoreContextSlot, "store-context-slot")
DECLARE_HYDROGEN_ACCESSOR(StoreContextSlot)
LOperand* context() { return InputAt(0); }
LOperand* value() { return InputAt(1); }
int slot_index() { return hydrogen()->slot_index(); }
int needs_write_barrier() { return hydrogen()->NeedsWriteBarrier(); }
virtual void PrintDataTo(StringStream* stream);
};
class LPushArgument: public LTemplateInstruction<0, 1, 0> {
public:
explicit LPushArgument(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(PushArgument, "push-argument")
};
class LContext: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(Context, "context")
};
class LOuterContext: public LTemplateInstruction<1, 1, 0> {
public:
explicit LOuterContext(LOperand* context) {
inputs_[0] = context;
}
DECLARE_CONCRETE_INSTRUCTION(OuterContext, "outer-context")
LOperand* context() { return InputAt(0); }
};
class LGlobalObject: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(GlobalObject, "global-object")
};
class LGlobalReceiver: public LTemplateInstruction<1, 1, 0> {
public:
explicit LGlobalReceiver(LOperand* global_object) {
inputs_[0] = global_object;
}
DECLARE_CONCRETE_INSTRUCTION(GlobalReceiver, "global-receiver")
LOperand* global() { return InputAt(0); }
};
class LCallConstantFunction: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallConstantFunction, "call-constant-function")
DECLARE_HYDROGEN_ACCESSOR(CallConstantFunction)
virtual void PrintDataTo(StringStream* stream);
Handle<JSFunction> function() { return hydrogen()->function(); }
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LInvokeFunction: public LTemplateInstruction<1, 1, 0> {
public:
explicit LInvokeFunction(LOperand* function) {
inputs_[0] = function;
}
DECLARE_CONCRETE_INSTRUCTION(InvokeFunction, "invoke-function")
DECLARE_HYDROGEN_ACCESSOR(InvokeFunction)
LOperand* function() { return inputs_[0]; }
virtual void PrintDataTo(StringStream* stream);
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallKeyed: public LTemplateInstruction<1, 1, 0> {
public:
explicit LCallKeyed(LOperand* key) {
inputs_[0] = key;
}
DECLARE_CONCRETE_INSTRUCTION(CallKeyed, "call-keyed")
DECLARE_HYDROGEN_ACCESSOR(CallKeyed)
LOperand* key() { return inputs_[0]; }
virtual void PrintDataTo(StringStream* stream);
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallNamed: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallNamed, "call-named")
DECLARE_HYDROGEN_ACCESSOR(CallNamed)
virtual void PrintDataTo(StringStream* stream);
Handle<String> name() const { return hydrogen()->name(); }
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallFunction: public LTemplateInstruction<1, 0, 0> {
public:
LCallFunction() {}
DECLARE_CONCRETE_INSTRUCTION(CallFunction, "call-function")
DECLARE_HYDROGEN_ACCESSOR(CallFunction)
int arity() const { return hydrogen()->argument_count() - 2; }
};
class LCallGlobal: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallGlobal, "call-global")
DECLARE_HYDROGEN_ACCESSOR(CallGlobal)
virtual void PrintDataTo(StringStream* stream);
Handle<String> name() const {return hydrogen()->name(); }
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallKnownGlobal: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallKnownGlobal, "call-known-global")
DECLARE_HYDROGEN_ACCESSOR(CallKnownGlobal)
virtual void PrintDataTo(StringStream* stream);
Handle<JSFunction> target() const { return hydrogen()->target(); }
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallNew: public LTemplateInstruction<1, 1, 0> {
public:
explicit LCallNew(LOperand* constructor) {
inputs_[0] = constructor;
}
DECLARE_CONCRETE_INSTRUCTION(CallNew, "call-new")
DECLARE_HYDROGEN_ACCESSOR(CallNew)
virtual void PrintDataTo(StringStream* stream);
int arity() const { return hydrogen()->argument_count() - 1; }
};
class LCallRuntime: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(CallRuntime, "call-runtime")
DECLARE_HYDROGEN_ACCESSOR(CallRuntime)
const Runtime::Function* function() const { return hydrogen()->function(); }
int arity() const { return hydrogen()->argument_count(); }
};
class LInteger32ToDouble: public LTemplateInstruction<1, 1, 0> {
public:
explicit LInteger32ToDouble(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(Integer32ToDouble, "int32-to-double")
};
class LNumberTagI: public LTemplateInstruction<1, 1, 0> {
public:
explicit LNumberTagI(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(NumberTagI, "number-tag-i")
};
class LNumberTagD: public LTemplateInstruction<1, 1, 1> {
public:
explicit LNumberTagD(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(NumberTagD, "number-tag-d")
};
// Sometimes truncating conversion from a tagged value to an int32.
class LDoubleToI: public LTemplateInstruction<1, 1, 0> {
public:
explicit LDoubleToI(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(DoubleToI, "double-to-i")
DECLARE_HYDROGEN_ACCESSOR(Change)
bool truncating() { return hydrogen()->CanTruncateToInt32(); }
};
// Truncating conversion from a tagged value to an int32.
class LTaggedToI: public LTemplateInstruction<1, 1, 1> {
public:
LTaggedToI(LOperand* value, LOperand* temp) {
inputs_[0] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(TaggedToI, "tagged-to-i")
DECLARE_HYDROGEN_ACCESSOR(Change)
bool truncating() { return hydrogen()->CanTruncateToInt32(); }
};
class LSmiTag: public LTemplateInstruction<1, 1, 0> {
public:
explicit LSmiTag(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(SmiTag, "smi-tag")
};
class LNumberUntagD: public LTemplateInstruction<1, 1, 0> {
public:
explicit LNumberUntagD(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(NumberUntagD, "double-untag")
};
class LSmiUntag: public LTemplateInstruction<1, 1, 0> {
public:
LSmiUntag(LOperand* value, bool needs_check)
: needs_check_(needs_check) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(SmiUntag, "smi-untag")
bool needs_check() const { return needs_check_; }
private:
bool needs_check_;
};
class LStoreNamedField: public LTemplateInstruction<0, 2, 1> {
public:
LStoreNamedField(LOperand* object, LOperand* value, LOperand* temp) {
inputs_[0] = object;
inputs_[1] = value;
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(StoreNamedField, "store-named-field")
DECLARE_HYDROGEN_ACCESSOR(StoreNamedField)
virtual void PrintDataTo(StringStream* stream);
LOperand* object() { return inputs_[0]; }
LOperand* value() { return inputs_[1]; }
Handle<Object> name() const { return hydrogen()->name(); }
bool is_in_object() { return hydrogen()->is_in_object(); }
int offset() { return hydrogen()->offset(); }
bool needs_write_barrier() { return hydrogen()->NeedsWriteBarrier(); }
Handle<Map> transition() const { return hydrogen()->transition(); }
};
class LStoreNamedGeneric: public LTemplateInstruction<0, 2, 0> {
public:
LStoreNamedGeneric(LOperand* object, LOperand* value) {
inputs_[0] = object;
inputs_[1] = value;
}
DECLARE_CONCRETE_INSTRUCTION(StoreNamedGeneric, "store-named-generic")
DECLARE_HYDROGEN_ACCESSOR(StoreNamedGeneric)
virtual void PrintDataTo(StringStream* stream);
LOperand* object() { return inputs_[0]; }
LOperand* value() { return inputs_[1]; }
Handle<Object> name() const { return hydrogen()->name(); }
bool strict_mode() { return hydrogen()->strict_mode(); }
};
class LStoreKeyedFastElement: public LTemplateInstruction<0, 3, 0> {
public:
LStoreKeyedFastElement(LOperand* obj, LOperand* key, LOperand* val) {
inputs_[0] = obj;
inputs_[1] = key;
inputs_[2] = val;
}
DECLARE_CONCRETE_INSTRUCTION(StoreKeyedFastElement,
"store-keyed-fast-element")
DECLARE_HYDROGEN_ACCESSOR(StoreKeyedFastElement)
virtual void PrintDataTo(StringStream* stream);
LOperand* object() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
LOperand* value() { return inputs_[2]; }
};
class LStoreKeyedSpecializedArrayElement: public LTemplateInstruction<0, 3, 0> {
public:
LStoreKeyedSpecializedArrayElement(LOperand* external_pointer,
LOperand* key,
LOperand* val) {
inputs_[0] = external_pointer;
inputs_[1] = key;
inputs_[2] = val;
}
DECLARE_CONCRETE_INSTRUCTION(StoreKeyedSpecializedArrayElement,
"store-keyed-specialized-array-element")
DECLARE_HYDROGEN_ACCESSOR(StoreKeyedSpecializedArrayElement)
LOperand* external_pointer() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
LOperand* value() { return inputs_[2]; }
ExternalArrayType array_type() const {
return hydrogen()->array_type();
}
};
class LStoreKeyedGeneric: public LTemplateInstruction<0, 3, 0> {
public:
LStoreKeyedGeneric(LOperand* object, LOperand* key, LOperand* value) {
inputs_[0] = object;
inputs_[1] = key;
inputs_[2] = value;
}
DECLARE_CONCRETE_INSTRUCTION(StoreKeyedGeneric, "store-keyed-generic")
DECLARE_HYDROGEN_ACCESSOR(StoreKeyedGeneric)
virtual void PrintDataTo(StringStream* stream);
LOperand* object() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
LOperand* value() { return inputs_[2]; }
bool strict_mode() { return hydrogen()->strict_mode(); }
};
class LStringAdd: public LTemplateInstruction<1, 2, 0> {
public:
LStringAdd(LOperand* left, LOperand* right) {
inputs_[0] = left;
inputs_[1] = right;
}
DECLARE_CONCRETE_INSTRUCTION(StringAdd, "string-add")
DECLARE_HYDROGEN_ACCESSOR(StringAdd)
LOperand* left() { return inputs_[0]; }
LOperand* right() { return inputs_[1]; }
};
class LStringCharCodeAt: public LTemplateInstruction<1, 2, 0> {
public:
LStringCharCodeAt(LOperand* string, LOperand* index) {
inputs_[0] = string;
inputs_[1] = index;
}
DECLARE_CONCRETE_INSTRUCTION(StringCharCodeAt, "string-char-code-at")
DECLARE_HYDROGEN_ACCESSOR(StringCharCodeAt)
LOperand* string() { return inputs_[0]; }
LOperand* index() { return inputs_[1]; }
};
class LStringCharFromCode: public LTemplateInstruction<1, 1, 0> {
public:
explicit LStringCharFromCode(LOperand* char_code) {
inputs_[0] = char_code;
}
DECLARE_CONCRETE_INSTRUCTION(StringCharFromCode, "string-char-from-code")
DECLARE_HYDROGEN_ACCESSOR(StringCharFromCode)
LOperand* char_code() { return inputs_[0]; }
};
class LStringLength: public LTemplateInstruction<1, 1, 0> {
public:
explicit LStringLength(LOperand* string) {
inputs_[0] = string;
}
DECLARE_CONCRETE_INSTRUCTION(StringLength, "string-length")
DECLARE_HYDROGEN_ACCESSOR(StringLength)
LOperand* string() { return inputs_[0]; }
};
class LCheckFunction: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCheckFunction(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CheckFunction, "check-function")
DECLARE_HYDROGEN_ACCESSOR(CheckFunction)
};
class LCheckInstanceType: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCheckInstanceType(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CheckInstanceType, "check-instance-type")
DECLARE_HYDROGEN_ACCESSOR(CheckInstanceType)
};
class LCheckMap: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCheckMap(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CheckMap, "check-map")
DECLARE_HYDROGEN_ACCESSOR(CheckMap)
};
class LCheckPrototypeMaps: public LTemplateInstruction<0, 0, 1> {
public:
explicit LCheckPrototypeMaps(LOperand* temp) {
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(CheckPrototypeMaps, "check-prototype-maps")
DECLARE_HYDROGEN_ACCESSOR(CheckPrototypeMaps)
Handle<JSObject> prototype() const { return hydrogen()->prototype(); }
Handle<JSObject> holder() const { return hydrogen()->holder(); }
};
class LCheckSmi: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCheckSmi(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CheckSmi, "check-smi")
};
class LCheckNonSmi: public LTemplateInstruction<0, 1, 0> {
public:
explicit LCheckNonSmi(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(CheckNonSmi, "check-non-smi")
};
class LArrayLiteral: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(ArrayLiteral, "array-literal")
DECLARE_HYDROGEN_ACCESSOR(ArrayLiteral)
};
class LObjectLiteral: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(ObjectLiteral, "object-literal")
DECLARE_HYDROGEN_ACCESSOR(ObjectLiteral)
};
class LRegExpLiteral: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(RegExpLiteral, "regexp-literal")
DECLARE_HYDROGEN_ACCESSOR(RegExpLiteral)
};
class LFunctionLiteral: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(FunctionLiteral, "function-literal")
DECLARE_HYDROGEN_ACCESSOR(FunctionLiteral)
Handle<SharedFunctionInfo> shared_info() { return hydrogen()->shared_info(); }
};
class LToFastProperties: public LTemplateInstruction<1, 1, 0> {
public:
explicit LToFastProperties(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(ToFastProperties, "to-fast-properties")
DECLARE_HYDROGEN_ACCESSOR(ToFastProperties)
};
class LTypeof: public LTemplateInstruction<1, 1, 0> {
public:
explicit LTypeof(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(Typeof, "typeof")
};
class LTypeofIs: public LTemplateInstruction<1, 1, 0> {
public:
explicit LTypeofIs(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(TypeofIs, "typeof-is")
DECLARE_HYDROGEN_ACCESSOR(TypeofIs)
Handle<String> type_literal() { return hydrogen()->type_literal(); }
virtual void PrintDataTo(StringStream* stream);
};
class LTypeofIsAndBranch: public LControlInstruction<1, 0> {
public:
explicit LTypeofIsAndBranch(LOperand* value) {
inputs_[0] = value;
}
DECLARE_CONCRETE_INSTRUCTION(TypeofIsAndBranch, "typeof-is-and-branch")
DECLARE_HYDROGEN_ACCESSOR(TypeofIs)
Handle<String> type_literal() { return hydrogen()->type_literal(); }
virtual void PrintDataTo(StringStream* stream);
};
class LIsConstructCall: public LTemplateInstruction<1, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(IsConstructCall, "is-construct-call")
DECLARE_HYDROGEN_ACCESSOR(IsConstructCall)
};
class LIsConstructCallAndBranch: public LControlInstruction<0, 1> {
public:
explicit LIsConstructCallAndBranch(LOperand* temp) {
temps_[0] = temp;
}
DECLARE_CONCRETE_INSTRUCTION(IsConstructCallAndBranch,
"is-construct-call-and-branch")
};
class LDeleteProperty: public LTemplateInstruction<1, 2, 0> {
public:
LDeleteProperty(LOperand* obj, LOperand* key) {
inputs_[0] = obj;
inputs_[1] = key;
}
DECLARE_CONCRETE_INSTRUCTION(DeleteProperty, "delete-property")
LOperand* object() { return inputs_[0]; }
LOperand* key() { return inputs_[1]; }
};
class LOsrEntry: public LTemplateInstruction<0, 0, 0> {
public:
LOsrEntry();
DECLARE_CONCRETE_INSTRUCTION(OsrEntry, "osr-entry")
LOperand** SpilledRegisterArray() { return register_spills_; }
LOperand** SpilledDoubleRegisterArray() { return double_register_spills_; }
void MarkSpilledRegister(int allocation_index, LOperand* spill_operand);
void MarkSpilledDoubleRegister(int allocation_index,
LOperand* spill_operand);
private:
// Arrays of spill slot operands for registers with an assigned spill
// slot, i.e., that must also be restored to the spill slot on OSR entry.
// NULL if the register has no assigned spill slot. Indexed by allocation
// index.
LOperand* register_spills_[Register::kNumAllocatableRegisters];
LOperand* double_register_spills_[DoubleRegister::kNumAllocatableRegisters];
};
class LStackCheck: public LTemplateInstruction<0, 0, 0> {
public:
DECLARE_CONCRETE_INSTRUCTION(StackCheck, "stack-check")
};
class LChunkBuilder;
class LChunk: public ZoneObject {
public:
explicit LChunk(CompilationInfo* info, HGraph* graph)
: spill_slot_count_(0),
info_(info),
graph_(graph),
instructions_(32),
pointer_maps_(8),
inlined_closures_(1) { }
void AddInstruction(LInstruction* instruction, HBasicBlock* block);
LConstantOperand* DefineConstantOperand(HConstant* constant);
Handle<Object> LookupLiteral(LConstantOperand* operand) const;
Representation LookupLiteralRepresentation(LConstantOperand* operand) const;
int GetNextSpillIndex(bool is_double);
LOperand* GetNextSpillSlot(bool is_double);
int ParameterAt(int index);
int GetParameterStackSlot(int index) const;
int spill_slot_count() const { return spill_slot_count_; }
CompilationInfo* info() const { return info_; }
HGraph* graph() const { return graph_; }
const ZoneList<LInstruction*>* instructions() const { return &instructions_; }
void AddGapMove(int index, LOperand* from, LOperand* to);
LGap* GetGapAt(int index) const;
bool IsGapAt(int index) const;
int NearestGapPos(int index) const;
void MarkEmptyBlocks();
const ZoneList<LPointerMap*>* pointer_maps() const { return &pointer_maps_; }
LLabel* GetLabel(int block_id) const {
HBasicBlock* block = graph_->blocks()->at(block_id);
int first_instruction = block->first_instruction_index();
return LLabel::cast(instructions_[first_instruction]);
}
int LookupDestination(int block_id) const {
LLabel* cur = GetLabel(block_id);
while (cur->replacement() != NULL) {
cur = cur->replacement();
}
return cur->block_id();
}
Label* GetAssemblyLabel(int block_id) const {
LLabel* label = GetLabel(block_id);
ASSERT(!label->HasReplacement());
return label->label();
}
const ZoneList<Handle<JSFunction> >* inlined_closures() const {
return &inlined_closures_;
}
void AddInlinedClosure(Handle<JSFunction> closure) {
inlined_closures_.Add(closure);
}
private:
int spill_slot_count_;
CompilationInfo* info_;
HGraph* const graph_;
ZoneList<LInstruction*> instructions_;
ZoneList<LPointerMap*> pointer_maps_;
ZoneList<Handle<JSFunction> > inlined_closures_;
};
class LChunkBuilder BASE_EMBEDDED {
public:
LChunkBuilder(CompilationInfo* info, HGraph* graph, LAllocator* allocator)
: chunk_(NULL),
info_(info),
graph_(graph),
status_(UNUSED),
current_instruction_(NULL),
current_block_(NULL),
next_block_(NULL),
argument_count_(0),
allocator_(allocator),
position_(RelocInfo::kNoPosition),
instruction_pending_deoptimization_environment_(NULL),
pending_deoptimization_ast_id_(AstNode::kNoNumber) { }
// Build the sequence for the graph.
LChunk* Build();
// Declare methods that deal with the individual node types.
#define DECLARE_DO(type) LInstruction* Do##type(H##type* node);
HYDROGEN_CONCRETE_INSTRUCTION_LIST(DECLARE_DO)
#undef DECLARE_DO
private:
enum Status {
UNUSED,
BUILDING,
DONE,
ABORTED
};
LChunk* chunk() const { return chunk_; }
CompilationInfo* info() const { return info_; }
HGraph* graph() const { return graph_; }
bool is_unused() const { return status_ == UNUSED; }
bool is_building() const { return status_ == BUILDING; }
bool is_done() const { return status_ == DONE; }
bool is_aborted() const { return status_ == ABORTED; }
void Abort(const char* format, ...);
// Methods for getting operands for Use / Define / Temp.
LRegister* ToOperand(Register reg);
LUnallocated* ToUnallocated(Register reg);
LUnallocated* ToUnallocated(XMMRegister reg);
// Methods for setting up define-use relationships.
MUST_USE_RESULT LOperand* Use(HValue* value, LUnallocated* operand);
MUST_USE_RESULT LOperand* UseFixed(HValue* value, Register fixed_register);
MUST_USE_RESULT LOperand* UseFixedDouble(HValue* value,
XMMRegister fixed_register);
// A value that is guaranteed to be allocated to a register.
// Operand created by UseRegister is guaranteed to be live until the end of
// instruction. This means that register allocator will not reuse it's
// register for any other operand inside instruction.
// Operand created by UseRegisterAtStart is guaranteed to be live only at
// instruction start. Register allocator is free to assign the same register
// to some other operand used inside instruction (i.e. temporary or
// output).
MUST_USE_RESULT LOperand* UseRegister(HValue* value);
MUST_USE_RESULT LOperand* UseRegisterAtStart(HValue* value);
// An input operand in a register that may be trashed.
MUST_USE_RESULT LOperand* UseTempRegister(HValue* value);
// An input operand in a register or stack slot.
MUST_USE_RESULT LOperand* Use(HValue* value);
MUST_USE_RESULT LOperand* UseAtStart(HValue* value);
// An input operand in a register, stack slot or a constant operand.
MUST_USE_RESULT LOperand* UseOrConstant(HValue* value);
MUST_USE_RESULT LOperand* UseOrConstantAtStart(HValue* value);
// An input operand in a register or a constant operand.
MUST_USE_RESULT LOperand* UseRegisterOrConstant(HValue* value);
MUST_USE_RESULT LOperand* UseRegisterOrConstantAtStart(HValue* value);
// An input operand in register, stack slot or a constant operand.
// Will not be moved to a register even if one is freely available.
MUST_USE_RESULT LOperand* UseAny(HValue* value);
// Temporary operand that must be in a register.
MUST_USE_RESULT LUnallocated* TempRegister();
MUST_USE_RESULT LOperand* FixedTemp(Register reg);
MUST_USE_RESULT LOperand* FixedTemp(XMMRegister reg);
// Methods for setting up define-use relationships.
// Return the same instruction that they are passed.
template<int I, int T>
LInstruction* Define(LTemplateInstruction<1, I, T>* instr,
LUnallocated* result);
template<int I, int T>
LInstruction* Define(LTemplateInstruction<1, I, T>* instr);
template<int I, int T>
LInstruction* DefineAsRegister(LTemplateInstruction<1, I, T>* instr);
template<int I, int T>
LInstruction* DefineAsSpilled(LTemplateInstruction<1, I, T>* instr,
int index);
template<int I, int T>
LInstruction* DefineSameAsFirst(LTemplateInstruction<1, I, T>* instr);
template<int I, int T>
LInstruction* DefineFixed(LTemplateInstruction<1, I, T>* instr,
Register reg);
template<int I, int T>
LInstruction* DefineFixedDouble(LTemplateInstruction<1, I, T>* instr,
XMMRegister reg);
LInstruction* AssignEnvironment(LInstruction* instr);
LInstruction* AssignPointerMap(LInstruction* instr);
enum CanDeoptimize { CAN_DEOPTIMIZE_EAGERLY, CANNOT_DEOPTIMIZE_EAGERLY };
// By default we assume that instruction sequences generated for calls
// cannot deoptimize eagerly and we do not attach environment to this
// instruction.
LInstruction* MarkAsCall(
LInstruction* instr,
HInstruction* hinstr,
CanDeoptimize can_deoptimize = CANNOT_DEOPTIMIZE_EAGERLY);
LInstruction* MarkAsSaveDoubles(LInstruction* instr);
LInstruction* SetInstructionPendingDeoptimizationEnvironment(
LInstruction* instr, int ast_id);
void ClearInstructionPendingDeoptimizationEnvironment();
LEnvironment* CreateEnvironment(HEnvironment* hydrogen_env);
void VisitInstruction(HInstruction* current);
void DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block);
LInstruction* DoBit(Token::Value op, HBitwiseBinaryOperation* instr);
LInstruction* DoShift(Token::Value op, HBitwiseBinaryOperation* instr);
LInstruction* DoArithmeticD(Token::Value op,
HArithmeticBinaryOperation* instr);
LInstruction* DoArithmeticT(Token::Value op,
HArithmeticBinaryOperation* instr);
LChunk* chunk_;
CompilationInfo* info_;
HGraph* const graph_;
Status status_;
HInstruction* current_instruction_;
HBasicBlock* current_block_;
HBasicBlock* next_block_;
int argument_count_;
LAllocator* allocator_;
int position_;
LInstruction* instruction_pending_deoptimization_environment_;
int pending_deoptimization_ast_id_;
DISALLOW_COPY_AND_ASSIGN(LChunkBuilder);
};
#undef DECLARE_HYDROGEN_ACCESSOR
#undef DECLARE_CONCRETE_INSTRUCTION
} } // namespace v8::int
#endif // V8_X64_LITHIUM_X64_H_
| [
"[email protected]"
] | [
[
[
1,
2238
]
]
] |
77ceef7daa506567b36d2fa3a9f20de22e920976 | c82d009662b7b3da2707a577a3143066d128093a | /numeric/units/unitlibtest.h | 0243a414684ead750e1068b0e21ce1b17265fff4 | [] | no_license | canilao/cpp_framework | 01a2c0787440d9fca64dbb0fb10c1175a4f7d198 | da5c612e8f15f6987be0c925f46e854b2e703d73 | refs/heads/master | 2021-01-10T13:26:39.376268 | 2011-02-04T16:26:26 | 2011-02-04T16:26:26 | 49,291,836 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,863 | h | /*******************************************************************************
\file unitlibrary.h
\brief Executes a test on the library.
\note C Anilao 10/23/2006 Created.
\note C Anilao 11/27/2006 Added test for floors and fps. Added repetitive
division and multiplication operations to test
that numbers are not degrading over time.
Added test for fpm (floors per minute).
\note C Anilao 11/28/2006 Added test for addition and subtraction
operators. '-=' '+=' and '-' Added assert for
boolean operator for repeatative math test
loops.
\note N Alcantara 12/05/2006 Added additional tests: Logic and its
complement, decimal precision, proximity
to zero.
\note C Anilao 12/06/2006 Removed 'int i' declarations in several for
loops. Microsoft will not compile with this.
*******************************************************************************/
#ifndef UNITLIBTEST_H
#define UNITLIBTEST_H
// Standard Library Dependancies.
#include <cmath>
#include <limits>
#include <string>
#include <cassert>
// General Dependancies.
#include "../../numeric.h"
using namespace std;
const double ALMOST_ZERO = 1e-10;
namespace numeric
{
/*******************************************************************************
\class CUnitLibTest
\brief Test the library.
*******************************************************************************/
template<class unitType, class unitParent>
class CUnitLibTest
{
public:
// Constructor.
CUnitLibTest(){};
// Destructor.
virtual ~CUnitLibTest(){};
// Execute Test.
void Test();
};
/*******************************************************************************
\brief Test
*******************************************************************************/
template<class unitType, class unitParent>
inline void CUnitLibTest<unitType, unitParent>::Test()
{
/*** Constructor Tests ***/
unitType unitWholeNumber = 10;
assert(static_cast<int>(unitWholeNumber) == 10);
unitType unitDouble = 10.5;
assert(fabs(static_cast<double>(unitDouble) - 10.5) < ALMOST_ZERO);
unitType unitInitOnConstructWhole(25);
assert(static_cast<int>(unitInitOnConstructWhole) == 25);
unitType unitConstructDouble(25.5);
assert(unitConstructDouble == unitType(25.5));
/*** Assignment Tests ***/
unitWholeNumber = 1;
assert(static_cast<int>(unitWholeNumber) == 1);
unitDouble = 20.1;
assert(fabs(
static_cast<double>(unitDouble) -
static_cast<double>(20.1)) <
ALMOST_ZERO);
unitDouble = 20.11;
assert(fabs(
static_cast<double>(unitDouble) -
static_cast<double>(20.11)) <
ALMOST_ZERO);
unitDouble = 20.101;
assert(fabs(static_cast<double>(unitDouble) -
static_cast<double>(20.101)) < ALMOST_ZERO);
unitDouble = 20.1009;
assert(fabs(static_cast<double>(unitDouble) -
static_cast<double>(20.1009)) < ALMOST_ZERO);
/*** Comparison Tests ***/
unitType greater = 10.1009, lesser = 10.1008, equal = 10.1009;
assert(greater > lesser);
assert(lesser < greater);
assert(lesser <= greater);
assert(greater >= lesser);
assert(lesser <= lesser);
assert(greater >= greater);
assert(lesser != greater);
assert(equal == greater);
// Complement
assert(!(lesser > greater));
assert(!(greater < lesser));
assert(!(greater <= lesser));
assert(!(lesser >= greater));
assert(!(lesser == greater));
assert(!(equal != greater));
/*** String Tests ***/
unitType unitString1 = 1;
unitType unitString2 = 20;
unitType unitString3 = 2.7;
unitType unitString4 = 30.1;
unitType unitString5 = 30.11;
unitType unitString6 = 30.111;
unitType unitString7 = 30.1111;
std::string testString1 = unitString1.ToString();
assert(testString1 == "1");
std::string testString2 = unitString2.ToString();
assert(testString2 == "20");
std::string testString3 = unitString3.ToString();
assert(testString3 == "2.7");
std::string testString4 = unitString4.ToString();
assert(testString4 == "30.1");
std::string testString5 = unitString5.ToString();
assert(testString5 == "30.11");
std::string testString6 = unitString6.ToString();
assert(testString6 == "30.111");
std::string testString7 = unitString7.ToString();
assert(testString7 == "30.1111");
/*** Zero Tests ***/
double zero = 0.0;
// One decimal place
unitDouble = 17.1;
zero = (static_cast<double>(unitDouble) - 17.1);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to zero - One decimal places
int i;
for (i = 0; i < 171; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.1;
}
assert(unitDouble == unitType(0.0));
// Two decimal places
unitDouble = 17.11;
zero = (static_cast<double>(unitDouble) - 17.11);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to zero - Two decimal places
for (i = 0; i < 1711; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.01;
}
assert(unitDouble == unitType(0.0));
// Three decimal places
unitDouble = 17.101;
zero = (static_cast<double>(unitDouble) - 17.101);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to zero - Three decimal places
for (i = 0; i < 17101; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.001;
}
assert(unitDouble == unitType(0.0));
// Four decimal places
unitDouble = 1.1009;
zero = (static_cast<double>(unitDouble) - 1.1009);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to zero - Four decimal places
for (i = 0; i < 11009; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.0001;
}
assert(unitDouble == unitType(0.0));
/*** Near-Zero Tests ***/
// One decimal place
unitDouble = 17.1;
zero = (static_cast<double>(unitDouble) - 17.1);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to nearly zero - One decimal place
for (i = 0; i < 170; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.1;
}
assert(unitDouble != unitType(0.0));
// Two decimal places
unitDouble = 17.11;
zero = (static_cast<double>(unitDouble) - 17.11);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to nearly zero - Two decimal places
for (i = 0; i < 1710; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.01;
}
assert(unitDouble != unitType(0.0));
// Three decimal places
unitDouble = 17.101;
zero = (static_cast<double>(unitDouble) - 17.101);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to nearly zero - Three decimal places
for (i = 0; i < 17100; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.001;
}
assert(unitDouble != unitType(0.0));
// Four decimal places
unitDouble = 17.1009;
zero = (static_cast<double>(unitDouble) - 17.1009);
assert(fabs(zero - 0.0) < ALMOST_ZERO);
// Repetitive subtractions to nearly zero - Four decimal places
for (i = 0; i < 171008; ++i)
{
unitDouble = static_cast<double>(unitDouble) - 0.0001;
}
assert(unitDouble != unitType(0.0));
/*** "To One" Tests ***/
unitType toOne(0.0), _toOne(0.0);
for (i = 0; i < 10000; ++i)
{
toOne = toOne + unitType(0.0001);
_toOne += unitType(0.0001);
}
assert(toOne == unitType(1.0));
assert(_toOne == unitType(1.0));
/*** Addition Tests ***/
// Whole numbers
unitType unitAdd1 = 10;
unitType unitAdd2 = 20;
unitType unitAddTotal = unitAdd1 + unitAdd2;
assert(unitAddTotal == unitType(30));
// One decimal place
unitAdd1 = 0.1;
unitAdd2 = 0.1;
unitAddTotal = unitAdd1 + unitAdd2;
assert(unitAddTotal == unitType(0.2));
// Two decimal place
unitAdd1 = 0.11;
unitAdd2 = 0.11;
unitAddTotal = unitAdd1 + unitAdd2;
assert(unitAddTotal == unitType(0.22));
// One decimal place
unitAdd1 = 0.101;
unitAdd2 = 0.101;
unitAddTotal = unitAdd1 + unitAdd2;
assert(unitAddTotal == unitType(0.202));
// One decimal place
unitAdd1 = 0.1009;
unitAdd2 = 0.1009;
unitAddTotal = unitAdd1 + unitAdd2;
assert(unitAddTotal == unitType(0.2018));
/*** Convertion Operator Tests ***/
unitType conversionOperatorTesting = 100.1009;
double DoubleConv = conversionOperatorTesting;
assert(unitType(DoubleConv) == unitType(100.1009));
unsigned long LongConv = conversionOperatorTesting;
assert(LongConv == 100);
// Test for conversion to base class, then back again.
unitType unitBaseLengthTest = 100.123956789;
unitParent baseClassConvTest = unitBaseLengthTest;
std::string baseStringTest1 = baseClassConvTest.ToString();
unitBaseLengthTest = baseClassConvTest;
assert(unitBaseLengthTest == baseClassConvTest);
}
/*******************************************************************************
\brief ExecuteUnitLibraryTest
*******************************************************************************/
void ExecuteUnitLibraryTest()
{
/*** Length Test Suite ***/
CUnitLibTest<inches, length> inchesTestObj;
inchesTestObj.Test();
assert(miles(1) == inches(63360));
CUnitLibTest<feet, length> feetTestObj;
feetTestObj.Test();
assert(feet(1) == inches(12));
CUnitLibTest<millimeters, length> mmTestObj;
mmTestObj.Test();
assert(miles(1) == millimeters(1609344));
CUnitLibTest<centimeters, length> cmTestObj;
cmTestObj.Test();
assert(inches(1) == centimeters(2.54));
CUnitLibTest<kilometers, length> kmTestObj;
kmTestObj.Test();
assert(inches(39370.07874015748) == kilometers(1));
CUnitLibTest<miles, length> milesTestObj;
milesTestObj.Test();
assert(miles(1) == millimeters(1609344));
/*** Mass Test Suite ***/
// Test out the mass units.
CUnitLibTest<pounds, mass> lbsTestObj;
lbsTestObj.Test();
assert(pounds(1) == kilograms(0.45359237000));
CUnitLibTest<kilograms, mass> kgTestObj;
kgTestObj.Test();
assert(kilograms(1) == pounds(2.204622622));
/*** Time Test Suite ***/
CUnitLibTest<hours, time> hoursTestObj;
hoursTestObj.Test();
assert(seconds(1) == hours(2.7777777777777777777777777777778e-4));
CUnitLibTest<milliseconds, time> msTestObj;
msTestObj.Test();
assert(milliseconds(1) == seconds(0.001));
CUnitLibTest<seconds, time> secTestObj;
secTestObj.Test();
assert(seconds(1) == milliseconds(1000));
CUnitLibTest<minutes, time> minTestObj;
minTestObj.Test();
assert(minutes(1) == milliseconds(60000));
/*** Speed Test Suite ***/
CUnitLibTest<mph, speed> mphTestObj;
mphTestObj.Test();
assert(kph(1.609344) == mph(1));
length oneMile = mph(1) * minutes(60);
assert(oneMile == miles(1));
CUnitLibTest<kph, speed> kphTestObj;
kphTestObj.Test();
assert(mph(0.62137119223733) == kph(1));
/*** Pace Test Suite ***/
kmpace tenMinKm1 = minutes(10);
kph sixKmPerHour = tenMinKm1;
double sixKmPerHourScalar = sixKmPerHour;
assert(sixKmPerHourScalar == 6.0);
kmpace tenMinKm2 = sixKmPerHour;
assert(minutes(10) == tenMinKm2);
assert(std::string("10:00") == tenMinKm2.ToString());
milepace tenMinMile1 = minutes(10);
mph sixMilePerHour = tenMinMile1;
double sixMilePerHourScalar = sixMilePerHour;
assert(mph(sixMilePerHourScalar) == mph(6.0));
milepace tenMinMile2 = sixMilePerHour;
assert(minutes(10) == tenMinMile2);
assert(std::string("10:00") == tenMinMile2.ToString());
// Repetitively execute the division and multiplication operator.
speed speedDivTest1;
length lenDivTest1 = miles(1);
for(int i=0 ; i<1000 ; ++i)
{
speedDivTest1 = lenDivTest1 / minutes(60);
lenDivTest1 = speedDivTest1 * minutes(60);
assert(lenDivTest1 == miles(1));
assert(speedDivTest1 == mph(1));
}
// Test out the division operator for length, will return a speed object.
miles divMiles = 1;
hours divHours = 2;
speed divSpeed = divMiles / divHours;
assert(mph(0.5) == mph(divSpeed));
mph oneMPH = 1;
time divTime = divMiles / oneMPH;
assert(hours(1) == hours(divTime));
/*** Time Struct Test Suite ***/
time oneOfAllTest = days(1) +
hours(1) +
minutes(1) +
seconds(1) +
milliseconds(1);
timestruct timeStructTest(oneOfAllTest);
assert(timeStructTest.days_data == 1);
assert(timeStructTest.hours_data == 1);
assert(timeStructTest.minutes_data == 1);
assert(timeStructTest.seconds_data == 1);
assert(timeStructTest.milliseconds_data == 1);
assert(timeStructTest.GetTimeObject() == oneOfAllTest);
}
}
#endif
| [
"Chris@55e5c601-11dd-bd4b-a960-93a593583956"
] | [
[
[
1,
433
]
]
] |
eb9d1bd0888699266acddfe18934258fc50b3213 | 942b88e59417352fbbb1a37d266fdb3f0f839d27 | /src/argss/color.cxx | e5f57cb3a53c9d96c52c53e7e663237b29502643 | [
"BSD-2-Clause"
] | permissive | take-cheeze/ARGSS... | 2c1595d924c24730cc714d017edb375cfdbae9ef | 2f2830e8cc7e9c4a5f21f7649287cb6a4924573f | refs/heads/master | 2016-09-05T15:27:26.319404 | 2010-12-13T09:07:24 | 2010-12-13T09:07:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,836 | cxx | //////////////////////////////////////////////////////////////////////////////////
/// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
/// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
/// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <boost/format.hpp>
#include <argss/color.hxx>
#include <color.hxx>
namespace ARGSS
{
namespace AColor
{
namespace
{
////////////////////////////////////////////////////////////
/// Global Variables
////////////////////////////////////////////////////////////
VALUE id;
} // namespace
VALUE& getID() { return id; }
////////////////////////////////////////////////////////////
/// Cap color value between 0 and 255
////////////////////////////////////////////////////////////
double CapColorValue(double v)
{
return (v > 255) ? 255 : (v < 0) ? 0 : v;
}
////////////////////////////////////////////////////////////
/// ARGSS Color ruby functions
////////////////////////////////////////////////////////////
VALUE rinitialize(int argc, VALUE *argv, VALUE self)
{
if (argc < 3) raise_argn(argc, 3);
else if (argc > 4) raise_argn(argc, 4);
rb_iv_set(self, "@red", rb_float_new(CapColorValue(NUM2DBL(argv[0]))));
rb_iv_set(self, "@green", rb_float_new(CapColorValue(NUM2DBL(argv[1]))));
rb_iv_set(self, "@blue", rb_float_new(CapColorValue(NUM2DBL(argv[2]))));
if (argc == 4) {
rb_iv_set(self, "@alpha", rb_float_new(CapColorValue(NUM2DBL(argv[3]))));
}
else {
rb_iv_set(self, "@alpha", rb_float_new(255));
}
return self;
}
VALUE rset(int argc, VALUE *argv, VALUE self)
{
if (argc < 3) raise_argn(argc, 3);
else if (argc > 4) raise_argn(argc, 4);
rb_iv_set(self, "@red", rb_float_new(CapColorValue(NUM2DBL(argv[0]))));
rb_iv_set(self, "@green", rb_float_new(CapColorValue(NUM2DBL(argv[1]))));
rb_iv_set(self, "@blue", rb_float_new(CapColorValue(NUM2DBL(argv[2]))));
if (argc == 4) {
rb_iv_set(self, "@alpha", rb_float_new(CapColorValue(NUM2DBL(argv[3]))));
}
else {
rb_iv_set(self, "@alpha", rb_float_new(255));
}
return self;
}
VALUE rred(VALUE self)
{
return rb_iv_get(self, "@red");
}
VALUE rredE(VALUE self, VALUE red)
{
return rb_iv_set(self, "@red", rb_float_new(CapColorValue(NUM2DBL(red))));
}
VALUE rgreen(VALUE self)
{
return rb_iv_get(self, "@green");
}
VALUE rgreenE(VALUE self, VALUE green)
{
return rb_iv_set(self, "@green", rb_float_new(CapColorValue(NUM2DBL(green))));
}
VALUE rblue(VALUE self)
{
return rb_iv_get(self, "@blue");
}
VALUE rblueE(VALUE self, VALUE blue)
{
return rb_iv_set(self, "@blue", rb_float_new(CapColorValue(NUM2DBL(blue))));
}
VALUE ralpha(VALUE self)
{
return rb_iv_get(self, "@alpha");
}
VALUE ralphaE(VALUE self, VALUE alpha)
{
return rb_iv_set(self, "@alpha", rb_float_new(CapColorValue(NUM2DBL(alpha))));
}
VALUE rinspect(VALUE self)
{
std::string str = ( boost::format("(%f, %f, %f, %f)")
% NUM2DBL(rb_iv_get(self, "@red"))
% NUM2DBL(rb_iv_get(self, "@green"))
% NUM2DBL(rb_iv_get(self, "@blue"))
% NUM2DBL(rb_iv_get(self, "@alpha"))
).str();
return rb_str_new( str.c_str(), str.length() );
}
VALUE rdump(int argc, VALUE* argv, VALUE self)
{
if (argc > 1) raise_argn(argc, 1);
VALUE arr = rb_ary_new3(4, rb_iv_get(self, "@red"), rb_iv_get(self, "@green"), rb_iv_get(self, "@blue"), rb_iv_get(self, "@alpha"));
return rb_funcall(arr, rb_intern("pack"), 1, rb_str_new2("d4"));
}
VALUE rload(VALUE self, VALUE str)
{
VALUE arr = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("d4"));
VALUE args[4] = {rb_ary_entry(arr, 0), rb_ary_entry(arr, 1), rb_ary_entry(arr, 2), rb_ary_entry(arr, 3)};
VALUE color = rb_class_new_instance(4, args, id);
return color;
}
////////////////////////////////////////////////////////////
/// ARGSS Color initialize
////////////////////////////////////////////////////////////
void Init()
{
id = rb_define_class("Color", rb_cObject);
static FuncTable funcTable =
{
{ ARGSS_FUNC(initialize), -1 },
{ ARGSS_FUNC(set), -1 },
ARGSS_GETTER_SETTER(red),
ARGSS_GETTER_SETTER(green),
ARGSS_GETTER_SETTER(blue),
ARGSS_GETTER_SETTER(alpha),
{ ARGSS_FUNC(inspect), 0 },
{ "_dump", RubyFunc(rdump), -1 },
};
defineMethods(id, funcTable);
rb_define_singleton_method(id, "_load", RubyFunc(rload), 1);
}
////////////////////////////////////////////////////////////
/// ARGSS Color new ruby instance
////////////////////////////////////////////////////////////
VALUE New()
{
VALUE args[4] = {rb_float_new(0), rb_float_new(0), rb_float_new(0), rb_float_new(255)};
return rb_class_new_instance(4, args, id);
}
VALUE New(VALUE color)
{
VALUE args[4] = {rb_iv_get(color, "@red"), rb_iv_get(color, "@green"), rb_iv_get(color, "@blue"), rb_iv_get(color, "@alpha")};
return rb_class_new_instance(4, args, id);
}
VALUE New(double r, double g, double b, double a)
{
VALUE args[4] = {rb_float_new(r), rb_float_new(g), rb_float_new(b), rb_float_new(a)};
return rb_class_new_instance(4, args, id);
}
} // namespace AColor
} // namespace ARGSS
| [
"[email protected]"
] | [
[
[
1,
185
]
]
] |
c8d71e3ca2a281e0f43974220771f22ea33a5ee1 | 48ab31a0a6a8605d57b5e140309c910f46eb5b35 | /Root/API/Synchronized/CursorSync.h | d329e2e36b7fb9d6866c86e90e5eeabbd0de203d | [] | no_license | firebreath/indexeddb | 4c3106027a70e233eb0f91c6e0b5d60847d75800 | 50136d2fadced369788a42d249157b8a0d06eb88 | refs/heads/master | 2023-08-31T11:28:42.664028 | 2011-01-03T23:29:46 | 2011-01-03T23:29:46 | 1,218,008 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,173 | h | /**********************************************************\
Copyright Brandon Haynes
http://code.google.com/p/indexeddb
GNU Lesser General Public License
\**********************************************************/
#ifndef BRANDONHAYNES_INDEXEDDB_API_SYNC_CURSORSYNC_H
#define BRANDONHAYNES_INDEXEDDB_API_SYNC_CURSORSYNC_H
#include <boost/optional.hpp>
#include "../Cursor.h"
#include "../KeyRange.h"
#include "../../Support/TransactionFactory.h"
#include "../../Support/LifeCycleObservable.h"
namespace BrandonHaynes {
namespace IndexedDB {
namespace API {
FB_FORWARD_PTR(ObjectStoreSync);
FB_FORWARD_PTR(IndexSync);
FB_FORWARD_PTR(KeyRange);
///<summary>
/// This class represents a synchronized cursor as defined by the Indexed Database API.
///</summary>
class CursorSync : public Cursor
{
protected:
typedef boost::shared_ptr<Support::LifeCycleObserver<CursorSync> > LifeCycleObserverPtr;
boost::shared_ptr<Support::LifeCycleObservable<CursorSync> > _observable;
public:
// This constructor creates a cursor over the given object store
CursorSync(FB::BrowserHostPtr host, const ObjectStoreSyncPtr& objectStore, TransactionFactory& transactionFactory, const KeyRangePtr& range, const Cursor::Direction direction);
// This constructor creates a cursor over the given index
CursorSync(FB::BrowserHostPtr host, const IndexSyncPtr& index, TransactionFactory& transactionFactory, const KeyRangePtr& range, const Cursor::Direction direction, const bool returnKeys);
virtual ~CursorSync(void);
// Gets the key associated with the current cursor position
FB::variant getKey();
// Gets the value associated with the current cursor position
FB::variant getValue();
// Gets the count of key/value pairs associated with this cursor, over the configured key range
int getCount();
// Iterates the cursor either to the next key/value pair, or the given (optional) key
bool next(const FB::CatchAll& args);
// Remove the key/value pair at the current cursor position
void remove();
// Close this cursor
void close();
public:
// Forwarding methods for the embedded Observable
void addLifeCycleObserver(const LifeCycleObserverPtr& observer);
void removeLifeCycleObserver(const LifeCycleObserverPtr& observer);
// By being lifecycle-observable, this object will receive messages when an associated transaction is
// aborted or committed. We don't need any of that implementation here.
virtual void onTransactionAborted(const TransactionPtr& transaction) { }
virtual void onTransactionCommitted(const TransactionPtr& transaction) { }
private:
// The underlying implementation for this cursor
const std::auto_ptr<Implementation::Cursor> implementation;
// We need a reference to the browser for JSON encoding
FB::BrowserHostPtr host;
// Hold a reference to a factory for transactions (including for our current context)
TransactionFactory transactionFactory;
// Cursors may or may not have an associated range
const KeyRangePtr range;
const bool readOnly;
void initializeMethods();
};
}
}
}
#endif | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
19
],
[
23,
26
],
[
28,
28
],
[
32,
33
],
[
35,
35
],
[
37,
51
],
[
56,
57
],
[
60,
64
],
[
66,
69
],
[
71,
73
],
[
75,
80
]
],
[
[
20,
22
],
[
27,
27
],
[
29,
31
],
[
34,
34
],
[
36,
36
],
[
52,
55
],
[
58,
59
],
[
65,
65
],
[
70,
70
],
[
74,
74
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.