hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c79a9f56211ed369504ade91987ebad227cad13 | 54,144 | cpp | C++ | visual/GraphicsLoaderIntf.cpp | 3c1u/krkrz | 3655de95a45cc72e22f04ac9fa10cfbff320f53f | [
"BSD-3-Clause"
] | null | null | null | visual/GraphicsLoaderIntf.cpp | 3c1u/krkrz | 3655de95a45cc72e22f04ac9fa10cfbff320f53f | [
"BSD-3-Clause"
] | null | null | null | visual/GraphicsLoaderIntf.cpp | 3c1u/krkrz | 3655de95a45cc72e22f04ac9fa10cfbff320f53f | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------
/*
TVP2 ( T Visual Presenter 2 ) A script authoring tool
Copyright (C) 2000 W.Dee <dee@kikyou.info> and contributors
See details of license at "license.txt"
*/
//---------------------------------------------------------------------------
// Graphics Loader ( loads graphic format from storage )
//---------------------------------------------------------------------------
#include "tjsCommHead.h"
#include <stdlib.h>
#include "GraphicsLoaderIntf.h"
#include "LayerBitmapIntf.h"
#include "LayerIntf.h"
#include "StorageIntf.h"
#include "MsgIntf.h"
#include "tjsHashSearch.h"
#include "EventIntf.h"
#include "SysInitIntf.h"
#include "DebugIntf.h"
#include "tvpgl.h"
#include "TickCount.h"
//#include "DetectCPU.h"
#include "UtilStreams.h"
#include "tjsDictionary.h"
#include "ScriptMgnIntf.h"
#include <cstdlib>
#include <cmath>
#include "StorageImpl.h"
//---------------------------------------------------------------------------
void tTVPGraphicHandlerType::Load( void* formatdata, void *callbackdata, tTVPGraphicSizeCallback sizecallback, tTVPGraphicScanLineCallback scanlinecallback,
tTVPMetaInfoPushCallback metainfopushcallback, tTJSBinaryStream *src, tjs_int32 keyidx, tTVPGraphicLoadMode mode)
{
if( LoadHandler == NULL ) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, TJS_W("unknown"));
#if defined(_WIN32) || 1
if( IsPlugin )
{
tTVPIStreamAdapter *istream = new tTVPIStreamAdapter(src);
try {
LoadHandlerPlugin( formatdata, callbackdata, sizecallback, scanlinecallback, metainfopushcallback,
istream, keyidx, mode);
} catch(...) {
istream->ClearStream();
istream->Release();
throw;
}
istream->ClearStream();
istream->Release();
}
else
#endif
{
LoadHandler( formatdata, callbackdata, sizecallback, scanlinecallback, metainfopushcallback,
src, keyidx, mode);
}
}
void tTVPGraphicHandlerType::Save( const ttstr & storagename, const ttstr & mode, const tTVPBaseBitmap* image, iTJSDispatch2* meta )
{
if( SaveHandler == NULL ) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, mode );
tTJSBinaryStream *stream = TVPCreateStream(TVPNormalizeStorageName(storagename), TJS_BS_WRITE);
#if defined(_WIN32) || 1
if( IsPlugin )
{
tTVPIStreamAdapter *istream = new tTVPIStreamAdapter(stream);
try {
tjs_uint h = image->GetHeight();
tjs_uint w = image->GetWidth();
SaveHandlerPlugin( FormatData, (void*)image, istream, mode, w, h, tTVPBitmapScanLineCallbackForSave, meta );
} catch(...) {
istream->Release();
throw;
}
istream->Release();
}
else
#endif
{
try {
SaveHandler( FormatData, stream, image, mode, meta );
} catch(...) {
delete stream;
throw;
}
delete stream;
}
}
void tTVPGraphicHandlerType::Header( tTJSBinaryStream *src, iTJSDispatch2** dic )
{
if( HeaderHandler == NULL ) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, TJS_W("unknown") );
#if defined(_WIN32) || 1
if( IsPlugin )
{
tTVPIStreamAdapter *istream = new tTVPIStreamAdapter(src);
try {
HeaderHandlerPlugin( FormatData, istream, dic );
} catch(...) {
istream->ClearStream();
istream->Release();
throw;
}
istream->ClearStream();
istream->Release();
}
else
#endif
{
HeaderHandler( FormatData, src, dic );
}
}
//---------------------------------------------------------------------------
bool TVPAcceptSaveAsBMP( void* formatdata, const ttstr & type, class iTJSDispatch2** dic )
{
bool result = false;
if( type.StartsWith(TJS_W("bmp")) ) result = true;
else if( type == TJS_W(".bmp") ) result = true;
else if( type == TJS_W(".dib") ) result = true;
if( result && dic ) {
tTJSVariant result;
TVPExecuteExpression(
TJS_W("(const)%[")
TJS_W("\"bpp\"=>(const)%[\"type\"=>\"select\",\"items\"=>(const)[\"32\",\"24\",\"8\"],\"desc\"=>\"bpp\",\"default\"=>0]")
TJS_W("]"),
NULL, &result );
if( result.Type() == tvtObject ) {
*dic = result.AsObject();
}
//*dic = TJSCreateDictionaryObject();
}
return result;
}
//---------------------------------------------------------------------------
// Graphics Format Management
//---------------------------------------------------------------------------
class tTVPGraphicType
{
public:
tTJSHashTable<ttstr, tTVPGraphicHandlerType> Hash;
std::vector<tTVPGraphicHandlerType> Handlers;
static bool Avail;
tTVPGraphicType()
{
// register some native-supported formats
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".bmp"), TVPLoadBMP, TVPLoadHeaderBMP, TVPSaveAsBMP, TVPAcceptSaveAsBMP, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".dib"), TVPLoadBMP, TVPLoadHeaderBMP, TVPSaveAsBMP, TVPAcceptSaveAsBMP, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".jpeg"), TVPLoadJPEG, TVPLoadHeaderJPG, TVPSaveAsJPG, TVPAcceptSaveAsJPG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".jpg"), TVPLoadJPEG, TVPLoadHeaderJPG, TVPSaveAsJPG, TVPAcceptSaveAsJPG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".jif"), TVPLoadJPEG, TVPLoadHeaderJPG, TVPSaveAsJPG, TVPAcceptSaveAsJPG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".png"), TVPLoadPNG, TVPLoadHeaderPNG, TVPSaveAsPNG, TVPAcceptSaveAsPNG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".tlg"), TVPLoadTLG, TVPLoadHeaderTLG, TVPSaveAsTLG, TVPAcceptSaveAsTLG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".tlg5"), TVPLoadTLG, TVPLoadHeaderTLG, TVPSaveAsTLG, TVPAcceptSaveAsTLG, NULL));
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".tlg6"), TVPLoadTLG, TVPLoadHeaderTLG, TVPSaveAsTLG, TVPAcceptSaveAsTLG, NULL));
#if 0 && defined(_WIN32)
Handlers.push_back(tTVPGraphicHandlerType(
TJS_W(".jxr"), TVPLoadJXR, TVPLoadHeaderJXR, TVPSaveAsJXR, TVPAcceptSaveAsJXR, NULL));
#endif
ReCreateHash();
Avail = true;
}
~tTVPGraphicType()
{
Avail = false;
}
void ReCreateHash()
{
// re-create hash table for faster search
std::vector<tTVPGraphicHandlerType>::iterator i;
for(i = Handlers.begin();
i!= Handlers.end(); i++)
{
Hash.Add(i->Extension, *i);
}
}
void Register( const tTVPGraphicHandlerType& hander )
{
// register graphic format to the table.
Handlers.push_back(hander);
ReCreateHash();
}
void Unregister( const tTVPGraphicHandlerType& hander )
{
// unregister format from table.
std::vector<tTVPGraphicHandlerType>::iterator i;
if(Handlers.size() > 0)
{
//for(i = Handlers.end() -1; i >= Handlers.begin(); i--)
for(i = Handlers.begin(); i != Handlers.end(); i++)
{
if(hander == *i)
{
Handlers.erase(i);
break;
}
}
}
ReCreateHash();
}
} static TVPGraphicType;
bool tTVPGraphicType::Avail = false;
//---------------------------------------------------------------------------
void TVPRegisterGraphicLoadingHandler(const ttstr & name,
tTVPGraphicLoadingHandler loading,
tTVPGraphicHeaderLoadingHandler header,
tTVPGraphicSaveHandler save,
tTVPGraphicAcceptSaveHandler accept,
void * formatdata)
{
// name must be un-capitalized
if(TVPGraphicType.Avail)
{
TVPGraphicType.Register(tTVPGraphicHandlerType(name, loading, header, save, accept, formatdata));
}
}
//---------------------------------------------------------------------------
void TVPUnregisterGraphicLoadingHandler(const ttstr & name,
tTVPGraphicLoadingHandler loading,
tTVPGraphicHeaderLoadingHandler header,
tTVPGraphicSaveHandler save,
tTVPGraphicAcceptSaveHandler accept,
void * formatdata)
{
// name must be un-capitalized
if(TVPGraphicType.Avail)
{
TVPGraphicType.Unregister(tTVPGraphicHandlerType(name, loading, header, save, accept, formatdata));
}
}
//---------------------------------------------------------------------------
void TVPRegisterGraphicLoadingHandler(const ttstr & name,
tTVPGraphicLoadingHandlerForPlugin loading,
tTVPGraphicHeaderLoadingHandlerForPlugin header,
tTVPGraphicSaveHandlerForPlugin save,
tTVPGraphicAcceptSaveHandler accept,
void* formatdata)
{
// name must be un-capitalized
if(TVPGraphicType.Avail)
{
TVPGraphicType.Register(tTVPGraphicHandlerType(name, loading, header, save, accept, formatdata));
}
}
//---------------------------------------------------------------------------
void TVPUnregisterGraphicLoadingHandler(const ttstr & name,
tTVPGraphicLoadingHandlerForPlugin loading,
tTVPGraphicHeaderLoadingHandlerForPlugin header,
tTVPGraphicSaveHandlerForPlugin save,
tTVPGraphicAcceptSaveHandler accept,
void* formatdata)
{
// name must be un-capitalized
if(TVPGraphicType.Avail)
{
TVPGraphicType.Unregister(tTVPGraphicHandlerType(name, loading, header, save, accept, formatdata));
}
}
//---------------------------------------------------------------------------
tTVPGraphicHandlerType* TVPGetGraphicLoadHandler( const ttstr& ext )
{
return TVPGraphicType.Hash.Find(ext);
}
/*
loading handlers return whether the image contains an alpha channel.
*/
//---------------------------------------------------------------------------
const void* tTVPBitmapScanLineCallbackForSave(void *callbackdata, tjs_int y)
{
tTVPBaseBitmap* image = (tTVPBaseBitmap*)callbackdata;
return image->GetScanLine(y);
}
//---------------------------------------------------------------------------
void TVPLoadImageHeader( const ttstr & storagename, iTJSDispatch2** dic )
{
if( dic == NULL ) return;
ttstr ext = TVPExtractStorageExt(storagename);
if(ext == TJS_W("")) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, storagename);
tTVPGraphicHandlerType * handler = TVPGraphicType.Hash.Find(ext);
if(!handler) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, storagename);
tTVPStreamHolder holder(storagename); // open a storage named "storagename"
handler->Header( holder.Get(), dic );
}
//---------------------------------------------------------------------------
void TVPSaveImage( const ttstr & storagename, const ttstr & mode, const tTVPBaseBitmap* image, iTJSDispatch2* meta )
{
if(!image->Is32BPP())
TVPThrowInternalError;
tTVPGraphicHandlerType * handler;
tTJSHashTable<ttstr, tTVPGraphicHandlerType>::tIterator i;
for(i = TVPGraphicType.Hash.GetFirst(); !i.IsNull(); i++)
{
handler = & i.GetValue();
if( handler->AcceptSave( mode, NULL ) )
{
break;
}
else
{
handler = NULL;
}
}
if( handler ) handler->Save( storagename, mode, image, meta );
else TVPThrowExceptionMessage(TVPUnknownGraphicFormat, mode);
}
//---------------------------------------------------------------------------
bool TVPGetSaveOption( const ttstr & type, iTJSDispatch2** dic )
{
tTVPGraphicHandlerType * handler;
tTJSHashTable<ttstr, tTVPGraphicHandlerType>::tIterator i;
for(i = TVPGraphicType.Hash.GetFirst(); !i.IsNull(); i++ )
{
handler = & i.GetValue();
if( handler->AcceptSave( type, dic ) )
{
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// BMP loading handler
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#define TVP_BMP_READ_LINE_MAX 8
void TVPInternalLoadBMP(void *callbackdata,
tTVPGraphicSizeCallback sizecallback,
tTVPGraphicScanLineCallback scanlinecallback,
TVP_WIN_BITMAPINFOHEADER &bi,
const tjs_uint8 *palsrc,
tTJSBinaryStream * src,
tjs_int keyidx,
tTVPBMPAlphaType alphatype,
tTVPGraphicLoadMode mode)
{
// mostly taken ( but totally re-written ) from SDL,
// http://www.libsdl.org/
// TODO: only checked on Win32 platform
if(bi.biSize == 12)
{
// OS/2
bi.biCompression = BI_RGB;
bi.biClrUsed = 1 << bi.biBitCount;
}
tjs_uint16 orgbitcount = bi.biBitCount;
if(bi.biBitCount == 1 || bi.biBitCount == 4)
{
bi.biBitCount = 8;
}
switch(bi.biCompression)
{
case BI_RGB:
// if there are no masks, use the defaults
break; // use default
/*
if( bf.bfOffBits == ( 14 + bi.biSize) )
{
}
// fall through -- read the RGB masks
*/
case BI_BITFIELDS:
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPBitFieldsNotSupported );
default:
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPCompressedBmpNotSupported );
}
// load palette
tjs_uint32 palette[256]; // (msb) argb (lsb)
if(orgbitcount <= 8)
{
if(bi.biClrUsed == 0) bi.biClrUsed = 1 << orgbitcount ;
if(bi.biSize == 12)
{
// read OS/2 palette
for(tjs_uint i = 0; i < bi.biClrUsed; i++)
{
palette[i] = palsrc[0] + (palsrc[1]<<8) + (palsrc[2]<<16) +
0xff000000;
palsrc += 3;
}
}
else
{
// read Windows palette
for(tjs_uint i = 0; i<bi.biClrUsed; i++)
{
palette[i] = palsrc[0] + (palsrc[1]<<8) + (palsrc[2]<<16) +
0xff000000;
// we assume here that the palette's unused segment is useless.
// fill it with 0xff ( = completely opaque )
palsrc += 4;
}
}
if(mode == glmGrayscale)
{
TVPDoGrayScale(palette, 256);
}
if(keyidx != -1)
{
// if color key by palette index is specified
palette[keyidx&0xff] &= 0x00ffffff; // make keyidx transparent
}
}
else
{
if(mode == glmPalettized)
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPUnsupportedColorModeForPalettImage );
}
tjs_int height;
height = bi.biHeight<0?-bi.biHeight:bi.biHeight;
// positive value of bi.biHeight indicates top-down DIB
sizecallback(callbackdata, bi.biWidth, height);
tjs_int pitch;
pitch = (((bi.biWidth * orgbitcount) + 31) & ~31) /8;
tjs_uint8 *readbuf = (tjs_uint8 *)TJSAlignedAlloc(pitch * TVP_BMP_READ_LINE_MAX, 4);
tjs_uint8 *buf;
tjs_int bufremain = 0;
try
{
// process per a line
tjs_int src_y = 0;
tjs_int dest_y;
if(bi.biHeight>0) dest_y = bi.biHeight-1; else dest_y = 0;
for(; src_y < height; src_y++)
{
if(bufremain == 0)
{
tjs_int remain = height - src_y;
tjs_int read_lines = remain > TVP_BMP_READ_LINE_MAX ?
TVP_BMP_READ_LINE_MAX : remain;
src->ReadBuffer(readbuf, pitch * read_lines);
bufremain = read_lines;
buf = readbuf;
}
void *scanline = scanlinecallback(callbackdata, dest_y);
if(!scanline) break;
switch(orgbitcount)
{
// convert pixel format
case 1:
if(mode == glmPalettized)
{
TVPBLExpand1BitTo8Bit(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth);
}
else if(mode == glmGrayscale)
{
TVPBLExpand1BitTo8BitPal(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
else
{
TVPBLExpand1BitTo32BitPal(
(tjs_uint32*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
break;
case 4:
if(mode == glmPalettized)
{
TVPBLExpand4BitTo8Bit(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth);
}
else if(mode == glmGrayscale)
{
TVPBLExpand4BitTo8BitPal(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
else
{
TVPBLExpand4BitTo32BitPal(
(tjs_uint32*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
break;
case 8:
if(mode == glmPalettized)
{
// intact copy
memcpy(scanline, buf, bi.biWidth);
}
else
if(mode == glmGrayscale)
{
// convert to grayscale
TVPBLExpand8BitTo8BitPal(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
else
{
TVPBLExpand8BitTo32BitPal(
(tjs_uint32*)scanline,
(tjs_uint8*)buf, bi.biWidth, palette);
}
break;
case 15:
case 16:
if(mode == glmGrayscale)
{
TVPBLConvert15BitTo8Bit(
(tjs_uint8*)scanline,
(tjs_uint16*)buf, bi.biWidth);
}
else
{
TVPBLConvert15BitTo32Bit(
(tjs_uint32*)scanline,
(tjs_uint16*)buf, bi.biWidth);
}
break;
case 24:
if(mode == glmGrayscale)
{
TVPBLConvert24BitTo8Bit(
(tjs_uint8*)scanline,
(tjs_uint8*)buf, bi.biWidth);
}
else
{
TVPBLConvert24BitTo32Bit(
(tjs_uint32*)scanline,
(tjs_uint8*)buf, bi.biWidth);
}
break;
case 32:
if(mode == glmGrayscale)
{
TVPBLConvert32BitTo8Bit(
(tjs_uint8*)scanline,
(tjs_uint32*)buf, bi.biWidth);
}
else
{
if(alphatype == batNone)
{
// alpha channel is not given by the bitmap.
// destination alpha is filled with 255.
TVPBLConvert32BitTo32Bit_NoneAlpha(
(tjs_uint32*)scanline,
(tjs_uint32*)buf, bi.biWidth);
}
else if(alphatype == batMulAlpha)
{
// this is the TVP native representation of the alpha channel.
// simply copy from the buffer.
TVPBLConvert32BitTo32Bit_MulAddAlpha(
(tjs_uint32*)scanline,
(tjs_uint32*)buf, bi.biWidth);
}
else if(alphatype == batAddAlpha)
{
// this is alternate representation of the alpha channel,
// this must be converted to TVP native representation.
TVPBLConvert32BitTo32Bit_AddAlpha(
(tjs_uint32*)scanline,
(tjs_uint32*)buf, bi.biWidth);
}
}
break;
}
scanlinecallback(callbackdata, -1); // image was written
if(bi.biHeight>0) dest_y--; else dest_y++;
buf += pitch;
bufremain--;
}
if(mode == glmNormalRGBA)
{
for(tjs_int y = 0; y < height; y++)
{
tjs_uint32 *current = (tjs_uint32*)scanlinecallback(callbackdata, y);
TVPRedBlueSwap( current, bi.biWidth );
}
}
}
catch(...)
{
TJSAlignedDealloc(readbuf);
throw;
}
TJSAlignedDealloc(readbuf);
}
//---------------------------------------------------------------------------
void TVPLoadBMP(void* formatdata, void *callbackdata, tTVPGraphicSizeCallback sizecallback,
tTVPGraphicScanLineCallback scanlinecallback, tTVPMetaInfoPushCallback metainfopushcallback,
tTJSBinaryStream *src, tjs_int keyidx, tTVPGraphicLoadMode mode)
{
// Windows BMP Loader
// mostly taken ( but totally re-written ) from SDL,
// http://www.libsdl.org/
// TODO: only checked in Win32 platform
tjs_uint64 firstpos = src->GetPosition();
// check the magic
tjs_uint8 magic[2];
src->ReadBuffer(magic, 2);
if(magic[0] != TJS_N('B') || magic[1] != TJS_N('M'))
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPNotWindowsBmp );
// read the BITMAPFILEHEADER
TVP_WIN_BITMAPFILEHEADER bf;
bf.bfSize = src->ReadI32LE();
bf.bfReserved1 = src->ReadI16LE();
bf.bfReserved2 = src->ReadI16LE();
bf.bfOffBits = src->ReadI32LE();
// read the BITMAPINFOHEADER
TVP_WIN_BITMAPINFOHEADER bi;
bi.biSize = src->ReadI32LE();
if(bi.biSize == 12)
{
// OS/2 Bitmap
memset(&bi, 0, sizeof(bi));
bi.biWidth = (tjs_uint32)src->ReadI16LE();
bi.biHeight = (tjs_uint32)src->ReadI16LE();
bi.biPlanes = src->ReadI16LE();
bi.biBitCount = src->ReadI16LE();
bi.biClrUsed = 1 << bi.biBitCount;
}
else if(bi.biSize == 40)
{
// Windows Bitmap
bi.biWidth = src->ReadI32LE();
bi.biHeight = src->ReadI32LE();
bi.biPlanes = src->ReadI16LE();
bi.biBitCount = src->ReadI16LE();
bi.biCompression = src->ReadI32LE();
bi.biSizeImage = src->ReadI32LE();
bi.biXPelsPerMeter = src->ReadI32LE();
bi.biYPelsPerMeter = src->ReadI32LE();
bi.biClrUsed = src->ReadI32LE();
bi.biClrImportant = src->ReadI32LE();
}
else
{
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPUnsupportedHeaderVersion );
}
// load palette
tjs_int palsize = (bi.biBitCount <= 8) ?
((bi.biClrUsed == 0 ? (1<<bi.biBitCount) : bi.biClrUsed) *
((bi.biSize == 12) ? 3:4)) : 0; // bi.biSize == 12 ( OS/2 palette )
tjs_uint8 *palette = NULL;
if(palsize) palette = new tjs_uint8 [palsize];
try
{
src->ReadBuffer(palette, palsize);
src->SetPosition(firstpos + bf.bfOffBits);
TVPInternalLoadBMP(callbackdata, sizecallback, scanlinecallback,
bi, palette, src, keyidx, batMulAlpha, mode);
}
catch(...)
{
if(palette) delete [] palette;
throw;
}
if(palette) delete [] palette;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// BMP saving handler
//---------------------------------------------------------------------------
static void TVPWriteLE16(tTJSBinaryStream * stream, tjs_uint16 number)
{
tjs_uint8 data[2];
data[0] = number & 0xff;
data[1] = (number >> 8) & 0xff;
stream->WriteBuffer(data, 2);
}
//---------------------------------------------------------------------------
static void TVPWriteLE32(tTJSBinaryStream * stream, tjs_uint32 number)
{
tjs_uint8 data[4];
data[0] = number & 0xff;
data[1] = (number >> 8) & 0xff;
data[2] = (number >> 16) & 0xff;
data[3] = (number >> 24) & 0xff;
stream->WriteBuffer(data, 4);
}
//---------------------------------------------------------------------------
void TVPSaveAsBMP( void* formatdata, tTJSBinaryStream* dst, const tTVPBaseBitmap* bmp, const ttstr & mode, iTJSDispatch2* meta )
{
tjs_int pixelbytes;
if(mode == TJS_W("bmp32") || mode == TJS_W("bmp"))
pixelbytes = 4;
else if(mode == TJS_W("bmp24"))
pixelbytes = 3;
else if(mode == TJS_W("bmp8"))
pixelbytes = 1;
else
pixelbytes = 4;
if( meta )
{
tTJSVariant val;
tjs_error er = meta->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("bpp"), NULL, &val, meta);
if(TJS_SUCCEEDED(er))
{
tjs_int index = (tjs_int)val.AsInteger();
switch( index ) {
case 0: pixelbytes = 4; break;
case 1: pixelbytes = 3; break;
case 2: pixelbytes = 1; break;
};
}
}
// open stream
tTJSBinaryStream *stream = dst;
tjs_uint8 * buf = NULL;
try
{
TVPClearGraphicCache();
// prepare header
tjs_uint bmppitch = bmp->GetWidth() * pixelbytes;
bmppitch = (((bmppitch - 1) >> 2) + 1) << 2;
TVPWriteLE16(stream, 0x4d42); /* bfType */
TVPWriteLE32(stream, sizeof(TVP_WIN_BITMAPFILEHEADER) +
sizeof(TVP_WIN_BITMAPINFOHEADER) + bmppitch * bmp->GetHeight() +
(pixelbytes == 1 ? 1024 : 0)); /* bfSize */
TVPWriteLE16(stream, 0); /* bfReserved1 */
TVPWriteLE16(stream, 0); /* bfReserved2 */
TVPWriteLE32(stream, sizeof(TVP_WIN_BITMAPFILEHEADER) +
sizeof(TVP_WIN_BITMAPINFOHEADER)+
(pixelbytes == 1 ? 1024 : 0)); /* bfOffBits */
TVPWriteLE32(stream, sizeof(TVP_WIN_BITMAPINFOHEADER)); /* biSize */
TVPWriteLE32(stream, bmp->GetWidth()); /* biWidth */
TVPWriteLE32(stream, bmp->GetHeight()); /* biHeight */
TVPWriteLE16(stream, 1); /* biPlanes */
TVPWriteLE16(stream, pixelbytes * 8); /* biBitCount */
TVPWriteLE32(stream, BI_RGB); /* biCompression */
TVPWriteLE32(stream, 0); /* biSizeImage */
TVPWriteLE32(stream, 0); /* biXPelsPerMeter */
TVPWriteLE32(stream, 0); /* biYPelsPerMeter */
TVPWriteLE32(stream, 0); /* biClrUsed */
TVPWriteLE32(stream, 0); /* biClrImportant */
// write palette
if(pixelbytes == 1)
{
tjs_uint8 palette[1024];
tjs_uint8 * p = palette;
for(tjs_int i = 0; i < 256; i++)
{
p[0] = TVP252DitherPalette[0][i];
p[1] = TVP252DitherPalette[1][i];
p[2] = TVP252DitherPalette[2][i];
p[3] = 0;
p += 4;
}
stream->WriteBuffer(palette, 1024);
}
// write bitmap body
for(tjs_int y = bmp->GetHeight() - 1; y >= 0; y --)
{
if(!buf) buf = new tjs_uint8[bmppitch];
if(pixelbytes == 4)
{
memcpy(buf, bmp->GetScanLine(y), bmppitch);
}
else if(pixelbytes == 1)
{
TVPDither32BitTo8Bit(buf, (const tjs_uint32*)bmp->GetScanLine(y),
bmp->GetWidth(), 0, y);
}
else
{
const tjs_uint8 *src = (const tjs_uint8 *)bmp->GetScanLine(y);
tjs_uint8 *dest = buf;
tjs_int w = bmp->GetWidth();
for(tjs_int x = 0; x < w; x++)
{
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest += 3;
src += 4;
}
}
stream->WriteBuffer(buf, bmppitch);
}
}
catch(...)
{
if(buf) delete [] buf;
throw;
}
if(buf) delete [] buf;
}
//---------------------------------------------------------------------------
void TVPLoadHeaderBMP( void* formatdata, tTJSBinaryStream *src, iTJSDispatch2** dic )
{
tjs_uint64 firstpos = src->GetPosition();
// check the magic
tjs_uint8 magic[2];
src->ReadBuffer(magic, 2);
if(magic[0] != TJS_N('B') || magic[1] != TJS_N('M'))
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPNotWindowsBmp );
// read the BITMAPFILEHEADER
TVP_WIN_BITMAPFILEHEADER bf;
bf.bfSize = src->ReadI32LE();
bf.bfReserved1 = src->ReadI16LE();
bf.bfReserved2 = src->ReadI16LE();
bf.bfOffBits = src->ReadI32LE();
// read the BITMAPINFOHEADER
TVP_WIN_BITMAPINFOHEADER bi;
bi.biSize = src->ReadI32LE();
if(bi.biSize == 12)
{
// OS/2 Bitmap
memset(&bi, 0, sizeof(bi));
bi.biWidth = (tjs_uint32)src->ReadI16LE();
bi.biHeight = (tjs_uint32)src->ReadI16LE();
bi.biPlanes = src->ReadI16LE();
bi.biBitCount = src->ReadI16LE();
bi.biClrUsed = 1 << bi.biBitCount;
}
else if(bi.biSize == 40)
{
// Windows Bitmap
bi.biWidth = src->ReadI32LE();
bi.biHeight = src->ReadI32LE();
bi.biPlanes = src->ReadI16LE();
bi.biBitCount = src->ReadI16LE();
bi.biCompression = src->ReadI32LE();
bi.biSizeImage = src->ReadI32LE();
bi.biXPelsPerMeter = src->ReadI32LE();
bi.biYPelsPerMeter = src->ReadI32LE();
bi.biClrUsed = src->ReadI32LE();
bi.biClrImportant = src->ReadI32LE();
}
else
{
TVPThrowExceptionMessage(TVPImageLoadError, (const tjs_char*)TVPUnsupportedHeaderVersion );
}
tjs_int palsize = (bi.biBitCount <= 8) ?
((bi.biClrUsed == 0 ? (1<<bi.biBitCount) : bi.biClrUsed) *
((bi.biSize == 12) ? 3:4)) : 0; // bi.biSize == 12 ( OS/2 palette )
palsize = palsize > 0 ? 1 : 0;
*dic = TJSCreateDictionaryObject();
tTJSVariant val(bi.biWidth);
(*dic)->PropSet(TJS_MEMBERENSURE, TJS_W("width"), 0, &val, (*dic) );
val = tTJSVariant(bi.biHeight);
(*dic)->PropSet(TJS_MEMBERENSURE, TJS_W("height"), 0, &val, (*dic) );
val = tTJSVariant(bi.biBitCount);
(*dic)->PropSet(TJS_MEMBERENSURE, TJS_W("bpp"), 0, &val, (*dic) );
val = tTJSVariant(palsize);
(*dic)->PropSet(TJS_MEMBERENSURE, TJS_W("palette"), 0, &val, (*dic) );
}
//---------------------------------------------------------------------------
// TVPLoadGraphic related
//---------------------------------------------------------------------------
enum tTVPLoadGraphicType
{
lgtFullColor, // full 32bit color
lgtPalGray, // palettized or grayscale
lgtMask // mask
};
struct tTVPLoadGraphicData
{
ttstr Name;
tTVPBaseBitmap *Dest;
tTVPLoadGraphicType Type;
tjs_int ColorKey;
tjs_uint8 *Buffer;
tjs_uint ScanLineNum;
tjs_uint DesW;
tjs_uint DesH;
tjs_uint OrgW;
tjs_uint OrgH;
tjs_uint BufW;
tjs_uint BufH;
bool NeedMetaInfo;
bool Unpadding;
std::vector<tTVPGraphicMetaInfoPair> * MetaInfo;
};
//---------------------------------------------------------------------------
static void TVPLoadGraphic_SizeCallback(void *callbackdata, tjs_uint w,
tjs_uint h)
{
tTVPLoadGraphicData * data = (tTVPLoadGraphicData *)callbackdata;
// check size
data->OrgW = w;
data->OrgH = h;
if(data->DesW && w < data->DesW) w = data->DesW;
if(data->DesH && h < data->DesH) h = data->DesH;
data->BufW = w;
data->BufH = h;
// create buffer
if(data->Type == lgtMask)
{
// mask ( _m ) load
// check the image previously loaded
if(data->Dest->GetWidth() != w || data->Dest->GetHeight() != h)
TVPThrowExceptionMessage(TVPMaskSizeMismatch);
// allocate line buffer
data->Buffer = new tjs_uint8 [w];
}
else
{
// normal load or province load
data->Dest->Recreate(w, h, data->Type!=lgtFullColor?8:32, data->Unpadding);
}
}
//---------------------------------------------------------------------------
static void * TVPLoadGraphic_ScanLineCallback(void *callbackdata, tjs_int y)
{
tTVPLoadGraphicData * data = (tTVPLoadGraphicData *)callbackdata;
if(y >= 0)
{
// query of line buffer
data->ScanLineNum = y;
if(data->Type == lgtMask)
{
// mask
return data->Buffer;
}
else
{
// return the scanline for writing
return data->Dest->GetScanLineForWrite(y);
}
}
else
{
// y==-1 indicates the buffer previously returned was written
if(data->Type == lgtMask)
{
// mask
// tile for horizontal direction
tjs_uint i;
for(i = data->OrgW; i<data->BufW; i+=data->OrgW)
{
tjs_uint w = data->BufW - i;
w = w > data->OrgW ? data->OrgW : w;
memcpy(data->Buffer + i, data->Buffer, w);
}
// bind mask buffer to main image buffer ( and tile for vertical )
for(i = data->ScanLineNum; i<data->BufH; i+=data->OrgH)
{
TVPBindMaskToMain(
(tjs_uint32*)data->Dest->GetScanLineForWrite(i),
data->Buffer, data->BufW);
}
return NULL;
}
else if(data->Type == lgtFullColor)
{
tjs_uint32 * sl =
(tjs_uint32*)data->Dest->GetScanLineForWrite(data->ScanLineNum);
if((data->ColorKey & 0xff000000) == 0x00000000)
{
// make alpha from color key
TVPMakeAlphaFromKey(
sl,
data->BufW,
data->ColorKey);
}
// tile for horizontal direction
tjs_uint i;
for(i = data->OrgW; i<data->BufW; i+=data->OrgW)
{
tjs_uint w = data->BufW - i;
w = w > data->OrgW ? data->OrgW : w;
memcpy(sl + i, sl, w * sizeof(tjs_uint32));
}
// tile for vertical direction
for(i = data->ScanLineNum + data->OrgH; i<data->BufH; i+=data->OrgH)
{
memcpy(
(tjs_uint32*)data->Dest->GetScanLineForWrite(i),
sl,
data->BufW * sizeof(tjs_uint32) );
}
return NULL;
}
else if(data->Type == lgtPalGray)
{
// nothing to do
if(data->OrgW < data->BufW || data->OrgH < data->BufH)
{
tjs_uint8 * sl =
(tjs_uint8*)data->Dest->GetScanLineForWrite(data->ScanLineNum);
tjs_uint i;
// tile for horizontal direction
for(i = data->OrgW; i<data->BufW; i+=data->OrgW)
{
tjs_uint w = data->BufW - i;
w = w > data->OrgW ? data->OrgW : w;
memcpy(sl + i, sl, w * sizeof(tjs_uint8));
}
// tile for vertical direction
for(i = data->ScanLineNum + data->OrgH; i<data->BufH; i+=data->OrgH)
{
memcpy(
(tjs_uint8*)data->Dest->GetScanLineForWrite(i),
sl,
data->BufW * sizeof(tjs_uint8));
}
}
return NULL;
}
}
return NULL;
}
//---------------------------------------------------------------------------
static void TVPLoadGraphic_MetaInfoPushCallback(void *callbackdata,
const ttstr & name, const ttstr & value)
{
tTVPLoadGraphicData * data = (tTVPLoadGraphicData *)callbackdata;
if(data->NeedMetaInfo)
{
if(!data->MetaInfo) data->MetaInfo = new std::vector<tTVPGraphicMetaInfoPair>();
data->MetaInfo->push_back(tTVPGraphicMetaInfoPair(name, value));
}
}
//---------------------------------------------------------------------------
//static int _USERENTRY TVPColorCompareFunc(const void *_a, const void *_b)
static int TVPColorCompareFunc(const void *_a, const void *_b)
{
tjs_uint32 a = *(const tjs_uint32*)_a;
tjs_uint32 b = *(const tjs_uint32*)_b;
if(a<b) return -1;
if(a==b) return 0;
return 1;
}
//---------------------------------------------------------------------------
static void TVPMakeAlphaFromAdaptiveColor(tTVPBaseBitmap *dest)
{
// make adaptive color key and make alpha from it.
// adaptive color key is most used(popular) color at first line of the
// graphic.
if(!dest->Is32BPP()) return;
// copy first line to buffer
tjs_int w = dest->GetWidth();
tjs_int pitch = std::abs(dest->GetPitchBytes());
tjs_uint32 * buffer = new tjs_uint32[pitch];
try
{
const void *d = dest->GetScanLine(0);
memcpy(buffer, d, pitch);
tjs_int i;
for(i = w -1; i>=0; i--) buffer[i] &= 0xffffff;
buffer[w] = (tjs_uint32)-1; // a sentinel
// sort by color
qsort(buffer, dest->GetWidth(), sizeof(tjs_uint32), TVPColorCompareFunc);
// find most used color
tjs_int maxlen = 0;
tjs_uint32 maxlencolor = 0;
tjs_uint32 pcolor = (tjs_uint32)-1;
tjs_int l = 0;
for(i = 0; i< w+1; i++)
{
if(buffer[i] != pcolor)
{
if(maxlen < l)
{
maxlen = l;
maxlencolor = pcolor;
l = 0;
}
}
else
{
l++;
}
pcolor = buffer[i];
}
if(maxlencolor == (tjs_uint32)-1)
{
// may color be not found...
maxlencolor = 0; // black is a default colorkey
}
// make alpha from maxlencolor
tjs_int h;
for(h = dest->GetHeight()-1; h>=0; h--)
{
TVPMakeAlphaFromKey((tjs_uint32*)dest->GetScanLineForWrite(h),
w, maxlencolor);
}
}
catch(...)
{
delete [] buffer;
throw;
}
delete [] buffer;
}
//---------------------------------------------------------------------------
static void TVPDoAlphaColorMat(tTVPBaseBitmap *dest, tjs_uint32 color)
{
// Do alpha matting.
// 'mat' means underlying color of the image. This function piles
// specified color under the image, then blend. The output image
// will be totally opaque. This function always assumes the image
// has pixel value for alpha blend mode, not additive alpha blend mode.
if(!dest->Is32BPP()) return;
tjs_int w = dest->GetWidth();
tjs_int h = dest->GetHeight();
for(tjs_int y = 0; y < h; y++)
{
tjs_uint32 * buffer = (tjs_uint32*)dest->GetScanLineForWrite(y);
TVPAlphaColorMat(buffer, color, w);
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
iTJSDispatch2 * TVPMetaInfoPairsToDictionary(
std::vector<tTVPGraphicMetaInfoPair> *vec)
{
if(!vec) return NULL;
std::vector<tTVPGraphicMetaInfoPair>::iterator i;
iTJSDispatch2 *dic = TJSCreateDictionaryObject();
try
{
for(i = vec->begin(); i != vec->end(); i++)
{
tTJSVariant val(i->Value);
dic->PropSet(TJS_MEMBERENSURE, i->Name.c_str(), 0,
&val, dic);
}
}
catch(...)
{
dic->Release();
throw;
}
return dic;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Graphics Cache Management
//---------------------------------------------------------------------------
bool TVPAllocGraphicCacheOnHeap = false;
// this allocates graphic cache's store memory on heap, rather than
// sharing bitmap object. ( since sucking win9x cannot have so many bitmap
// object at once, WinNT/2000 is ok. )
// this will take more time for memory copying.
//---------------------------------------------------------------------------
struct tTVPGraphicsSearchData
{
ttstr Name;
tjs_int32 KeyIdx; // color key index
tTVPGraphicLoadMode Mode; // image mode
tjs_uint DesW; // desired width ( 0 for original size )
tjs_uint DesH; // desired height ( 0 for original size )
bool operator == (const tTVPGraphicsSearchData &rhs) const
{
return KeyIdx == rhs.KeyIdx && Mode == rhs.Mode &&
Name == rhs.Name && DesW == rhs.DesW && DesH == rhs.DesH;
}
};
//---------------------------------------------------------------------------
class tTVPGraphicsSearchHashFunc
{
public:
static tjs_uint32 Make(const tTVPGraphicsSearchData &val)
{
tjs_uint32 v = tTJSHashFunc<ttstr>::Make(val.Name);
v ^= val.KeyIdx + (val.KeyIdx >> 23);
v ^= (val.Mode << 30);
v ^= val.DesW + (val.DesW >> 8);
v ^= val.DesH + (val.DesH >> 8);
return v;
}
};
//---------------------------------------------------------------------------
class tTVPGraphicImageData
{
private:
tTVPBaseBitmap *Bitmap;
tjs_uint8 * RawData;
tjs_int Width;
tjs_int Height;
tjs_int PixelSize;
public:
ttstr ProvinceName;
std::vector<tTVPGraphicMetaInfoPair> * MetaInfo;
private:
tjs_int RefCount;
tjs_uint Size;
public:
tTVPGraphicImageData()
{
RefCount = 1; Size = 0; Bitmap = NULL; RawData = NULL;
MetaInfo = NULL;
}
~tTVPGraphicImageData()
{
if(Bitmap) delete Bitmap;
if(RawData) delete [] RawData;
if(MetaInfo) delete MetaInfo;
}
void AssignBitmap(const tTVPBaseBitmap *bmp)
{
if(Bitmap) delete Bitmap, Bitmap = NULL;
if(RawData) delete [] RawData, RawData = NULL;
Width = bmp->GetWidth();
Height = bmp->GetHeight();
PixelSize = bmp->Is32BPP()?4:1;
Size = Width*Height*PixelSize;
if(!TVPAllocGraphicCacheOnHeap)
{
// simply assin to Bitmap
Bitmap = new tTVPBaseBitmap(*bmp);
}
else
{
// allocate heap and copy to it
tjs_int h = Height;
RawData = new tjs_uint8 [ Size ];
tjs_uint8 *p = RawData;
tjs_int rawpitch = Width * PixelSize;
for(h--; h>=0; h--)
{
memcpy(p, bmp->GetScanLine(h), rawpitch);
p += rawpitch;
}
}
}
void AssignToBitmap(tTVPBaseBitmap *bmp) const
{
if(!TVPAllocGraphicCacheOnHeap)
{
// simply assign to Bitmap
if(Bitmap) bmp->AssignBitmap(*Bitmap);
}
else
{
// copy from the rawdata heap
if(RawData)
{
bmp->Recreate(Width, Height, PixelSize==4?32:8);
tjs_int h = Height;
tjs_uint8 *p = RawData;
tjs_int rawpitch = Width * PixelSize;
for(h--; h>=0; h--)
{
memcpy(bmp->GetScanLineForWrite(h), p, rawpitch);
p += rawpitch;
}
}
}
}
tjs_uint GetSize() const { return Size; }
void AddRef() { RefCount ++; }
void Release()
{
if(RefCount == 1)
{
delete this;
}
else
{
RefCount--;
}
}
};
//---------------------------------------------------------------------------
typedef tTJSRefHolder<tTVPGraphicImageData> tTVPGraphicImageHolder;
typedef
tTJSHashTable<tTVPGraphicsSearchData, tTVPGraphicImageHolder, tTVPGraphicsSearchHashFunc>
tTVPGraphicCache;
tTVPGraphicCache TVPGraphicCache;
static bool TVPGraphicCacheEnabled = false;
static tjs_uint64 TVPGraphicCacheLimit = 0;
static tjs_uint64 TVPGraphicCacheTotalBytes = 0;
tjs_uint64 TVPGraphicCacheSystemLimit = 0; // maximum possible value of TVPGraphicCacheLimit
//---------------------------------------------------------------------------
static void TVPCheckGraphicCacheLimit()
{
while(TVPGraphicCacheTotalBytes > TVPGraphicCacheLimit)
{
// chop last graphics
tTVPGraphicCache::tIterator i;
i = TVPGraphicCache.GetLast();
if(!i.IsNull())
{
tjs_uint size = i.GetValue().GetObjectNoAddRef()->GetSize();
TVPGraphicCacheTotalBytes -= size;
TVPGraphicCache.ChopLast(1);
}
else
{
break;
}
}
}
//---------------------------------------------------------------------------
void TVPClearGraphicCache()
{
TVPGraphicCache.Clear();
TVPGraphicCacheTotalBytes = 0;
}
static tTVPAtExit
TVPUninitMessageLoad(TVP_ATEXIT_PRI_RELEASE, TVPClearGraphicCache);
//---------------------------------------------------------------------------
struct tTVPClearGraphicCacheCallback : public tTVPCompactEventCallbackIntf
{
virtual void TJS_INTF_METHOD OnCompact(tjs_int level)
{
if(level >= TVP_COMPACT_LEVEL_MINIMIZE)
{
// clear the font cache on application minimize
TVPClearGraphicCache();
}
}
} static TVPClearGraphicCacheCallback;
static bool TVPClearGraphicCacheCallbackInit = false;
//---------------------------------------------------------------------------
void TVPPushGraphicCache( const ttstr& nname, tTVPBaseBitmap* bmp, std::vector<tTVPGraphicMetaInfoPair>* meta )
{
if( TVPGraphicCacheEnabled ) {
// graphic compact initialization
if(!TVPClearGraphicCacheCallbackInit)
{
TVPAddCompactEventHook(&TVPClearGraphicCacheCallback);
TVPClearGraphicCacheCallbackInit = true;
}
tTVPGraphicImageData* data = NULL;
try {
tjs_uint32 hash;
tTVPGraphicsSearchData searchdata;
searchdata.Name = nname;
searchdata.KeyIdx = TVP_clNone;
searchdata.Mode = glmNormal;
searchdata.DesW = 0;
searchdata.DesH = 0;
hash = tTVPGraphicCache::MakeHash(searchdata);
data = new tTVPGraphicImageData();
data->AssignBitmap( bmp );
data->ProvinceName = TJS_W("");
data->MetaInfo = meta;
meta = NULL;
// check size limit
TVPCheckGraphicCacheLimit();
// push into hash table
tjs_uint datasize = data->GetSize();
TVPGraphicCacheTotalBytes += datasize;
tTVPGraphicImageHolder holder(data);
TVPGraphicCache.AddWithHash(searchdata, hash, holder);
} catch(...) {
if(meta) delete meta;
if(data) data->Release();
throw;
}
if(data) data->Release();
} else {
if( meta ) delete meta;
}
}
//---------------------------------------------------------------------------
bool TVPCheckImageCache( const ttstr& nname, tTVPBaseBitmap* dest, tTVPGraphicLoadMode mode, tjs_uint dw, tjs_uint dh, tjs_int32 keyidx, iTJSDispatch2** metainfo )
{
tjs_uint32 hash;
tTVPGraphicsSearchData searchdata;
if(TVPGraphicCacheEnabled)
{
searchdata.Name = nname;
searchdata.KeyIdx = keyidx;
searchdata.Mode = mode;
searchdata.DesW = dw;
searchdata.DesH = dh;
hash = tTVPGraphicCache::MakeHash(searchdata);
tTVPGraphicImageHolder * ptr =
TVPGraphicCache.FindAndTouchWithHash(searchdata, hash);
if(ptr)
{
// found in cache
ptr->GetObjectNoAddRef()->AssignToBitmap(dest);
if(metainfo)
*metainfo = TVPMetaInfoPairsToDictionary(ptr->GetObjectNoAddRef()->MetaInfo);
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
// 検索だけする
bool TVPHasImageCache( const ttstr& nname, tTVPGraphicLoadMode mode, tjs_uint dw, tjs_uint dh, tjs_int32 keyidx )
{
tjs_uint32 hash;
tTVPGraphicsSearchData searchdata;
if(TVPGraphicCacheEnabled)
{
searchdata.Name = nname;
searchdata.KeyIdx = keyidx;
searchdata.Mode = mode;
searchdata.DesW = dw;
searchdata.DesH = dh;
hash = tTVPGraphicCache::MakeHash(searchdata);
tTVPGraphicImageHolder * ptr =
TVPGraphicCache.FindAndTouchWithHash(searchdata, hash);
if(ptr)
{
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
static bool TVPInternalLoadGraphic(tTVPBaseBitmap *dest, const ttstr &_name,
tjs_uint32 keyidx, tjs_uint desw, tjs_int desh, std::vector<tTVPGraphicMetaInfoPair> * * MetaInfo,
tTVPGraphicLoadMode mode, ttstr *provincename, bool unpadding=false)
{
// name must be normalized.
// if "provincename" is non-null, this function set it to province storage
// name ( with _p suffix ) for convinience.
// desw and desh are desired size. if the actual picture is smaller than
// the given size, the graphic is to be tiled. give 0,0 to obtain default
// size graphic.
// graphic compact initialization
if(!TVPClearGraphicCacheCallbackInit)
{
TVPAddCompactEventHook(&TVPClearGraphicCacheCallback);
TVPClearGraphicCacheCallbackInit = true;
}
// search according with its extension
tjs_int namelen = _name.GetLen();
ttstr name(_name);
ttstr ext = TVPExtractStorageExt(name);
int extlen = ext.GetLen();
tTVPGraphicHandlerType * handler;
if(ext == TJS_W(""))
{
// missing extension
// suggest registered extensions
tTJSHashTable<ttstr, tTVPGraphicHandlerType>::tIterator i;
for(i = TVPGraphicType.Hash.GetFirst(); !i.IsNull(); /*i++*/)
{
ttstr newname = name + i.GetKey();
if(TVPIsExistentStorage(newname))
{
// file found
name = newname;
break;
}
i++;
}
if(i.IsNull())
{
// not found
TVPThrowExceptionMessage(TVPCannotSuggestGraphicExtension, name);
}
handler = & i.GetValue();
}
else
{
handler = TVPGraphicType.Hash.Find(ext);
}
if(!handler) TVPThrowExceptionMessage(TVPUnknownGraphicFormat, name);
tTVPStreamHolder holder(name); // open a storage named "name"
// load the image
tTVPLoadGraphicData data;
data.Dest = dest;
data.ColorKey = keyidx;
data.Type = (mode == glmNormal || mode == glmNormalRGBA) ? lgtFullColor : lgtPalGray;
data.Name = name;
data.DesW = desw;
data.DesH = desh;
data.NeedMetaInfo = true;
data.MetaInfo = NULL;
data.Unpadding = unpadding;
bool keyadapt = (keyidx == TVP_clAdapt);
bool doalphacolormat = TVP_Is_clAlphaMat(keyidx);
tjs_uint32 alphamatcolor = TVP_get_clAlphaMat(keyidx);
if(TVP_Is_clPalIdx(keyidx))
{
// pass the palette index number to the handler.
// ( since only Graphic Loading Handler can process the palette information )
keyidx = TVP_get_clPalIdx(keyidx);
}
else
{
keyidx = -1;
}
(handler->Load)(handler->FormatData, (void*)&data, TVPLoadGraphic_SizeCallback,
TVPLoadGraphic_ScanLineCallback, TVPLoadGraphic_MetaInfoPushCallback,
holder.Get(), keyidx, mode);
*MetaInfo = data.MetaInfo;
if(keyadapt && mode == glmNormal)
{
// adaptive color key
TVPMakeAlphaFromAdaptiveColor(dest);
}
if(mode != glmNormal) return true;
if(provincename)
{
// set province name
*provincename = ttstr(_name, namelen-extlen) + TJS_W("_p");
// search extensions
tTJSHashTable<ttstr, tTVPGraphicHandlerType>::tIterator i;
for(i = TVPGraphicType.Hash.GetFirst(); !i.IsNull(); /*i++*/)
{
ttstr newname = *provincename + i.GetKey();
if(TVPIsExistentStorage(newname))
{
// file found
*provincename = newname;
break;
}
i++;
}
if(i.IsNull())
{
// not found
provincename->Clear();
}
}
// mask image handling ( addding _m suffix with the filename )
while(true)
{
name = ttstr(_name, namelen-extlen) + TJS_W("_m") + ext;
if(ext.IsEmpty())
{
// missing extension
// suggest registered extensions
tTJSHashTable<ttstr, tTVPGraphicHandlerType>::tIterator i;
for(i = TVPGraphicType.Hash.GetFirst(); !i.IsNull(); /*i++*/)
{
ttstr newname = name;
newname += i.GetKey();
if(TVPIsExistentStorage(newname))
{
// file found
name = newname;
break;
}
i++;
}
if(i.IsNull())
{
// not found
handler = NULL;
break;
}
handler = & i.GetValue();
break;
}
else
{
if(!TVPIsExistentStorage(name))
{
// not found
ext.Clear();
continue; // retry searching
}
handler = TVPGraphicType.Hash.Find(ext);
break;
}
}
if(handler)
{
// open the mask file
holder.Open(name);
// fill "data"'s member
data.Type = lgtMask;
data.Name = name;
data.Buffer = NULL;
data.DesW = desw;
data.DesH = desh;
data.NeedMetaInfo = false;
try
{
// load image via handler
(handler->Load)(handler->FormatData, (void*)&data,
TVPLoadGraphic_SizeCallback, TVPLoadGraphic_ScanLineCallback,
NULL,
holder.Get(), -1, glmGrayscale);
}
catch(...)
{
if(data.Buffer) delete [] data.Buffer;
throw;
}
if(data.Buffer) delete [] data.Buffer;
}
// do color matting
if(doalphacolormat)
{
// alpha color mat
TVPDoAlphaColorMat(dest, alphamatcolor);
}
return true;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TVPLoadGraphic
//---------------------------------------------------------------------------
void TVPLoadGraphic(tTVPBaseBitmap *dest, const ttstr &name, tjs_int32 keyidx,
tjs_uint desw, tjs_uint desh,
tTVPGraphicLoadMode mode, ttstr *provincename, iTJSDispatch2 ** metainfo, bool unpadding)
{
// loading with cache management
ttstr nname = TVPNormalizeStorageName(name);
tjs_uint32 hash;
tTVPGraphicsSearchData searchdata;
if(TVPGraphicCacheEnabled)
{
searchdata.Name = nname;
searchdata.KeyIdx = keyidx;
searchdata.Mode = mode;
searchdata.DesW = desw;
searchdata.DesH = desh;
hash = tTVPGraphicCache::MakeHash(searchdata);
tTVPGraphicImageHolder * ptr =
TVPGraphicCache.FindAndTouchWithHash(searchdata, hash);
if(ptr)
{
// found in cache
ptr->GetObjectNoAddRef()->AssignToBitmap(dest);
if(provincename) *provincename = ptr->GetObjectNoAddRef()->ProvinceName;
if(metainfo)
*metainfo = TVPMetaInfoPairsToDictionary(ptr->GetObjectNoAddRef()->MetaInfo);
return;
}
}
// not found
// load into dest
tTVPGraphicImageData * data = NULL;
ttstr pn;
std::vector<tTVPGraphicMetaInfoPair> * mi = NULL;
try
{
TVPInternalLoadGraphic(dest, nname, keyidx, desw, desh, &mi, mode, &pn, unpadding);
if(provincename) *provincename = pn;
if(metainfo)
*metainfo = TVPMetaInfoPairsToDictionary(mi);
if(TVPGraphicCacheEnabled)
{
data = new tTVPGraphicImageData();
data->AssignBitmap(dest);
data->ProvinceName = pn;
data->MetaInfo = mi; // now mi is managed under tTVPGraphicImageData
mi = NULL;
// check size limit
TVPCheckGraphicCacheLimit();
// push into hash table
tjs_uint datasize = data->GetSize();
// if(datasize < TVPGraphicCacheLimit)
// {
TVPGraphicCacheTotalBytes += datasize;
tTVPGraphicImageHolder holder(data);
TVPGraphicCache.AddWithHash(searchdata, hash, holder);
// }
}
}
catch(...)
{
if(mi) delete mi;
if(data) data->Release();
throw;
}
if(mi) delete mi;
if(data) data->Release();
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TVPTouchImages
//---------------------------------------------------------------------------
void TVPTouchImages(const std::vector<ttstr> & storages, tjs_int64 limit,
tjs_uint64 timeout)
{
// preload graphic files into the cache.
// "limit" is a limit memory for preload, in bytes.
// this function gives up when "timeout" (in ms) expired.
// currently this function only loads normal graphics.
// (univ.trans rule graphics nor province image may not work properly)
if(!TVPGraphicCacheLimit) return;
tjs_uint64 limitbytes;
if(limit >= 0)
{
if( (tjs_uint64)limit > TVPGraphicCacheLimit || limit == 0)
limitbytes = TVPGraphicCacheLimit;
else
limitbytes = limit;
}
else
{
// negative value of limit indicates remaining bytes after loading
if((tjs_uint64)-limit >= TVPGraphicCacheLimit) return;
limitbytes = TVPGraphicCacheLimit + limit;
}
tjs_int count = 0;
tjs_uint64 bytes = 0;
tjs_uint64 starttime = TVPGetTickCount();
tjs_uint64 limittime = starttime + timeout;
tTVPBaseBitmap tmp(32, 32, 32);
ttstr statusstr( (const tjs_char*)TVPInfoTouching );
bool first = true;
while((tjs_uint)count < storages.size())
{
if(timeout && TVPGetTickCount() >= limittime)
{
statusstr += (const tjs_char*)TVPAbortedTimeOut;
break;
}
if(bytes >= limitbytes)
{
statusstr += (const tjs_char*)TVPAbortedLimitByte;
break;
}
try
{
if(!first) statusstr += TJS_W(", ");
first = false;
statusstr += storages[count];
TVPLoadGraphic(&tmp, storages[count++], TVP_clNone,
0, 0, glmNormal, NULL); // load image
// get image size
tTVPGraphicImageData * data = new tTVPGraphicImageData();
try
{
data->AssignBitmap(&tmp);
bytes += data->GetSize();
}
catch(...)
{
data->Release();
throw;
}
data->Release();
}
catch(eTJS &e)
{
statusstr += TJS_W("(error!:");
statusstr += e.GetMessage();
statusstr += TJS_W(")");
}
catch(...)
{
// ignore all errors
}
}
// re-touch graphic cache to ensure that more earlier graphics in storages
// array can get more priority in cache order.
count--;
for(;count >= 0; count--)
{
tTVPGraphicsSearchData searchdata;
searchdata.Name = TVPNormalizeStorageName(storages[count]);
searchdata.KeyIdx = TVP_clNone;
searchdata.Mode = glmNormal;
searchdata.DesW = 0;
searchdata.DesH = 0;
tjs_uint32 hash = tTVPGraphicCache::MakeHash(searchdata);
TVPGraphicCache.FindAndTouchWithHash(searchdata, hash);
}
statusstr += TJS_W(" (elapsed ");
statusstr += ttstr((tjs_int)(TVPGetTickCount() - starttime));
statusstr += TJS_W("ms)");
TVPAddLog(statusstr);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TVPSetGraphicCacheLimit
//---------------------------------------------------------------------------
void TVPSetGraphicCacheLimit(tjs_uint64 limit)
{
// set limit of graphic cache by total bytes.
if(limit == 0 )
{
TVPGraphicCacheLimit = limit;
TVPGraphicCacheEnabled = false;
}
else if(limit == -1)
{
TVPGraphicCacheLimit = TVPGraphicCacheSystemLimit;
TVPGraphicCacheEnabled = true;
}
else
{
if(limit > TVPGraphicCacheSystemLimit)
limit = TVPGraphicCacheSystemLimit;
TVPGraphicCacheLimit = limit;
TVPGraphicCacheEnabled = true;
}
TVPCheckGraphicCacheLimit();
}
//---------------------------------------------------------------------------
tjs_uint64 TVPGetGraphicCacheLimit()
{
return TVPGraphicCacheLimit;
}
//---------------------------------------------------------------------------
| 27.044955 | 164 | 0.594637 | [
"object",
"vector"
] |
4c86e2417898d9e5b7fc5957edc1c2e49add0cc0 | 577 | cpp | C++ | src/0409.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0409.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0409.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <map>
#include <set>
#include <hash_map>
#include <hash_set>
#include <queue>
#include <stack>
#include <iomanip>
using namespace std;
class Solution {
public:
int longestPalindrome(string s) {
int m[128] = {0};
for (auto c:s)m[c]++;
bool has_odd = false;
int sum = 0;
for (int i = 0; i < 128; i++) {
if (m[i] % 2) {
has_odd = true;
sum += m[i] - 1;
} else sum += m[i];
}
return has_odd ? sum + 1 : sum;
}
}; | 17.484848 | 35 | 0.568458 | [
"vector"
] |
4c8a79c8ffcc8c8052738849f6cc4a30c12debe9 | 5,794 | hpp | C++ | inc/dcs/math/stats/distribution/pareto.hpp | sguazt/dcsxx-commons | 0fc1fd8a38b7c412941b401c00a9293bc5df8b21 | [
"Apache-2.0"
] | null | null | null | inc/dcs/math/stats/distribution/pareto.hpp | sguazt/dcsxx-commons | 0fc1fd8a38b7c412941b401c00a9293bc5df8b21 | [
"Apache-2.0"
] | null | null | null | inc/dcs/math/stats/distribution/pareto.hpp | sguazt/dcsxx-commons | 0fc1fd8a38b7c412941b401c00a9293bc5df8b21 | [
"Apache-2.0"
] | null | null | null | /**
* \file dcs/math/stats/distribution/pareto.hpp
*
* \brief The Pareto probability distribution.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
*
* 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.
*/
#ifndef DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP
#define DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP
#include <dcs/detail/config/boost.hpp>
#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35
# error "Required Boost library version >= 1.35"
#endif
#include <boost/math/distributions/pareto.hpp>
#include <cmath>
#include <cstddef>
#include <dcs/math/policies/policy.hpp>
#include <dcs/math/random/uniform_01_adaptor.hpp>
#include <iostream>
#include <vector>
namespace dcs { namespace math { namespace stats {
/**
* \brief The Pareto distribution with shape parameter \f$\alpha\f$ and scale
* parameter \f$\beta\f$.
*
* \tparam RealT The type used for real numbers.
* \tparam PolicyT The policy type.
*
* The probability density function (pdf):
* \f[
* \Pr(x|\lambda) = \frac{\alpha\,\beta^\alpha}{x^{\alpha+1}}, \quad
* \text{ for }x>\beta
* \f]
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*/
template < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >
class pareto_distribution
{
public: typedef RealT support_type;
public: typedef RealT value_type;
public: typedef PolicyT policy_type;
public: explicit pareto_distribution(support_type shape=1, support_type scale=1)
: dist_(shape, scale)
{
// empty
}
// compiler-generated copy ctor and assignment operator are fine
/**
* \brief Generate a random number distributed according to this
* pareto distribution.
*
* \param rng A uniform random number generator.
* \return A random number distributed according to this pareto
* distribution.
*
* A \c pareto random number distribution produces random numbers
* \f$x > 0\f$ distributed according to the probability density function:
* \f[
* \Pr(x|\alpha) = \frac{\alpha\,k^\alpha}{x^{\alpha+1}}, \quad
* \text{ for }x>k
* \f]
*/
public: template <typename UniformRandomGeneratorT>
support_type rand(UniformRandomGeneratorT& rng) const
{
::dcs::math::random::uniform_01_adaptor<UniformRandomGeneratorT&, support_type> eng(rng);
// Use the inversion method:
// x=\frac{k}{(1-p)^{1/\alpha}}
// => x=k(1-p)^{-1/\alpha}
// => x=ku^{-1/\alpha}, where u is a uniform random number in [0,1)
#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)
return dist_.scale()*::std::pow(value_type(1)-eng(), -value_type(1)/dist_.shape());
// return dist_.scale()*::std::pow(eng(), -value_type(1)/dist_.shape());
#else
return dist_.location()*::std::pow(value_type(1)-eng(), -value_type(1)/dist_.shape());
// return dist_.location()*::std::pow(eng(), -value_type(1)/dist_.shape());
#endif // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION
}
/**
* \brief Generate a vector of random numbers distributed according to this
* pareto distribution.
*
* \param rng A uniform random number generator.
* \param n The number of random numbers to generate.
* \return A vector of random numbers distributed according to this
* pareto distribution.
*
* A \c pareto random number distribution produces random numbers
* \f$x > 0\f$ distributed according to the probability density function:
* \f[
* \Pr(x|\lambda) = \frac{\alpha\,\beta^\alpha}{x^{\alpha+1}}, \quad
* \text{ for }x>\beta
* \f]
*/
public: template <typename UniformRandomGeneratorT>
::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n)
{
::std::vector<support_type> rnds(n);
for ( ; n > 0; --n)
{
rnds.push_back(rand());
}
return rnds;
}
public: support_type shape() const
{
return dist_.shape();
}
public: support_type scale() const
{
#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)
return dist_.scale();
#else
return dist_.location();
#endif // DCS_DETAIL_CONFIG_BOOST_VERSION
}
public: support_type quantile(value_type p) const
{
return ::boost::math::quantile(dist_, p);
}
public: value_type mean() const
{
#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)
return dist_.scale()*dist_.shape()/(dist_.shape()-1);
#else
return dist_.location()*dist_.shape()/(dist_.shape()-1);
#endif // DCS_DETAIL_CONFIG_BOOST_VERSION
}
public: value_type variance() const
{
#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)
return dist_.scale()*dist_.scale()*dist_.shape()/((dist_.shape()-1)*(dist_.shape()-2));
#else
return dist_.location()*dist_.location()*dist_.shape()/((dist_.shape()-1)*(dist_.shape()-2));
#endif // DCS_DETAIL_CONFIG_BOOST_VERSION
}
private: ::boost::math::pareto_distribution<value_type,policy_type> dist_;
};
template <
typename CharT,
typename CharTraitsT,
typename RealT,
typename PolicyT
>
::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, pareto_distribution<RealT,PolicyT> const& dist)
{
return os << "Pareto("
<< "shape=" << dist.shape()
<< ", scale=" << dist.scale()
<< ")";
}
}}} // Namespace dcs::math::stats
#endif // DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP
| 28.126214 | 144 | 0.695547 | [
"shape",
"vector"
] |
4c8d2db6b86d2e7f19326b1087b4554c09b91281 | 8,029 | cc | C++ | src/macro/smallbank/api_adapters/FabricV2.cc | David-Sat/blockbench | 47f09cbfee013b3e7d8dd0b696068461b8a37eb6 | [
"Apache-2.0"
] | null | null | null | src/macro/smallbank/api_adapters/FabricV2.cc | David-Sat/blockbench | 47f09cbfee013b3e7d8dd0b696068461b8a37eb6 | [
"Apache-2.0"
] | null | null | null | src/macro/smallbank/api_adapters/FabricV2.cc | David-Sat/blockbench | 47f09cbfee013b3e7d8dd0b696068461b8a37eb6 | [
"Apache-2.0"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <array>
#include <sstream>
#include <restclient-cpp/restclient.h>
#include "FabricV2.h"
#include "utils/timer.h"
// using namespace std;
const std::string HEIGHT_END_POINT = "/height";
const std::string BLOCK_END_POINT = "/block";
const std::string INVOKE_END_POINT = "/invoke";
const std::string QUERY_END_POINT = "/query";
const std::string TXCODE_END_POINT = "/txcode";
const std::string REQUEST_HEADERS = "application/json";
inline void split(const std::string &s, char delim,
std::vector<std::string> *elems) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
(*elems).push_back(item);
}
}
inline std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, &elems);
return elems;
}
inline std::string get_json_field(const std::string &json,
const std::string &key) {
auto key_pos = json.find(key);
auto quote_sign_pos_1 = json.find('\"', key_pos + 1);
auto quote_sign_pos_2 = json.find('\"', quote_sign_pos_1 + 1);
auto quote_sign_pos_3 = json.find('\"', quote_sign_pos_2 + 1);
std::string extracted = json.substr(quote_sign_pos_2 + 1, quote_sign_pos_3 - quote_sign_pos_2 - 1);
return extracted;
}
inline std::vector<std::string> get_list_field(const std::string &json,
const std::string &key) {
auto key_pos = json.find(key);
auto quote_sign_pos_1 = json.find('\"', key_pos + 1);
auto quote_sign_pos_2 = json.find('[', quote_sign_pos_1 + 1);
auto quote_sign_pos_3 = json.find(']', quote_sign_pos_2 + 1);
return split(json.substr(quote_sign_pos_2 + 1,
quote_sign_pos_3 - quote_sign_pos_2 - 1),
',');
}
// get all tx from the start_block until latest
std::vector<std::string> FabricV2::poll_tx(int block_number) {
std::string serviceAddr;
this->addresses(&serviceAddr, NULL);
char buff[100];
std::sprintf(buff, "?num=%d", block_number);
std::string requestArg(buff);
auto r = RestClient::get(serviceAddr + BLOCK_END_POINT + requestArg).body;
if (get_json_field(r, "status") == "1") {
std::cerr << "Fail to read with error "
<< get_json_field(r, "message") << std::endl;
return std::vector<std::string>();
} else {
std::vector<std::string> txns = get_list_field(r, "txns");
std::vector<std::string> trimedTxns;
// std::cout << "Block " << block_number << " has txns: " << std::endl;
for (auto i = txns.begin(); i != txns.end(); ++i) {
// remove the surrounding "" and the last whitespace
std::string trimed = (*i).substr(1, i->length()-2);
trimedTxns.push_back(trimed);
// std::cout << "\t[" << trimed << "]" << std::endl;
}
return trimedTxns;
}
}
std::vector<std::string> FabricV2::poll_tx_codes(int block_number) {
std::string serviceAddr;
this->addresses(&serviceAddr, NULL);
char buff[100];
std::sprintf(buff, "?num=%d", block_number);
std::string requestArg(buff);
auto r = RestClient::get(serviceAddr + TXCODE_END_POINT + requestArg).body;
if (get_json_field(r, "status") == "1") {
std::cerr << "Fail to read with error "
<< get_json_field(r, "message") << std::endl;
return std::vector<std::string>();
} else {
std::vector<std::string> txns = get_list_field(r, "TxValidationCodes");
std::vector<std::string> trimmedTxns;
// std::cout << "Block " << block_number << " has txns: " << std::endl;
for (auto i = txns.begin(); i != txns.end(); ++i) {
// remove the surrounding "" and the last whitespace
std::string trimmed = (*i);
trimmedTxns.push_back(trimmed);
// std::cout << "\t[" << trimed << "]" << std::endl;
}
return trimmedTxns;
}
}
int FabricV2::get_tip_block_number() {
std::string serviceAddr;
this->addresses(&serviceAddr, NULL);
auto r = RestClient::get(serviceAddr + HEIGHT_END_POINT).body;
if (get_json_field(r, "status") == "1") {
std::cerr << "Fail to query for the ledger height "
<< get_json_field(r, "message") << std::endl;
return -1;
} else {
std::string height = get_json_field(r, "height");
return atoi(height.c_str())-1;
}
}
// no error handler, assume always success
void FabricV2::deploy(const std::string& path, const std::string& endpoint) {
std::cout << "Make sure to deploy Smallbank chaincode based on README.md. " << std::endl;
}
void FabricV2::add_to_queue(std::string json){
std::string status = get_json_field(json, "status");
if (status == "0") {
double start_time = time_now();
std::string txn_hash = get_json_field(json, "txnID");
txlock_->lock();
(*pendingtx_)[txn_hash] = start_time;
txlock_->unlock();
} else {
std::cerr << "Fail to invoke with error: "
<< get_json_field(json, "message") << std::endl;
}
}
std::string FabricV2::randomTxnServiceAddr() {
std::string blkServiceAddr;
std::vector<std::string> txnServiceAddrs;
this->addresses(&blkServiceAddr, &txnServiceAddrs);
srand (time(NULL));
size_t i = std::rand() % txnServiceAddrs.size();
return txnServiceAddrs[i];
}
void FabricV2::InvokeWithOneArg(std::string funcName, std::string arg) {
const char* COMMAND_TEMPLATE =
"{ \"function\": \"%s\", \"args\": [\"%s\"] }";
char buff[200 + funcName.length() + arg.length()];
std::sprintf(buff, COMMAND_TEMPLATE, funcName.c_str(), arg.c_str());
std::string writeReq(buff);
std::string addr = this->randomTxnServiceAddr();
auto r = RestClient::post(addr + INVOKE_END_POINT,
REQUEST_HEADERS,
writeReq).body;
this->add_to_queue(r);
}
void FabricV2::InvokeWithTwoArgs(std::string funcName, std::string arg1, std::string arg2) {
std::string addr = this->randomTxnServiceAddr();
const char* COMMAND_TEMPLATE =
"{ \"function\": \"%s\", \"args\": [\"%s\", \"%s\"] }";
char buff[200 + funcName.length() + arg1.length() + arg2.length()];
std::sprintf(buff, COMMAND_TEMPLATE, funcName.c_str(), arg1.c_str(), arg2.c_str());
std::string writeReq(buff);
auto r = RestClient::post(addr + INVOKE_END_POINT,
REQUEST_HEADERS,
writeReq).body;
this->add_to_queue(r);
}
void FabricV2::InvokeWithThreeArgs(std::string funcName, std::string arg1, std::string arg2, std::string arg3) {
std::string addr = this->randomTxnServiceAddr();
const char* COMMAND_TEMPLATE =
"{ \"function\": \"%s\", \"args\": [\"%s\", \"%s\", \"%s\"] }";
char buff[200 + funcName.length() + arg1.length() + arg2.length() + arg3.length()];
std::sprintf(buff, COMMAND_TEMPLATE, funcName.c_str(), arg1.c_str(), arg2.c_str(), arg3.c_str());
std::string writeReq(buff);
auto r = RestClient::post(addr + INVOKE_END_POINT,
REQUEST_HEADERS,
writeReq).body;
this->add_to_queue(r);
}
void FabricV2::Amalgate(unsigned acc1, unsigned acc2) {
this->InvokeWithTwoArgs("Almagate", std::to_string(acc1), std::to_string(acc2));
}
void FabricV2::GetBalance(unsigned acc) {
this->InvokeWithOneArg("GetBalance", std::to_string(acc));
}
void FabricV2::UpdateBalance(unsigned acc, unsigned amount) {
this->InvokeWithTwoArgs("UpdateBalance", std::to_string(acc), std::to_string(amount));
}
void FabricV2::UpdateSaving(unsigned acc, unsigned amount) {
this->InvokeWithTwoArgs("UpdateSaving", std::to_string(acc), std::to_string(amount));
}
void FabricV2::SendPayment(unsigned acc1, unsigned acc2, unsigned amount) {
this->InvokeWithThreeArgs("SendPayment", std::to_string(acc1), std::to_string(acc2), std::to_string(amount));
}
void FabricV2::WriteCheck(unsigned acc, unsigned amount) {
this->InvokeWithTwoArgs("WriteCheck", std::to_string(acc), std::to_string(amount));
}
| 35.370044 | 112 | 0.639681 | [
"vector"
] |
4c95d12ecc01dd5cf552569f1f01d7bb2a016b82 | 8,718 | cpp | C++ | Render3D/BaseNode.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | Render3D/BaseNode.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | Render3D/BaseNode.cpp | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | /*
BaseNode.cpp
(c)2005 Palestar, Richard Lyle
*/
#pragma warning( disable: 4786 ) // identifier was truncated to '255' characters in the browser information
#define RENDER3D_DLL
#include "Render3D/BaseNode.h"
#include "Debug/Assert.h"
#include "Debug/Trace.h"
#include "Standard/Exception.h"
#include "Standard/STLHelper.h"
#include <algorithm>
//----------------------------------------------------------------------------
IMPLEMENT_RESOURCE_FACTORY( BaseNode, Resource );
BEGIN_PROPERTY_LIST( BaseNode, Resource )
ADD_PROPERTY( m_Name );
ADD_BITS_PROPERTY( m_nNodeFlags );
ADD_BIT_OPTION( m_nNodeFlags, NF_NOBOUNDS );
ADD_BIT_OPTION( m_nNodeFlags, NF_NOSHADOW );
ADD_OBJECT_PROPERTY( m_Children );
END_PROPERTY_LIST();
bool BaseNode::s_ShowSelected = false; // draw box around selected node
BaseNode * BaseNode::s_pSelectedNode = NULL;
//-------------------------------------------------------------------------------
BaseNode::BaseNode() : m_pParent( NULL ), m_nNodeFlags( 0 )
{}
BaseNode::BaseNode( const BaseNode © ) :
m_Name( copy.m_Name ),
m_nNodeFlags( copy.m_nNodeFlags ),
m_Children( copy.m_Children ),
m_pParent( copy.m_pParent )
{}
BaseNode::BaseNode( BaseNode * pParent ) : m_pParent( NULL ), m_nNodeFlags( 0 )
{
pParent->attachNode( this );
}
BaseNode::~BaseNode()
{
// set the parent pointers to NULL
for(size_t i=0;i<m_Children.size();i++)
{
if ( m_Children[i].valid() )
m_Children[i]->m_pParent = NULL;
}
}
//----------------------------------------------------------------------------
bool BaseNode::read( const InStream & input )
{
if (! Resource::read( input ) )
return false;
// set the parent for all the children nodes and remove any NULL children..
for(size_t i=0;i<m_Children.size();++i)
{
BaseNode * pChild = m_Children[i];
if (! pChild )
continue;
// This can happen when the port is copied using the file system rather than Resourcer, which can
// result in duplicate unique ID's
if ( pChild->m_pParent != NULL && pChild->m_pParent != this )
{
LOG_ERROR( "BaseNode", "Child %u has wrong parent pointer in node %s", i, m_Name.cstr() );
return false;
}
pChild->m_pParent = this;
}
return true;
}
//----------------------------------------------------------------------------
BoxHull BaseNode::hull() const
{
return( BoxHull( Vector3(0,0,0), Vector3(0,0,0) ) );
}
float BaseNode::radius() const
{
// use the hull, so nobody has to implement both functions
return( hull().radius() );
}
//----------------------------------------------------------------------------
int BaseNode::attachNode( BaseNode * pChild )
{
if ( this == NULL || pChild == NULL )
return -1;
if ( pChild->isChild( this ) ) // assert that this isn't a circular attachment
return -1;
// this checks if this node is already attached to this node, if so just pretend we are attaching..
if ( this == pChild->m_pParent )
{
for(size_t i=0;i<m_Children.size();++i)
if ( m_Children[i] == pChild )
{
// notify ourselves
onAttach( pChild );
// notify the child object
pChild->onAttached();
return (int)i;
}
return -1;
}
// grab a reference to the child, otherwise when we detach from the old parent the child
// may get deleted.
Ref rChild( pChild );
if ( pChild->m_pParent != NULL )
pChild->m_pParent->detachNode( pChild );
// update the internal version number of the parent object, this is important for
// serialization reasons.
updateVersion();
pChild->m_pParent = this;
m_Children.push_back( pChild );
// notify ourselves
onAttach( pChild );
// notify the child object
pChild->onAttached();
return( m_Children.size() - 1 );
}
int BaseNode::insertNode( int n, BaseNode * pChild )
{
if (! pChild )
return -1;
if ( this == NULL || pChild == NULL )
return -1;
if ( pChild->isChild( this ) ) // assert that this isn't a circular attachment
return -1;
// grab a reference to the child, otherwise when we detach from the old parent the child
// may get deleted.
Ref rChild( pChild );
if ( pChild->m_pParent != NULL )
pChild->m_pParent->detachNode( pChild );
updateVersion();
pChild->m_pParent = this;
m_Children.insert( m_Children.begin() + n, pChild );
// notify ourselves
onAttach( pChild );
// notify the child object
pChild->onAttached();
return n;
}
void BaseNode::detachNode( int child )
{
ASSERT( this != NULL );
if ( child >= 0 && child < (int)m_Children.size() )
{
updateVersion();
BaseNode * pChild = m_Children[ child ];
if ( pChild != NULL )
{
// inform the child it is being detached
pChild->onDetaching();
// inform ourselves
onDetach( pChild );
// null the parent pointer and remove from the child list
pChild->m_pParent = NULL;
}
m_Children.erase( m_Children.begin() + child );
// notify this object that a child object has been detached
onChildDetached();
}
}
void BaseNode::detachNode( BaseNode * pChild )
{
if ( pChild != NULL )
{
for(size_t i=0;i<m_Children.size();i++)
if ( m_Children[i].pointer() == pChild )
{
detachNode( i );
break;
}
}
}
void BaseNode::detachNodeSwap( int nChild )
{
if ( nChild >= 0 && nChild < (int)m_Children.size() )
{
updateVersion();
BaseNode * pChild = m_Children[ nChild ];
if ( pChild != NULL )
{
// inform the child it is being detached
pChild->onDetaching();
// inform ourselves
onDetach( pChild );
// null the parent pointer and remove from the child list
pChild->m_pParent = NULL;
}
removeSwapIndex( m_Children, nChild );
// notify this object that a child object has been detached
onChildDetached();
}
}
void BaseNode::detachNodeSwap( BaseNode * pChild )
{
for(size_t i=0;i<m_Children.size();i++)
if ( m_Children[i].pointer() == pChild )
{
detachNodeSwap( i );
break;
}
}
void BaseNode::detachAllNodes()
{
updateVersion();
for(size_t i=0;i<m_Children.size();i++)
{
BaseNode * pChild = m_Children[ i ];
if (! pChild )
continue;
// inform the child it is being detached
pChild->onDetaching();
// inform ourselves
onDetach( pChild );
// set the parent pointer to NULL
pChild->m_pParent = NULL;
}
m_Children.clear();
// notify this object that a child object has been detached
onChildDetached();
}
void BaseNode::detachSelf()
{
if ( m_pParent.valid() )
m_pParent->detachNode( this );
}
void BaseNode::onAttach( BaseNode * pChild )
{}
void BaseNode::onAttached()
{}
void BaseNode::onDetach( BaseNode * pChild )
{}
void BaseNode::onChildDetached()
{}
void BaseNode::onDetaching()
{}
void BaseNode::render( RenderContext &context, const Matrix33 & frame, const Vector3 & position )
{}
void BaseNode::preRender( RenderContext &context, const Matrix33 & frame, const Vector3 & position )
{
context.setInstanceKey( context.instanceKey() + key() );
if (! context.isShadowPass() || (m_nNodeFlags & NF_NOSHADOW) == 0 )
render( context, frame, position );
// recurse into the child nodes
for(size_t i=0;i<m_Children.size();i++)
m_Children[i]->preRender( context, frame, position );
context.setInstanceKey( context.instanceKey() - key() );
}
bool BaseNode::intersect( const Matrix33 &frame, const Vector3 & position,
IntersectContext & context )
{
// rotate and transform the bounding box, it is still axis-aligned
BoxHull tHull( hull(), frame, position );
// test for intersection with the bounding box
return ( tHull.intersect( context.origin, context.ray, context.intersect ) );
}
void BaseNode::sortNodes()
{
// sort the child nodes by name
updateVersion();
std::sort( m_Children.begin(), m_Children.end(), sorter );
}
//-------------------------------------------------------------------------------
bool BaseNode::isChild( const BaseNode * pNode )
{
if ( pNode == this )
return( true );
for(size_t i=0;i<m_Children.size();i++)
if ( m_Children[i]->isChild( pNode ) )
return true;
return false;
}
BaseNode * BaseNode::findNode( const char * name )
{
if ( strcmp<char>( m_Name, name) == 0 )
return( this );
BaseNode * found = NULL;
for(size_t i=0;i<m_Children.size();i++)
if ( (found = m_Children[i]->findNode( name )) != NULL )
return( found );
return( NULL );
}
BaseNode * BaseNode::findNode( const WidgetKey & key )
{
if ( m_Key == key )
return( this );
BaseNode * found = NULL;
for(size_t i=0;i<m_Children.size();i++)
if ( (found = m_Children[i]->findNode( key )) != NULL )
return( found );
return( NULL );
}
//----------------------------------------------------------------------------
bool BaseNode::sorter( Ref p1, Ref p2 )
{
return p1->m_Name.compareNoCase( p2->m_Name ) > 0;
}
//----------------------------------------------------------------------------
// EOF
| 23.435484 | 107 | 0.623308 | [
"render",
"object",
"transform"
] |
4c997e8c1a6511509989e3a408b74b4d81ae7967 | 545 | hpp | C++ | dynamic_programming/levenshtein_distance.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 1 | 2021-12-26T14:17:29.000Z | 2021-12-26T14:17:29.000Z | dynamic_programming/levenshtein_distance.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 3 | 2020-07-13T06:23:02.000Z | 2022-02-16T08:54:26.000Z | dynamic_programming/levenshtein_distance.hpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | null | null | null | #pragma once
#include <algorithm>
#include <numeric>
#include <vector>
template <typename T>
int levenshtein_distance(const T &a, const T &b) {
int n = a.size(), m = b.size();
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1));
for (int i = 1; i <= n; ++i) dp[i][0] = i;
std::iota(dp[0].begin(), dp[0].end(), 0);
for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) {
dp[i][j] = std::min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] != b[j - 1])});
}
return dp[n][m];
}
| 32.058824 | 106 | 0.486239 | [
"vector"
] |
4c9d503c745d65305616c73a4504f1b07bf42959 | 9,330 | cpp | C++ | code/cmt/src/nonlinearities.cpp | itsb/cmt | dd37a2bcc7d477d0ee82994711acd13ee02f47a9 | [
"MIT"
] | 33 | 2015-06-15T16:52:23.000Z | 2019-11-26T19:49:36.000Z | code/cmt/src/nonlinearities.cpp | itsb/cmt | dd37a2bcc7d477d0ee82994711acd13ee02f47a9 | [
"MIT"
] | 35 | 2015-03-17T09:27:32.000Z | 2022-01-13T00:44:05.000Z | code/cmt/src/nonlinearities.cpp | itsb/cmt | dd37a2bcc7d477d0ee82994711acd13ee02f47a9 | [
"MIT"
] | 17 | 2015-01-20T10:39:59.000Z | 2020-12-16T10:24:13.000Z | #include "nonlinearities.h"
#include "exception.h"
#include "utils.h"
#include <cmath>
using std::exp;
using std::log;
using std::tanh;
#include "Eigen/Core"
using Eigen::ArrayXd;
using Eigen::ArrayXXd;
CMT::Nonlinearity::~Nonlinearity() {
}
CMT::LogisticFunction::LogisticFunction(double epsilon) : mEpsilon(epsilon) {
}
ArrayXXd CMT::LogisticFunction::operator()(const ArrayXXd& data) const {
return mEpsilon / 2. + (1. - mEpsilon) / (1. + (-data).exp());
}
double CMT::LogisticFunction::operator()(double data) const {
return mEpsilon / 2. + (1. - mEpsilon) / (1. + exp(-data));
}
ArrayXXd CMT::LogisticFunction::derivative(const ArrayXXd& data) const {
ArrayXXd tmp = operator()(data);
return (1. - mEpsilon) * tmp * (1. - tmp);
}
ArrayXXd CMT::LogisticFunction::inverse(const ArrayXXd& data) const {
return ((data - mEpsilon / 2.) / (1. - data - mEpsilon / 2.)).log();
}
double CMT::LogisticFunction::inverse(double data) const {
return log((data - mEpsilon / 2.) / (1. - data - mEpsilon / 2.));
}
CMT::ExponentialFunction::ExponentialFunction(double epsilon) : mEpsilon(epsilon) {
}
ArrayXXd CMT::ExponentialFunction::operator()(const ArrayXXd& data) const {
return data.exp() + mEpsilon;
}
double CMT::ExponentialFunction::operator()(double data) const {
return exp(data) + mEpsilon;
}
ArrayXXd CMT::ExponentialFunction::derivative(const ArrayXXd& data) const {
return data.exp();
}
ArrayXXd CMT::ExponentialFunction::inverse(const ArrayXXd& data) const {
return (data - mEpsilon).log();
}
double CMT::ExponentialFunction::inverse(double data) const {
return log(data - mEpsilon);
}
CMT::HistogramNonlinearity::HistogramNonlinearity(
const ArrayXXd& inputs,
const ArrayXXd& outputs,
int numBins,
double epsilon) : mEpsilon(epsilon)
{
initialize(inputs, outputs, numBins);
}
CMT::HistogramNonlinearity::HistogramNonlinearity(
const ArrayXXd& inputs,
const ArrayXXd& outputs,
const vector<double>& binEdges,
double epsilon) : mEpsilon(epsilon)
{
initialize(inputs, outputs, binEdges);
}
CMT::HistogramNonlinearity::HistogramNonlinearity(
const vector<double>& binEdges,
double epsilon) : mEpsilon(epsilon), mBinEdges(binEdges)
{
mHistogram = vector<double>(mBinEdges.size() - 1);
for(int k = 0; k < mHistogram.size(); ++k)
mHistogram[k] = 0.;
}
void CMT::HistogramNonlinearity::initialize(
const ArrayXXd& inputs,
const ArrayXXd& outputs,
int numBins)
{
double max = inputs.maxCoeff();
double min = inputs.minCoeff();
mBinEdges = vector<double>(numBins + 1);
double binWidth = (max - min) / numBins;
for(int k = 0; k < mBinEdges.size(); ++k)
mBinEdges[k] = min + k * binWidth;
initialize(inputs, outputs);
}
/**
* @param binEdges a list of bin edges sorted in ascending order
*/
void CMT::HistogramNonlinearity::initialize(
const ArrayXXd& inputs,
const ArrayXXd& outputs,
const vector<double>& binEdges)
{
mBinEdges = binEdges;
initialize(inputs, outputs);
}
void CMT::HistogramNonlinearity::initialize(
const ArrayXXd& inputs,
const ArrayXXd& outputs)
{
if(inputs.rows() != outputs.rows() || inputs.cols() != outputs.cols())
throw Exception("Inputs and outputs have to have same size.");
mHistogram = vector<double>(mBinEdges.size() - 1);
vector<int> counter(mBinEdges.size() - 1);
for(int k = 0; k < mHistogram.size(); ++k) {
mHistogram[k] = 0.;
counter[k] = 0;
}
for(int i = 0; i < inputs.rows(); ++i)
for(int j = 0; j < inputs.cols(); ++j) {
// find bin
int k = bin(inputs(i, j));
// update histogram
counter[k] += 1;
mHistogram[k] += outputs(i, j);
}
for(int k = 0; k < mHistogram.size(); ++k)
if(mHistogram[k] > 0.)
// average output observed in bin k
mHistogram[k] /= counter[k];
}
ArrayXXd CMT::HistogramNonlinearity::operator()(const ArrayXXd& inputs) const {
ArrayXXd outputs(inputs.rows(), inputs.cols());
for(int i = 0; i < inputs.rows(); ++i)
for(int j = 0; j < inputs.cols(); ++j)
outputs(i, j) = mHistogram[bin(inputs(i, j))] + mEpsilon;
return outputs;
}
double CMT::HistogramNonlinearity::operator()(double input) const {
return mHistogram[bin(input)] + mEpsilon;
}
/**
* Finds index into histogram.
*/
int CMT::HistogramNonlinearity::bin(double input) const {
// find bin
for(int k = 0; k < mBinEdges.size() - 1; ++k)
if(input < mBinEdges[k + 1])
return k;
return mHistogram.size() - 1;
}
ArrayXd CMT::HistogramNonlinearity::parameters() const {
ArrayXd histogram(mHistogram.size());
for(int i = 0; i < mHistogram.size(); ++i)
histogram[i] = mHistogram[i];
return histogram;
}
void CMT::HistogramNonlinearity::setParameters(const ArrayXd& parameters) {
if(parameters.size() != mHistogram.size())
throw Exception("Wrong number of parameters.");
for(int i = 0; i < mHistogram.size(); ++i)
mHistogram[i] = parameters[i];
}
int CMT::HistogramNonlinearity::numParameters() const {
return mHistogram.size();
}
ArrayXXd CMT::HistogramNonlinearity::gradient(const ArrayXXd& inputs) const {
if(inputs.rows() != 1)
throw Exception("Data has to be stored in one row.");
ArrayXXd gradient = ArrayXXd::Zero(mHistogram.size(), inputs.cols());
for(int i = 0; i < inputs.rows(); ++i)
for(int j = 0; j < inputs.rows(); ++j)
gradient(bin(inputs(i, j)), j) = 1;
return gradient;
}
CMT::BlobNonlinearity::BlobNonlinearity(int numComponents, double epsilon) :
mEpsilon(epsilon),
mNumComponents(numComponents),
mMeans(sampleNormal(numComponents, 1)),
mLogPrecisions((ArrayXd::Random(numComponents).abs() + 0.5).log()),
mLogWeights(((ArrayXd::Random(numComponents).abs() * 0.4 + 0.1) / numComponents).log())
{
}
ArrayXXd CMT::BlobNonlinearity::operator()(const ArrayXXd& inputs) const {
if(inputs.rows() != 1)
throw Exception("Data has to be stored in one row.");
ArrayXXd diff = ArrayXXd::Zero(mNumComponents, inputs.cols());
diff.rowwise() += inputs.row(0);
diff.colwise() -= mMeans;
ArrayXXd negEnergy = diff.square().colwise() * (-mLogPrecisions.exp() / 2.);
return (mLogWeights.exp().transpose().matrix() * negEnergy.exp().matrix()).array() + mEpsilon;
}
double CMT::BlobNonlinearity::operator()(double input) const {
ArrayXd negEnergy = -mLogPrecisions.exp() / 2. * (mMeans - input).square();
return mLogWeights.exp().matrix().dot(negEnergy.exp().matrix()) + mEpsilon;
}
ArrayXd CMT::BlobNonlinearity::parameters() const {
ArrayXd parameters(3 * mNumComponents);
parameters << mMeans, mLogPrecisions, mLogWeights;
return parameters;
}
void CMT::BlobNonlinearity::setParameters(const ArrayXd& parameters) {
mMeans = parameters.topRows(mNumComponents);
mLogPrecisions = parameters.middleRows(mNumComponents, mNumComponents);
mLogWeights = parameters.bottomRows(mNumComponents);
}
int CMT::BlobNonlinearity::numParameters() const {
return 3 * mNumComponents;
}
ArrayXXd CMT::BlobNonlinearity::gradient(const ArrayXXd& inputs) const {
if(inputs.rows() != 1)
throw Exception("Data has to be stored in one row.");
ArrayXXd diff = ArrayXXd::Zero(mNumComponents, inputs.cols());
diff.rowwise() += inputs.row(0);
diff.colwise() -= mMeans;
ArrayXXd diffSq = diff.square();
ArrayXd precisions = mLogPrecisions.exp();
ArrayXd weights = mLogWeights.exp();
ArrayXXd negEnergy = diffSq.colwise() * (-precisions / 2.);
ArrayXXd negEnergyExp = negEnergy.exp();
ArrayXXd gradient(3 * mNumComponents, inputs.cols());
// gradient of mean
gradient.topRows(mNumComponents) = (diff * negEnergyExp).colwise() * (weights * precisions);
// gradient of log-precisions
gradient.middleRows(mNumComponents, mNumComponents) = (diffSq / 2. * negEnergyExp).colwise() * (-weights * precisions);
// gradient of log-weights
gradient.bottomRows(mNumComponents) = negEnergyExp.colwise() * weights;
return gradient;
}
ArrayXXd CMT::BlobNonlinearity::derivative(const ArrayXXd& inputs) const {
if(inputs.rows() != 1)
throw Exception("Data has to be stored in one row.");
ArrayXXd diff = ArrayXXd::Zero(mNumComponents, inputs.cols());
diff.rowwise() -= inputs.row(0);
diff.colwise() += mMeans;
ArrayXd precisions = mLogPrecisions.exp();
ArrayXXd negEnergy = diff.square().colwise() * (-precisions / 2.);
return (mLogWeights.exp() * precisions).transpose().matrix() * (diff * negEnergy.exp()).matrix();
}
CMT::TanhBlobNonlinearity::TanhBlobNonlinearity(int numComponents, double epsilon) :
mNonlinearity(numComponents, epsilon)
{
}
ArrayXXd CMT::TanhBlobNonlinearity::operator()(const ArrayXXd& inputs) const {
return tanh(mNonlinearity(inputs));
}
double CMT::TanhBlobNonlinearity::operator()(double input) const {
return std::tanh(mNonlinearity(input));
}
ArrayXd CMT::TanhBlobNonlinearity::parameters() const {
return mNonlinearity.parameters();
}
void CMT::TanhBlobNonlinearity::setParameters(const ArrayXd& parameters) {
mNonlinearity.setParameters(parameters);
}
int CMT::TanhBlobNonlinearity::numParameters() const {
return mNonlinearity.numParameters();
}
ArrayXXd CMT::TanhBlobNonlinearity::gradient(const ArrayXXd& inputs) const {
return mNonlinearity.gradient(inputs).rowwise() * sech(mNonlinearity(inputs)).square().row(0);
}
ArrayXXd CMT::TanhBlobNonlinearity::derivative(const ArrayXXd& inputs) const {
return mNonlinearity.derivative(inputs).rowwise() * sech(mNonlinearity(inputs)).square().row(0);
}
| 22.481928 | 120 | 0.701608 | [
"vector"
] |
4ca018c3581697c484d40acee0b431163000aca3 | 13,603 | cc | C++ | src/model.cc | violet-zct/multisense-prob-fasttext | fbc78b4dfe55e6f152b90ae5227a557f8c5f5105 | [
"BSD-3-Clause"
] | null | null | null | src/model.cc | violet-zct/multisense-prob-fasttext | fbc78b4dfe55e6f152b90ae5227a557f8c5f5105 | [
"BSD-3-Clause"
] | null | null | null | src/model.cc | violet-zct/multisense-prob-fasttext | fbc78b4dfe55e6f152b90ae5227a557f8c5f5105 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2016-present, Facebook, Inc.
* 2018-present, Ben Athiwaratkun
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "model.h"
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <random>
#include <cmath>
namespace fasttext {
Model::Model(std::shared_ptr<Matrix> wi,
std::shared_ptr<Matrix> wo,
// for variance
std::shared_ptr<Vector> invar,
std::shared_ptr<Vector> outvar,
std::shared_ptr<Args> args,
int32_t seed)
: hidden_(args->dim), output_(wo->m_), gradmu_p_(args->dim), gradmu_n_(args->dim),
grad_(args->dim), temp_(args->dim), rng(seed), quant_(false), wp_diff_(args->dim), wn_diff_(args->dim)
{
wi_ = wi;
wo_ = wo;
invar_ = invar;
outvar_ = outvar;
args_ = args;
osz_ = wo->m_;
hsz_ = args->dim;
negpos = 0;
loss_ = 0.0;
nexamples_ = 1;
initSigmoid();
initLog();
gradvar_p_ = 0.0;
gradvar_n_ = 0.0;
gradvar_ = 0.0;
}
Model::~Model() {
delete[] t_sigmoid;
delete[] t_log;
}
void Model::reset_loss() {
nexamples_ = 1;
loss_ = 0.0;
}
void Model::setQuantizePointer(std::shared_ptr<QMatrix> qwi,
std::shared_ptr<QMatrix> qwo, bool qout) {
qwi_ = qwi;
qwo_ = qwo;
if (qout) {
osz_ = qwo_->getM();
}
}
real Model::binaryLogistic(int32_t target, bool label, real lr) {
real score = sigmoid(wo_->dotRow(hidden_, target));
real alpha = lr * (real(label) - score);
grad_.addRow(*wo_, target, alpha);
wo_->addRow(hidden_, target, alpha);
if (label) {
return -log(score);
} else {
return -log(1.0 - score);
}
}
real Model::negativeSamplingSingleVar(int32_t wordidx, int32_t target, real lr) {
real eplus_result = energy_singleVecvar(wordidx, target, true);
int32_t negTarget = getNegative(target);
real eminus_result = energy_singleVecvar(wordidx, negTarget, false);
real loss = args_->margin - eplus_result + eminus_result;
if (loss > 0.0){
real wp_invsumd = 1./(1e-8 + wp_var_sum_);
real wn_invsumd = 1./(1e-8 + wn_var_sum_);
real wp_invsumd_square = pow(wp_invsumd, 2.);
real wn_invsumd_square = pow(wn_invsumd, 2.);
gradmu_p_.zero();
gradmu_n_.zero();
grad_.zero();
gradvar_p_ = 0.0;
gradvar_n_ = 0.0;
gradvar_ = 0.0;
for (int64_t ii = 0; ii < hidden_.m_; ii++) {
// eplus_results simplified so only lr left
gradvar_p_ += 0.5 * lr * (-wp_invsumd + wp_invsumd_square * pow(wp_diff_[ii], 2.));
gradvar_n_ += -0.5 * lr * (-wn_invsumd + wn_invsumd_square * pow(wn_diff_[ii], 2.));
gradvar_ += gradvar_p_ + gradvar_n_;
}
gradvar_p_ = exp(outvar_->data_[target]) * gradvar_p_;
gradvar_n_ = exp(outvar_->data_[negTarget]) * gradvar_n_;
gradvar_ = exp(invar_->data_[wordidx]) * gradvar_;
outvar_->data_[target] += gradvar_p_;
outvar_->data_[negTarget] += gradvar_n_;
// TODO: thresholding the variance within a range
for (int64_t ii = 0; ii < grad_.m_; ii++) {
gradmu_p_[ii] += lr * (wp_invsumd * wp_diff_[ii]);
gradmu_n_[ii] += -lr * (wn_invsumd * wn_diff_[ii]);
grad_.data_[ii] -= (gradmu_p_[ii] + gradmu_n_[ii]);
}
if (args_->c != 0.0) {
gradmu_p_.addRow(*wo_, target, -2*lr*args_->c);
gradmu_n_.addRow(*wo_, negTarget, -2*lr*args_->c);
}
wo_->addRow(gradmu_p_, target, 1.);
wo_->addRow(gradmu_n_, negTarget, 1.);
if (args_->min_logvar !=0 || args_->max_logvar !=0) {
outvar_->data_[target] = regLogVar(outvar_->data_[target]);
outvar_->data_[negTarget] = regLogVar(outvar_->data_[negTarget]);
}
}
return std::max((real) 0.0, loss);
}
real Model::regLogVar(real logvar) {
return std::max(args_->min_logvar, std::min(logvar, args_->max_logvar));
}
// partial energy expdot
real Model::partial_energy_vecvar(Vector& hidden, Vector& grad, std::shared_ptr<Matrix> wo, int32_t wordidx, int32_t target, std::shared_ptr<Vector> varin, std::shared_ptr<Vector> varout, bool true_label){
temp_.zero();
real var_sum = exp(varin->data_[wordidx]) + exp(varout->data_[target]);
hidden_.addRow(*wo, target, -1.); // mu - vec
if (true_label) {
wp_diff_.copy(hidden_);
wp_var_sum_ = var_sum;
} else {
wn_diff_.copy(hidden_);
wn_var_sum_ = var_sum;
}
real sim = 0.0;
for (int64_t i = 0; i < hidden_.m_; i++) {
sim += pow(hidden_.data_[i], 2.0)/(1e-8 + var_sum);
}
sim += log(var_sum) * args_->dim; // This is the log det part
sim += args_->dim*log(2*M_PI); // TODO This should be part of the formula
sim *= -0.5;
hidden.addRow(*wo, target, 1.); // mu
return sim;
}
// energy_vecvar but for single case
real Model::energy_singleVecvar(int32_t wordidx, int32_t target, bool true_label) {
return partial_energy_vecvar(hidden_, grad_, wo_, wordidx, target, invar_, outvar_, true_label);
}
real Model::hierarchicalSoftmax(int32_t target, real lr) {
real loss = 0.0;
grad_.zero();
const std::vector<bool>& binaryCode = codes[target];
const std::vector<int32_t>& pathToRoot = paths[target];
for (int32_t i = 0; i < pathToRoot.size(); i++) {
loss += binaryLogistic(pathToRoot[i], binaryCode[i], lr);
}
return loss;
}
real Model::negativeSampling(int32_t target, real lr) {
real loss = 0.0;
grad_.zero();
for (int32_t n = 0; n <= args_->neg; n++) {
if (n == 0) {
loss += binaryLogistic(target, true, lr);
} else {
loss += binaryLogistic(getNegative(target), false, lr);
}
}
return loss;
}
void Model::computeOutputSoftmax(Vector& hidden, Vector& output) const {
if (quant_ && args_->qout) {
output.mul(*qwo_, hidden);
} else {
output.mul(*wo_, hidden);
}
real max = output[0], z = 0.0;
for (int32_t i = 0; i < osz_; i++) {
max = std::max(output[i], max);
}
for (int32_t i = 0; i < osz_; i++) {
output[i] = exp(output[i] - max);
z += output[i];
}
for (int32_t i = 0; i < osz_; i++) {
output[i] /= z;
}
}
void Model::computeOutputSoftmax() {
computeOutputSoftmax(hidden_, output_);
}
real Model::softmax(int32_t target, real lr) {
grad_.zero();
computeOutputSoftmax();
for (int32_t i = 0; i < osz_; i++) {
real label = (i == target) ? 1.0 : 0.0;
real alpha = lr * (label - output_[i]);
grad_.addRow(*wo_, i, alpha);
wo_->addRow(hidden_, i, alpha);
}
return -log(output_.data_[target]);
}
void Model::computeHidden(const std::vector<int32_t>& input, Vector& hidden)
const {
assert(hidden.size() == hsz_);
hidden.zero();
for (auto it = input.cbegin(); it != input.cend(); ++it) {
hidden.addRow(*wi_, *it);
}
hidden.mul(1.0 / input.size());
}
bool Model::comparePairs(const std::pair<real, int32_t> &l,
const std::pair<real, int32_t> &r) {
return l.first > r.first;
}
void Model::predict(const std::vector<int32_t>& input, int32_t k,
std::vector<std::pair<real, int32_t>>& heap,
Vector& hidden, Vector& output) const {
assert(k > 0);
heap.reserve(k + 1);
computeHidden(input, hidden);
if (args_->loss == loss_name::hs) {
dfs(k, 2 * osz_ - 2, 0.0, heap, hidden);
} else {
findKBest(k, heap, hidden, output);
}
std::sort_heap(heap.begin(), heap.end(), comparePairs);
}
void Model::predict(const std::vector<int32_t>& input, int32_t k,
std::vector<std::pair<real, int32_t>>& heap) {
predict(input, k, heap, hidden_, output_);
}
void Model::findKBest(int32_t k, std::vector<std::pair<real, int32_t>>& heap,
Vector& hidden, Vector& output) const {
computeOutputSoftmax(hidden, output);
for (int32_t i = 0; i < osz_; i++) {
if (heap.size() == k && log(output[i]) < heap.front().first) {
continue;
}
heap.push_back(std::make_pair(log(output[i]), i));
std::push_heap(heap.begin(), heap.end(), comparePairs);
if (heap.size() > k) {
std::pop_heap(heap.begin(), heap.end(), comparePairs);
heap.pop_back();
}
}
}
void Model::dfs(int32_t k, int32_t node, real score,
std::vector<std::pair<real, int32_t>>& heap,
Vector& hidden) const {
if (heap.size() == k && score < heap.front().first) {
return;
}
if (tree[node].left == -1 && tree[node].right == -1) {
heap.push_back(std::make_pair(score, node));
std::push_heap(heap.begin(), heap.end(), comparePairs);
if (heap.size() > k) {
std::pop_heap(heap.begin(), heap.end(), comparePairs);
heap.pop_back();
}
return;
}
real f;
if (quant_ && args_->qout) {
f= sigmoid(qwo_->dotRow(hidden, node - osz_));
} else {
f= sigmoid(wo_->dotRow(hidden, node - osz_));
}
dfs(k, tree[node].left, score + log(1.0 - f), heap, hidden);
dfs(k, tree[node].right, score + log(f), heap, hidden);
}
float probRand() {
static thread_local std::mt19937 generator;
std::uniform_int_distribution<int> distribution(0,1000);
return distribution(generator)/(1.*1000);
}
void Model::update(const std::vector<int32_t>& input, int32_t target, real lr) {
assert(target >= 0);
assert(target < osz_);
if (input.size() == 0) return;
// get the word index --> this is the first element in 'input'
int32_t wordidx = 0;
for (auto it = input.cbegin(); it != input.cend(); ++it) {
wordidx = *it;
break;
}
computeHidden(input, hidden_);
if (args_->loss == loss_name::gs) {
loss_ += negativeSamplingSingleVar(wordidx, target, lr);
} else if (args_->loss == loss_name::ns) {
loss_ += negativeSampling(target, lr);
} else if (args_->loss == loss_name::hs) {
// not using
loss_ += hierarchicalSoftmax(target, lr);
} else {
// not using
loss_ += softmax(target, lr);
}
nexamples_ += 1;
if (args_->norm_grad) {
grad_.mul(1.0 / input.size());
}
for (auto it = input.cbegin(); it != input.cend(); ++it) {
wi_->addRow(grad_, *it, 1.0);
}
if (args_->loss == loss_name::gs) {
if (args_->c != 0.0) {
grad_.addRow(*wi_, wordidx, -2*lr*args_->c);
}
invar_->data_[wordidx] += gradvar_;
if (args_->min_logvar !=0 || args_->max_logvar !=0) {
invar_->data_[wordidx] = regLogVar(invar_->data_[wordidx]);
}
}
}
void Model::setTargetCounts(const std::vector<int64_t>& counts) {
assert(counts.size() == osz_);
if (args_->loss == loss_name::ns || args_->loss == loss_name::gs) {
initTableNegatives(counts);
}
if (args_->loss == loss_name::hs) {
buildTree(counts);
}
}
void Model::initTableNegatives(const std::vector<int64_t>& counts) {
real z = 0.0;
for (size_t i = 0; i < counts.size(); i++) {
z += pow(counts[i], 0.5);
}
for (size_t i = 0; i < counts.size(); i++) {
real c = pow(counts[i], 0.5);
for (size_t j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) {
negatives.push_back(i);
}
}
std::shuffle(negatives.begin(), negatives.end(), rng);
}
int32_t Model::getNegative(int32_t target) {
int32_t negative;
do {
negative = negatives[negpos];
negpos = (negpos + 1) % negatives.size();
} while (target == negative);
return negative;
}
void Model::buildTree(const std::vector<int64_t>& counts) {
tree.resize(2 * osz_ - 1);
for (int32_t i = 0; i < 2 * osz_ - 1; i++) {
tree[i].parent = -1;
tree[i].left = -1;
tree[i].right = -1;
tree[i].count = 1e15;
tree[i].binary = false;
}
for (int32_t i = 0; i < osz_; i++) {
tree[i].count = counts[i];
}
int32_t leaf = osz_ - 1;
int32_t node = osz_;
for (int32_t i = osz_; i < 2 * osz_ - 1; i++) {
int32_t mini[2];
for (int32_t j = 0; j < 2; j++) {
if (leaf >= 0 && tree[leaf].count < tree[node].count) {
mini[j] = leaf--;
} else {
mini[j] = node++;
}
}
tree[i].left = mini[0];
tree[i].right = mini[1];
tree[i].count = tree[mini[0]].count + tree[mini[1]].count;
tree[mini[0]].parent = i;
tree[mini[1]].parent = i;
tree[mini[1]].binary = true;
}
for (int32_t i = 0; i < osz_; i++) {
std::vector<int32_t> path;
std::vector<bool> code;
int32_t j = i;
while (tree[j].parent != -1) {
path.push_back(tree[j].parent - osz_);
code.push_back(tree[j].binary);
j = tree[j].parent;
}
paths.push_back(path);
codes.push_back(code);
}
}
real Model::getLoss() const {
return loss_ / nexamples_;
}
void Model::initSigmoid() {
t_sigmoid = new real[SIGMOID_TABLE_SIZE + 1];
for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) {
real x = real(i * 2 * MAX_SIGMOID) / SIGMOID_TABLE_SIZE - MAX_SIGMOID;
t_sigmoid[i] = 1.0 / (1.0 + std::exp(-x));
}
}
void Model::initLog() {
t_log = new real[LOG_TABLE_SIZE + 1];
for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) {
real x = (real(i) + 1e-5) / LOG_TABLE_SIZE;
t_log[i] = std::log(x);
}
}
real Model::log(real x) const {
if (x > 1.0) {
return 0.0;
}
int i = int(x * LOG_TABLE_SIZE);
return t_log[i];
}
real Model::sigmoid(real x) const {
if (x < -MAX_SIGMOID) {
return 0.0;
} else if (x > MAX_SIGMOID) {
return 1.0;
} else {
int i = int((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2);
return t_sigmoid[i];
}
}
void Model::expVar() {
int64_t m = invar_->m_;
assert(m == outvar_->m_);
for (int32_t i = 0; i < m; ++i) {
invar_->data_[i] = exp(invar_->data_[i]);
outvar_->data_[i] = exp(outvar_->data_[i]);
}
}
}
| 28.047423 | 205 | 0.602588 | [
"vector",
"model"
] |
4ca2b976f923ec34770977eaa995163bfd940573 | 2,149 | cpp | C++ | src/base/io_occ_gltf_reader.cpp | SudatiSimone/color-mayo | 7e931f6565f71359fd586caf2ec144674b91aaf3 | [
"BSD-2-Clause"
] | null | null | null | src/base/io_occ_gltf_reader.cpp | SudatiSimone/color-mayo | 7e931f6565f71359fd586caf2ec144674b91aaf3 | [
"BSD-2-Clause"
] | null | null | null | src/base/io_occ_gltf_reader.cpp | SudatiSimone/color-mayo | 7e931f6565f71359fd586caf2ec144674b91aaf3 | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************
** Copyright (c) 2020, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#include "io_occ_gltf_reader.h"
#include "property_builtins.h"
namespace Mayo {
namespace IO {
class OccGltfReader::Properties : public OccBaseMeshReaderProperties {
MAYO_DECLARE_TEXT_ID_FUNCTIONS(Mayo::IO::OccGltfReader_Properties)
public:
Properties(PropertyGroup* parentGroup)
: OccBaseMeshReaderProperties(parentGroup),
skipEmptyNodes(this, textId("skipEmptyNodes")),
useMeshNameAsFallback(this, textId("useMeshNameAsFallback"))
{
this->skipEmptyNodes.setDescription(
textIdTr("Ignore nodes without geometry(`Yes` by default)"));
this->useMeshNameAsFallback.setDescription(
textIdTr("Use mesh name in case if node name is empty(`Yes` by default)"));
}
void restoreDefaults() override {
OccBaseMeshReaderProperties::restoreDefaults();
this->skipEmptyNodes.setValue(true);
this->useMeshNameAsFallback.setValue(true);
}
PropertyBool skipEmptyNodes;
PropertyBool useMeshNameAsFallback;
};
OccGltfReader::OccGltfReader()
: OccBaseMeshReader(m_reader)
{
}
std::unique_ptr<PropertyGroup> OccGltfReader::createProperties(PropertyGroup* parentGroup)
{
return std::make_unique<Properties>(parentGroup);
}
void OccGltfReader::applyProperties(const PropertyGroup* params)
{
OccBaseMeshReader::applyProperties(params);
auto ptr = dynamic_cast<const Properties*>(params);
if (ptr) {
m_params.useMeshNameAsFallback = ptr->useMeshNameAsFallback.value();
m_params.skipEmptyNodes = ptr->skipEmptyNodes.value();
}
}
void OccGltfReader::applyParameters()
{
OccBaseMeshReader::applyParameters();
m_reader.SetSkipEmptyNodes(m_params.skipEmptyNodes);
m_reader.SetMeshNameAsFallback(m_params.useMeshNameAsFallback);
}
} // namespace IO
} // namespace Mayo
| 32.560606 | 95 | 0.673336 | [
"mesh",
"geometry"
] |
4ca640a597a2d2a6aaadd0e5cf8eeb3791973f13 | 1,209 | cpp | C++ | LeetCode/Problems/Algorithms/#10_RegularExpressionMatching_sol8_dp_12ms_6.6MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#10_RegularExpressionMatching_sol8_dp_12ms_6.6MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#10_RegularExpressionMatching_sol8_dp_12ms_6.6MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isMatch(string s, string p) {
// '#' - notation for empty char
s = "#" + s;
p = "#" + p;
int n = (int)s.length() - 1;
int m = (int)p.length() - 1;
vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, false));
// dp[i][j]: 1, if s[0 .. i] is a match of p[0 .. j]
// 0, if s[0 .. i] is not a match of p[0 .. j]
// s[0] = p[0] = '#' => dp[0][0] = true
// Also s[0] = p[0 .. j] if and only if p[0 .. j] is ".*.*.* ... .*"
dp[0][0] = true;
for(int j = 2; j <= m && p[j] == '*'; j += 2){
dp[0][j] = true;
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
bool match1 = (s[i] == p[j] || p[j] == '.') && dp[i - 1][j - 1];
bool match2 = (p[j] == '*' && (dp[i][j - 1] || (j >= 2 && dp[i][j - 2])));
bool match3 = (p[j] == '*' && (s[i] == p[j - 1] || p[j - 1] == '.') && dp[i - 1][j]);
dp[i][j] = (match1 || match2 || match3);
}
}
return dp[n][m];
}
}; | 36.636364 | 102 | 0.307692 | [
"vector"
] |
4ca8cf1bf9a7d38d19bae0d2d32a0e32be4597bc | 1,850 | cpp | C++ | ExplosionPuzzle/ExplosionPuzzle/text.cpp | jesseroffel/explosion-game | df8e1481072d7ea4ecc61997b39d0575d63386b3 | [
"MIT"
] | null | null | null | ExplosionPuzzle/ExplosionPuzzle/text.cpp | jesseroffel/explosion-game | df8e1481072d7ea4ecc61997b39d0575d63386b3 | [
"MIT"
] | null | null | null | ExplosionPuzzle/ExplosionPuzzle/text.cpp | jesseroffel/explosion-game | df8e1481072d7ea4ecc61997b39d0575d63386b3 | [
"MIT"
] | null | null | null | #include "text.h"
Text::Text()
{
}
Text::Text(std::string Text, TTF_Font* fFont, SDL_Renderer* rRend, int posx, int posy, SDL_Color cColor)
{
mPosX = posx;
mPosY = posy;
mFontID = 0;
if (Text == "") {
tTextTexture = new Texture();
mTextWidth = 0;
mTextHeight = 0;
hasText = false;
} else {
tTextTexture = new Texture();
tTextTexture->RenderStringToTexture(Text, rRend, fFont, cColor);
mTextWidth = tTextTexture->getWidth();
mTextHeight = tTextTexture->getHeight();
hasText = true;
}
renderOutlines = false;
}
Text::~Text()
{
delete tTextTexture;
}
void Text::RenderStringToTexture(std::string Text, SDL_Renderer* rRend, TTF_Font* fFont, SDL_Color cColor)
{
tTextTexture->RenderStringToTexture(Text, rRend, fFont, cColor);
mTextWidth = tTextTexture->getWidth();
mTextHeight = tTextTexture->getHeight();
if (!hasText) { hasText = true; }
}
void Text::Render(SDL_Renderer* rRend)
{
if (hasText)
{
tTextTexture->Render(rRend, mPosX, mPosY);
if (renderOutlines) {
SDL_Rect renderQuad = { mPosX, mPosY, mTextWidth, mTextHeight };
//Render (green) outline for debugging if true
SDL_SetRenderDrawColor(rRend, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawRect(rRend, &renderQuad);
SDL_SetRenderDrawColor(rRend, 0x00, 0x00, 0x00, 0xFF);
}
}
}
void Text::freeTexture() {
if (tTextTexture != nullptr) {
tTextTexture->clearTexture();
tTextTexture = nullptr;
}
}
void Text::setFontID(int newID) { mFontID = newID; }
void Text::setPosX(int newposx) { mPosX = newposx; }
void Text::setPosY(int newposy) { mPosY = newposy; }
void Text::setText(std::string newText) { mText = newText; }
int Text::getPosX() { return mPosX; }
int Text::getPosY() { return mPosY; }
bool Text::getHasText() { return hasText; }
void Text::setHasText(bool state)
{
if (state) { hasText = true; }
else { hasText = false; }
} | 24.025974 | 106 | 0.691892 | [
"render"
] |
4cac9a208df1271d0c66ae1b8cbf87d8f56d9fa9 | 635 | cpp | C++ | Chef and Queries/main.cpp | raafatabualazm/Competitive-Programming-Solutions | 3c8c953e9597e64a77e804ba4d3881c8f0354c7a | [
"MIT"
] | null | null | null | Chef and Queries/main.cpp | raafatabualazm/Competitive-Programming-Solutions | 3c8c953e9597e64a77e804ba4d3881c8f0354c7a | [
"MIT"
] | null | null | null | Chef and Queries/main.cpp | raafatabualazm/Competitive-Programming-Solutions | 3c8c953e9597e64a77e804ba4d3881c8f0354c7a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
int64_t Q, S1, A, B, sum = 0;
cin >> Q >> S1 >> A >> B;
//bitset<4294967296> nums;
vector<bool> nums(4294967296, 0);
for (int64_t i = 0; i < Q; i++)
{
if (S1&1)
{ if (!nums[(S1 / 2)])
{
nums[(S1 / 2)] = true;
sum += (S1 / 2);
}
} else
{
if (nums[(S1 / 2)])
{
nums[(S1 / 2)] = false;
sum -= (S1 / 2);
}
}
S1 = (A*S1 + B) % 4294967296;
}
cout << sum;
return 0;
}
| 18.676471 | 39 | 0.340157 | [
"vector"
] |
4caebdce24c5605b8a9dc9081ff04e54a2929038 | 3,899 | cpp | C++ | Engine/Src/Runtime/GUI/Implementations/Default/Widgets/WindowFrame.cpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | Engine/Src/Runtime/GUI/Implementations/Default/Widgets/WindowFrame.cpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | Engine/Src/Runtime/GUI/Implementations/Default/Widgets/WindowFrame.cpp | Septus10/Fade-Engine | 285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6 | [
"MIT"
] | null | null | null | #include <GUI/Widgets/WindowFrame.hpp>
#include <GUI/Widgets/Button.hpp>
#include <PlatformCore/PlatformCore.hpp>
namespace Fade { inline namespace GUI {
CWindowFrame::CWindowFrame()
: m_IsHoveringExit(false)
, m_IsHoveringMaximize(false)
, m_IsHoveringMinimize(false)
, m_IsHoveringRight(false)
, m_IsHoveringLeft(false)
, m_IsHoveringTop(false)
, m_IsHoveringBot(false)
{
CButton* Close = new CButton();
AddWidget(Close);
CButton* Restore = new CButton();
AddWidget(Restore);
CButton* Minimize = new CButton();
AddWidget(Minimize);
}
void CWindowFrame::Render(IRenderer* a_Renderer)
{
// draw top left corner
//a_Renderer->DrawFilledQuad(SRect(-1.0f, -0.99f, 1.0f, 0.99f), Fade::SColor::Cyan);
// Draw logo top left
// Draw top bar
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Left, m_Rect.m_Right, m_Rect.m_Top, m_Rect.m_Top - 4), Fade::SColor::Cyan);
// Draw top right buttons
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 64, m_Rect.m_Right - 4, m_Rect.m_Top - 4, m_Rect.m_Top - 24), SColor::Cyan);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 20, m_Rect.m_Right - 4, m_Rect.m_Top - 4, m_Rect.m_Top - 20), SColor::Black);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 19, m_Rect.m_Right - 5, m_Rect.m_Top - 5, m_Rect.m_Top - 19), m_IsHoveringExit ? SColor::Magenta : SColor::Red);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 40, m_Rect.m_Right - 24, m_Rect.m_Top - 4, m_Rect.m_Top - 20), SColor::Black);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 39, m_Rect.m_Right - 25, m_Rect.m_Top - 5, m_Rect.m_Top - 19), SColor::Yellow);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 60, m_Rect.m_Right - 44, m_Rect.m_Top - 4, m_Rect.m_Top - 20), SColor::Black);
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 59, m_Rect.m_Right - 45, m_Rect.m_Top - 5, m_Rect.m_Top - 19), SColor::Green);
// Draw top right corner
// Draw right bar
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Right - 4, m_Rect.m_Right, m_Rect.m_Top, m_Rect.m_Bottom), Fade::SColor::Cyan);
// Draw bottom right corner
// Draw bottom bar
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Left, m_Rect.m_Right, m_Rect.m_Bottom + 4, m_Rect.m_Bottom), Fade::SColor::Cyan);
// Draw bottom left corner
// Draw left bar
a_Renderer->DrawFilledQuad(SRect(m_Rect.m_Left, m_Rect.m_Left + 4, m_Rect.m_Top, m_Rect.m_Bottom), Fade::SColor::Cyan);
}
bool CWindowFrame::OnMouseMove(int a_X, int a_Y, int a_DX, int a_DY)
{
a_Y = m_Rect.m_Top - a_Y;
m_IsHoveringRight = a_X >= (int)m_Rect.m_Right - 4;
m_IsHoveringLeft = a_X <= (int)m_Rect.m_Left + 4;
m_IsHoveringTop = a_Y >= (int)m_Rect.m_Top - 4;
m_IsHoveringBot = a_Y <= (int)m_Rect.m_Bottom + 4;
m_IsHoveringExit =
a_X >= ((int)m_Rect.m_Right - 20) &&
a_X <= ((int)m_Rect.m_Right - 4) &&
a_Y >= ((int)m_Rect.m_Top - 20) &&
a_Y <= ((int)m_Rect.m_Top - 4);
if (m_IsHoveringRight && m_IsHoveringTop ||
m_IsHoveringLeft && m_IsHoveringBot)
{
Fade::PlatformCore::SetCursorType(PlatformCore::ECursorType::ResizeNESW);
}
else if (m_IsHoveringRight && m_IsHoveringBot ||
m_IsHoveringLeft && m_IsHoveringTop)
{
Fade::PlatformCore::SetCursorType(PlatformCore::ECursorType::ResizeNWSE);
}
else if (m_IsHoveringRight || m_IsHoveringLeft)
{
Fade::PlatformCore::SetCursorType(PlatformCore::ECursorType::ResizeLeftRight);
}
else if (m_IsHoveringTop || m_IsHoveringBot)
{
Fade::PlatformCore::SetCursorType(PlatformCore::ECursorType::ResizeUpDown);
}
else
{
Fade::PlatformCore::SetCursorType(PlatformCore::ECursorType::Pointer);
}
return false;
}
bool CWindowFrame::OnMouseButtonUp(EMouseButton a_Button)
{
if (a_Button == EMouseButton::Left)
{
if (m_IsHoveringExit)
{
// Close the window
//m_Window->Close();
}
else if (m_IsHoveringMaximize)
{
// Maximize the window
}
else if (m_IsHoveringMinimize)
{
// Minimize the window
}
}
return false;
}
} } | 29.992308 | 163 | 0.717876 | [
"render"
] |
4cb6b4dacbe87f5195750c5ece895e5fae0f5839 | 39,428 | cpp | C++ | regxmllib/src/main/cpp/com/sandflow/smpte/regxml/FragmentBuilder.cpp | ErikCJohansson/regxmllib | 57b44282a890e475d7601faec4e275df07e3f812 | [
"BSD-2-Clause"
] | null | null | null | regxmllib/src/main/cpp/com/sandflow/smpte/regxml/FragmentBuilder.cpp | ErikCJohansson/regxmllib | 57b44282a890e475d7601faec4e275df07e3f812 | [
"BSD-2-Clause"
] | null | null | null | regxmllib/src/main/cpp/com/sandflow/smpte/regxml/FragmentBuilder.cpp | ErikCJohansson/regxmllib | 57b44282a890e475d7601faec4e275df07e3f812 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c), Pierre-Anthony Lemieux (pal@palemieux.com)
* 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "FragmentBuilder.h"
#include "com/sandflow/smpte/util/IDAU.h"
#include <algorithm>
#include <iostream>
#include <iterator>
namespace rxml {
const UL FragmentBuilder::INSTANCE_UID_ITEM_UL = "urn:smpte:ul:060e2b34.01010101.01011502.00000000";
const UL FragmentBuilder::AUID_UL = "urn:smpte:ul:060e2b34.01040101.01030100.00000000";
const UL FragmentBuilder::UUID_UL = "urn:smpte:ul:060e2b34.01040101.01030300.00000000";
const UL FragmentBuilder::DateStruct_UL = "urn:smpte:ul:060e2b34.01040101.03010500.00000000";
const UL FragmentBuilder::PackageID_UL = "urn:smpte:ul:060e2b34.01040101.01030200.00000000";
const UL FragmentBuilder::Rational_UL = "urn:smpte:ul:060e2b34.01040101.03010100.00000000";
const UL FragmentBuilder::TimeStruct_UL = "urn:smpte:ul:060e2b34.01040101.03010600.00000000";
const UL FragmentBuilder::TimeStamp_UL = "urn:smpte:ul:060e2b34.01040101.03010700.00000000";
const UL FragmentBuilder::VersionType_UL = "urn:smpte:ul:060e2b34.01040101.03010300.00000000";
const UL FragmentBuilder::ByteOrder_UL = "urn:smpte:ul:060e2b34.01010101.03010201.02000000";
const UL FragmentBuilder::Character_UL = "urn:smpte:ul:060e2b34.01040101.01100100.00000000";
const UL FragmentBuilder::Char_UL = "urn:smpte:ul:060e2b34.01040101.01100300.00000000";
const UL FragmentBuilder::UTF8Character_UL = "urn:smpte:ul:060e2b34.01040101.01100500.00000000";
const UL FragmentBuilder::ProductReleaseType_UL = "urn:smpte:ul:060e2b34.01040101.02010101.00000000";
const UL FragmentBuilder::Boolean_UL = "urn:smpte:ul:060e2b34.01040101.01040100.00000000";
const UL FragmentBuilder::PrimaryPackage_UL = "urn:smpte:ul:060e2b34.01010104.06010104.01080000";
const UL FragmentBuilder::LinkedGenerationID_UL = "urn:smpte:ul:060e2b34.01010102.05200701.08000000";
const UL FragmentBuilder::GenerationID_UL = "urn:smpte:ul:060e2b34.01010102.05200701.01000000";
const UL FragmentBuilder::ApplicationProductID_UL = "urn:smpte:ul:060e2b34.01010102.05200701.07000000";
const std::string FragmentBuilder::BYTEORDER_BE = "BigEndian";
const std::string FragmentBuilder::BYTEORDER_LE = "LittleEndian";
const std::string FragmentBuilder::REGXML_NS = "http://sandflow.com/ns/SMPTEST2001-1/baseline";
const std::string FragmentBuilder::XMLNS_NS = "http://www.w3.org/2000/xmlns/";
const std::string FragmentBuilder::ACTUALTYPE_ATTR = "actualType";
const std::string FragmentBuilder::UID_ATTR = "uid";
const std::string FragmentBuilder::ESCAPE_ATTR = "escape";
const Definition * FragmentBuilder::findBaseTypeDefinition(const Definition * definition, const DefinitionResolver & defresolver) {
while (instance_of<RenameTypeDefinition>(*definition)) {
definition = defresolver.getDefinition(((RenameTypeDefinition*)definition)->renamedType);
}
return definition;
}
/**
* Creates a RegXML Fragment, represented an XML DOM Document Fragment
*
* @param group KLV Group for which the Fragment will be generated.
* @param document Document from which the XML DOM Document Fragment will be
* created.
*
* @return XML DOM Document Fragment containing a single RegXML Fragment
*
* @throws KLVException
* @throws com.sandflow.smpte.regxml.FragmentBuilder.RuleException
*/
const Definition * FragmentBuilder::findBaseDefinition(const Definition * definition) {
while (instance_of<RenameTypeDefinition>(*definition)) {
definition = defresolver.getDefinition(((RenameTypeDefinition*)definition)->renamedType);
}
return definition;
}
/**
* Instantiates a FragmentBuilder. If the anamresolver argument is not null,
* the FragmentBuilder will attempt to resolve the name of each AUID it
* writes to the output and add it as an XML comment. If the evthandler
* argument is not null, the Fragment builder will call back the caller with
* events it encounters as it transforms a Triplet.
*
* @param defresolver Maps Group Keys to MetaDictionary definitions. Must
* not be null;
* @param setresolver Resolves Strong References to groups. Must not be
* null.
* @param anameresolver Resolves a AUID to a human-readable symbol. May be
* null.
* @param evthandler Calls back the caller when an event occurs. May be
* null.
*/
FragmentBuilder::FragmentBuilder(const DefinitionResolver & defresolver, const std::map<UUID, Set>& setresolver, const AUIDNameResolver * anameresolver, EventHandler * evthandler) : defresolver(defresolver), setresolver(setresolver), anameresolver(anameresolver), evthandler(evthandler) {
}
xercesc::DOMDocumentFragment * FragmentBuilder::fromTriplet(const Group & group, xercesc::DOMDocument & document) {
xercesc::DOMDocumentFragment *df = NULL;
try {
nsprefixes.clear();
df = document.createDocumentFragment();
applyRule3(df, group);
/* NOTE: Hack to clean-up namespace prefixes */
for (std::map<std::string, std::string>::const_iterator it = this->nsprefixes.begin(); it != this->nsprefixes.end(); it++) {
((xercesc::DOMElement*)df->getFirstChild())->setAttributeNS(DOMHelper::fromUTF8(XMLNS_NS), DOMHelper::fromUTF8("xmlns:" + it->second), DOMHelper::fromUTF8(it->first));
}
} catch (const std::exception &e) {
UncaughtExceptionError err(
e,
rxml::fmt(
"Group key {}",
group.getKey().to_string()
)
);
evthandler->fatal(err);
} catch (...) {
UncaughtExceptionError err(
rxml::fmt(
"Group key {}",
group.getKey().to_string()
)
);
evthandler->fatal(err);
}
return df;
}
std::string FragmentBuilder::getElementNSPrefix(const std::string & ns) {
std::map<std::string, std::string>::const_iterator it = this->nsprefixes.find(ns);
if (it == this->nsprefixes.end()) {
std::string prefix = "r" + rxml::to_string(this->nsprefixes.size());
return this->nsprefixes[ns] = prefix;
} else {
return it->second;
}
}
void FragmentBuilder::addInformativeComment(xercesc::DOMElement *element, std::string comment) {
element->appendChild(element->getOwnerDocument()->createComment(DOMHelper::fromUTF8(comment)));
}
void FragmentBuilder::appendCommentWithAUIDName(AUID auid, xercesc::DOMElement* elem) {
if (this->anameresolver != NULL) {
const std::string *ename = this->anameresolver->getLocalName(auid);
if (ename != NULL) {
elem->appendChild(elem->getOwnerDocument()->createComment(DOMHelper::fromUTF8(*ename)));
}
}
}
void FragmentBuilder::applyRule3(xercesc::DOMNode * node, const Group & group) {
const Definition *definition = defresolver.getDefinition(group.getKey());
if (definition == NULL) {
evthandler->info(UnknownGroupError(group.getKey(), ""));
return;
}
if (definition->identification.isUL() &&
definition->identification.asUL().getVersion() != group.getKey().getVersion()) {
evthandler->info(
VersionByteMismatchError(
group.getKey(),
definition->identification.asUL(),
rxml::fmt(
"Group UL {} in file does not have the same version byte as in the register",
group.getKey().to_string()
)
)
);
}
/* is the definition for a Class */
if (!instance_of<ClassDefinition>(*definition)) {
UnexpectedDefinitionError err(group.getKey(), "Class Definition", group.getKey().to_string());
evthandler->error(err);
return;
}
/* create the element */
xercesc::DOMElement *objelem = node->getOwnerDocument()->createElementNS(
DOMHelper::fromUTF8(definition->ns),
DOMHelper::fromUTF8(definition->symbol)
);
objelem->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(definition->ns)));
node->appendChild(objelem);
/* process the properties of the group */
for (std::vector<Triplet*>::const_iterator item = group.getItems().begin(); item != group.getItems().end(); item++) {
/* skip if the property is not defined in the registers */
const Definition *itemdef = defresolver.getDefinition((*item)->getKey());
if (itemdef == NULL) {
UnknownPropertyError err((*item)->getKey(), "Group " + group.getKey().to_string());
evthandler->info(err);
addInformativeComment(
objelem,
rxml::fmt(
"Unknown property\nKey: {}\nData: {}",
(*item)->getKey().to_string(),
rxml::bytesToString((*item)->getValue(), (*item)->getLength())
)
);
continue;
}
/* make sure this is a property definition */
if (!instance_of<PropertyDefinition>(*itemdef) && !instance_of<PropertyAliasDefinition>(*itemdef)) {
UnexpectedDefinitionError err(itemdef->identification, "Property", "Group " + group.getKey().to_string());
evthandler->warn(err);
addInformativeComment(objelem, err.getReason());
continue;
}
/* warn if version byte of the property does not match the register version byte */
if (itemdef->identification.isUL() && itemdef->identification.asUL().getVersion() != (*item)->getKey().asUL().getVersion()) {
VersionByteMismatchError err((*item)->getKey(), itemdef->identification, "Group " + group.getKey().to_string());
evthandler->info(err);
}
xercesc::DOMElement *elem = node->getOwnerDocument()->createElementNS(
DOMHelper::fromUTF8(itemdef->ns),
DOMHelper::fromUTF8(itemdef->symbol)
);
objelem->appendChild(elem);
elem->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(itemdef->ns)));
/* write the property */
membuf mb((char*)(*item)->getValue(), (*item)->getLength());
MXFInputStream mis(&mb);
applyRule4(elem, mis, (const PropertyDefinition*)itemdef);
/* detect cyclic references */
if ((*item)->getKey().isUL() && INSTANCE_UID_ITEM_UL.equals((*item)->getKey().asUL(), UL::IGNORE_VERSION)) {
const XMLCh* iidns = objelem->getLastChild()->getNamespaceURI();
const XMLCh* iidname = objelem->getLastChild()->getLocalName();
const XMLCh* iid = objelem->getLastChild()->getTextContent();
/* look for identical instanceID in parent elements */
xercesc::DOMNode *parent = node;
while (parent->getNodeType() == xercesc::DOMNode::ELEMENT_NODE) {
for (xercesc::DOMNode *n = parent->getFirstChild(); n != NULL; n = n->getNextSibling()) {
if (n->getNodeType() == xercesc::DOMNode::ELEMENT_NODE
&& xercesc::XMLString::compareIString(iidname, n->getLocalName()) == 0
&& xercesc::XMLString::compareIString(iidns, n->getNamespaceURI()) == 0
&& xercesc::XMLString::compareIString(iid, n->getTextContent()) == 0) {
CircularStrongReferenceError err(std::string(DOMHelper::toUTF8(iid)), "Group " + definition->symbol);
evthandler->info(err);
addInformativeComment((xercesc::DOMElement*)n, err.getReason());
return;
}
}
parent = parent->getParentNode();
}
}
/* add reg:uid if property is a unique ID */
if (((PropertyDefinition*)itemdef)->uniqueIdentifier.is_valid() && ((PropertyDefinition*)itemdef)->uniqueIdentifier.get()) {
xercesc::DOMAttr *attr = node->getOwnerDocument()->createAttributeNS(
DOMHelper::fromUTF8(REGXML_NS),
DOMHelper::fromUTF8(UID_ATTR)
);
attr->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(REGXML_NS)));
attr->setTextContent(elem->getTextContent());
objelem->setAttributeNodeNS(attr);
}
}
}
void FragmentBuilder::applyRule4(xercesc::DOMElement * element, MXFInputStream & value, const PropertyDefinition * propdef) {
try {
if (propdef->identification.equals(ByteOrder_UL)) {
int byteorder;
byteorder = value.readUnsignedShort();
/* ISSUE: ST 2001-1 inverses these constants */
if (byteorder == 0x4D4D) {
element->setTextContent(DOMHelper::fromUTF8(BYTEORDER_BE));
} else if (byteorder == 0x4949) {
element->setTextContent(DOMHelper::fromUTF8(BYTEORDER_LE));
UnexpectedByteOrderError err(ByteOrder_UL.to_string());
evthandler->error(err);
addInformativeComment(element, err.getReason());
} else {
throw new FragmentBuilder::UnknownByteOrderError(ByteOrder_UL.to_string());
}
} else {
/*if (propdef instanceof PropertyAliasDefinition) {
propdef = defresolver.getDefinition(((PropertyAliasDefinition)propdef).getOriginalProperty());
}*/
const Definition *tdef = findBaseTypeDefinition(defresolver.getDefinition(propdef->type), this->defresolver);
/* return if no type definition is found */
if (tdef == NULL) {
throw UnknownTypeError(
propdef->type,
rxml::fmt(
"Property {} at Element {}",
propdef->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
if (propdef->identification.equals(PrimaryPackage_UL)) {
/* EXCEPTION: PrimaryPackage is encoded as the Instance UUID of the target set
but needs to be the UMID contained in the unique ID of the target set */
UUID uuid = value.readUUID();
/* is this a local reference through Instance ID? */
std::map<UUID, Set>::const_iterator iset = setresolver.find(uuid);
if (iset != setresolver.end()) {
bool foundUniqueID = false;
const std::vector<Triplet*> &items = iset->second.getItems();
/* find the unique identifier in the group */
for (std::vector<Triplet*>::const_iterator item = items.begin(); item != items.end(); item++) {
const Definition *itemdef = defresolver.getDefinition((*item)->getKey());
if (itemdef == NULL) {
continue;
}
if (!(instance_of<PropertyDefinition>(*itemdef) || instance_of<PropertyAliasDefinition>(*itemdef))) {
continue;
}
if (((PropertyDefinition*)itemdef)->uniqueIdentifier.is_valid() && ((PropertyDefinition*)itemdef)->uniqueIdentifier.get()) {
membuf mb((char*)(*item)->getValue(), (*item)->getLength());
MXFInputStream mis(&mb);
applyRule4(element, mis, (PropertyDefinition*)itemdef);
foundUniqueID = true;
break;
}
}
if (foundUniqueID != true) {
throw MissingUniquePropertyError(
PrimaryPackage_UL,
rxml::fmt(
"Element {}",
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
} else {
throw MissingPrimaryPackageError(
uuid,
rxml::fmt(
"Property {} at Element {}",
propdef->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
} else {
if (propdef->identification.equals(LinkedGenerationID_UL)
|| propdef->identification.equals(GenerationID_UL)
|| propdef->identification.equals(ApplicationProductID_UL)) {
/* EXCEPTION: LinkedGenerationID, GenerationID and ApplicationProductID
are encoded using UUID */
tdef = defresolver.getDefinition(UUID_UL);
}
applyRule5(element, value, tdef);
}
}
} catch (const std::ios_base::failure &e) {
IOError err(
e,
rxml::fmt(
"Property {} at Element {}",
propdef->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
));
evthandler->error(err);
addInformativeComment(element, err.getReason());
} catch (const Event &e) {
evthandler->error(e);
addInformativeComment(element, e.getReason());
} catch (const std::exception &e) {
UncaughtExceptionError err(
e,
rxml::fmt(
"Property {} at Element {}",
propdef->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
evthandler->error(err);
addInformativeComment(element, err.getReason());
} catch (...) {
UncaughtExceptionError err(
rxml::fmt(
"Property {} at Element {}",
propdef->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
evthandler->error(err);
addInformativeComment(element, err.getReason());
}
}
void FragmentBuilder::applyRule5(xercesc::DOMElement * element, MXFInputStream & value, const Definition * definition) {
try {
if (instance_of<CharacterTypeDefinition>(*definition)) {
applyRule5_1(element, value, (CharacterTypeDefinition*)definition);
} else if (instance_of<EnumerationTypeDefinition>(*definition)) {
applyRule5_2(element, value, (EnumerationTypeDefinition*)definition);
} else if (instance_of<ExtendibleEnumerationTypeDefinition>(*definition)) {
applyRule5_3(element, value, (ExtendibleEnumerationTypeDefinition*)definition);
} else if (instance_of<FixedArrayTypeDefinition>(*definition)) {
applyRule5_4(element, value, (FixedArrayTypeDefinition*)definition);
} else if (instance_of<IndirectTypeDefinition>(*definition)) {
applyRule5_5(element, value, (IndirectTypeDefinition*)definition);
} else if (instance_of<IntegerTypeDefinition>(*definition)) {
applyRule5_6(element, value, (IntegerTypeDefinition*)definition);
} else if (instance_of<OpaqueTypeDefinition>(*definition)) {
applyRule5_7(element, value, (OpaqueTypeDefinition*)definition);
} else if (instance_of<RecordTypeDefinition>(*definition)) {
applyRule5_8(element, value, (RecordTypeDefinition*)definition);
} else if (instance_of<RenameTypeDefinition>(*definition)) {
applyRule5_9(element, value, (RenameTypeDefinition*)definition);
} else if (instance_of<SetTypeDefinition>(*definition)) {
applyRule5_10(element, value, (SetTypeDefinition*)definition);
} else if (instance_of<StreamTypeDefinition>(*definition)) {
applyRule5_11(element, value, (StreamTypeDefinition*)definition);
} else if (instance_of<StringTypeDefinition>(*definition)) {
applyRule5_12(element, value, (StringTypeDefinition*)definition);
} else if (instance_of<StrongReferenceTypeDefinition>(*definition)) {
applyRule5_13(element, value, (StrongReferenceTypeDefinition*)definition);
} else if (instance_of<VariableArrayTypeDefinition>(*definition)) {
applyRule5_14(element, value, (VariableArrayTypeDefinition*)definition);
} else if (instance_of<WeakReferenceTypeDefinition>(*definition)) {
applyRule5_15(element, value, (WeakReferenceTypeDefinition*)definition);
/*} else if (instance_of<FloatTypeDefinition>(*definition)) {
applyRule5_alpha(element, value, (FloatTypeDefinition*)definition);*/
} else if (instance_of<LensSerialFloatTypeDefinition>(*definition)) {
applyRule5_beta(element, value, (LensSerialFloatTypeDefinition*)definition);
} else {
throw FragmentBuilder::Exception(
rxml::fmt(
"Unknown Kind for Definition {} in Rule 5.",
definition->symbol
)
);
}
} catch (const std::ios_base::failure &e) {
IOError err(
e,
rxml::fmt(
"Definition {} at Element {}",
definition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
));
evthandler->error(err);
addInformativeComment(element, err.getReason());
} catch (const Event &e) {
evthandler->error(e);
addInformativeComment(element, e.getReason());
}
}
void FragmentBuilder::readCharacters(xercesc::DOMElement * element, MXFInputStream & value, const CharacterTypeDefinition * definition, bool isSingleChar) {
std::vector<char> sb;
static const size_t chars_sz = 32;
char chars[chars_sz];
while (value.good()) {
value.read(chars, chars_sz);
sb.insert(sb.end(), chars, chars + value.gcount());
}
/* return if there is not text to add */
if (sb.size() == 0) return;
/* choose the character decoder */
std::string codec;
if (definition->identification.equals(Character_UL)) {
if (value.getByteOrder() == MXFInputStream::BIG_ENDIAN_BYTE_ORDER) {
codec = "UTF-16BE";
} else {
codec = "UTF-16LE";
}
} else if (definition->identification.equals(Char_UL)) {
codec = "US-ASCII";
} else if (definition->identification.equals(UTF8Character_UL)) {
/* NOTE: Use of UTF-8 character encoding is specified in RP 2057 */
codec = "UTF-8";
} else {
throw UnsupportedCharTypeError(definition->symbol,
rxml::fmt(
"Element {}",
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
xercesc::TranscodeFromStr mxfchars((XMLByte*) sb.data(), sb.size(), codec.c_str());
std::vector<XMLCh> xmlchar;
/* do we need to use the escape mechanism specified in ST 2001-1? */
bool isescaped = false;
for (int i = 0; i < mxfchars.length(); i++) {
XMLCh c = mxfchars.str()[i];
/* terminate on the first null character unless we are parsing a single character type */
if (c == 0 && (!isSingleChar)) break;
if (c == 0x09
|| c == 0x0A
|| (c >= 0x20 && c <= 0x23)
|| c >= 0x25) {
xmlchar.push_back(c);
} else {
isescaped = true;
std::stringstream ss;
/* c is guaranteed to be less than 0xFF */
ss << "$#x" << std::hex << c << ";";
std::copy(std::istream_iterator<unsigned char>(ss), std::istream_iterator<unsigned char>(), std::back_inserter(xmlchar));
}
}
if (isescaped) {
xercesc::DOMAttr *attr = element->getOwnerDocument()->createAttributeNS(
DOMHelper::fromUTF8(REGXML_NS),
DOMHelper::fromUTF8(ESCAPE_ATTR)
);
attr->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(REGXML_NS)));
attr->setTextContent(DOMHelper::fromUTF8("true"));
element->setAttributeNodeNS(attr);
}
xmlchar.push_back(0);
element->setTextContent(&(xmlchar[0]));
}
void FragmentBuilder::applyRule5_1(xercesc::DOMElement * element, MXFInputStream & value, const CharacterTypeDefinition * definition) {
readCharacters(element, value, definition, true /* do not remove trailing zeroes for a single char */);
}
void FragmentBuilder::applyRule5_2(xercesc::DOMElement * element, MXFInputStream & value, const EnumerationTypeDefinition * definition) {
const Definition *bdef = findBaseDefinition(defresolver.getDefinition(definition->elementType));
if (!instance_of<IntegerTypeDefinition>(*bdef)) {
throw UnsupportedEnumTypeError(definition->symbol,
rxml::fmt(
"Enum {} at Element {}",
definition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
/*evthandler->error(err);
addInformativeComment(element, err.getReason());
return;*/
}
IntegerTypeDefinition* idef = (IntegerTypeDefinition*)bdef;
if (idef->isSigned) {
throw FragmentBuilder::Exception("Cannot handle signed Enumeration Definitions");
}
int len = 0;
if (definition->identification.equals(ProductReleaseType_UL)) {
/* EXCEPTION: ProductReleaseType_UL is listed as
a UInt8 enum but encoded as a UInt16 */
len = 2;
} else {
len = idef->size;
}
unsigned long bi = 0;
switch (len) {
case 1:
bi = value.readUnsignedByte();
break;
case 2:
bi = value.readUnsignedShort();
break;
case 4:
bi = value.readUnsignedLong();
break;
default:
throw FragmentBuilder::Exception("Enumerations Definitions wider than 4 bytes are not supported");
}
std::string str;
if (definition->elementType.equals(Boolean_UL)) {
/* find the "true" enum element */
/* MXF can encode "true" as any value other than 0 */
for (std::vector<EnumerationTypeDefinition::Element>::const_iterator it = definition->elements.begin();
it != definition->elements.end();
it++) {
if ((bi == 0 && it->value == 0) || (bi != 0 && it->value == 1)) {
str = it->name;
}
}
} else {
for (std::vector<EnumerationTypeDefinition::Element>::const_iterator it = definition->elements.begin();
it != definition->elements.end();
it++) {
if (it->value == bi) {
str = it->name;
}
}
}
if (str.size() == 0) {
str = "UNDEFINED";
UnknownEnumValueError err(bi,
rxml::fmt(
"Enum {} at Element {}",
definition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
evthandler->error(err);
addInformativeComment(element, err.getReason());
}
element->setTextContent(DOMHelper::fromUTF8(str));
}
void FragmentBuilder::applyRule5_3(xercesc::DOMElement * element, MXFInputStream & value, const ExtendibleEnumerationTypeDefinition * definition) {
UL ul = value.readUL();
/* NOTE: ST 2001-1 XML Schema does not allow ULs as values for Extendible Enumerations, which
defeats the purpose of the type. This issue could be addressed at the next revision opportunity. */
element->setTextContent(DOMHelper::fromUTF8(ul.to_string()));
this->appendCommentWithAUIDName(ul, element);
}
void FragmentBuilder::applyRule5_4(xercesc::DOMElement * element, MXFInputStream & value, const FixedArrayTypeDefinition * definition) {
if (definition->identification.equals(UUID_UL)) {
UUID uuid = value.readUUID();
element->setTextContent(DOMHelper::fromUTF8(uuid.to_string()));
} else {
const Definition* tdef = findBaseDefinition(defresolver.getDefinition(definition->elementType));
applyCoreRule5_4(element, value, tdef, definition->elementCount);
}
}
void FragmentBuilder::applyCoreRule5_4(xercesc::DOMElement * element, MXFInputStream & value, const Definition * tdef, unsigned long elementcount) {
for (unsigned long i = 0; i < elementcount; i++) {
if (instance_of<StrongReferenceTypeDefinition>(*tdef)) {
/* Rule 5.4.1 */
applyRule5_13(element, value, (StrongReferenceTypeDefinition*)tdef);
} else {
/* Rule 5.4.2 */
xercesc::DOMElement *elem = element->getOwnerDocument()->createElementNS(
DOMHelper::fromUTF8(tdef->ns),
DOMHelper::fromUTF8(tdef->symbol)
);
elem->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(tdef->ns)));
applyRule5(elem, value, tdef);
element->appendChild(elem);
}
}
}
void FragmentBuilder::applyRule5_5(xercesc::DOMElement * element, MXFInputStream & value, const IndirectTypeDefinition * definition) {
/* see https://github.com/sandflow/regxmllib/issues/74 for a discussion on Indirect Type */
KLVStream::ByteOrder bo;
switch (value.readUnsignedByte()) {
case 0x4c /* little endian */:
bo = KLVStream::LITTLE_ENDIAN_BYTE_ORDER;
break;
case 0x42 /* big endian */:
bo = KLVStream::BIG_ENDIAN_BYTE_ORDER;
break;
default:
throw UnknownByteOrderError(
rxml::fmt(
"Indirect Definition {} at Element {}",
definition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
MXFInputStream orderedval(value.rdbuf(), bo);
IDAU idau = orderedval.readIDAU();
AUID auid = idau.asAUID();
const Definition *def = defresolver.getDefinition(auid);
if (def == NULL) {
throw UnknownTypeError(
auid.to_string(),
rxml::fmt(
"Indirect Type {} at Element {}",
definition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
// create reg:actualType attribute
xercesc::DOMAttr *attr = element->getOwnerDocument()->createAttributeNS(
DOMHelper::fromUTF8(REGXML_NS),
DOMHelper::fromUTF8(ACTUALTYPE_ATTR)
);
attr->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(REGXML_NS)));
attr->setTextContent(DOMHelper::fromUTF8(def->symbol));
element->setAttributeNodeNS(attr);
applyRule5(element, orderedval, def);
}
void FragmentBuilder::applyRule5_6(xercesc::DOMElement * element, MXFInputStream & value, const IntegerTypeDefinition * definition) {
switch (definition->size) {
case 1:
if (definition->isSigned) {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readByte())
)
);
} else {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readUnsignedByte())
)
);
}
break;
case 2:
if (definition->isSigned) {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readShort())
)
);
} else {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readUnsignedShort())
)
);
}
break;
case 4:
if (definition->isSigned) {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readLong())
)
);
} else {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readUnsignedLong())
)
);
}
break;
case 8:
if (definition->isSigned) {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readLongLong())
)
);
} else {
element->setTextContent(
DOMHelper::fromUTF8(
rxml::to_string(value.readUnsignedLongLong())
)
);
}
break;
default:
throw FragmentBuilder::Exception("Unsupported Integer type");
}
/*if (value.gcount() == 0 || (!value.good())) {
element->setTextContent(DOMHelper::fromUTF8("Nan"));
FragmentEvent evt = new FragmentEvent(
EventCodes.VALUE_LENGTH_MISMATCH,
"No data",
String.format(
"Integer %s at Element %s",
definition.getSymbol(),
element.getLocalName()
)
);
handleEvent(evt);
addInformativeComment(element, evt.getReason());
}*/
}
void FragmentBuilder::applyRule5_7(xercesc::DOMElement * element, MXFInputStream & value, const OpaqueTypeDefinition * definition) {
/* NOTE: Opaque Types are not used in MXF */
throw FragmentBuilder::Exception("Opaque types are not supported.");
}
std::string FragmentBuilder::generateISO8601Time(int hour, int minutes, int seconds, int millis) {
std::stringstream sb;
sb << std::setw(2) << std::setfill('0') << hour << ":";
sb << std::setw(2) << std::setfill('0') << minutes << ":";
sb << std::setw(2) << std::setfill('0') << seconds;
if (millis != 0) {
sb << "." << std::setw(3) << std::setfill('0') << millis;
}
sb << "Z";
return sb.str();
}
std::string FragmentBuilder::generateISO8601Date(int year, int month, int day) {
std::stringstream sb;
sb << std::setw(4) << std::setfill('0') << year << "-";
sb << std::setw(2) << std::setfill('0') << month << "-";
sb << std::setw(2) << std::setfill('0') << day;
return sb.str();
}
void FragmentBuilder::applyRule5_8(xercesc::DOMElement * element, MXFInputStream & value, const RecordTypeDefinition * definition) {
if (definition->identification.equals(AUID_UL)) {
AUID auid = value.readAUID();
element->setTextContent(DOMHelper::fromUTF8(auid.to_string()));
this->appendCommentWithAUIDName(auid, element);
} else if (definition->identification.equals(DateStruct_UL)) {
int year = value.readUnsignedShort();
int month = value.readUnsignedByte();
int day = value.readUnsignedByte();
element->setTextContent(DOMHelper::fromUTF8(generateISO8601Date(year, month, day)));
} else if (definition->identification.equals(PackageID_UL)) {
UMID umid = value.readUMID();
element->setTextContent(DOMHelper::fromUTF8(umid.to_string()));
} else if (definition->identification.equals(Rational_UL)) {
long numerator = value.readLong();
long denominator = value.readLong();
element->setTextContent(
DOMHelper::fromUTF8(rxml::fmt("{}/{}", rxml::to_string(numerator), rxml::to_string(denominator)))
);
} else if (definition->identification.equals(TimeStruct_UL)) {
/*INFO: ST 2001-1 and ST 377-1 diverge on the meaning of 'fraction'.
fraction is msec/4 according to 377-1 */
int hour = value.readUnsignedByte();
int minute = value.readUnsignedByte();
int second = value.readUnsignedByte();
int fraction = value.readUnsignedByte();
element->setTextContent(DOMHelper::fromUTF8(generateISO8601Time(hour, minute, second, 4 * fraction)));
} else if (definition->identification.equals(TimeStamp_UL)) {
int year = value.readUnsignedShort();
int month = value.readUnsignedByte();
int day = value.readUnsignedByte();
int hour = value.readUnsignedByte();
int minute = value.readUnsignedByte();
int second = value.readUnsignedByte();
int fraction = value.readUnsignedByte();
element->setTextContent(
DOMHelper::fromUTF8(
generateISO8601Date(year, month, day) + "T" +
generateISO8601Time(hour, minute, second, 4 * fraction)
)
);
} else if (definition->identification.equals(VersionType_UL)) {
/* EXCEPTION: registers used Int8 but MXF specifies UInt8 */
unsigned char major = value.readUnsignedByte();
unsigned char minor = value.readUnsignedByte();
element->setTextContent(
DOMHelper::fromUTF8(rxml::fmt("{}.{}", rxml::to_string(major), rxml::to_string(minor)))
);
} else {
for (std::vector<RecordTypeDefinition::Member>::const_iterator it = definition->members.begin();
it != definition->members.end();
it++) {
const Definition *itemdef = findBaseDefinition(defresolver.getDefinition(it->type));
xercesc::DOMElement *elem = element->getOwnerDocument()->createElementNS(
DOMHelper::fromUTF8(definition->ns),
DOMHelper::fromUTF8(it->name)
);
elem->setPrefix(DOMHelper::fromUTF8(getElementNSPrefix(definition->ns)));
applyRule5(elem, value, itemdef);
element->appendChild(elem);
}
}
}
void FragmentBuilder::applyRule5_9(xercesc::DOMElement * element, MXFInputStream & value, const RenameTypeDefinition * definition) {
const Definition *rdef = defresolver.getDefinition(definition->renamedType);
applyRule5(element, value, rdef);
}
void FragmentBuilder::applyRule5_10(xercesc::DOMElement * element, MXFInputStream & value, const SetTypeDefinition * definition) {
const Definition* tdef = findBaseDefinition(defresolver.getDefinition(definition->elementType));
unsigned long itemcount = value.readUnsignedLong();
value.readUnsignedLong(); // item length
applyCoreRule5_4(element, value, tdef, (unsigned long)itemcount);
}
void FragmentBuilder::applyRule5_11(xercesc::DOMElement * element, MXFInputStream & value, const StreamTypeDefinition * definition) {
throw FragmentBuilder::Exception("Rule 5.11 is not supported yet.");
}
void FragmentBuilder::applyRule5_12(xercesc::DOMElement * element, MXFInputStream & value, const StringTypeDefinition * definition) {
/* Rule 5.12 */
const Definition *chrdef = findBaseDefinition(defresolver.getDefinition(definition->elementType));
/* NOTE: ST 2001-1 implies that integer-based strings are supported, but
does not described semantics.
*/
if (!instance_of<CharacterTypeDefinition>(*chrdef)) {
throw UnsupportedStringTypeError(definition->symbol,
rxml::fmt(
"Element {}",
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
return;
}
readCharacters(
element,
value,
(CharacterTypeDefinition*)chrdef,
false /* remove trailing zeroes */
);
}
void FragmentBuilder::applyRule5_13(xercesc::DOMElement * element, MXFInputStream & value, const StrongReferenceTypeDefinition * definition) {
const Definition *tdef = findBaseDefinition(defresolver.getDefinition(definition->referencedType));
if (!instance_of<ClassDefinition>(*tdef)) {
throw InvalidStrongReferenceTypeError(
definition->symbol,
rxml::fmt(
"Element {}",
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
UUID uuid = value.readUUID();
std::map<UUID, Set>::const_iterator it = setresolver.find(uuid);
if (it != setresolver.end()) {
applyRule3(element, it->second);
} else {
throw MissingStrongReferenceError(
uuid,
rxml::fmt(
"Element {}",
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
}
void FragmentBuilder::applyRule5_beta(xercesc::DOMElement * element, MXFInputStream & value, const LensSerialFloatTypeDefinition * definition) {
throw FragmentBuilder::Exception("Lens serial floats not supported.");
}
std::vector<const PropertyDefinition*> FragmentBuilder::getAllMembersOf(const ClassDefinition * cdef) {
std::vector<const PropertyDefinition*> props;
while (cdef) {
std::set<AUID> members = defresolver.getMembersOf(cdef->identification);
for (std::set<AUID>::const_iterator it = members.begin(); it != members.end(); it++) {
props.push_back((const PropertyDefinition*)defresolver.getDefinition(*it));
}
if (cdef->parentClass.is_valid()) {
cdef = (ClassDefinition*)defresolver.getDefinition(cdef->parentClass.get());
} else {
cdef = NULL;
}
}
return props;
}
void FragmentBuilder::applyRule5_14(xercesc::DOMElement * element, MXFInputStream & value, const VariableArrayTypeDefinition * definition) {
const Definition *tdef = findBaseDefinition(defresolver.getDefinition(definition->elementType));
if (definition->symbol == "DataValue") {
/* RULE 5.14.2 */
/* DataValue is string of octets, without number of elements or size of elements */
std::stringstream ss;
char c;
while (value.get(c)) {
ss << std::hex << std::setw(2) << std::setfill('0') << ((unsigned int)c & 0xFF);
}
element->setTextContent(DOMHelper::fromUTF8(ss.str()));
} else {
const Definition *base = findBaseDefinition(tdef);
if (instance_of<CharacterTypeDefinition>(*base) || base->name.find("StringArray") != std::string::npos) {
/* RULE 5.14.1 */
/* INFO: StringArray is not used in MXF (ST 377-1) */
throw FragmentBuilder::Exception("StringArray not supported.");
} else {
unsigned long itemcount = value.readLong();
value.readLong(); // item length
applyCoreRule5_4(element, value, tdef, itemcount);
}
}
}
void FragmentBuilder::applyRule5_15(xercesc::DOMElement * element, MXFInputStream & value, const WeakReferenceTypeDefinition * typedefinition) {
const ClassDefinition *classdef = (ClassDefinition*)defresolver.getDefinition(typedefinition->referencedType);
const PropertyDefinition* uniquepropdef = NULL;
std::vector<const PropertyDefinition*> props = getAllMembersOf(classdef);
for (std::vector<const PropertyDefinition*>::const_iterator it = props.begin(); it != props.end(); it++) {
if ((*it)->uniqueIdentifier.is_valid() && (*it)->uniqueIdentifier.get()) {
uniquepropdef = *it;
break;
}
}
if (uniquepropdef == NULL) {
throw MissingUniquePropertyError(
classdef->identification,
rxml::fmt(
"Definition {} at Element {}",
typedefinition->symbol,
DOMHelper::toUTF8(element->getLocalName()).c_str()
)
);
}
applyRule4(element, value, uniquepropdef);
}
}
| 27.380556 | 289 | 0.689028 | [
"vector"
] |
4cbb8a6c3f7f347290c43f893ac416a9db3f4418 | 3,125 | hpp | C++ | src/config.hpp | MaBunny/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | 1 | 2019-04-29T15:01:57.000Z | 2019-04-29T15:01:57.000Z | src/config.hpp | OtakuSenpai/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | 7 | 2016-07-01T06:41:23.000Z | 2016-10-31T13:35:20.000Z | src/config.hpp | MaBunny/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | null | null | null | #ifndef CONFIG_HPP
#define CONFIG_HPP
#include <string>
#include <fstream>
#include "helpers.hpp"
class Config
{
private:
std::string cfg_file;
std::string meta_file;
Settings settings;
Metadata meta;
void GetFilename(std::string &a)
{
cfg_file = a;
}
//Helper functions to get and put input from user
Settings GetInput();
void PutInput(Settings &sett);
//Read from the meta_file file and return as a Metadata object
//To be called in ReadData()
Metadata ReadMetadata();
//Take a Metadata object as parameter and write it to meta_file file
//To be called in WriteData()
void WriteMetadata(Metadata &to_be_written_obj);
//Read the size of the Metadata file
std::streamsize ReadSize();
public:
Config()
{
meta_file = "./meta.logs"; cfg_file = " ";
logger.GetLogs( static_cast<std::string>("In Config class: Created a Config object with meta_file = ") + meta_file + static_cast<std::string>(" ,and default cfg_file. ") );
logger.GetLogs( static_cast<std::string>("In Config class: Also created a Settings object and Metadata object.") );
logger.Log(0);
}
Config(std::string &file) : cfg_file(file)
{
meta_file = "./meta.logs";
logger.GetLogs( static_cast<std::string>("In Config class: Created a Config object.") );
logger.GetLogs( static_cast<std::string>("In Config class: meta_file is = ") + meta_file + static_cast<std::string>(" .") );
logger.GetLogs( static_cast<std::string>("In Config class: cfg_file is = ") + cfg_file + static_cast<std::string>(" .") );
logger.GetLogs( static_cast<std::string>("In Config class: Also created a Settings object and Metadata object.") );
logger.Log(0);
}
Config(std::string &Cfg_file,std::string &Meta_file) : cfg_file(Cfg_file),
meta_file(Meta_file)
{
logger.GetLogs( static_cast<std::string>("In Config class: Created a Config object.") );
logger.GetLogs( static_cast<std::string>("In Config class: meta_file is = ") + meta_file + static_cast<std::string>(" .") );
logger.GetLogs( static_cast<std::string>("In Config class: cfg_file is = ") + cfg_file + static_cast<std::string>(" .") );
logger.GetLogs( static_cast<std::string>("In Config class: Also created a Settings object and Metadata object.") );
logger.Log(0);
}
~Config()
{
logger.GetLogs( static_cast<std::string>("In Config class: Deleted Config object.") );
logger.Log(0);
}
//Take config from user input
//To call WriteData()
void Take_Config();
//Show config to user
//To call ReadData()
void Show_Config();
//Read the data of a Settings object and show it
//It returns a Settings object
Settings ReadData();
//Write to the cfg_file the data stored in Settings object
//It takes a Settings object as parameter
void WriteData(Settings &sett);
//Function to return a config entry
//void Search(std::string &serv);
};
#endif
| 33.244681 | 179 | 0.63968 | [
"object"
] |
4cc0ee7ad38174cf93e6d8371123f21c1b49551a | 1,737 | cpp | C++ | src/parse.cpp | likunlun0618/snn | 65d2d919ad40842eb1682b9484a067d792503318 | [
"MIT"
] | 4 | 2020-01-16T08:15:22.000Z | 2020-03-30T04:30:23.000Z | src/parse.cpp | likunlun0618/snn | 65d2d919ad40842eb1682b9484a067d792503318 | [
"MIT"
] | null | null | null | src/parse.cpp | likunlun0618/snn | 65d2d919ad40842eb1682b9484a067d792503318 | [
"MIT"
] | null | null | null | #include <cstring>
#include <fstream>
#include <sstream>
#include "parse.h"
namespace snn
{
namespace parse
{
vector<string> readFile(string filename)
{
std::ifstream file(filename);
char buffer[1024];
vector<string> lines;
while (file.getline(buffer, sizeof(buffer)))
lines.push_back(string(buffer));
file.close();
return lines;
}
vector<string> deleteComments(vector<string> &lines)
{
vector<string> ret;
for (string line : lines)
{
for (int i = 0; i < (int)line.length() - 1; ++i)
if (line[i] == '/' && line[i + 1] == '/')
{
line = line.substr(0, i);
break;
}
ret.push_back(line);
}
return ret;
}
vector<string> deleteEmptyLines(vector<string> &lines)
{
vector<string> ret;
for (string &line : lines)
if (line.length() > 0)
ret.push_back(line);
return ret;
}
vector<string> split(string s, string separator)
{
char *token = strtok((char *)s.data(), (char *)separator.data());
vector<string> ret;
while (token != NULL)
{
ret.push_back(string(token));
token = strtok(NULL, (char *)separator.data());
}
return ret;
}
vector<int> readArray(string s, string separator)
{
vector<string> items = split(s, separator);
vector<int> ret(items.size());
for (int i = 0; i < items.size(); ++i)
std::stringstream(items[i]) >> ret[i];
return ret;
}
string parseItem(string item, string arg)
{
string ret;
if (item.length() < arg.length() + 2)
return ret;
ret = item.substr(arg.length() + 1, item.length() - arg.length() - 2);
return ret;
}
} // namespace parse
} // namespace snn
| 21.444444 | 74 | 0.572827 | [
"vector"
] |
4ccf613cf27f16e4c553b692f7b1e45fe9479dda | 1,779 | hpp | C++ | include/blue/camera/OrthographicCamera.hpp | szszszsz/blue | a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8 | [
"MIT"
] | 4 | 2019-07-21T17:09:48.000Z | 2021-02-20T03:34:10.000Z | include/blue/camera/OrthographicCamera.hpp | szszszsz/blue | a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8 | [
"MIT"
] | 2 | 2019-07-25T08:29:18.000Z | 2020-01-07T09:04:51.000Z | include/blue/camera/OrthographicCamera.hpp | szszszsz/blue | a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8 | [
"MIT"
] | 1 | 2019-08-10T08:35:55.000Z | 2019-08-10T08:35:55.000Z | #pragma once
#include "blue/camera/Camera.hpp"
class OrthographicCamera : public Camera {
public:
enum class Mode
{
CLIP_SPACE, // for 3d rendering
SCREEN_SPACE // for 2d rendering
};
explicit OrthographicCamera(Mode mode, std::uint16_t viewport_width, std::uint16_t viewport_height) :
_mode(mode), Camera(viewport_width, viewport_height)
{
reset();
}
void reset();
glm::mat4 get_view() override;
glm::mat4 get_projection() override;
void set_pos(const glm::vec3&);
void set_rotation(const glm::vec3& euler);
// moving
void go_forward(float distance);
void go_backward(float distance);
void go_left(float distance);
void go_right(float distance);
void mouse_rotation(double xpos, double ypos);
// getters
float get_roll() const;
float get_pitch() const;
float get_yaw() const;
float get_fov() const;
glm::vec3 get_position() const;
glm::vec3 get_front() const;
glm::vec3 get_up() const;
GLfloat get_last_x() const;
GLfloat get_last_y() const;
void set_near(float);
void set_far(float);
private:
Mode _mode;
// roll is always 0
GLfloat _yaw = 0;
GLfloat _pitch = 0;
GLfloat _lastX = 0;
GLfloat _lastY = 0;
GLfloat _fov = 0;
float _aspect{}; // (view ratio)
glm::vec3 _position = glm::vec3(0.0f, 0.0f, 10.0f);
glm::vec3 _front = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 _HELPER_CAMERA_TARGET = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 _HELPER_CAMERA_DIRECTION = glm::normalize(_position - _HELPER_CAMERA_TARGET);
glm::vec3 _HELPER_UP = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 _CAMERA_RIGHT = glm::normalize(glm::cross(_HELPER_UP, _HELPER_CAMERA_DIRECTION));
glm::vec3 _CAMERA_UP = glm::cross(_HELPER_CAMERA_DIRECTION, _CAMERA_RIGHT);
float _near = -1;
float _far = 1;
};
| 19.549451 | 103 | 0.698145 | [
"3d"
] |
4cd0e336cf92a3f1da7c8b2a24cc79dbc2182765 | 13,324 | cpp | C++ | source/engine.cpp | EfeDursun125/CS-EBOT | 8ced23754a082ea52d03d2e79c98aeb2a1c51a5b | [
"Apache-2.0"
] | null | null | null | source/engine.cpp | EfeDursun125/CS-EBOT | 8ced23754a082ea52d03d2e79c98aeb2a1c51a5b | [
"Apache-2.0"
] | null | null | null | source/engine.cpp | EfeDursun125/CS-EBOT | 8ced23754a082ea52d03d2e79c98aeb2a1c51a5b | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2003-2009, by Yet Another POD-Bot Development Team.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS 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.
//
// $Id: engine.cpp 35 2009-06-24 16:43:26Z jeefo $
//
#include <core.h>
ConVar::ConVar(const char* name, const char* initval, VarType type)
{
engine->RegisterVariable(name, initval, type, this);
}
void Engine::InitFastRNG(void)
{
m_divider = (static_cast <uint64_t> (1)) << 32;
m_rnd[0] = clock();
m_rnd[1] = ~(m_rnd[0] + 6);
m_rnd[1] = GetRandomBase();
}
uint32_t Engine::GetRandomBase(void)
{
m_rnd[0] ^= m_rnd[1] << 5;
m_rnd[0] *= 1664525L;
m_rnd[0] += 1013904223L;
m_rnd[1] *= 1664525L;
m_rnd[1] += 1013904223L;
m_rnd[1] ^= m_rnd[0] << 3;
return m_rnd[0];
}
float Engine::RandomFloat(float low, float high)
{
if (low >= high)
return low;
return RANDOM_FLOAT(low, high);
}
int Engine::RandomInt(int low, int high)
{
if (low >= high)
return low;
return RANDOM_LONG(low, high);
}
void Engine::SubtractVectors(Vector first, Vector second, Vector output)
{
Vector result;
result.x = (first.x - second.x);
result.y = (first.y - second.y);
result.z = (first.z - second.z);
output = result;
}
float Engine::GetVectorDotProduct(Vector first, Vector second)
{
Vector product;
for (int i = 0; i < 3; i++)
{
product.x = product.y + first.x * second.x;
product.x = product.y + first.y * second.y;
}
return ((product.x / 2) - (product.y / 2));
}
void Engine::NormalizeVector(Vector vector, Vector output)
{
Vector result;
float length = Q_rsqrt((vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z));
result.x = (vector.x / length);
result.y = (vector.y / length);
result.z = (vector.z / length);
output = result;
}
float Engine::ApproachAngle(float target, float value, float speed)
{
float delta = AngleDiff(target, value);
if (speed < 0.0)
speed = -speed;
if (delta > speed)
value += speed;
else if (delta < -speed)
value -= speed;
else
value = target;
return AngleNormalize(value);
}
float Engine::Sine(float X)
{
return static_cast <float> (sin(X));
}
float Engine::AngleDiff(float destAngle, float srcAngle)
{
return AngleNormalize(destAngle - srcAngle);
}
float Engine::Clamp(float a, float b, float c)
{
return (a > c ? c : (a < b ? b : a));
}
int Engine::MinInt(int one, int two)
{
if (one < two)
return one;
else if (two < one)
return two;
return two;
}
float Engine::Max(float one, float two)
{
if (one > two)
return one;
else if (two > one)
return two;
return two;
}
void Engine::RegisterVariable(const char* variable, const char* value, VarType varType, ConVar* self)
{
VarPair newVariable;
newVariable.reg.name = const_cast <char*> (variable);
newVariable.reg.string = const_cast <char*> (value);
int engineFlags = FCVAR_EXTDLL;
if (varType == VARTYPE_NORMAL)
engineFlags |= FCVAR_SERVER;
else if (varType == VARTYPE_READONLY)
engineFlags |= FCVAR_SERVER | FCVAR_SPONLY | FCVAR_PRINTABLEONLY;
else if (varType == VARTYPE_PASSWORD)
engineFlags |= FCVAR_PROTECTED;
newVariable.reg.flags = engineFlags;
newVariable.self = self;
memcpy(&m_regVars[m_regCount], &newVariable, sizeof(VarPair));
m_regCount++;
}
void Engine::PushRegisteredConVarsToEngine(void)
{
for (int i = 0; i < m_regCount; i++)
{
VarPair* ptr = &m_regVars[i];
if (ptr == null)
break;
g_engfuncs.pfnCVarRegister(&ptr->reg);
ptr->self->m_eptr = g_engfuncs.pfnCVarGetPointer(ptr->reg.name);
}
}
void Engine::GetGameConVarsPointers(void)
{
m_gameVars[GVAR_C4TIMER] = g_engfuncs.pfnCVarGetPointer("mp_c4timer");
m_gameVars[GVAR_BUYTIME] = g_engfuncs.pfnCVarGetPointer("mp_buytime");
m_gameVars[GVAR_FRIENDLYFIRE] = g_engfuncs.pfnCVarGetPointer("mp_friendlyfire");
m_gameVars[GVAR_ROUNDTIME] = g_engfuncs.pfnCVarGetPointer("mp_roundtime");
m_gameVars[GVAR_FREEZETIME] = g_engfuncs.pfnCVarGetPointer("mp_freezetime");
m_gameVars[GVAR_FOOTSTEPS] = g_engfuncs.pfnCVarGetPointer("mp_footsteps");
m_gameVars[GVAR_GRAVITY] = g_engfuncs.pfnCVarGetPointer("sv_gravity");
m_gameVars[GVAR_DEVELOPER] = g_engfuncs.pfnCVarGetPointer("developer");
// if buytime is null, just set it to round time
if (m_gameVars[GVAR_BUYTIME] == null)
m_gameVars[GVAR_BUYTIME] = m_gameVars[3];
}
const Vector& Engine::GetGlobalVector(GlobalVector id)
{
switch (id)
{
case GLOBALVECTOR_FORWARD:
return g_pGlobals->v_forward;
case GLOBALVECTOR_RIGHT:
return g_pGlobals->v_right;
case GLOBALVECTOR_UP:
return g_pGlobals->v_up;
}
return nullvec;
}
void Engine::SetGlobalVector(GlobalVector id, const Vector& newVector)
{
switch (id)
{
case GLOBALVECTOR_FORWARD:
g_pGlobals->v_forward = newVector;
break;
case GLOBALVECTOR_RIGHT:
g_pGlobals->v_right = newVector;
break;
case GLOBALVECTOR_UP:
g_pGlobals->v_up = newVector;
break;
}
}
void Engine::BuildGlobalVectors(const Vector& on)
{
on.BuildVectors(&g_pGlobals->v_forward, &g_pGlobals->v_right, &g_pGlobals->v_up);
}
bool Engine::IsFootstepsOn(void)
{
return m_gameVars[GVAR_FOOTSTEPS]->value > 0;
}
float Engine::GetC4TimerTime(void)
{
return m_gameVars[GVAR_C4TIMER]->value;
}
float Engine::GetBuyTime(void)
{
return m_gameVars[GVAR_BUYTIME]->value;
}
float Engine::GetRoundTime(void)
{
return m_gameVars[GVAR_ROUNDTIME]->value;
}
float Engine::GetFreezeTime(void)
{
return m_gameVars[GVAR_FREEZETIME]->value;
}
int Engine::GetGravity(void)
{
return static_cast <int> (m_gameVars[GVAR_GRAVITY]->value);
}
int Engine::GetDeveloperLevel(void)
{
return static_cast <int> (m_gameVars[GVAR_DEVELOPER]->value);
}
bool Engine::IsFriendlyFireOn(void)
{
return m_gameVars[GVAR_FRIENDLYFIRE]->value > 0;
}
void Engine::PrintServer(const char* format, ...)
{
static char buffer[1024];
va_list ap;
va_start(ap, format);
vsprintf(buffer, format, ap);
va_end(ap);
strcat(buffer, "\n");
g_engfuncs.pfnServerPrint(buffer);
}
int Engine::GetMaxClients(void)
{
return g_pGlobals->maxClients;
}
float Engine::GetTime(void)
{
return g_pGlobals->time;
}
void Engine::PrintAllClients(PrintType printType, const char* format, ...)
{
char buffer[1024];
va_list ap;
va_start(ap, format);
vsprintf(buffer, format, ap);
va_end(ap);
if (printType == PRINT_CONSOLE)
{
for (int i = 0; i < GetMaxClients(); i++)
{
const Client& client = GetClientByIndex(i);
if (client.IsPlayer())
client.Print(PRINT_CONSOLE, buffer);
}
}
else
{
strcat(buffer, "\n");
g_engfuncs.pfnMessageBegin(MSG_BROADCAST, g_netMsg->GetId(NETMSG_TEXTMSG), null, null);
g_engfuncs.pfnWriteByte(printType == PRINT_CENTER ? 4 : 3);
g_engfuncs.pfnWriteString(buffer);
g_engfuncs.pfnMessageEnd();
}
}
#pragma warning (disable : 4172)
const Entity& Engine::GetEntityByIndex(int index)
{
return g_engfuncs.pfnPEntityOfEntIndex(index);
}
#pragma warning (default : 4172)
const Client& Engine::GetClientByIndex(int index)
{
return m_clients[index];
}
void Engine::MaintainClients(void)
{
for (int i = 0; i < GetMaxClients(); i++)
m_clients[i].Maintain(g_engfuncs.pfnPEntityOfEntIndex(i));
}
void Engine::DrawLine(const Client& client, const Vector& start, const Vector& end, const Color& color, int width, int noise, int speed, int life, int lineType)
{
if (!client.IsValid())
return;
g_engfuncs.pfnMessageBegin(MSG_ONE_UNRELIABLE, SVC_TEMPENTITY, null, client);
g_engfuncs.pfnWriteByte(TE_BEAMPOINTS);
g_engfuncs.pfnWriteCoord(start.x);
g_engfuncs.pfnWriteCoord(start.y);
g_engfuncs.pfnWriteCoord(start.z);
g_engfuncs.pfnWriteCoord(end.x);
g_engfuncs.pfnWriteCoord(end.y);
g_engfuncs.pfnWriteCoord(end.z);
switch (lineType)
{
case LINE_SIMPLE:
g_engfuncs.pfnWriteShort(g_modelIndexLaser);
break;
case LINE_ARROW:
g_engfuncs.pfnWriteShort(g_modelIndexArrow);
break;
}
g_engfuncs.pfnWriteByte(0);
g_engfuncs.pfnWriteByte(10);
g_engfuncs.pfnWriteByte(life);
g_engfuncs.pfnWriteByte(width);
g_engfuncs.pfnWriteByte(noise);
g_engfuncs.pfnWriteByte(color.red);
g_engfuncs.pfnWriteByte(color.green);
g_engfuncs.pfnWriteByte(color.blue);
g_engfuncs.pfnWriteByte(color.alpha); // alpha as brightness here
g_engfuncs.pfnWriteByte(speed);
g_engfuncs.pfnMessageEnd();
}
void Engine::IssueBotCommand(edict_t* ent, const char* fmt, ...)
{
// the purpose of this function is to provide fakeclients (bots) with the same client
// command-scripting advantages (putting multiple commands in one line between semicolons)
// as real players. It is an improved version of botman's FakeClientCommand, in which you
// supply directly the whole string as if you were typing it in the bot's "console". It
// is supposed to work exactly like the pfnClientCommand (server-sided client command).
if (FNullEnt(ent))
return;
va_list ap;
static char string[256];
va_start(ap, fmt);
vsnprintf(string, 256, fmt, ap);
va_end(ap);
if (IsNullString(string))
return;
m_arguments[0] = 0x0;
m_argumentCount = 0;
m_isBotCommand = true;
int i, pos = 0;
int length = strlen(string);
while (pos < length)
{
int start = pos;
int stop = pos;
while (pos < length && string[pos] != ';')
pos++;
if (string[pos - 1] == '\n')
stop = pos - 2;
else
stop = pos - 1;
for (i = start; i <= stop; i++)
m_arguments[i - start] = string[i];
m_arguments[i - start] = 0;
pos++;
int index = 0;
m_argumentCount = 0;
while (index < i - start)
{
while (index < i - start && m_arguments[index] == ' ')
index++;
if (m_arguments[index] == '"')
{
index++;
while (index < i - start && m_arguments[index] != '"')
index++;
index++;
}
else
while (index < i - start && m_arguments[index] != ' ')
index++;
m_argumentCount++;
}
MDLL_ClientCommand(ent);
}
m_isBotCommand = false;
m_arguments[0] = 0x0;
m_argumentCount = 0;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// CLIENT
//////////////////////////////////////////////////////////////////////////
float Client::GetShootingConeDeviation(const Vector& pos) const
{
engine->BuildGlobalVectors(GetViewAngles());
return g_pGlobals->v_forward | (pos - GetHeadOrigin()).Normalize();
}
bool Client::IsInViewCone(const Vector& pos) const
{
engine->BuildGlobalVectors(GetViewAngles());
return ((pos - GetHeadOrigin()).Normalize() | g_pGlobals->v_forward) >= cosf(Math::DegreeToRadian((GetFOV() > 0.0f ? GetFOV() : 90.0f) * 0.5f));
}
bool Client::IsVisible(const Vector& pos) const
{
Tracer trace(GetHeadOrigin(), pos, NO_BOTH, m_ent);
return !(trace.Fire() != 1.0);
}
bool Client::HasFlag(int clientFlags)
{
return (m_flags & clientFlags) == clientFlags;
}
Vector Client::GetOrigin(void) const
{
return m_safeOrigin;
}
bool Client::IsAlive(void) const
{
return !!(m_flags & CLIENT_ALIVE | CLIENT_VALID);
}
void Client::Maintain(const Entity& ent)
{
if (ent.IsPlayer())
{
m_ent = ent;
m_safeOrigin = ent.GetOrigin();
m_flags |= ent.IsAlive() ? CLIENT_VALID | CLIENT_ALIVE : CLIENT_VALID;
}
else
{
m_safeOrigin = nullvec;
m_flags = ~(CLIENT_VALID | CLIENT_ALIVE);
}
}
| 24.765799 | 160 | 0.631492 | [
"vector"
] |
4cd2e325918f02590b9453121776932f2c5dd78a | 279 | cpp | C++ | Cpp_primer_5th/code_part9/prog9_5.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part9/prog9_5.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | Cpp_primer_5th/code_part9/prog9_5.cpp | Links789/Cpp_primer_5th | 18a60b75c358a79fdf006f8cb978c9be6e6aedd5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int>::const_iterator func(vector<int>::const_iterator begin, vector<int>::const_iterator end, int i){
while(begin != end){
if(*begin == i)
return begin;
++begin;
}
return end;
}
| 17.4375 | 108 | 0.677419 | [
"vector"
] |
4cd61eefb89003d5c1cc9fa1a1af8ca3bf49318c | 16,841 | cpp | C++ | iris_sfs/FTModel.cpp | amrotork/face_swap | e97de5eac4c182f62cf1c31279ed2127c2252c50 | [
"Apache-2.0"
] | 2 | 2018-03-20T05:30:20.000Z | 2018-07-27T02:35:06.000Z | iris_sfs/FTModel.cpp | zzjf/faceSwap | e51e9aadc0ed5aa3fe5f303b5c0591205930b484 | [
"Apache-2.0"
] | null | null | null | iris_sfs/FTModel.cpp | zzjf/faceSwap | e51e9aadc0ed5aa3fe5f303b5c0591205930b484 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2015 USC, IRIS, Computer vision Lab */
//----------------------------------------------------------------------
// File: FTModel.cpp
// Authors: Yann Dumortier (yann.dumortier@gmail.com),
// Jongmoo Choi (jongmooc@usc.edu),
// Sang-il Choi (csichoisi@gmail.net)
// Description:
// This file is part of the "Real-time 3D Face Tracking and Modeling Using a Webcam"
// developed at the University of Southern California by:
//
// Yann Dumortier (yann.dumortier@gmail.com),
// Jongmoo Choi (jongmooc@usc.edu),
// Gerard Medioni (medioni@usc.edu).
//----------------------------------------------------------------------
// Copyright (c) 2011 University of Southern California. All Rights Reserved.
#include "FTModel.h"
#include "MeshModel.h"
//CHECKED and APPROUVED without bug ;)
//Give fx=fy and Tx Ty Tz in the face coordinate system (to be consistent with the tracking, also in this system)
int
StatiCam::calibIntWoRot( float cx,
float cy,
unsigned n,
float *pts2D,
float *pts3D,
float *t )
{
float height = cy*2;
cx_ = cx;
cy_ = cy;
float *tab_A = new float[8*n];
for ( unsigned i_2D=0, i_3D=0, i_A=0; i_2D<2*n; i_2D+=2, i_3D+=3 )
{
//"1st row"
tab_A[i_A++] = -pts3D[i_3D]; //-Xi
tab_A[i_A++] = pts3D[i_3D+2]*(cx_-pts2D[i_2D]); //Zi(cx-ui)
tab_A[i_A++] = 1; //1
tab_A[i_A++] = 0; //0
//"2nd row"
tab_A[i_A++] = pts3D[i_3D+1]; //Yi
tab_A[i_A++] = pts3D[i_3D+2]*(cy_-pts2D[i_2D+1]); //Zi(cy-vi)
tab_A[i_A++] = 0; //0
tab_A[i_A++] = 1; //1
}
cv::Mat A( 2*n, 4, CV_32F, tab_A );
cv::Mat b( 2*n, 1, CV_32F, pts2D );
cv::Mat x = (A.t()*A).inv()*A.t()*b;
//Intrinsic parameters
f_ = (( float* )( x.data ))[0] / (( float* )( x.data ))[1];
//Extrinsic parameters
t[0] = -((( float* )( x.data ))[2]-cx_ ) / (( float* )( x.data ))[0];
t[1] = ((( float* )( x.data ))[3]-cy_ ) / (( float* )( x.data ))[0];
t[2] = 1.f / (( float* )( x.data ))[1];
/*std::cerr << "focal: " << f_ << ", (cx,cy): (" << cx_ << "," << cy_ << ")\n";
std::cerr << "t=[" << t[0] << "," << t[1] << "," << t[2] << "]\n";*/
if(t[2]>0)
{
t[0] = ((( float* )( x.data ))[2]-cx_ ) / (( float* )( x.data ))[0];
t[1] = -((( float* )( x.data ))[3]-cy_ ) / (( float* )( x.data ))[0];
t[2] = -1.f / (( float* )( x.data ))[1];
f_ = -1*f_;
}
delete[] tab_A;
return 1;
}
int
StatiCam::calibIntWoRot2( float cx,
float cy,
unsigned n,
float *pts2D,
float *pts3D,
float *t )
{
float height = cy*2;
cx_ = cx;
cy_ = cy;
int n2 = 6;
float *tab_A = new float[8*n2];
float *tab_B = new float[2*n2];
int* ind = new int[n];
float *t2 = new float[3];
float f_2;
cv::RNG rng;
int bestCons = 0;
for (int i=0; i< 100; i++)
{
for (int j=0; j<n; j++) ind[j] = j;
for (int j=0; j<n2;j++)
{
int jj = rng.next() % n;
if (j != jj)
{
int k= ind[jj];
ind[jj] = ind[j];
ind[j] = k;
}
}
for ( unsigned i_D=0; i_D<n2; i_D++ )
{
int j = ind[i_D];
//"1st row"
tab_A[i_D * 8] = -pts3D[j*3]; //-Xi
tab_A[i_D * 8 + 1] = pts3D[j*3+2]*(cx_-pts2D[j*2]); //Zi(cx-ui)
tab_A[i_D * 8 + 2] = 1; //1
tab_A[i_D * 8 + 3] = 0; //0
//"2nd row"
tab_A[i_D * 8 + 4] = pts3D[j*3+1]; //Yi
tab_A[i_D * 8 + 5] = pts3D[j*3+2]*(cy_-pts2D[j*2+1]); //Zi(cy-vi)
tab_A[i_D * 8 + 6] = 0; //0
tab_A[i_D * 8 + 7] = 1; //1
tab_B[i_D * 2] = pts2D[j*2];
tab_B[i_D * 2 + 1] = pts2D[j*2 + 1];
}
cv::Mat A( 2*n2, 4, CV_32F, tab_A );
cv::Mat b( 2*n2, 1, CV_32F, tab_B );
cv::Mat x = (A.t()*A).inv()*A.t()*b;
//Intrinsic parameters
f_2 = (( float* )( x.data ))[0] / (( float* )( x.data ))[1];
//Extrinsic parameters
t2[0] = -((( float* )( x.data ))[2]-cx_ ) / (( float* )( x.data ))[0];
t2[1] = ((( float* )( x.data ))[3]-cy_ ) / (( float* )( x.data ))[0];
t2[2] = 1.f / (( float* )( x.data ))[1];
// Fix focal len
float scale = 1000/f_2;
f_2 = 1000;
t2[0] = t2[0] * scale;
t2[1] = t2[1] * scale;
t2[2] = t2[2] * scale;
//printf("f_2 = %f t2[2] = %f \n",f_2,t2[2]);
/*std::cerr << "focal: " << f_ << ", (cx,cy): (" << cx_ << "," << cy_ << ")\n";
std::cerr << "t=[" << t[0] << "," << t[1] << "," << t[2] << "]\n";*/
//if(t2[2]>0)
//{
//t2[0] = ((( float* )( x.data ))[2]-cx_ ) / (( float* )( x.data ))[0];
//t2[1] = -((( float* )( x.data ))[3]-cy_ ) / (( float* )( x.data ))[0];
//t2[2] = -1.f / (( float* )( x.data ))[1];
//f_2 = -1*f_2;
//}
int cons = 0;
float u, v;
for (unsigned i_D=0; i_D<n; i_D++)
{
u = -f_2*(pts3D[i_D *3] + t2[0])/(pts3D[i_D *3 + 2] + t2[2]) + cx_;
v = f_2*(pts3D[i_D *3+1] + t2[1])/(pts3D[i_D *3 + 2] + t2[2]) + cy_;
float dist = std::pow(u - pts2D[i_D *2],2);
dist += std::pow(v - pts2D[i_D *2 + 1],2);
if (dist < 100) cons++;
}
if (cons > bestCons)
{
bestCons = cons;
t[0] = t2[0];
t[1] = t2[1];
t[2] = t2[2];
f_ = f_2;
if (bestCons > 27) break;
}
}
//printf("Bc = %d\n",bestCons);
delete[] tab_A;
delete[] tab_B;
delete[] ind;
delete[] t2;
return 1;
}
//Load the correct 3-D shape according to the
//"id" returned by the recognition module (0 <=> generic model).
Face::Face( unsigned id )
{
id_ = id;
nLdmks_ = 0;
R_ = new float[6];
t_ = &R_[3];
memset(( void* )R_, 0, 6*sizeof( float ));
}
Face::Face( Face &f,
unsigned id )
{
if ( id ) id_ = id;
else id_ = f.id_;
nLdmks_ = f.nLdmks_;
memcpy( landmarks_, f.landmarks_, MAX_LDMKS*sizeof( int ));
//TODO: use a copy constructor of f.mesh instead;
mesh_.nFaces_ = f.mesh_.nFaces_ ;
mesh_.faces_ = new unsigned[3*mesh_.nFaces_];
memcpy( mesh_.faces_, f.mesh_.faces_, 3*mesh_.nFaces_*sizeof( unsigned ));
mesh_.nVertices_ = f.mesh_.nVertices_;
mesh_.vertices_ = new float[3*mesh_.nVertices_];
memcpy( mesh_.vertices_, f.mesh_.vertices_, 3*mesh_.nVertices_*sizeof( float ));
mesh_.texcoords_ = new float[3*mesh_.nVertices_];
R_ = new float[6];
t_ = &R_[3];
memcpy(( void* )R_, ( void* )f.R_, 6*sizeof( float ));
}
Face::~Face()
{
delete[] R_; //delete R_ AND t_;
}
//WARNING: triangle vertices order is important to ensure a correct display.
//See OpenGL documentation about glEnable( GL_CULL_FACE ) and glCullFace( GL_FRONT )
//for more details.
int
Face::loadPLYModel( const char *fileName )
{
std::ifstream file( fileName );
if ( !file ) return invalidPLYFile();
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
std::string buf = buffer.str();
if ( buf.substr( 0, 3 ) != "ply" ) return invalidPLYFile();
size_t pos;
pos = buf.find( "element vertex" );
if ( pos == std::string::npos) return invalidPLYFile();
buffer.seekg( pos + 14 );
buffer >> mesh_.nVertices_;
mesh_.vertices_ = new float[3*mesh_.nVertices_];
pos = buf.find( "element face" );
if ( pos == std::string::npos) return invalidPLYFile();
buffer.seekg( pos + 12 );
buffer >> mesh_.nFaces_;
mesh_.faces_ = new unsigned[3*mesh_.nFaces_];
pos = buf.find( "end_header" );
buffer.seekg( pos );
buffer.ignore( 1024, '\n' );
//Vertices
for ( unsigned i=0, idx=0; i<mesh_.nVertices_; ++i )
{
buffer >> mesh_.vertices_[idx++]; //x
mesh_.vertices_[idx-1] += MODEL_TX;
mesh_.vertices_[idx-1] *= MODEL_SCALE;
buffer >> mesh_.vertices_[idx++]; //y
mesh_.vertices_[idx-1] += MODEL_TY;
mesh_.vertices_[idx-1] *= MODEL_SCALE;
buffer >> mesh_.vertices_[idx++]; //z
mesh_.vertices_[idx-1] += MODEL_TZ;
mesh_.vertices_[idx-1] *= MODEL_SCALE;
buffer.ignore( 1024, '\n' ); //potential comments
}
//Faces
unsigned nEdges;
for ( unsigned i=0, idx=0; i<mesh_.nFaces_; ++i )
{
buffer >> nEdges;
if ( nEdges != 3 ) return invalidPLYFile();
buffer >> mesh_.faces_[idx++]; //v1
buffer >> mesh_.faces_[idx++]; //v2
buffer >> mesh_.faces_[idx++]; //v3
buffer.ignore( 1024, '\n' ); //potential comments
}
return 1;
}
//Load landmark points corresponding to the generic 3D face model
//Landmarks do not have to be point of the model. In such case,
//closest points are used.
int Face::loadPLYModel2(const char* ply_file){
int state = 0;
char str[250];
char* pos[10];
unsigned char prop_count = 0;
unsigned char props[9];
int count;
int vcount = 0;
int fcount = 0;
int i;
FILE* file = fopen(ply_file,"r");
if (!file) return -1;
while (!feof(file) && state <= 4){
fgets(str,250,file);
if (strlen(str) < 3) continue;
count = splittext(str, pos);
if (count < 1 || (strcmp(pos[0],"comment") == 0)) continue;
switch (state){
case 0: // at beginning
if (count != 3 || (strcmp(pos[0],"element") != 0) || (strcmp(pos[1],"vertex") != 0)) continue;
mesh_.nVertices_ = atoi(pos[2]);
if (mesh_.nVertices_ < 1) {
mesh_.nVertices_ = 0; return -1;
}
mesh_.vertices_ = new float[3*mesh_.nVertices_];
state = 1;
break;
case 1: // get properties
if (strcmp(pos[0],"end_header") == 0) state = 3;
else if (strcmp(pos[0],"element") == 0){
if (strcmp(pos[1],"face") == 0){
state = 2;
mesh_.nFaces_ = atoi(pos[2]);
mesh_.faces_ = new unsigned int[3*mesh_.nFaces_];
}
}
else if (count == 3 && (strcmp(pos[0],"property") == 0)){
if (strcmp(pos[2],"x") == 0) {
props[prop_count] = PROP_X;
prop_count++;
}
if (strcmp(pos[2],"y") == 0){
props[prop_count] = PROP_Y;
prop_count++;
}
if (strcmp(pos[2],"z") == 0){
props[prop_count] = PROP_Z;
prop_count++;
}
if (strcmp(pos[2],"red") == 0){
mesh_.colors_ = new float[4*mesh_.nVertices_];
props[prop_count] = PROP_R;
prop_count++;
}
if (strcmp(pos[2],"green") == 0){
props[prop_count] = PROP_G;
prop_count++;
}
if (strcmp(pos[2],"blue") == 0){
props[prop_count] = PROP_B;
prop_count++;
}
}
break;
case 2:
if (strcmp(pos[0],"end_header") == 0) state = 3;
break;
case 3:
for (i = 0; i < prop_count; i++){
switch (props[i]){
case PROP_X:
mesh_.vertices_[vcount*3] = atof(pos[i]); break;
case PROP_Y:
mesh_.vertices_[vcount*3+1] = atof(pos[i]); break;
case PROP_Z:
mesh_.vertices_[vcount*3+2] = atof(pos[i]); break;
case PROP_R:
mesh_.colors_[vcount*4] = atoi(pos[i])/255.0f;
mesh_.colors_[vcount*4+3] = 1.0f; break;
case PROP_G:
mesh_.colors_[vcount*4+1] = atoi(pos[i])/255.0f; break;
case PROP_B:
mesh_.colors_[vcount*4+2] = atoi(pos[i])/255.0f; break;
}
}
vcount++;
if (vcount == mesh_.nVertices_) {
if (mesh_.nFaces_ > 0)
state = 4;
else
state = 5;
}
break;
case 4:
mesh_.faces_[3*fcount] = atoi(pos[1]);
mesh_.faces_[3*fcount+1] = atoi(pos[2]);
mesh_.faces_[3*fcount+2] = atoi(pos[3]);
fcount++;
break;
}
}
fclose(file);
return 0;
}
void Face::loadMesh( cv::Mat shape, cv::Mat tex, cv::Mat faces){
mesh_.nVertices_ = shape.rows;
mesh_.vertices_ = new float[3*mesh_.nVertices_];
mesh_.colors_ = new float[4*mesh_.nVertices_];
for (int i=0;i<mesh_.nVertices_;i++){
for (int j=0;j<3;j++){
mesh_.vertices_[3*i+j] = shape.at<float>(i,j);
mesh_.colors_[4*i+j] = tex.at<float>(i,j)/255.0f;
}
mesh_.colors_[4*i+3] = 1.0f;
}
mesh_.nFaces_ = faces.rows;
mesh_.faces_ = new unsigned int[3*mesh_.nFaces_];
for (int i=0;i<mesh_.nFaces_;i++){
for (int j=0;j<3;j++){
mesh_.faces_[3*i+j] = faces.at<int>(i,j);
}
}
}
int
Face::loadPLYLandmarks( const char* fileName )
{
unsigned *idx;
std::ifstream file( fileName );
if ( !file ) return invalidPLYFile();
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
std::string buf = buffer.str();
if ( buf.substr( 0, 3 ) != "ply" ) return invalidPLYFile();
size_t pos;
pos = buf.find( "element vertex" );
if ( pos == std::string::npos) return invalidPLYFile();
buffer.seekg( pos + 14 );
buffer >> nLdmks_;
idx = new unsigned[nLdmks_];
pos = buf.find( "comment Landmark_seq:" );
if ( pos == std::string::npos) return invalidPLYFile();
buffer.seekg( pos + 21 );
for ( unsigned i=0; i<nLdmks_; ++i )
buffer >> idx[i];
pos = buf.find( "end_header" );
buffer.seekg( pos );
buffer.ignore( 1024, '\n' );
memset( landmarks_, -1, sizeof( int )*MAX_LDMKS );
//Landmarks
for ( unsigned i=0; i<nLdmks_; ++i )
{
float x, y, z;
buffer >> x >> y >> z;
x += MODEL_TX;
y += MODEL_TY;
z += MODEL_TZ;
x *= MODEL_SCALE;
y *= MODEL_SCALE;
z *= MODEL_SCALE;
buffer.ignore( 1024, '\n' ); //avoid potential comments
//Faster, but speed is useless at the initialization.
//for ( unsigned j=0; j<3*mesh_.nVertices_; j+=3 )
//{
// if ( x == mesh_.vertices_[j] && y == mesh_.vertices_[j+1] && z == mesh_.vertices_[j+2] )
// landmarks_[idx[i]] = j/3;
//}
//More generic since allows landmarks point to not be exact
//3D model points.
float minDist = FLT_MAX;
for ( unsigned j=0; j<3*mesh_.nVertices_; j+=3 )
{
float dist = pow( x-mesh_.vertices_[j], 2 ) + pow( y-mesh_.vertices_[j+1], 2 ) + pow( z-mesh_.vertices_[j+2], 2 );
if ( dist < minDist )
{
minDist = dist;
landmarks_[idx[i]] = j/3;
}
}
}
delete []idx;
return 1;
}
void
Face::savePLYModel( const char *fileName )
{
std::ofstream file( fileName );
if ( !file )
{
std::cerr << "Creation Error\n";
return;
}
printf("Infor: %d %d %p %p\n",mesh_.nVertices_,mesh_.nFaces_,mesh_.colors_,mesh_.texcoords_);
file << "ply\n";
file << "format ascii 1.0\n";
file << "element vertex " << mesh_.nVertices_ << std::endl;
file << "property float x\nproperty float y\nproperty float z\n";
file << "property uchar blue\nproperty uchar green\nproperty uchar red\n";
//file << "property float texture_u\nproperty float texture_v\n";
file << "element face " << mesh_.nFaces_ << std::endl;
file << "property list uchar int vertex_indices\n";
file << "end_header\n";
for ( unsigned i_3D=0, i_2D=0; i_3D<3*mesh_.nVertices_; i_3D+=3, i_2D+=2 )
{
file << mesh_.vertices_[i_3D] << " ";
file << mesh_.vertices_[i_3D+1] << " ";
file << mesh_.vertices_[i_3D+2] << " "; /*std::endl;*/
if (mesh_.colors_ != NULL) {
file << (int)static_cast<unsigned char>(mesh_.colors_[2*i_2D+2]*255) << " ";
file << (int)static_cast<unsigned char>(mesh_.colors_[2*i_2D+1]*255) << " ";
file << (int)static_cast<unsigned char>(mesh_.colors_[2*i_2D]*255) << std::endl;
}
else
{
unsigned x = mesh_.texcoords_[i_2D] * mesh_.tex_.img_.cols;
unsigned y = mesh_.texcoords_[i_2D+1] * mesh_.tex_.img_.rows;
unsigned idx = 3*(x+y*mesh_.tex_.img_.cols);
file << (int)static_cast<unsigned char>(mesh_.tex_.img_.data[idx]) << " ";
file << (int)static_cast<unsigned char>(mesh_.tex_.img_.data[idx+1]) << " ";
file << (int)static_cast<unsigned char>(mesh_.tex_.img_.data[idx+2]) << std::endl;
}
}
for ( unsigned i_3D=0; i_3D<3*mesh_.nFaces_; )
{
file << "3 ";
file << mesh_.faces_[i_3D++] << " ";
file << mesh_.faces_[i_3D++] << " ";
file << mesh_.faces_[i_3D++] << std::endl;
}
file.close();
//cv::imwrite( "texture.bmp", mesh_.tex_.img_ );
}
bool Face::estimateNormals( ){
if (mesh_.normals != 0){
delete mesh_.normals;
}
mesh_.normals = new float[3*mesh_.nVertices_];
for (int i=0;i<3*mesh_.nVertices_;i++) mesh_.normals[i] = 0;
float nx, ny, nz;
for (int i=0;i<mesh_.nFaces_;i++){
for (int j=0;j<3;j++) {
triangleNormalFromVertex(i, j, nx, ny, nz);
mesh_.normals[3*mesh_.faces_[3*i+j]] += nx;
mesh_.normals[3*mesh_.faces_[3*i+j]+1] += ny;
mesh_.normals[3*mesh_.faces_[3*i+j]+2] += nz;
}
}
for (int i=0;i<mesh_.nVertices_;i++){
float no = sqrt(mesh_.normals[3*i]*mesh_.normals[3*i]+mesh_.normals[3*i+1]*mesh_.normals[3*i+1]+mesh_.normals[3*i+2]*mesh_.normals[3*i+2]);
for (int j=0;j<3;j++) mesh_.normals[3*i+j] = mesh_.normals[3*i+j]/no;
}
return true;
}
void Face::triangleNormalFromVertex(int face_id, int vertex_id, float &nx, float &ny, float &nz) {
int ind0 = mesh_.faces_[3*face_id + vertex_id];
int ind1 = mesh_.faces_[3*face_id + (vertex_id+1)%3];
int ind2 = mesh_.faces_[3*face_id + (vertex_id+2)%3];
float a[3],b[3],v[3];
for (int j=0;j<3;j++){
a[j] = mesh_.vertices_[3*ind1+j] - mesh_.vertices_[3*ind0+j];
b[j] = mesh_.vertices_[3*ind2+j] - mesh_.vertices_[3*ind0+j];
}
v[0] = a[1]*b[2] - a[2]*b[1];
v[1] = a[2]*b[0] - a[0]*b[2];
v[2] = a[0]*b[1] - a[1]*b[0];
float no = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
float dp = a[0]*b[0]+a[1]*b[1]+a[2]*b[2];
float la = sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);
float lb = sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);
float alpha = acos(dp/(la*lb));
nx = alpha * v[0]/no;
ny = alpha * v[1]/no;
nz = alpha * v[2]/no;
}
| 27.836364 | 141 | 0.561546 | [
"mesh",
"shape",
"model",
"3d"
] |
4ce556af7eaa43cc20ae5a0a794f6503be30fbcb | 23,734 | cpp | C++ | ork.lev2/integrationtests/singularity/harness.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 25 | 2015-02-21T04:21:21.000Z | 2022-01-20T05:19:27.000Z | ork.lev2/integrationtests/singularity/harness.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 113 | 2019-08-23T04:52:14.000Z | 2021-09-13T04:04:11.000Z | ork.lev2/integrationtests/singularity/harness.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 4 | 2017-02-20T18:17:55.000Z | 2020-06-28T03:47:55.000Z | ////////////////////////////////////////////////////////////////
// Orkid Media Engine
// Copyright 1996-2020, Michael T. Mayers.
// Distributed under the Boost Software License - Version 1.0 - August 17, 2003
// see http://www.boost.org/LICENSE_1_0.txt
////////////////////////////////////////////////////////////////
#include "harness.h"
#include <boost/program_options.hpp>
#include <iostream>
#include <ork/lev2/aud/audiodevice.h>
#include <ork/lev2/aud/singularity/hud.h>
///////////////////////////////////////////////////////////////////////////////
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorDeferred.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorForward.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorPicking.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorScaleBias.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorScreen.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/NodeCompositorVr.h>
#include <ork/lev2/gfx/renderer/NodeCompositor/OutputNodeRtGroup.h>
#include <ork/lev2/gfx/gfxprimitives.h>
#include <ork/lev2/gfx/gfxmaterial_ui.h>
#include <ork/lev2/ui/layoutgroup.inl>
///////////////////////////////////////////////////////////////////////////////
namespace po = boost::program_options;
///////////////////////////////////////////////////////////////////////////////
#if defined(__APPLE__)
namespace ork::lev2 {
extern bool _macosUseHIDPI;
}
#endif
///////////////////////////////////////////////////////////////////////////////
static auto the_synth = synth::instance();
audiodevice_ptr_t gaudiodevice;
///////////////////////////////////////////////////////////////////////////////
SingularityTestApp::SingularityTestApp(int& argc, char** argv)
: OrkEzQtApp(argc, argv,AppInitData()) {
_hudvp = the_synth->_hudvp;
gaudiodevice = AudioDevice::instance();
//startupAudio();
}
///////////////////////////////////////////////////////////////////////////////
SingularityTestApp::~SingularityTestApp() {
//tearDownAudio();
}
///////////////////////////////////////////////////////////////////////////////
std::string testpatternname = "";
std::string testprogramname = "";
std::string midiportname = "";
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
singularitytestapp_ptr_t createEZapp(int& argc, char** argv) {
po::options_description desc("Allowed options");
desc.add_options() //
("help", "produce help message") //
("test", po::value<std::string>(), "test name (list,vo,nvo)") //
("port", po::value<std::string>(), "midiport name (list)") //
("program", po::value<std::string>(), "program name") //
("hidpi", "hidpi mode");
po::variables_map vars;
po::store(po::parse_command_line(argc, argv, desc), vars);
po::notify(vars);
if (vars.count("help")) {
std::cout << desc << "\n";
exit(0);
}
if (vars.count("port")) {
midiportname = vars["port"].as<std::string>();
}
if (vars.count("test")) {
testpatternname = vars["test"].as<std::string>();
}
if (vars.count("program")) {
testprogramname = vars["program"].as<std::string>();
}
if (vars.count("hidpi")) {
#if defined(__APPLE__)
ork::lev2::_macosUseHIDPI = true;
#endif
}
//////////////////////////////////////////////////////////////////////////////
// boot up debug HUD
//////////////////////////////////////////////////////////////////////////////
static auto& qti = qtinit(argc, argv);
//QApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
auto qtapp = std::make_shared<SingularityTestApp>(qti._argc, qti._argvp);
auto qtwin = qtapp->_mainWindow;
auto gfxwin = qtwin->_gfxwin;
//////////////////////////////////////////////////////////
// a wee bit convoluted, TODO: fixme
auto hudvplayout = qtapp->_topLayoutGroup->layoutAndAddChild(qtapp->_hudvp);
qtapp->_hudvp->_layout = hudvplayout;
//////////////////////////////////////////////////////////
// create references to various items scoped by qtapp
//////////////////////////////////////////////////////////
auto renderer = qtapp->_vars.makeSharedForKey<DefaultRenderer>("renderer");
auto lmd = qtapp->_vars.makeSharedForKey<LightManagerData>("lmgrdata");
auto lightmgr = qtapp->_vars.makeSharedForKey<LightManager>("lmgr", *lmd);
auto compdata = qtapp->_vars.makeSharedForKey<CompositingData>("compdata");
auto material = qtapp->_vars.makeSharedForKey<FreestyleMaterial>("material");
auto CPD = qtapp->_vars.makeSharedForKey<CompositingPassData>("CPD");
auto cameras = qtapp->_vars.makeSharedForKey<CameraDataLut>("cameras");
auto camdata = qtapp->_vars.makeSharedForKey<CameraData>("camdata");
//////////////////////////////////////////////////////////
compdata->presetForward();
compdata->mbEnable = true;
auto nodetek = compdata->tryNodeTechnique<NodeCompositingTechnique>("scene1"_pool, "item1"_pool);
auto outpnode = nodetek->tryOutputNodeAs<RtGroupOutputCompositingNode>();
auto compositorimpl = compdata->createImpl();
compositorimpl->bindLighting(lightmgr.get());
CPD->addStandardLayers();
cameras->AddSorted("spawncam", camdata.get());
//////////////////////////////////////////////////////////
qtapp->onGpuInit([=](Context* ctx) {
renderer->setContext(ctx);
const FxShaderTechnique* fxtechnique = nullptr;
const FxShaderParam* fxparameterMVP = nullptr;
const FxShaderParam* fxparameterMODC = nullptr;
material->gpuInit(ctx, "orkshader://solid");
fxtechnique = material->technique("mmodcolor");
fxparameterMVP = material->param("MatMVP");
fxparameterMODC = material->param("modcolor");
deco::printf(fvec3::White(), "gpuINIT - context<%p>\n", ctx, fxtechnique);
deco::printf(fvec3::Yellow(), " fxtechnique<%p>\n", fxtechnique);
deco::printf(fvec3::Yellow(), " fxparameterMVP<%p>\n", fxparameterMVP);
deco::printf(fvec3::Yellow(), " fxparameterMODC<%p>\n", fxparameterMODC);
});
//////////////////////////////////////////////////////////
qtapp->onUpdate([=](ui::updatedata_ptr_t updata) {
///////////////////////////////////////
auto DB = DrawableBuffer::acquireForWrite(0);
DB->Reset();
DB->copyCameras(*cameras);
qtapp->_hudvp->onUpdateThreadTick(updata);
DrawableBuffer::releaseFromWrite(DB);
});
//////////////////////////////////////////////////////////
qtapp->onDraw([=](ui::drawevent_constptr_t drwev) {
////////////////////////////////////////////////
auto DB = DrawableBuffer::acquireForRead(7);
if (nullptr == DB)
return;
////////////////////////////////////////////////
auto context = drwev->GetTarget();
auto fbi = context->FBI(); // FrameBufferInterface
auto fxi = context->FXI(); // FX Interface
auto mtxi = context->MTXI(); // FX Interface
fbi->SetClearColor(fvec4(0.0, 0.0, 0.1, 1));
////////////////////////////////////////////////////
// draw the synth HUD
////////////////////////////////////////////////////
RenderContextFrameData RCFD(context); // renderer per/frame data
RCFD._cimpl = compositorimpl;
RCFD.setUserProperty("DB"_crc, lev2::rendervar_t(DB));
context->pushRenderContextFrameData(&RCFD);
lev2::UiViewportRenderTarget rt(nullptr);
auto tgtrect = context->mainSurfaceRectAtOrigin();
CPD->_irendertarget = &rt;
CPD->SetDstRect(tgtrect);
compositorimpl->pushCPD(*CPD);
context->beginFrame();
mtxi->PushUIMatrix();
// qtapp->_hudvp->Draw(drwev);
qtapp->_ezviewport->_topLayoutGroup->Draw(drwev);
mtxi->PopUIMatrix();
context->endFrame();
////////////////////////////////////////////////////
DrawableBuffer::releaseFromRead(DB);
});
//////////////////////////////////////////////////////////
qtapp->onResize([=](int w, int h) { //
// printf("GOTRESIZE<%d %d>\n", w, h);
// qtapp->_ezviewport->_topLayoutGroup->SetSize(w, h);
qtapp->_hudvp->SetSize(w, h);
});
//////////////////////////////////////////////////////////
const int64_t trackMAX = (4095 << 16);
qtapp->onUiEvent([=](ui::event_constptr_t ev) -> ui::HandlerResult {
bool isalt = ev->mbALT;
bool isctrl = ev->mbCTRL;
switch (ev->_eventcode) {
case ui::EventCode::KEY_DOWN:
case ui::EventCode::KEY_REPEAT:
switch (ev->miKeyCode) {
case 'p':
the_synth->_hudpage = (the_synth->_hudpage + 1) % 2;
break;
default:
break;
}
break;
default:
return qtapp->_hudvp->handleUiEvent(ev);
break;
}
ui::HandlerResult rval;
return rval;
});
return qtapp;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
singularitybenchapp_ptr_t createBenchmarkApp(
int& argc, //
char** argv,
prgdata_constptr_t program) {
//////////////////////////////////////////////////////////////////////////////
// benchmark
//////////////////////////////////////////////////////////////////////////////
constexpr size_t histosize = 65536;
/////////////////////////////////////////
auto uicontext = std::make_shared<ui::Context>();
auto app = std::make_shared<SingularityBenchMarkApp>(argc, argv);
auto qtwin = app->_mainWindow;
auto gfxwin = qtwin->_gfxwin;
gfxwin->mRootWidget->_uicontext = uicontext.get();
//////////////////////////////////////////////////////////////////////////////
app->onGpuInit([=](Context* ctx) { //
app->_material = std::make_shared<ork::lev2::FreestyleMaterial>();
app->_material->gpuInit(ctx, "orkshader://ui2");
app->_fxtechniqueMODC = app->_material->technique("ui_modcolor");
app->_fxtechniqueVTXC = app->_material->technique("ui_vtxcolor");
app->_fxparameterMVP = app->_material->param("mvp");
app->_fxparameterMODC = app->_material->param("modcolor");
app->_timer.Start();
memset(app->_inpbuf, 0, SingularityBenchMarkApp::KNUMFRAMES * 2 * sizeof(float));
app->_cur_time = app->_timer.SecsSinceStart();
app->_prev_time = app->_cur_time;
app->_time_histogram.resize(histosize);
app->_font = lev2::FontMan::GetFont("i14");
app->_charw = app->_font->GetFontDesc().miAdvanceWidth;
app->_charh = app->_font->GetFontDesc().miAdvanceHeight;
});
//////////////////////////////////////////////////////////////////////////////
app->onUpdate([=](ui::updatedata_ptr_t updata) {
const auto& obuf = the_synth->_obuf;
/////////////////////////////////////////
double upd_time = 0.0;
bool done = false;
while (done == false) {
int numcurvoices = the_synth->_numactivevoices.load();
if (numcurvoices < int(app->_maxvoices)) {
int irand = rand() & 0xffff;
if (irand < 32768)
enqueue_audio_event(program, 0.0f, 2.5, 48);
}
the_synth->compute(SingularityBenchMarkApp::KNUMFRAMES, app->_inpbuf);
app->_cur_time = app->_timer.SecsSinceStart();
double iter_time = app->_cur_time - app->_prev_time;
upd_time += iter_time;
///////////////////////////////////////////
// histogram for looking for timing spikes
///////////////////////////////////////////
size_t index = size_t(double(histosize) * iter_time / 0.02);
index = std::clamp(index, size_t(0), histosize - 1);
app->_time_histogram[index]++;
///////////////////////////////////////////
app->_prev_time = app->_cur_time;
app->_numiters++;
app->_accumnumvoices += app->_maxvoices;
done = upd_time > 1.0 / 60.0;
}
});
//////////////////////////////////////////////////////////////////////////////
app->onDraw([=](ui::drawevent_constptr_t drwev) { //
////////////////////////////////////////////////
auto context = drwev->GetTarget();
auto fbi = context->FBI(); // FrameBufferInterface
auto fxi = context->FXI(); // FX Interface
auto mtxi = context->MTXI(); // FX Interface
fbi->SetClearColor(fvec4(0.1, 0.1, 0.1, 1));
////////////////////////////////////////////////////
// draw the synth HUD
////////////////////////////////////////////////////
RenderContextFrameData RCFD(context); // renderer per/frame data
context->beginFrame();
auto tgtrect = context->mainSurfaceRectAtOrigin();
auto uimtx = mtxi->uiMatrix(tgtrect._w, tgtrect._h);
app->_material->begin(app->_fxtechniqueMODC, RCFD);
app->_material->bindParamMatrix(app->_fxparameterMVP, uimtx);
{
//////////////////////////////////////////////
// draw background
//////////////////////////////////////////////
auto& primi = lev2::GfxPrimitives::GetRef();
app->_material->bindParamVec4(app->_fxparameterMODC, fvec4(0, 0, 0, 1));
primi.RenderEMLQuadAtZV16T16C16(
context,
8, // x0
tgtrect._w - 8, // x1
8, // y0
tgtrect._h - 8, // y1
0.0f, // z
0.0f, // u0
1.0f, // u1
0.0f, // v0
1.0f // v1
);
}
app->_material->end(RCFD);
//////////////////////////////////////////////
app->_material->begin(app->_fxtechniqueVTXC, RCFD);
{
app->_material->bindParamMatrix(app->_fxparameterMVP, uimtx);
//////////////////////////////////////////////
double desired_blockperiod = 1000.0 / (48000.0 / double(SingularityBenchMarkApp::KNUMFRAMES));
//////////////////////////////////////////////
// compute histogram vertical extents
//////////////////////////////////////////////
int maxval = 0;
int minbin = 0;
int maxbin = 0;
double avgbin = 0.0;
double avgdiv = 0.0;
int numunderruns = 0;
for (size_t i = 0; i < histosize; i++) {
int item = app->_time_histogram[i];
if (item > maxval) {
maxval = item;
}
if (minbin == 0 and item != 0) {
minbin = i;
}
if (item != 0) {
maxbin = i;
}
avgbin += double(i) * double(item);
avgdiv += double(item);
double bin_time = 1000.0 * 0.02 * double(i) / double(histosize);
if (bin_time > desired_blockperiod) {
numunderruns += item;
}
}
avgbin /= avgdiv;
if (numunderruns <= app->_numunderruns) {
app->_maxvoices += 0.1;
} else {
app->_maxvoices -= 2.5;
}
app->_numunderruns = numunderruns;
//////////////////////////////////////////////
// draw histogram
//////////////////////////////////////////////
app->_material->bindParamVec4(app->_fxparameterMODC, fvec4(0, 1, 0, 1));
size_t numlines = histosize;
lev2::DynamicVertexBuffer<vtx_t>& VB = lev2::GfxEnv::GetSharedDynamicV16T16C16();
lev2::VtxWriter<vtx_t> vw;
vw.Lock(context, &VB, numlines * 2);
for (size_t index_r = 1; index_r < histosize; index_r++) {
size_t index_l = index_r - 1;
int item_l = app->_time_histogram[index_l];
int item_r = app->_time_histogram[index_r];
double time_l = 20.0 * double(index_l) / double(histosize);
double xl = 8.0 + double(tgtrect._w - 16.0) * double(index_l) / double(histosize);
double xr = 8.0 + double(tgtrect._w - 16.0) * double(index_r) / double(histosize);
double yl = 8.0 + double(tgtrect._h - 16.0) * double(item_l) / double(maxval);
double yr = 8.0 + double(tgtrect._h - 16.0) * double(item_r) / double(maxval);
fvec4 color = time_l < desired_blockperiod //
? fvec4(0, 1, 0, 1)
: fvec4(1, 0, 0, 1);
vw.AddVertex(vtx_t(fvec4(xl, tgtrect._h - yl, 0.0), fvec4(), color));
vw.AddVertex(vtx_t(fvec4(xr, tgtrect._h - yr, 0.0), fvec4(), color));
}
vw.UnLock(context);
context->GBI()->DrawPrimitiveEML(vw, PrimitiveType::LINES);
//////////////////////////////////////////////
// bin_time = 20 * i / histosize
// bin_time/i = 20/histosize
// i/bin_time = histosize/20
// i=histosize/(20*bin_time)
double desi = desired_blockperiod / 20.0;
double desx = 8.0 + double(tgtrect._w - 16.0) * desi;
lev2::VtxWriter<vtx_t> vw2;
vw2.Lock(context, &VB, 2);
vw2.AddVertex(vtx_t(fvec4(desx, 0, 0.0), fvec4(), fvec4(1, 1, 0, 0)));
vw2.AddVertex(vtx_t(fvec4(desx, tgtrect._h, 0.0), fvec4(), fvec4(1, 1, 0, 0)));
vw2.UnLock(context);
context->GBI()->DrawPrimitiveEML(vw2, PrimitiveType::LINES);
//////////////////////////////////////////////
// draw text
//////////////////////////////////////////////
{
context->MTXI()->PushUIMatrix(tgtrect._w, tgtrect._h);
lev2::FontMan::PushFont(app->_font);
{ //
int y = 0;
std::string str[8];
double avgnumvoices = app->_accumnumvoices / double(app->_numiters);
context->PushModColor(fcolor4::White());
lev2::FontMan::beginTextBlock(context);
str[0] = " Synth Compute Timing Histogram";
str[1] = FormatString("Program<%s>", program->_name.c_str());
str[2] = FormatString("NumIters<%d>", app->_numiters);
str[3] = FormatString("NumActiveVoices<%d>", the_synth->_numactivevoices.load());
str[4] = FormatString("AvgActiveVoices<%d>", int(avgnumvoices));
lev2::FontMan::DrawText(context, 32, y += 32, str[0].c_str());
lev2::FontMan::DrawText(context, 32, y += 32, str[1].c_str());
lev2::FontMan::DrawText(context, 32, y += 16, str[2].c_str());
lev2::FontMan::DrawText(context, 32, y += 16, str[3].c_str());
lev2::FontMan::DrawText(context, 32, y += 16, str[4].c_str());
lev2::FontMan::endTextBlock(context);
context->PopModColor();
double minbin_time = 0.02 * double(minbin) / double(histosize);
double maxbin_time = 0.02 * double(maxbin) / double(histosize);
double avgbin_time = 0.02 * avgbin / double(histosize);
str[0] = FormatString("Min IterTime <%g msec>", minbin_time * 1000.0);
str[1] = FormatString("Max IterTime <%g msec>", maxbin_time * 1000.0);
str[2] = FormatString("Avg IterTime <%g msec>", avgbin_time * 1000.0);
context->PushModColor(fcolor4::Green());
lev2::FontMan::beginTextBlock(context);
lev2::FontMan::DrawText(context, 32, y += 16, str[0].c_str());
lev2::FontMan::DrawText(context, 32, y += 16, str[1].c_str());
lev2::FontMan::DrawText(context, 32, y += 16, str[2].c_str());
lev2::FontMan::endTextBlock(context);
context->PopModColor();
context->PushModColor(fcolor4::Yellow());
lev2::FontMan::beginTextBlock(context);
str[0] = FormatString("Desired Blockperiod @ 48KhZ <%g msec>", desired_blockperiod);
lev2::FontMan::DrawText(context, 32, y += 16, str[0].c_str());
lev2::FontMan::endTextBlock(context);
context->PopModColor();
context->PushModColor(fcolor4::Red());
lev2::FontMan::beginTextBlock(context);
str[0] = FormatString("Number of Underruns <%d>", numunderruns);
lev2::FontMan::DrawText(context, 32, y += 16, str[0].c_str());
lev2::FontMan::endTextBlock(context);
context->PopModColor();
}
lev2::FontMan::PopFont();
context->MTXI()->PopUIMatrix();
}
}
app->_material->end(RCFD);
context->endFrame();
});
/////////////////////////////////////////
app->setRefreshPolicy({EREFRESH_FIXEDFPS, 60});
return app;
}
prgdata_constptr_t testpattern(
syndata_ptr_t syndat, //
int argc,
char** argv) {
auto midictx = MidiContext::instance();
if (midiportname == "list") {
for (auto portitem : midictx->_portmap) {
printf("midiport<%d:%s>\n", portitem.second, portitem.first.c_str());
}
exit(0);
}
auto program = syndat->getProgramByName(testprogramname);
int count = 0;
if (testpatternname == "list") {
for (auto item : syndat->_bankdata->_programs) {
int id = item.first;
auto prog = item.second;
printf("program<%d:%s>\n", id, prog->_name.c_str());
}
return nullptr;
} else if (testpatternname == "none") {
the_synth->_globalprog = program;
return program;
} else if (testpatternname == "midi") {
midictx->startMidiInputByName(midiportname);
the_synth->_globalprog = program;
return program;
} else if (testpatternname == "sq1") {
seq1(120.0f, 0, program);
seq1(120.0f, 4, program);
seq1(120.0f, 8, program);
seq1(120.0f, 12, program);
} else if (testpatternname == "slow") {
for (int i = 0; i < 12; i++) { // note length
for (int n = 0; n <= 64; n += 12) { // note
enqueue_audio_event(program, count * 3.0, 2.0, 36 + n, 128);
count++;
}
}
} else if (testpatternname == "vo") {
for (int i = 0; i < 12; i++) { // note length
for (int velocity = 0; velocity <= 128; velocity += 8) { // velocity
for (int n = 0; n <= 64; n += 12) { // note
// printf("getProgramByName<%s>\n", program->_name.c_str());
enqueue_audio_event(program, count * 0.15, (i + 1) * 0.05, 36 + n, velocity);
count++;
}
}
}
} else if (testpatternname == "vo2") {
for (int i = 0; i < 12; i++) { // note length
for (int n = 0; n <= 64; n += 12) { // note
for (int velocity = 0; velocity <= 128; velocity += 8) { // velocity
// printf("getProgramByName<%s>\n", program->_name.c_str());
enqueue_audio_event(program, count * 0.15, (i + 1) * 0.05, 36 + n, velocity);
count++;
}
}
}
} else if (testpatternname == "vo3") {
for (int i = 0; i < 12; i++) { // note length
for (int n = 0; n <= 64; n += 12) { // note
for (int velocity = 0; velocity <= 128; velocity += 8) { // velocity
// printf("getProgramByName<%s>\n", program->_name.c_str());
enqueue_audio_event(program, count * 0.15, (velocity / 128.0f) * 0.33, 36 + n, velocity);
count++;
}
}
}
} else if (testpatternname == "nvo") {
for (int i = 0; i < 12; i++) { // 2 32 patch banks
for (int velocity = 0; velocity <= 128; velocity += 8) {
for (int n = 0; n <= 64; n += 12) {
// printf("getProgramByName<%s>\n", program->_name.c_str());
enqueue_audio_event(program, count * 0.20, (i + 1) * 0.05, 48 + n + i, velocity);
count++;
}
}
}
} else {
for (int rep = 0; rep <= 16; rep++) {
for (int velocity = 0; velocity <= 128; velocity += 8) {
enqueue_audio_event(program, count * 0.25, 0.1, 48, velocity);
count++;
}
}
}
return program;
}
| 42.68705 | 106 | 0.504761 | [
"solid"
] |
4ce7373f68654f52c097d9e035eead9e7b33e004 | 6,147 | cpp | C++ | WiFiWeatherAndClockAuto/src/WiFiWeatherAndClockAuto.cpp | Carlo47/WiFiWeatherAndClockAuto | 484503e83fb80feeb899433cdb645d604352bc3d | [
"Unlicense"
] | null | null | null | WiFiWeatherAndClockAuto/src/WiFiWeatherAndClockAuto.cpp | Carlo47/WiFiWeatherAndClockAuto | 484503e83fb80feeb899433cdb645d604352bc3d | [
"Unlicense"
] | null | null | null | WiFiWeatherAndClockAuto/src/WiFiWeatherAndClockAuto.cpp | Carlo47/WiFiWeatherAndClockAuto | 484503e83fb80feeb899433cdb645d604352bc3d | [
"Unlicense"
] | null | null | null | /**
* Sketch WiFiWeatherAndClockAuto.cpp
* Author 2019-02-15 Ch. Geiser
* Purpose Connects via WLAN to openWeatherMap.org and fetches the weather data
* in JSON format, parses the strings with the JSON parser and displays
* the data on the integrated OLED display of the ESP32 module.
* Date and Time are also retrieved from a time server.
* Board ESP32-Shield_WiFi / Bluetooth / OLED / 18650 Li-Ion
* Reference https://www.youtube.com/watch?v=zYfWcEgPi2g
* https://techtutorialsx.com/2018/03/17/esp32-arduino-getting-weather-data-from-api/
* https://www.hackster.io/hieromon-ikasamo/esp8266-esp32-connect-wifi-made-easy-d75f45
* https://openweathermap.org/guide
* Remarks To be able to access the owm-Api, you have to register and get a key.
*/
#include <Arduino.h>
#include "WiFiWeatherAndClockAuto.h"
const String owmKey = "2359ecb608ce6cf3b72a0d1b2bc3930a"; // Get your own key
const String cityCodeBaden = "2661646";
const String cityCodeBrugg = "2661374";
const String cityCodeZuoz = "2657898";
// Initialize the OLED display using Wire library
#define I2C_ADDR 0x3c
#define PIN_SDA 5
#define PIN_SCL 4
struct tm rtcTime;
bool setupOK;
OwmData owmData;
WebServer Server;
AutoConnect Portal(Server);
AutoConnectConfig Config;
NtpClock myNtpClock(NTP_SERVER_POOL, TZ_INFO, rtcTime);
Owm myOwm(owmKey, cityCodeBaden, owmData);
SSD1306Wire display(I2C_ADDR, PIN_SDA, PIN_SCL);
/**
* Displays the weather data on the oled
*/
void displayOwmData(OwmData &owmdata)
{
char buf[64];
display.clear();
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.setFont(ArialMT_Plain_10);
display.drawString(0, 0, owmdata.city.c_str());
display.drawString(46, 0, owmdata.description.c_str());
strftime(buf, 64, "Rise %H:%M", &owmdata.struct_sunrise);
display.drawString(0, 12, buf);
strftime(buf, 64, "Set %H:%M", &owmdata.struct_sunset);
display.drawString(64, 12, buf);
sprintf(buf, "%4.1f C %2.0f %% %4.0f hPa", owmdata.actTempC, owmdata.relHum, owmdata.preshPa);
display.drawString(0, 24, buf);
sprintf(buf, "Wind %3.0f m/s %3d Grad", owmdata.windSpeed, owmdata.windDirection);
display.drawString(0, 36, buf);
getLocalTime(&rtcTime);
strftime(buf, 64, "%F %H:%M", &rtcTime);
display.drawString(0, 48, buf);
display.display();
}
/**
* Displays connection details of the WiFi connection
* SSID, IP, MAC, RSSI
*/
void displayConnectionDetails()
{
char buf[32];
display.clear();
display.setFont(ArialMT_Plain_16);
display.setTextAlignment(TEXT_ALIGN_CENTER);
sprintf(buf, "%s", WiFi.SSID().c_str());
display.drawString(64,0, buf);
sprintf(buf, "%s", WiFi.localIP().toString().c_str());
display.setFont(ArialMT_Plain_10);
display.drawString(64,18, buf);
display.setFont(ArialMT_Plain_10);
sprintf(buf, "%s", WiFi.macAddress().c_str());
display.drawString(64,34, buf);
sprintf(buf, "RSSI %d", WiFi.RSSI());
display.drawString(64,50, buf);
display.display();
}
/**
* Gets time and date every everySecs seconds from the RTC
* and displays the values on the oled
*/
void displayTime(struct tm &rtctime, unsigned long everySecs)
{
char buf[40];
static unsigned long msPrevious = millis();
if (millis() > msPrevious + everySecs * 1000)
{
getLocalTime(&rtctime);
display.clear();
display.setFont(ArialMT_Plain_16);
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(64, 0, "NTP-Clock");
strftime(buf, 40, "%T", &rtctime); // Zeit als hh:mm:ss
display.drawString(64, 18, buf);
strftime(buf, 40, "%F", &rtctime); // Datum als yyyy-mo-dd
display.drawString(64, 36, buf);
display.display();
}
}
/**
* Cyclically generates a task number from 0 to nbrOfTasks-1
* and returns the next one everySecs seconds. Is used to
* cyclically display either connection date, date and time or
* the weather data.
*/
int selectTask(int nbrOfTasks, int everySecs)
{
static int taskNbr = 0;
static unsigned long msPrevious = millis();
if (millis() > (msPrevious + everySecs * 1000))
{
msPrevious = millis();
taskNbr = ((taskNbr + 1) % nbrOfTasks);
}
return taskNbr;
}
void setup()
{
Serial.begin(COMPORT_SPEED);
display.init();
Config.autoReconnect = true;
Portal.config(Config);
if (Portal.begin())
{
Serial.println("WiFi connected: " + WiFi.localIP().toString());
myNtpClock.setVerbose(false);
myNtpClock.setResyncInterval(6*60*60); // Resync every 6 hours
myNtpClock.setup();
myOwm.setup();
setupOK = true;
}
else
setupOK = false;
}
void loop()
{
if (! setupOK)
{
display.clear();
display.drawString(64, 0, "Restart");
delay(5000);
ESP.restart();
}
else
{
myNtpClock.loop(); // Look whether RTC must be synchronized with NTP
myOwm.loop(); // Get weather data
switch (selectTask(3, 10)) // Switch every 10 sec to display connectionDetails,
{ // date / time and weather data
case 0:
displayConnectionDetails();
break;
case 1:
displayTime(rtcTime, 1); // Display time every second
break;
case 2:
displayOwmData(owmData);
break;
}
}
delay(200); // Pass some time away
}
/*
owmPayload to be parsed:
{
"coord":{"lon":8.31,"lat":47.47},
"weather":[{"id":800,"main":"Clear","description":"Klarer Himmel","icon":"01n"}],
"base":"stations",
"main":{"temp":1.99,"pressure":1035,"humidity":76,"temp_min":1,"temp_max":3},
"visibility":10000,
"wind":{"speed":0.5},
"clouds":{"all":0},
"dt":1550173800,
"sys":{"type":1,"id":6941,"message":0.0038,"country":"CH","sunrise":1550125987,"sunset":1550162962},
"id":2661646,
"name":"Baden",
"cod":200
}
*/
| 31.362245 | 101 | 0.63104 | [
"3d"
] |
4ce968f4807fa14e05d1d7b848a9681250ae72ab | 9,350 | cpp | C++ | src/seed.cpp | soybin/idyll | c05f0c79f97c6e701ccf8cc2d5c2e68bc271ddfc | [
"MIT"
] | 13 | 2020-05-31T13:07:19.000Z | 2021-08-21T14:55:50.000Z | src/seed.cpp | soybin/idyll | c05f0c79f97c6e701ccf8cc2d5c2e68bc271ddfc | [
"MIT"
] | 1 | 2021-08-21T15:06:44.000Z | 2021-08-21T15:06:44.000Z | src/seed.cpp | soybin/idyll | c05f0c79f97c6e701ccf8cc2d5c2e68bc271ddfc | [
"MIT"
] | null | null | null | /*
* MIT License
* Copyright (c) 2020 Pablo Peñarroja
*/
#include "seed.h"
#include <algorithm>
// mersennes' twister prng algo initialized with random device
// seed
seed::seed() : rng(dev()) {
// //
//======== r e n d e r e r c o n s t a n t s ========//
// //
// chance for a ray to be reflected with a cone distribution
values["GLOSSINESS_CHANCE"] = d(0.0, 0.4);
// how glossy should the reflection be
values["GLOSSINESS_AMOUNT"] = d(0.0, 1.0);
// direction in which a ray should be marched until getting
// out of the fractal distance estimator
math::vec3 cameraDirection = math::normalize(vec3(-1.0, 1.0));
values["xcameraDirection"] = cameraDirection.x;
values["ycameraDirection"] = cameraDirection.y;
values["zcameraDirection"] = cameraDirection.z;
// how far away should the camera be from the surface of the
// distance estimator
values["cameraDistance"] = i(2, 4);
// directional light direction
math::vec3 lightDirection = math::normalize(cameraDirection + vec3(-1.0, 1.0));
values["xlightDirection"] = lightDirection.x;
values["ylightDirection"] = lightDirection.y;
values["zlightDirection"] = lightDirection.z;
// directional light color
math::vec3 lightColor;
lightColor.x = d(0.9, 1.1);
lightColor.y = d(lightColor.x - 0.1, lightColor.x + 0.1);
lightColor.z = d(lightColor.x - 0.1, lightColor.x + 0.1);
lightColor = math::normalize(lightColor);
values["xlightColor"] = lightColor.x;
values["ylightColor"] = lightColor.y;
values["zlightColor"] = lightColor.z;
// sky color
math::vec3 skyColor;
skyColor.x = d(0.9, 1.1);
skyColor.y = d(skyColor.x - 0.1, skyColor.x + 0.1);
skyColor.z = d(skyColor.x - 0.1, skyColor.x + 0.1);
skyColor = math::normalize(skyColor);
values["xskyColor"] = skyColor.x;
values["yskyColor"] = skyColor.y;
values["zskyColor"] = skyColor.z;
// //
//======== f r a c t a l c o n s t a n t s ========//
// //
// number of iterations
values["iterations"] = i(16, 18);
// shadow softess
values["shadowSoftness"] = d(0.5, 1.0);
// fractal base color
math::vec3 color;
color.x = 1.0;
color.y = 0.25;
color.z = 0.125;
color = math::normalize(color);
for (int ii = i(0, 6); ii > 0; --ii) {
int jj = i(0, 2);
if (jj == 0) {
double temp = color.x;
color.x = color.y;
color.y = temp;
} else if (jj == 1) {
double temp = color.y;
color.y = color.z;
color.z = temp;
} else {
double temp = color.z;
color.z = color.x;
color.x = temp;
}
}
values["xcolor"] = color.x;
values["ycolor"] = color.y;
values["zcolor"] = color.z;
// top sky gradient color
math::vec3 normalizedGradientTop = math::normalize(vec3(0, 255));
values["xgradientTop"] = normalizedGradientTop.x;
values["ygradientTop"] = normalizedGradientTop.y;
values["zgradientTop"] = normalizedGradientTop.z;
// bottom sky gradient color
math::vec3 normalizedGradientBottom = math::normalize(vec3(0, 255));
values["xgradientBottom"] = normalizedGradientBottom.x;
values["ygradientBottom"] = normalizedGradientBottom.y;
values["zgradientBottom"] = normalizedGradientBottom.z;
// fractal point space shift per iteration
values["xshift"] = d(-0.4, -0.1);
values["zshift"] = d(-0.4, -0.1);
// fractal point space rotation per iteration
values["xrotation"] = d(-0.2, -0.1);
values["zrotation"] = d(-0.2, -0.1);
// point iteration polymorphic function
values["pointIterator"] = i(0, 2);
}
seed::seed(std::string s) {
seedParsingSuccessful = false;
std::vector<char> startOps = { '{', '(', '<', '[' };
std::vector<char> endOps = { '}', ')', '>', ']' };
std::vector<char> separationOps = { '!', '@', '#', '$', '%', '^', '&', '*' };
int n = s.size();
std::string str = "";
int arg = 0;
for (int i = 0; i < n; ++i) {
char c = s[i];
bool end = false;
for (int j = 0; j < 4; ++j) {
if (c == endOps[j]) {
end = true;
break;
}
}
if ((c == '.' || c == '-' || (c >= '0' && c <= '9')) && !end) {
str += c;
} else if (str.size() || end) {
//str += c;
double value;
try {
value = std::stod(str);
} catch (...) {
seedParsingSuccessful = false;
return;
}
switch (arg) {
case 0:
values["GLOSSINESS_CHANCE"] = value;
break;
case 1:
values["GLOSSINESS_AMOUNT"] = value;
break;
case 2:
values["xcameraDirection"] = value;
break;
case 3:
values["ycameraDirection"] = value;
break;
case 4:
values["zcameraDirection"] = value;
break;
case 5:
values["cameraDistance"] = value;
break;
case 6:
values["xlightDirection"] = value;
break;
case 7:
values["ylightDirection"] = value;
break;
case 8:
values["zlightDirection"] = value;
break;
case 9:
values["xlightColor"] = value;
break;
case 10:
values["ylightColor"] = value;
break;
case 11:
values["zlightColor"] = value;
break;
case 12:
values["xskyColor"] = value;
break;
case 13:
values["yskyColor"] = value;
break;
case 14:
values["zskyColor"] = value;
break;
case 15:
values["iterations"] = value;
break;
case 16:
values["shadowSoftness"] = value;
break;
case 17:
values["xcolor"] = value;
break;
case 18:
values["ycolor"] = value;
break;
case 19:
values["zcolor"] = value;
break;
case 20:
values["xgradientTop"] = value;
break;
case 21:
values["ygradientTop"] = value;
break;
case 22:
values["zgradientTop"] = value;
break;
case 23:
values["xgradientBottom"] = value;
break;
case 24:
values["ygradientBottom"] = value;
break;
case 25:
values["zgradientBottom"] = value;
break;
case 26:
values["xshift"] = value;
break;
case 27:
values["zshift"] = value;
break;
case 28:
values["xrotation"] = value;
break;
case 29:
values["zrotation"] = value;
break;
case 30:
values["pointIterator"] = value;
break;
}
++arg;
str = "";
}
}
seedParsingSuccessful = arg == 31;
}
seed::~seed() {
}
std::string seed::buildSeed() {
std::vector<char> startOps = { '{', '(', '<', '[' };
std::vector<char> endOps = { '}', ')', '>', ']' };
std::vector<char> separationOps = { '!', '@', '#', '$', '%', '^', '&', '*' };
int n = startOps.size() - 1, m = separationOps.size() - 1;
std::string s = "";
s += startOps[i(0, n)];
s += std::to_string(values["GLOSSINESS_CHANCE"]);
s += separationOps[i(0, m)];
s += std::to_string(values["GLOSSINESS_AMOUNT"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xcameraDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ycameraDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zcameraDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["cameraDistance"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xlightDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ylightDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zlightDirection"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xlightColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ylightColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zlightColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xskyColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["yskyColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zskyColor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["iterations"]);
s += separationOps[i(0, m)];
s += std::to_string(values["shadowSoftness"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xcolor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ycolor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zcolor"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xgradientTop"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ygradientTop"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zgradientTop"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xgradientBottom"]);
s += separationOps[i(0, m)];
s += std::to_string(values["ygradientBottom"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zgradientBottom"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xshift"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zshift"]);
s += separationOps[i(0, m)];
s += std::to_string(values["xrotation"]);
s += separationOps[i(0, m)];
s += std::to_string(values["zrotation"]);
s += separationOps[i(0, m)];
s += std::to_string(values["pointIterator"]);
s += endOps[i(0, n)];
return s;
}
int seed::i(int min, int max) {
std::uniform_int_distribution<int> dice(min, max);
return dice(rng);
}
double seed::d(double min, double max) {
std::uniform_real_distribution<double> dice(min, max);
return dice(rng);
}
math::vec3 seed::vec3(double min, double max) {
return math::vec3(d(min, max), d(min, max), d(min, max));
}
| 28.593272 | 80 | 0.586203 | [
"vector"
] |
4cf0a69dcf1881b4e6a25cd86d11b8a7e2e25af0 | 5,728 | cpp | C++ | text_billboard/main.cpp | if1live/libsora.so-src | a5fa7bd9bd313422a5e174db270a9784262a5f9e | [
"MIT"
] | 1 | 2016-10-10T06:40:16.000Z | 2016-10-10T06:40:16.000Z | text_billboard/main.cpp | if1live/libsora.so-src | a5fa7bd9bd313422a5e174db270a9784262a5f9e | [
"MIT"
] | null | null | null | text_billboard/main.cpp | if1live/libsora.so-src | a5fa7bd9bd313422a5e174db270a9784262a5f9e | [
"MIT"
] | 3 | 2019-06-06T08:39:39.000Z | 2021-10-05T09:23:18.000Z | // Ŭnicode please
#include <cstdlib>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "sys_font.h"
#include "primitive_mesh.h"
const int kWidth = 300;
const int kHeight = 300;
using namespace glm;
using namespace haruna;
using namespace haruna::gl;
glm::mat4 g_proj_mat;
glm::mat4 g_view_mat;
glm::mat4 g_model_mat;
GLenum DrawModeToGLMode(haruna::DrawType draw_mode)
{
switch(draw_mode) {
case kDrawPoints:
return GL_POINTS;
case kDrawLines:
return GL_LINES;
case kDrawLineStrip:
return GL_LINE_STRIP;
case kDrawLineLoop:
return GL_LINE_LOOP;
case kDrawTriangles:
return GL_TRIANGLES;
case kDrawTriangleStrip:
return GL_TRIANGLE_STRIP;
case kDrawTriangleFan:
return GL_TRIANGLE_FAN;
default:
assert(!"do not reach");
return GL_TRIANGLES;
}
}
void RenderMesh(const std::vector<DrawCmdData<Vertex_1P1N1UV>> &draw_cmd_list)
{
auto it = draw_cmd_list.begin();
auto endit = draw_cmd_list.end();
for( ; it != endit ; ++it) {
const DrawCmdData<Vertex_1P1N1UV> &draw_cmd = *it;
GLenum mode = DrawModeToGLMode(draw_cmd.draw_mode);
int stride = sizeof(Vertex_1P1N1UV);
glVertexPointer(3, GL_FLOAT, stride, &draw_cmd.vertex_list[0].p);
glTexCoordPointer(2, GL_FLOAT, stride, &draw_cmd.vertex_list[0].uv);
glNormalPointer(GL_FLOAT, stride, &draw_cmd.vertex_list[0].n);
glDrawElements(mode, draw_cmd.index_list.size(), GL_UNSIGNED_SHORT, &draw_cmd.index_list[0]);
}
}
void RenderBillboardLabel(const haruna::gl::Label &label, float x, float y, float z)
{
mat4 mvp = g_proj_mat * g_view_mat * g_model_mat;
//billboard 같은 느낌으로 글자 쓰기
//기울어지는거 없이 항상 글자가 뜨도록 적절히 만들기
vec4 cliping_pos = mvp * vec4(x, y, z, 1); // -1~1에 적절히 위치한 좌표
cliping_pos /= cliping_pos.w;
cliping_pos.z = -cliping_pos.z; //보정된 좌표계는 z방향 다르다
// -1~+1로 보정된 좌표를 윈도우좌표로 변환
vec3 win_coord(
(cliping_pos.x+1) * kWidth/2.0f,
(cliping_pos.y+1) * kHeight/2.0f,
cliping_pos.z
);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, kWidth, 0, kHeight, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(win_coord.x, win_coord.y, win_coord.z);
glVertexPointer(2, GL_FLOAT, sizeof(FontVertex), &label.vertex_list()[0].p);
glTexCoordPointer(2, GL_FLOAT, sizeof(FontVertex), &label.vertex_list()[0].uv);
glDrawElements(GL_TRIANGLES, label.index_count(), GL_UNSIGNED_SHORT, label.index_data());
{
// restore 3d matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(glm::value_ptr(g_proj_mat));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glm::mat4 modelview = g_view_mat * g_model_mat;
glLoadMatrixf(glm::value_ptr(modelview));
}
}
int main()
{
GLFWwindow *window = nullptr;
if(!glfwInit()) {
exit(EXIT_FAILURE);
}
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(kWidth, kHeight, "Hello World", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
//initialize
haruna::gl::SysFont_Init();
//set default gl env
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
//create cube
SolidCubeFactory factory(2, 2, 2);
auto solid_cube_mesh = factory.CreateNormalMesh();
float rot = 0;
int running = GL_TRUE;
while (!glfwWindowShouldClose(window) && running) {
glViewport(0, 0, kWidth, kHeight);
// OpenGL rendering goes here...
glClearColor(0, 0, 0, 0);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
//render 3d
{
g_proj_mat = glm::perspective(glm::radians(60.0f), (float)(kWidth / kHeight), 0.1f, 100.0f);
g_view_mat = glm::lookAt(glm::vec3(0, 2, 5), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(glm::value_ptr(g_proj_mat));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixf(glm::value_ptr(g_view_mat));
g_model_mat = glm::rotate(glm::mat4(), rot, glm::vec3(0, 1, 0));
glMultMatrixf(glm::value_ptr(g_model_mat));
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, light_ambient);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
RenderMesh(solid_cube_mesh);
}
//render 2d
{
glDisable(GL_LIGHTING);
//bind font texture + set env
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, g_sysFont->tex_id());
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderBillboardLabel(Label(g_sysFont.get(), "1/1/1"), 1, 1, 1);
RenderBillboardLabel(Label(g_sysFont.get(), "1/1/-1"), 1, 1, -1);
RenderBillboardLabel(Label(g_sysFont.get(), "1/-1/1"), 1, -1, 1);
RenderBillboardLabel(Label(g_sysFont.get(), "1/-1/-1"), 1, -1, -1);
RenderBillboardLabel(Label(g_sysFont.get(), "-1/1/1"), -1, 1, 1);
RenderBillboardLabel(Label(g_sysFont.get(), "-1/1/-1"), -1, 1, -1);
RenderBillboardLabel(Label(g_sysFont.get(), "-1/-1/1"), -1, -1, 1);
RenderBillboardLabel(Label(g_sysFont.get(), "-1/-1/-1"), -1, -1, -1);
RenderBillboardLabel(Label(g_sysFont.get(), "--------- 0/0/0"), 0, 0, 0);
}
assert(glGetError() == GL_NO_ERROR);
// Swap front and back rendering buffers
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
// Check if ESC key was pressed or window was closed
running = !glfwGetKey(window, GLFW_KEY_ESCAPE);
rot += glm::radians(0.03f);
}
//cleanup
haruna::gl::SysFont_Deinit();
glfwTerminate();
return 0;
}
| 27.27619 | 101 | 0.696753 | [
"render",
"vector",
"3d"
] |
e07a82d7d7637509a813bc8ae3f943afc87ceb2e | 137,026 | cpp | C++ | CWE-399/source_files/CVE-2013-0781/firefox_18.0_CVE_2013_0781_layout_printing_nsPrintEngine.cpp | CGCL-codes/VulDeePecker | 98610f3e116df97a1e819ffc81fbc7f6f138a8f2 | [
"Apache-2.0"
] | 185 | 2017-12-14T08:18:15.000Z | 2022-03-30T02:58:36.000Z | B2G/gecko/layout/printing/nsPrintEngine.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 11 | 2018-01-30T23:31:20.000Z | 2022-01-17T05:03:56.000Z | CWE-399/source_files/CVE-2013-0781/firefox_18.0_CVE_2013_0781_layout_printing_nsPrintEngine.cpp | CGCL-codes/VulDeePecker | 98610f3e116df97a1e819ffc81fbc7f6f138a8f2 | [
"Apache-2.0"
] | 87 | 2018-01-10T08:12:32.000Z | 2022-02-19T10:29:31.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsPrintEngine.h"
#include "nsIStringBundle.h"
#include "nsReadableUtils.h"
#include "nsCRT.h"
#include "nsISelection.h"
#include "nsIScriptGlobalObject.h"
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIFrame.h"
#include "nsIURI.h"
#include "nsITextToSubURI.h"
#include "nsError.h"
#include "nsView.h"
#include "nsAsyncDOMEvent.h"
// Print Options
#include "nsIPrintSettings.h"
#include "nsIPrintSettingsService.h"
#include "nsIPrintOptions.h"
#include "nsIPrintSession.h"
#include "nsGfxCIID.h"
#include "nsIServiceManager.h"
#include "nsGkAtoms.h"
#include "nsXPCOM.h"
#include "nsISupportsPrimitives.h"
static const char sPrintSettingsServiceContractID[] = "@mozilla.org/gfx/printsettings-service;1";
// Printing Events
#include "nsPrintPreviewListener.h"
#include "nsThreadUtils.h"
// Printing
#include "nsIWebBrowserPrint.h"
#include "nsIDOMHTMLFrameElement.h"
#include "nsIDOMHTMLFrameSetElement.h"
#include "nsIDOMHTMLIFrameElement.h"
#include "nsIDOMHTMLObjectElement.h"
#include "nsIDOMHTMLEmbedElement.h"
// Print Preview
#include "imgIContainer.h" // image animation mode constants
#include "nsIWebBrowserPrint.h" // needed for PrintPreview Navigation constants
// Print Progress
#include "nsIPrintProgress.h"
#include "nsIPrintProgressParams.h"
#include "nsIObserver.h"
// Print error dialog
#include "nsIPrompt.h"
#include "nsIWindowWatcher.h"
// Printing Prompts
#include "nsIPrintingPromptService.h"
static const char kPrintingPromptService[] = "@mozilla.org/embedcomp/printingprompt-service;1";
// Printing Timer
#include "nsPagePrintTimer.h"
// FrameSet
#include "nsIDocument.h"
// Focus
#include "nsIDOMEventTarget.h"
#include "nsISelectionController.h"
// Misc
#include "nsISupportsUtils.h"
#include "nsIScriptContext.h"
#include "nsIDOMDocument.h"
#include "nsISelectionListener.h"
#include "nsISelectionPrivate.h"
#include "nsIDOMRange.h"
#include "nsContentCID.h"
#include "nsLayoutCID.h"
#include "nsContentUtils.h"
#include "nsIPresShell.h"
#include "nsLayoutUtils.h"
#include "mozilla/Preferences.h"
#include "nsViewsCID.h"
#include "nsWidgetsCID.h"
#include "nsIDeviceContextSpec.h"
#include "nsIViewManager.h"
#include "nsIView.h"
#include "nsRenderingContext.h"
#include "nsIPageSequenceFrame.h"
#include "nsIURL.h"
#include "nsIContentViewerEdit.h"
#include "nsIContentViewerFile.h"
#include "nsIMarkupDocumentViewer.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocShellTreeNode.h"
#include "nsIDocShellTreeOwner.h"
#include "nsIWebBrowserChrome.h"
#include "nsIBaseWindow.h"
#include "nsILayoutHistoryState.h"
#include "nsFrameManager.h"
#include "nsGUIEvent.h"
#include "nsHTMLReflowState.h"
#include "nsIDOMHTMLAnchorElement.h"
#include "nsIDOMHTMLAreaElement.h"
#include "nsIDOMHTMLLinkElement.h"
#include "nsIDOMHTMLImageElement.h"
#include "nsIContentViewerContainer.h"
#include "nsIContentViewer.h"
#include "nsIDocumentViewerPrint.h"
#include "nsFocusManager.h"
#include "nsRange.h"
#include "nsCDefaultURIFixup.h"
#include "nsIURIFixup.h"
#include "mozilla/dom/Element.h"
#include "nsContentList.h"
using namespace mozilla;
using namespace mozilla::dom;
//-----------------------------------------------------
// PR LOGGING
#ifdef MOZ_LOGGING
#define FORCE_PR_LOG /* Allow logging in the release build */
#endif
#include "prlog.h"
#ifdef PR_LOGGING
#ifdef DEBUG
// PR_LOGGING is force to always be on (even in release builds)
// but we only want some of it on,
//#define EXTENDED_DEBUG_PRINTING
#endif
#define DUMP_LAYOUT_LEVEL 9 // this turns on the dumping of each doucment's layout info
static PRLogModuleInfo * kPrintingLogMod = PR_NewLogModule("printing");
#define PR_PL(_p1) PR_LOG(kPrintingLogMod, PR_LOG_DEBUG, _p1);
#ifdef EXTENDED_DEBUG_PRINTING
static uint32_t gDumpFileNameCnt = 0;
static uint32_t gDumpLOFileNameCnt = 0;
#endif
#define PRT_YESNO(_p) ((_p)?"YES":"NO")
static const char * gFrameTypesStr[] = {"eDoc", "eFrame", "eIFrame", "eFrameSet"};
static const char * gPrintFrameTypeStr[] = {"kNoFrames", "kFramesAsIs", "kSelectedFrame", "kEachFrameSep"};
static const char * gFrameHowToEnableStr[] = {"kFrameEnableNone", "kFrameEnableAll", "kFrameEnableAsIsAndEach"};
static const char * gPrintRangeStr[] = {"kRangeAllPages", "kRangeSpecifiedPageRange", "kRangeSelection", "kRangeFocusFrame"};
#else
#define PRT_YESNO(_p)
#define PR_PL(_p1)
#endif
#ifdef EXTENDED_DEBUG_PRINTING
// Forward Declarations
static void DumpPrintObjectsListStart(const char * aStr, nsTArray<nsPrintObject*> * aDocList);
static void DumpPrintObjectsTree(nsPrintObject * aPO, int aLevel= 0, FILE* aFD = nullptr);
static void DumpPrintObjectsTreeLayout(nsPrintObject * aPO,nsDeviceContext * aDC, int aLevel= 0, FILE * aFD = nullptr);
#define DUMP_DOC_LIST(_title) DumpPrintObjectsListStart((_title), mPrt->mPrintDocList);
#define DUMP_DOC_TREE DumpPrintObjectsTree(mPrt->mPrintObject);
#define DUMP_DOC_TREELAYOUT DumpPrintObjectsTreeLayout(mPrt->mPrintObject, mPrt->mPrintDC);
#else
#define DUMP_DOC_LIST(_title)
#define DUMP_DOC_TREE
#define DUMP_DOC_TREELAYOUT
#endif
class nsScriptSuppressor
{
public:
nsScriptSuppressor(nsPrintEngine* aPrintEngine)
: mPrintEngine(aPrintEngine), mSuppressed(false) {}
~nsScriptSuppressor() { Unsuppress(); }
void Suppress()
{
if (mPrintEngine) {
mSuppressed = true;
mPrintEngine->TurnScriptingOn(false);
}
}
void Unsuppress()
{
if (mPrintEngine && mSuppressed) {
mPrintEngine->TurnScriptingOn(true);
}
mSuppressed = false;
}
void Disconnect() { mPrintEngine = nullptr; }
protected:
nsRefPtr<nsPrintEngine> mPrintEngine;
bool mSuppressed;
};
// Class IDs
static NS_DEFINE_CID(kViewManagerCID, NS_VIEW_MANAGER_CID);
NS_IMPL_ISUPPORTS3(nsPrintEngine, nsIWebProgressListener,
nsISupportsWeakReference, nsIObserver)
//---------------------------------------------------
//-- nsPrintEngine Class Impl
//---------------------------------------------------
nsPrintEngine::nsPrintEngine() :
mIsCreatingPrintPreview(false),
mIsDoingPrinting(false),
mIsDoingPrintPreview(false),
mProgressDialogIsShown(false),
mScreenDPI(115.0f),
mPrt(nullptr),
mPagePrintTimer(nullptr),
mPageSeqFrame(nullptr),
mPrtPreview(nullptr),
mOldPrtPreview(nullptr),
mDebugFile(nullptr),
mLoadCounter(0),
mDidLoadDataForPrinting(false)
{
}
//-------------------------------------------------------
nsPrintEngine::~nsPrintEngine()
{
Destroy(); // for insurance
}
//-------------------------------------------------------
void nsPrintEngine::Destroy()
{
if (mPrt) {
delete mPrt;
mPrt = nullptr;
}
#ifdef NS_PRINT_PREVIEW
if (mPrtPreview) {
delete mPrtPreview;
mPrtPreview = nullptr;
}
// This is insruance
if (mOldPrtPreview) {
delete mOldPrtPreview;
mOldPrtPreview = nullptr;
}
#endif
mDocViewerPrint = nullptr;
}
//-------------------------------------------------------
void nsPrintEngine::DestroyPrintingData()
{
if (mPrt) {
delete mPrt;
mPrt = nullptr;
}
}
//---------------------------------------------------------------------------------
//-- Section: Methods needed by the DocViewer
//---------------------------------------------------------------------------------
//--------------------------------------------------------
nsresult nsPrintEngine::Initialize(nsIDocumentViewerPrint* aDocViewerPrint,
nsIWeakReference* aContainer,
nsIDocument* aDocument,
float aScreenDPI,
FILE* aDebugFile)
{
NS_ENSURE_ARG_POINTER(aDocViewerPrint);
NS_ENSURE_ARG_POINTER(aContainer);
NS_ENSURE_ARG_POINTER(aDocument);
mDocViewerPrint = aDocViewerPrint;
mContainer = aContainer;
mDocument = aDocument;
mScreenDPI = aScreenDPI;
mDebugFile = aDebugFile; // ok to be NULL
return NS_OK;
}
//-------------------------------------------------------
bool
nsPrintEngine::CheckBeforeDestroy()
{
if (mPrt && mPrt->mPreparingForPrint) {
mPrt->mDocWasToBeDestroyed = true;
return true;
}
return false;
}
//-------------------------------------------------------
nsresult
nsPrintEngine::Cancelled()
{
if (mPrt && mPrt->mPrintSettings) {
return mPrt->mPrintSettings->SetIsCancelled(true);
}
return NS_ERROR_FAILURE;
}
//-------------------------------------------------------
// Install our event listeners on the document to prevent
// some events from being processed while in PrintPreview
//
// No return code - if this fails, there isn't much we can do
void
nsPrintEngine::InstallPrintPreviewListener()
{
if (!mPrt->mPPEventListeners) {
nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(mContainer);
nsCOMPtr<nsPIDOMWindow> win(do_GetInterface(docShell));
if (win) {
nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(win->GetFrameElementInternal()));
mPrt->mPPEventListeners = new nsPrintPreviewListener(target);
mPrt->mPPEventListeners->AddListeners();
}
}
}
//----------------------------------------------------------------------
nsresult
nsPrintEngine::GetSeqFrameAndCountPagesInternal(nsPrintObject* aPO,
nsIFrame*& aSeqFrame,
int32_t& aCount)
{
NS_ENSURE_ARG_POINTER(aPO);
// Finds the SimplePageSequencer frame
nsIPageSequenceFrame* seqFrame = aPO->mPresShell->GetPageSequenceFrame();
if (seqFrame) {
aSeqFrame = do_QueryFrame(seqFrame);
} else {
aSeqFrame = nullptr;
}
if (aSeqFrame == nullptr) return NS_ERROR_FAILURE;
// first count the total number of pages
aCount = 0;
nsIFrame* pageFrame = aSeqFrame->GetFirstPrincipalChild();
while (pageFrame != nullptr) {
aCount++;
pageFrame = pageFrame->GetNextSibling();
}
return NS_OK;
}
//-----------------------------------------------------------------
nsresult nsPrintEngine::GetSeqFrameAndCountPages(nsIFrame*& aSeqFrame, int32_t& aCount)
{
NS_ASSERTION(mPrtPreview, "mPrtPreview can't be null!");
return GetSeqFrameAndCountPagesInternal(mPrtPreview->mPrintObject, aSeqFrame, aCount);
}
//---------------------------------------------------------------------------------
//-- Done: Methods needed by the DocViewer
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//-- Section: nsIWebBrowserPrint
//---------------------------------------------------------------------------------
// Foward decl for Debug Helper Functions
#ifdef EXTENDED_DEBUG_PRINTING
static int RemoveFilesInDir(const char * aDir);
static void GetDocTitleAndURL(nsPrintObject* aPO, char *& aDocStr, char *& aURLStr);
static void DumpPrintObjectsTree(nsPrintObject * aPO, int aLevel, FILE* aFD);
static void DumpPrintObjectsList(nsTArray<nsPrintObject*> * aDocList);
static void RootFrameList(nsPresContext* aPresContext, FILE* out, int32_t aIndent);
static void DumpViews(nsIDocShell* aDocShell, FILE* out);
static void DumpLayoutData(char* aTitleStr, char* aURLStr,
nsPresContext* aPresContext,
nsDeviceContext * aDC, nsIFrame * aRootFrame,
nsIDocShell * aDocShell, FILE* aFD);
#endif
//--------------------------------------------------------------------------------
nsresult
nsPrintEngine::CommonPrint(bool aIsPrintPreview,
nsIPrintSettings* aPrintSettings,
nsIWebProgressListener* aWebProgressListener,
nsIDOMDocument* aDoc) {
nsresult rv = DoCommonPrint(aIsPrintPreview, aPrintSettings,
aWebProgressListener, aDoc);
if (NS_FAILED(rv)) {
if (aIsPrintPreview) {
SetIsCreatingPrintPreview(false);
SetIsPrintPreview(false);
} else {
SetIsPrinting(false);
}
if (mProgressDialogIsShown)
CloseProgressDialog(aWebProgressListener);
if (rv != NS_ERROR_ABORT && rv != NS_ERROR_OUT_OF_MEMORY)
ShowPrintErrorDialog(rv, !aIsPrintPreview);
delete mPrt;
mPrt = nullptr;
}
return rv;
}
nsresult
nsPrintEngine::DoCommonPrint(bool aIsPrintPreview,
nsIPrintSettings* aPrintSettings,
nsIWebProgressListener* aWebProgressListener,
nsIDOMDocument* aDoc)
{
nsresult rv;
if (aIsPrintPreview) {
// The WebProgressListener can be QI'ed to nsIPrintingPromptService
// then that means the progress dialog is already being shown.
nsCOMPtr<nsIPrintingPromptService> pps(do_QueryInterface(aWebProgressListener));
mProgressDialogIsShown = pps != nullptr;
if (mIsDoingPrintPreview) {
mOldPrtPreview = mPrtPreview;
mPrtPreview = nullptr;
}
} else {
mProgressDialogIsShown = false;
}
mPrt = new nsPrintData(aIsPrintPreview ? nsPrintData::eIsPrintPreview :
nsPrintData::eIsPrinting);
NS_ENSURE_TRUE(mPrt, NS_ERROR_OUT_OF_MEMORY);
// if they don't pass in a PrintSettings, then get the Global PS
mPrt->mPrintSettings = aPrintSettings;
if (!mPrt->mPrintSettings) {
rv = GetGlobalPrintSettings(getter_AddRefs(mPrt->mPrintSettings));
NS_ENSURE_SUCCESS(rv, rv);
}
rv = CheckForPrinters(mPrt->mPrintSettings);
NS_ENSURE_SUCCESS(rv, rv);
mPrt->mPrintSettings->SetIsCancelled(false);
mPrt->mPrintSettings->GetShrinkToFit(&mPrt->mShrinkToFit);
if (aIsPrintPreview) {
SetIsCreatingPrintPreview(true);
SetIsPrintPreview(true);
nsCOMPtr<nsIMarkupDocumentViewer> viewer =
do_QueryInterface(mDocViewerPrint);
if (viewer) {
viewer->SetTextZoom(1.0f);
viewer->SetFullZoom(1.0f);
viewer->SetMinFontSize(0);
}
}
// Create a print session and let the print settings know about it.
// The print settings hold an nsWeakPtr to the session so it does not
// need to be cleared from the settings at the end of the job.
// XXX What lifetime does the printSession need to have?
nsCOMPtr<nsIPrintSession> printSession;
if (!aIsPrintPreview) {
printSession = do_CreateInstance("@mozilla.org/gfx/printsession;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
mPrt->mPrintSettings->SetPrintSession(printSession);
}
if (aWebProgressListener != nullptr) {
mPrt->mPrintProgressListeners.AppendObject(aWebProgressListener);
}
// Get the currently focused window and cache it
// because the Print Dialog will "steal" focus and later when you try
// to get the currently focused windows it will be NULL
mPrt->mCurrentFocusWin = FindFocusedDOMWindow();
// Check to see if there is a "regular" selection
bool isSelection = IsThereARangeSelection(mPrt->mCurrentFocusWin);
// Get the docshell for this documentviewer
nsCOMPtr<nsIDocShell> webContainer(do_QueryReferent(mContainer, &rv));
NS_ENSURE_SUCCESS(rv, rv);
mPrt->mPrintObject = new nsPrintObject();
NS_ENSURE_TRUE(mPrt->mPrintObject, NS_ERROR_OUT_OF_MEMORY);
rv = mPrt->mPrintObject->Init(webContainer, aDoc, aIsPrintPreview);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(mPrt->mPrintDocList.AppendElement(mPrt->mPrintObject),
NS_ERROR_OUT_OF_MEMORY);
mPrt->mIsParentAFrameSet = IsParentAFrameSet(webContainer);
mPrt->mPrintObject->mFrameType = mPrt->mIsParentAFrameSet ? eFrameSet : eDoc;
// Build the "tree" of PrintObjects
nsCOMPtr<nsIDocShellTreeNode> parentAsNode =
do_QueryInterface(mPrt->mPrintObject->mDocShell);
BuildDocTree(parentAsNode, &mPrt->mPrintDocList, mPrt->mPrintObject);
if (!aIsPrintPreview) {
SetIsPrinting(true);
}
// XXX This isn't really correct...
if (!mPrt->mPrintObject->mDocument ||
!mPrt->mPrintObject->mDocument->GetRootElement())
return NS_ERROR_GFX_PRINTER_STARTDOC;
// Create the linkage from the sub-docs back to the content element
// in the parent document
MapContentToWebShells(mPrt->mPrintObject, mPrt->mPrintObject);
mPrt->mIsIFrameSelected = IsThereAnIFrameSelected(webContainer, mPrt->mCurrentFocusWin, mPrt->mIsParentAFrameSet);
// Setup print options for UI
if (mPrt->mIsParentAFrameSet) {
if (mPrt->mCurrentFocusWin) {
mPrt->mPrintSettings->SetHowToEnableFrameUI(nsIPrintSettings::kFrameEnableAll);
} else {
mPrt->mPrintSettings->SetHowToEnableFrameUI(nsIPrintSettings::kFrameEnableAsIsAndEach);
}
} else {
mPrt->mPrintSettings->SetHowToEnableFrameUI(nsIPrintSettings::kFrameEnableNone);
}
// Now determine how to set up the Frame print UI
mPrt->mPrintSettings->SetPrintOptions(nsIPrintSettings::kEnableSelectionRB, isSelection || mPrt->mIsIFrameSelected);
nsCOMPtr<nsIDeviceContextSpec> devspec
(do_CreateInstance("@mozilla.org/gfx/devicecontextspec;1", &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsScriptSuppressor scriptSuppressor(this);
if (!aIsPrintPreview) {
#ifdef DEBUG
mPrt->mDebugFilePtr = mDebugFile;
#endif
scriptSuppressor.Suppress();
bool printSilently;
mPrt->mPrintSettings->GetPrintSilent(&printSilently);
// Check prefs for a default setting as to whether we should print silently
printSilently =
Preferences::GetBool("print.always_print_silent", printSilently);
// Ask dialog to be Print Shown via the Plugable Printing Dialog Service
// This service is for the Print Dialog and the Print Progress Dialog
// If printing silently or you can't get the service continue on
if (!printSilently) {
nsCOMPtr<nsIPrintingPromptService> printPromptService(do_GetService(kPrintingPromptService));
if (printPromptService) {
nsIDOMWindow *domWin = mDocument->GetWindow();
NS_ENSURE_TRUE(domWin, NS_ERROR_FAILURE);
// Platforms not implementing a given dialog for the service may
// return NS_ERROR_NOT_IMPLEMENTED or an error code.
//
// NS_ERROR_NOT_IMPLEMENTED indicates they want default behavior
// Any other error code means we must bail out
//
nsCOMPtr<nsIWebBrowserPrint> wbp(do_QueryInterface(mDocViewerPrint));
rv = printPromptService->ShowPrintDialog(domWin, wbp,
mPrt->mPrintSettings);
//
// ShowPrintDialog triggers an event loop which means we can't assume
// that the state of this->{anything} matches the state we've checked
// above. Including that a given {thing} is non null.
if (NS_SUCCEEDED(rv)) {
// since we got the dialog and it worked then make sure we
// are telling GFX we want to print silent
printSilently = true;
if (mPrt && mPrt->mPrintSettings) {
// The user might have changed shrink-to-fit in the print dialog, so update our copy of its state
mPrt->mPrintSettings->GetShrinkToFit(&mPrt->mShrinkToFit);
}
} else if (rv == NS_ERROR_NOT_IMPLEMENTED) {
// This means the Dialog service was there,
// but they choose not to implement this dialog and
// are looking for default behavior from the toolkit
rv = NS_OK;
}
} else {
rv = NS_ERROR_GFX_NO_PRINTROMPTSERVICE;
}
} else {
// Call any code that requires a run of the event loop.
rv = mPrt->mPrintSettings->SetupSilentPrinting();
}
// Check explicitly for abort because it's expected
if (rv == NS_ERROR_ABORT)
return rv;
NS_ENSURE_SUCCESS(rv, rv);
}
rv = devspec->Init(nullptr, mPrt->mPrintSettings, aIsPrintPreview);
NS_ENSURE_SUCCESS(rv, rv);
mPrt->mPrintDC = new nsDeviceContext();
rv = mPrt->mPrintDC->InitForPrinting(devspec);
NS_ENSURE_SUCCESS(rv, rv);
if (aIsPrintPreview) {
mPrt->mPrintSettings->SetPrintFrameType(nsIPrintSettings::kFramesAsIs);
// override any UI that wants to PrintPreview any selection or page range
// we want to view every page in PrintPreview each time
mPrt->mPrintSettings->SetPrintRange(nsIPrintSettings::kRangeAllPages);
} else {
// Always check and set the print settings first and then fall back
// onto the PrintService if there isn't a PrintSettings
//
// Posiible Usage values:
// nsIPrintSettings::kUseInternalDefault
// nsIPrintSettings::kUseSettingWhenPossible
//
// NOTE: The consts are the same for PrintSettings and PrintSettings
int16_t printFrameTypeUsage = nsIPrintSettings::kUseSettingWhenPossible;
mPrt->mPrintSettings->GetPrintFrameTypeUsage(&printFrameTypeUsage);
// Ok, see if we are going to use our value and override the default
if (printFrameTypeUsage == nsIPrintSettings::kUseSettingWhenPossible) {
// Get the Print Options/Settings PrintFrameType to see what is preferred
int16_t printFrameType = nsIPrintSettings::kEachFrameSep;
mPrt->mPrintSettings->GetPrintFrameType(&printFrameType);
// Don't let anybody do something stupid like try to set it to
// kNoFrames when we are printing a FrameSet
if (printFrameType == nsIPrintSettings::kNoFrames) {
mPrt->mPrintFrameType = nsIPrintSettings::kEachFrameSep;
mPrt->mPrintSettings->SetPrintFrameType(mPrt->mPrintFrameType);
} else {
// First find out from the PrinService what options are available
// to us for Printing FrameSets
int16_t howToEnableFrameUI;
mPrt->mPrintSettings->GetHowToEnableFrameUI(&howToEnableFrameUI);
if (howToEnableFrameUI != nsIPrintSettings::kFrameEnableNone) {
switch (howToEnableFrameUI) {
case nsIPrintSettings::kFrameEnableAll:
mPrt->mPrintFrameType = printFrameType;
break;
case nsIPrintSettings::kFrameEnableAsIsAndEach:
if (printFrameType != nsIPrintSettings::kSelectedFrame) {
mPrt->mPrintFrameType = printFrameType;
} else { // revert back to a good value
mPrt->mPrintFrameType = nsIPrintSettings::kEachFrameSep;
}
break;
} // switch
mPrt->mPrintSettings->SetPrintFrameType(mPrt->mPrintFrameType);
}
}
} else {
mPrt->mPrintSettings->GetPrintFrameType(&mPrt->mPrintFrameType);
}
}
if (mPrt->mPrintFrameType == nsIPrintSettings::kEachFrameSep) {
CheckForChildFrameSets(mPrt->mPrintObject);
}
if (NS_FAILED(EnablePOsForPrinting())) {
return NS_ERROR_FAILURE;
}
// Attach progressListener to catch network requests.
nsCOMPtr<nsIWebProgress> webProgress = do_QueryInterface(mPrt->mPrintObject->mDocShell);
webProgress->AddProgressListener(
static_cast<nsIWebProgressListener*>(this),
nsIWebProgress::NOTIFY_STATE_REQUEST);
mLoadCounter = 0;
mDidLoadDataForPrinting = false;
if (aIsPrintPreview) {
bool notifyOnInit = false;
ShowPrintProgress(false, notifyOnInit);
// Very important! Turn Off scripting
TurnScriptingOn(false);
if (!notifyOnInit) {
InstallPrintPreviewListener();
rv = InitPrintDocConstruction(false);
} else {
rv = NS_OK;
}
} else {
bool doNotify;
ShowPrintProgress(true, doNotify);
if (!doNotify) {
// Print listener setup...
mPrt->OnStartPrinting();
rv = InitPrintDocConstruction(false);
}
}
// We will enable scripting later after printing has finished.
scriptSuppressor.Disconnect();
return NS_OK;
}
//---------------------------------------------------------------------------------
NS_IMETHODIMP
nsPrintEngine::Print(nsIPrintSettings* aPrintSettings,
nsIWebProgressListener* aWebProgressListener)
{
// If we have a print preview document, use that instead of the original
// mDocument. That way animated images etc. get printed using the same state
// as in print preview.
nsCOMPtr<nsIDOMDocument> doc =
do_QueryInterface(mPrtPreview && mPrtPreview->mPrintObject ?
mPrtPreview->mPrintObject->mDocument : mDocument);
return CommonPrint(false, aPrintSettings, aWebProgressListener, doc);
}
NS_IMETHODIMP
nsPrintEngine::PrintPreview(nsIPrintSettings* aPrintSettings,
nsIDOMWindow *aChildDOMWin,
nsIWebProgressListener* aWebProgressListener)
{
// Get the DocShell and see if it is busy
// (We can't Print Preview this document if it is still busy)
nsCOMPtr<nsIDocShell> docShell(do_QueryReferent(mContainer));
NS_ENSURE_STATE(docShell);
uint32_t busyFlags = nsIDocShell::BUSY_FLAGS_NONE;
if (NS_FAILED(docShell->GetBusyFlags(&busyFlags)) ||
busyFlags != nsIDocShell::BUSY_FLAGS_NONE) {
CloseProgressDialog(aWebProgressListener);
ShowPrintErrorDialog(NS_ERROR_GFX_PRINTER_DOC_IS_BUSY_PP, false);
return NS_ERROR_FAILURE;
}
NS_ENSURE_STATE(aChildDOMWin);
nsCOMPtr<nsIDOMDocument> doc;
aChildDOMWin->GetDocument(getter_AddRefs(doc));
NS_ENSURE_STATE(doc);
// Document is not busy -- go ahead with the Print Preview
return CommonPrint(true, aPrintSettings, aWebProgressListener, doc);
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean isFramesetDocument; */
NS_IMETHODIMP
nsPrintEngine::GetIsFramesetDocument(bool *aIsFramesetDocument)
{
nsCOMPtr<nsIDocShell> webContainer(do_QueryReferent(mContainer));
*aIsFramesetDocument = IsParentAFrameSet(webContainer);
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean isIFrameSelected; */
NS_IMETHODIMP
nsPrintEngine::GetIsIFrameSelected(bool *aIsIFrameSelected)
{
*aIsIFrameSelected = false;
// Get the docshell for this documentviewer
nsCOMPtr<nsIDocShell> webContainer(do_QueryReferent(mContainer));
// Get the currently focused window
nsCOMPtr<nsIDOMWindow> currentFocusWin = FindFocusedDOMWindow();
if (currentFocusWin && webContainer) {
// Get whether the doc contains a frameset
// Also, check to see if the currently focus docshell
// is a child of this docshell
bool isParentFrameSet;
*aIsIFrameSelected = IsThereAnIFrameSelected(webContainer, currentFocusWin, isParentFrameSet);
}
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean isRangeSelection; */
NS_IMETHODIMP
nsPrintEngine::GetIsRangeSelection(bool *aIsRangeSelection)
{
// Get the currently focused window
nsCOMPtr<nsIDOMWindow> currentFocusWin = FindFocusedDOMWindow();
*aIsRangeSelection = IsThereARangeSelection(currentFocusWin);
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean isFramesetFrameSelected; */
NS_IMETHODIMP
nsPrintEngine::GetIsFramesetFrameSelected(bool *aIsFramesetFrameSelected)
{
// Get the currently focused window
nsCOMPtr<nsIDOMWindow> currentFocusWin = FindFocusedDOMWindow();
*aIsFramesetFrameSelected = currentFocusWin != nullptr;
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute long printPreviewNumPages; */
NS_IMETHODIMP
nsPrintEngine::GetPrintPreviewNumPages(int32_t *aPrintPreviewNumPages)
{
NS_ENSURE_ARG_POINTER(aPrintPreviewNumPages);
nsPrintData* prt = nullptr;
nsIFrame* seqFrame = nullptr;
*aPrintPreviewNumPages = 0;
// When calling this function, the FinishPrintPreview() function might not
// been called as there are still some
if (mPrtPreview) {
prt = mPrtPreview;
} else {
prt = mPrt;
}
if ((!prt) ||
NS_FAILED(GetSeqFrameAndCountPagesInternal(prt->mPrintObject, seqFrame, *aPrintPreviewNumPages))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
//----------------------------------------------------------------------------------
// Enumerate all the documents for their titles
NS_IMETHODIMP
nsPrintEngine::EnumerateDocumentNames(uint32_t* aCount,
PRUnichar*** aResult)
{
NS_ENSURE_ARG(aCount);
NS_ENSURE_ARG_POINTER(aResult);
*aCount = 0;
*aResult = nullptr;
int32_t numDocs = mPrt->mPrintDocList.Length();
PRUnichar** array = (PRUnichar**) nsMemory::Alloc(numDocs * sizeof(PRUnichar*));
if (!array)
return NS_ERROR_OUT_OF_MEMORY;
for (int32_t i=0;i<numDocs;i++) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
PRUnichar * docTitleStr;
PRUnichar * docURLStr;
GetDocumentTitleAndURL(po->mDocument, &docTitleStr, &docURLStr);
// Use the URL if the doc is empty
if (!docTitleStr || !*docTitleStr) {
if (docURLStr && *docURLStr) {
nsMemory::Free(docTitleStr);
docTitleStr = docURLStr;
} else {
nsMemory::Free(docURLStr);
}
docURLStr = nullptr;
if (!docTitleStr || !*docTitleStr) {
CleanupDocTitleArray(array, i);
return NS_ERROR_OUT_OF_MEMORY;
}
}
array[i] = docTitleStr;
if (docURLStr) nsMemory::Free(docURLStr);
}
*aCount = numDocs;
*aResult = array;
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute nsIPrintSettings globalPrintSettings; */
nsresult
nsPrintEngine::GetGlobalPrintSettings(nsIPrintSettings **aGlobalPrintSettings)
{
NS_ENSURE_ARG_POINTER(aGlobalPrintSettings);
nsresult rv = NS_ERROR_FAILURE;
nsCOMPtr<nsIPrintSettingsService> printSettingsService =
do_GetService(sPrintSettingsServiceContractID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = printSettingsService->GetGlobalPrintSettings(aGlobalPrintSettings);
}
return rv;
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean doingPrint; */
NS_IMETHODIMP
nsPrintEngine::GetDoingPrint(bool *aDoingPrint)
{
NS_ENSURE_ARG_POINTER(aDoingPrint);
*aDoingPrint = mIsDoingPrinting;
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute boolean doingPrintPreview; */
NS_IMETHODIMP
nsPrintEngine::GetDoingPrintPreview(bool *aDoingPrintPreview)
{
NS_ENSURE_ARG_POINTER(aDoingPrintPreview);
*aDoingPrintPreview = mIsDoingPrintPreview;
return NS_OK;
}
//----------------------------------------------------------------------------------
/* readonly attribute nsIPrintSettings currentPrintSettings; */
NS_IMETHODIMP
nsPrintEngine::GetCurrentPrintSettings(nsIPrintSettings * *aCurrentPrintSettings)
{
NS_ENSURE_ARG_POINTER(aCurrentPrintSettings);
if (mPrt) {
*aCurrentPrintSettings = mPrt->mPrintSettings;
} else if (mPrtPreview) {
*aCurrentPrintSettings = mPrtPreview->mPrintSettings;
} else {
*aCurrentPrintSettings = nullptr;
}
NS_IF_ADDREF(*aCurrentPrintSettings);
return NS_OK;
}
//-----------------------------------------------------------------
//-- Section: Pre-Reflow Methods
//-----------------------------------------------------------------
//---------------------------------------------------------------------
// This method checks to see if there is at least one printer defined
// and if so, it sets the first printer in the list as the default name
// in the PrintSettings which is then used for Printer Preview
nsresult
nsPrintEngine::CheckForPrinters(nsIPrintSettings* aPrintSettings)
{
#if defined(XP_MACOSX) || defined(ANDROID)
// Mac doesn't support retrieving a printer list.
return NS_OK;
#else
NS_ENSURE_ARG_POINTER(aPrintSettings);
// See if aPrintSettings already has a printer
nsXPIDLString printerName;
nsresult rv = aPrintSettings->GetPrinterName(getter_Copies(printerName));
if (NS_SUCCEEDED(rv) && !printerName.IsEmpty()) {
return NS_OK;
}
// aPrintSettings doesn't have a printer set. Try to fetch the default.
nsCOMPtr<nsIPrintSettingsService> printSettingsService =
do_GetService(sPrintSettingsServiceContractID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = printSettingsService->GetDefaultPrinterName(getter_Copies(printerName));
if (NS_SUCCEEDED(rv) && !printerName.IsEmpty()) {
rv = aPrintSettings->SetPrinterName(printerName.get());
}
return rv;
#endif
}
//----------------------------------------------------------------------
// Set up to use the "pluggable" Print Progress Dialog
void
nsPrintEngine::ShowPrintProgress(bool aIsForPrinting, bool& aDoNotify)
{
// default to not notifying, that if something here goes wrong
// or we aren't going to show the progress dialog we can straight into
// reflowing the doc for printing.
aDoNotify = false;
// Assume we can't do progress and then see if we can
bool showProgresssDialog = false;
// if it is already being shown then don't bother to find out if it should be
// so skip this and leave mShowProgressDialog set to FALSE
if (!mProgressDialogIsShown) {
showProgresssDialog = Preferences::GetBool("print.show_print_progress");
}
// Turning off the showing of Print Progress in Prefs overrides
// whether the calling PS desire to have it on or off, so only check PS if
// prefs says it's ok to be on.
if (showProgresssDialog) {
mPrt->mPrintSettings->GetShowPrintProgress(&showProgresssDialog);
}
// Now open the service to get the progress dialog
// If we don't get a service, that's ok, then just don't show progress
if (showProgresssDialog) {
nsCOMPtr<nsIPrintingPromptService> printPromptService(do_GetService(kPrintingPromptService));
if (printPromptService) {
nsPIDOMWindow *domWin = mDocument->GetWindow();
if (!domWin) return;
nsCOMPtr<nsIDocShellTreeItem> docShellItem =
do_QueryInterface(domWin->GetDocShell());
if (!docShellItem) return;
nsCOMPtr<nsIDocShellTreeOwner> owner;
docShellItem->GetTreeOwner(getter_AddRefs(owner));
nsCOMPtr<nsIWebBrowserChrome> browserChrome = do_GetInterface(owner);
if (!browserChrome) return;
bool isModal = true;
browserChrome->IsWindowModal(&isModal);
if (isModal) {
// Showing a print progress dialog when printing a modal window
// isn't supported. See bug 301560.
return;
}
nsCOMPtr<nsIWebProgressListener> printProgressListener;
nsCOMPtr<nsIWebBrowserPrint> wbp(do_QueryInterface(mDocViewerPrint));
nsresult rv = printPromptService->ShowProgress(domWin, wbp, mPrt->mPrintSettings, this, aIsForPrinting,
getter_AddRefs(printProgressListener),
getter_AddRefs(mPrt->mPrintProgressParams),
&aDoNotify);
if (NS_SUCCEEDED(rv)) {
if (printProgressListener && mPrt->mPrintProgressParams) {
mPrt->mPrintProgressListeners.AppendObject(printProgressListener);
SetDocAndURLIntoProgress(mPrt->mPrintObject, mPrt->mPrintProgressParams);
}
}
}
}
}
//---------------------------------------------------------------------
bool
nsPrintEngine::IsThereARangeSelection(nsIDOMWindow* aDOMWin)
{
nsCOMPtr<nsIPresShell> presShell;
if (aDOMWin) {
nsCOMPtr<nsPIDOMWindow> window(do_QueryInterface(aDOMWin));
window->GetDocShell()->GetPresShell(getter_AddRefs(presShell));
}
if (!presShell)
return false;
// check here to see if there is a range selection
// so we know whether to turn on the "Selection" radio button
nsCOMPtr<nsISelection> selection;
selection = presShell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
if (selection) {
int32_t count;
selection->GetRangeCount(&count);
if (count == 1) {
nsCOMPtr<nsIDOMRange> range;
if (NS_SUCCEEDED(selection->GetRangeAt(0, getter_AddRefs(range)))) {
// check to make sure it isn't an insertion selection
bool isCollapsed;
selection->GetIsCollapsed(&isCollapsed);
return !isCollapsed;
}
}
if (count > 1) return true;
}
return false;
}
//---------------------------------------------------------------------
bool
nsPrintEngine::IsParentAFrameSet(nsIDocShell * aParent)
{
// See if the incoming doc is the root document
nsCOMPtr<nsIDocShellTreeItem> parentAsItem(do_QueryInterface(aParent));
if (!parentAsItem) return false;
// When it is the top level document we need to check
// to see if it contains a frameset. If it does, then
// we only want to print the doc's children and not the document itself
// For anything else we always print all the children and the document
// for example, if the doc contains an IFRAME we eant to print the child
// document (the IFRAME) and then the rest of the document.
//
// XXX we really need to search the frame tree, and not the content
// but there is no way to distinguish between IFRAMEs and FRAMEs
// with the GetFrameType call.
// Bug 53459 has been files so we can eventually distinguish
// between IFRAME frames and FRAME frames
bool isFrameSet = false;
// only check to see if there is a frameset if there is
// NO parent doc for this doc. meaning this parent is the root doc
nsCOMPtr<nsIDOMDocument> domDoc = do_GetInterface(aParent);
nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
if (doc) {
nsIContent *rootElement = doc->GetRootElement();
if (rootElement) {
isFrameSet = HasFramesetChild(rootElement);
}
}
return isFrameSet;
}
//---------------------------------------------------------------------
// Recursively build a list of sub documents to be printed
// that mirrors the document tree
void
nsPrintEngine::BuildDocTree(nsIDocShellTreeNode * aParentNode,
nsTArray<nsPrintObject*> * aDocList,
nsPrintObject * aPO)
{
NS_ASSERTION(aParentNode, "Pointer is null!");
NS_ASSERTION(aDocList, "Pointer is null!");
NS_ASSERTION(aPO, "Pointer is null!");
int32_t childWebshellCount;
aParentNode->GetChildCount(&childWebshellCount);
if (childWebshellCount > 0) {
for (int32_t i=0;i<childWebshellCount;i++) {
nsCOMPtr<nsIDocShellTreeItem> child;
aParentNode->GetChildAt(i, getter_AddRefs(child));
nsCOMPtr<nsIDocShell> childAsShell(do_QueryInterface(child));
nsCOMPtr<nsIContentViewer> viewer;
childAsShell->GetContentViewer(getter_AddRefs(viewer));
if (viewer) {
nsCOMPtr<nsIContentViewerFile> viewerFile(do_QueryInterface(viewer));
if (viewerFile) {
nsCOMPtr<nsIDocShell> childDocShell(do_QueryInterface(child));
nsCOMPtr<nsIDocShellTreeNode> childNode(do_QueryInterface(child));
nsCOMPtr<nsIDOMDocument> doc = do_GetInterface(childDocShell);
nsPrintObject * po = new nsPrintObject();
po->mParent = aPO;
nsresult rv = po->Init(childDocShell, doc, aPO->mPrintPreview);
if (NS_FAILED(rv))
NS_NOTREACHED("Init failed?");
aPO->mKids.AppendElement(po);
aDocList->AppendElement(po);
BuildDocTree(childNode, aDocList, po);
}
}
}
}
}
//---------------------------------------------------------------------
void
nsPrintEngine::GetDocumentTitleAndURL(nsIDocument* aDoc,
PRUnichar** aTitle,
PRUnichar** aURLStr)
{
NS_ASSERTION(aDoc, "Pointer is null!");
NS_ASSERTION(aTitle, "Pointer is null!");
NS_ASSERTION(aURLStr, "Pointer is null!");
*aTitle = nullptr;
*aURLStr = nullptr;
nsAutoString docTitle;
nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDoc);
doc->GetTitle(docTitle);
if (!docTitle.IsEmpty()) {
*aTitle = ToNewUnicode(docTitle);
}
nsIURI* url = aDoc->GetDocumentURI();
if (!url) return;
nsCOMPtr<nsIURIFixup> urifixup(do_GetService(NS_URIFIXUP_CONTRACTID));
if (!urifixup) return;
nsCOMPtr<nsIURI> exposableURI;
urifixup->CreateExposableURI(url, getter_AddRefs(exposableURI));
if (!exposableURI) return;
nsAutoCString urlCStr;
exposableURI->GetSpec(urlCStr);
nsresult rv;
nsCOMPtr<nsITextToSubURI> textToSubURI =
do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
if (NS_FAILED(rv)) return;
nsAutoString unescapedURI;
rv = textToSubURI->UnEscapeURIForUI(NS_LITERAL_CSTRING("UTF-8"),
urlCStr, unescapedURI);
if (NS_FAILED(rv)) return;
*aURLStr = ToNewUnicode(unescapedURI);
}
//---------------------------------------------------------------------
// The walks the PO tree and for each document it walks the content
// tree looking for any content that are sub-shells
//
// It then sets the mContent pointer in the "found" PO object back to the
// the document that contained it.
void
nsPrintEngine::MapContentToWebShells(nsPrintObject* aRootPO,
nsPrintObject* aPO)
{
NS_ASSERTION(aRootPO, "Pointer is null!");
NS_ASSERTION(aPO, "Pointer is null!");
// Recursively walk the content from the root item
// XXX Would be faster to enumerate the subdocuments, although right now
// nsIDocument doesn't expose quite what would be needed.
nsCOMPtr<nsIContentViewer> viewer;
aPO->mDocShell->GetContentViewer(getter_AddRefs(viewer));
if (!viewer) return;
nsCOMPtr<nsIDOMDocument> domDoc;
viewer->GetDOMDocument(getter_AddRefs(domDoc));
nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
if (!doc) return;
Element* rootElement = doc->GetRootElement();
if (rootElement) {
MapContentForPO(aPO, rootElement);
} else {
NS_WARNING("Null root content on (sub)document.");
}
// Continue recursively walking the chilren of this PO
for (uint32_t i=0;i<aPO->mKids.Length();i++) {
MapContentToWebShells(aRootPO, aPO->mKids[i]);
}
}
//-------------------------------------------------------
// A Frame's sub-doc may contain content or a FrameSet
// When it contains a FrameSet the mFrameType for the PrintObject
// is always set to an eFrame. Which is fine when printing "AsIs"
// but is incorrect when when printing "Each Frame Separately".
// When printing "Each Frame Separately" the Frame really acts like
// a frameset.
//
// This method walks the PO tree and checks to see if the PrintObject is
// an eFrame and has children that are eFrames (meaning it's a Frame containing a FrameSet)
// If so, then the mFrameType need to be changed to eFrameSet
//
// Also note: We only want to call this we are printing "Each Frame Separately"
// when printing "As Is" leave it as an eFrame
void
nsPrintEngine::CheckForChildFrameSets(nsPrintObject* aPO)
{
NS_ASSERTION(aPO, "Pointer is null!");
// Continue recursively walking the chilren of this PO
bool hasChildFrames = false;
for (uint32_t i=0;i<aPO->mKids.Length();i++) {
nsPrintObject* po = aPO->mKids[i];
if (po->mFrameType == eFrame) {
hasChildFrames = true;
CheckForChildFrameSets(po);
}
}
if (hasChildFrames && aPO->mFrameType == eFrame) {
aPO->mFrameType = eFrameSet;
}
}
//---------------------------------------------------------------------
// This method is key to the entire print mechanism.
//
// This "maps" or figures out which sub-doc represents a
// given Frame or IFrame in its parent sub-doc.
//
// So the Mcontent pointer in the child sub-doc points to the
// content in the its parent document, that caused it to be printed.
// This is used later to (after reflow) to find the absolute location
// of the sub-doc on its parent's page frame so it can be
// printed in the correct location.
//
// This method recursvely "walks" the content for a document finding
// all the Frames and IFrames, then sets the "mFrameType" data member
// which tells us what type of PO we have
void
nsPrintEngine::MapContentForPO(nsPrintObject* aPO,
nsIContent* aContent)
{
NS_PRECONDITION(aPO && aContent, "Null argument");
nsIDocument* doc = aContent->GetDocument();
NS_ASSERTION(doc, "Content without a document from a document tree?");
nsIDocument* subDoc = doc->GetSubDocumentFor(aContent);
if (subDoc) {
nsCOMPtr<nsISupports> container = subDoc->GetContainer();
nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(container));
if (docShell) {
nsPrintObject * po = nullptr;
int32_t cnt = aPO->mKids.Length();
for (int32_t i=0;i<cnt;i++) {
nsPrintObject* kid = aPO->mKids.ElementAt(i);
if (kid->mDocument == subDoc) {
po = kid;
break;
}
}
// XXX If a subdocument has no onscreen presentation, there will be no PO
// This is even if there should be a print presentation
if (po) {
nsCOMPtr<nsIDOMHTMLFrameElement> frame(do_QueryInterface(aContent));
// "frame" elements not in a frameset context should be treated
// as iframes
if (frame && po->mParent->mFrameType == eFrameSet) {
po->mFrameType = eFrame;
} else {
// Assume something iframe-like, i.e. iframe, object, or embed
po->mFrameType = eIFrame;
SetPrintAsIs(po, true);
NS_ASSERTION(po->mParent, "The root must be a parent");
po->mParent->mPrintAsIs = true;
}
}
}
}
// walk children content
for (nsIContent* child = aContent->GetFirstChild();
child;
child = child->GetNextSibling()) {
MapContentForPO(aPO, child);
}
}
//---------------------------------------------------------------------
bool
nsPrintEngine::IsThereAnIFrameSelected(nsIDocShell* aDocShell,
nsIDOMWindow* aDOMWin,
bool& aIsParentFrameSet)
{
aIsParentFrameSet = IsParentAFrameSet(aDocShell);
bool iFrameIsSelected = false;
if (mPrt && mPrt->mPrintObject) {
nsPrintObject* po = FindPrintObjectByDOMWin(mPrt->mPrintObject, aDOMWin);
iFrameIsSelected = po && po->mFrameType == eIFrame;
} else {
// First, check to see if we are a frameset
if (!aIsParentFrameSet) {
// Check to see if there is a currenlt focused frame
// if so, it means the selected frame is either the main docshell
// or an IFRAME
if (aDOMWin) {
// Get the main docshell's DOMWin to see if it matches
// the frame that is selected
nsCOMPtr<nsIDOMWindow> domWin = do_GetInterface(aDocShell);
if (domWin != aDOMWin) {
iFrameIsSelected = true; // we have a selected IFRAME
}
}
}
}
return iFrameIsSelected;
}
//---------------------------------------------------------------------
// Recursively sets all the PO items to be printed
// from the given item down into the tree
void
nsPrintEngine::SetPrintPO(nsPrintObject* aPO, bool aPrint)
{
NS_ASSERTION(aPO, "Pointer is null!");
// Set whether to print flag
aPO->mDontPrint = !aPrint;
for (uint32_t i=0;i<aPO->mKids.Length();i++) {
SetPrintPO(aPO->mKids[i], aPrint);
}
}
//---------------------------------------------------------------------
// This will first use a Title and/or URL from the PrintSettings
// if one isn't set then it uses the one from the document
// then if not title is there we will make sure we send something back
// depending on the situation.
void
nsPrintEngine::GetDisplayTitleAndURL(nsPrintObject* aPO,
PRUnichar** aTitle,
PRUnichar** aURLStr,
eDocTitleDefault aDefType)
{
NS_ASSERTION(aPO, "Pointer is null!");
NS_ASSERTION(aTitle, "Pointer is null!");
NS_ASSERTION(aURLStr, "Pointer is null!");
*aTitle = nullptr;
*aURLStr = nullptr;
if (!mPrt)
return;
// First check to see if the PrintSettings has defined an alternate title
// and use that if it did
PRUnichar * docTitleStrPS = nullptr;
PRUnichar * docURLStrPS = nullptr;
if (mPrt->mPrintSettings) {
mPrt->mPrintSettings->GetTitle(&docTitleStrPS);
mPrt->mPrintSettings->GetDocURL(&docURLStrPS);
if (docTitleStrPS && *docTitleStrPS) {
*aTitle = docTitleStrPS;
}
if (docURLStrPS && *docURLStrPS) {
*aURLStr = docURLStrPS;
}
// short circut
if (docTitleStrPS && docURLStrPS) {
return;
}
}
PRUnichar* docTitle;
PRUnichar* docUrl;
GetDocumentTitleAndURL(aPO->mDocument, &docTitle, &docUrl);
if (docUrl) {
if (!docURLStrPS)
*aURLStr = docUrl;
else
nsMemory::Free(docUrl);
}
if (docTitle) {
if (!docTitleStrPS)
*aTitle = docTitle;
else
nsMemory::Free(docTitle);
} else if (!docTitleStrPS) {
switch (aDefType) {
case eDocTitleDefBlank: *aTitle = ToNewUnicode(EmptyString());
break;
case eDocTitleDefURLDoc:
if (*aURLStr) {
*aTitle = NS_strdup(*aURLStr);
} else if (mPrt->mBrandName) {
*aTitle = NS_strdup(mPrt->mBrandName);
}
break;
case eDocTitleDefNone:
// *aTitle defaults to nullptr
break;
}
}
}
//---------------------------------------------------------------------
nsresult nsPrintEngine::DocumentReadyForPrinting()
{
if (mPrt->mPrintFrameType == nsIPrintSettings::kEachFrameSep) {
CheckForChildFrameSets(mPrt->mPrintObject);
}
//
// Send the document to the printer...
//
nsresult rv = SetupToPrintContent();
if (NS_FAILED(rv)) {
// The print job was canceled or there was a problem
// So remove all other documents from the print list
DonePrintingPages(nullptr, rv);
}
return rv;
}
/** ---------------------------------------------------
* Cleans up when an error occurred
*/
nsresult nsPrintEngine::CleanupOnFailure(nsresult aResult, bool aIsPrinting)
{
PR_PL(("**** Failed %s - rv 0x%X", aIsPrinting?"Printing":"Print Preview", aResult));
/* cleanup... */
if (mPagePrintTimer) {
mPagePrintTimer->Stop();
NS_RELEASE(mPagePrintTimer);
}
if (aIsPrinting) {
SetIsPrinting(false);
} else {
SetIsPrintPreview(false);
SetIsCreatingPrintPreview(false);
}
/* cleanup done, let's fire-up an error dialog to notify the user
* what went wrong...
*
* When rv == NS_ERROR_ABORT, it means we want out of the
* print job without displaying any error messages
*/
if (aResult != NS_ERROR_ABORT) {
ShowPrintErrorDialog(aResult, aIsPrinting);
}
FirePrintCompletionEvent();
return aResult;
}
//---------------------------------------------------------------------
void
nsPrintEngine::ShowPrintErrorDialog(nsresult aPrintError, bool aIsPrinting)
{
PR_PL(("nsPrintEngine::ShowPrintErrorDialog(nsresult aPrintError=%lx, bool aIsPrinting=%d)\n", (long)aPrintError, (int)aIsPrinting));
nsAutoCString stringName;
switch(aPrintError)
{
#define NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(nserr) case nserr: stringName.AssignLiteral(#nserr); break;
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_CMD_NOT_FOUND)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_CMD_FAILURE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_NO_PRINTER_AVAILABLE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_NAME_NOT_FOUND)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_ACCESS_DENIED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_INVALID_ATTRIBUTE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PRINTER_NOT_READY)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_OUT_OF_PAPER)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PRINTER_IO_ERROR)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_FILE_IO_ERROR)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PRINTPREVIEW)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_UNEXPECTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_OUT_OF_MEMORY)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_NOT_IMPLEMENTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_NOT_AVAILABLE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_ABORT)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_STARTDOC)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_ENDDOC)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_STARTPAGE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_ENDPAGE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PRINT_WHILE_PREVIEW)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PAPER_SIZE_NOT_SUPPORTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_ORIENTATION_NOT_SUPPORTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_COLORSPACE_NOT_SUPPORTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_TOO_MANY_COPIES)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_DRIVER_CONFIGURATION_ERROR)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_DOC_IS_BUSY_PP)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_DOC_WAS_DESTORYED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_NO_PRINTDIALOG_IN_TOOLKIT)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_NO_PRINTROMPTSERVICE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_NO_XUL) // Temporary code for Bug 136185 / bug 240490
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_PLEX_NOT_SUPPORTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_DOC_IS_BUSY)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTING_NOT_IMPLEMENTED)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_COULD_NOT_LOAD_PRINT_MODULE)
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_GFX_PRINTER_RESOLUTION_NOT_SUPPORTED)
default:
NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG(NS_ERROR_FAILURE)
#undef NS_ERROR_TO_LOCALIZED_PRINT_ERROR_MSG
}
PR_PL(("ShowPrintErrorDialog: stringName='%s'\n", stringName.get()));
nsXPIDLString msg, title;
nsresult rv =
nsContentUtils::GetLocalizedString(nsContentUtils::ePRINTING_PROPERTIES,
stringName.get(), msg);
if (NS_FAILED(rv)) {
PR_PL(("GetLocalizedString failed\n"));
return;
}
rv = nsContentUtils::GetLocalizedString(nsContentUtils::ePRINTING_PROPERTIES,
aIsPrinting ? "print_error_dialog_title"
: "printpreview_error_dialog_title",
title);
nsCOMPtr<nsIWindowWatcher> wwatch = do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
PR_PL(("ShowPrintErrorDialog(): wwatch==nullptr\n"));
return;
}
nsCOMPtr<nsIDOMWindow> active;
wwatch->GetActiveWindow(getter_AddRefs(active));
nsCOMPtr<nsIPrompt> dialog;
/* |GetNewPrompter| allows that |active| is |nullptr|
* (see bug 234982 ("nsPrintEngine::ShowPrintErrorDialog() fails in many cases")) */
wwatch->GetNewPrompter(active, getter_AddRefs(dialog));
if (!dialog) {
PR_PL(("ShowPrintErrorDialog(): dialog==nullptr\n"));
return;
}
dialog->Alert(title.get(), msg.get());
PR_PL(("ShowPrintErrorDialog(): alert displayed successfully.\n"));
}
//-----------------------------------------------------------------
//-- Section: Reflow Methods
//-----------------------------------------------------------------
nsresult
nsPrintEngine::ReconstructAndReflow(bool doSetPixelScale)
{
#if (defined(XP_WIN) || defined(XP_OS2)) && defined(EXTENDED_DEBUG_PRINTING)
// We need to clear all the output files here
// because they will be re-created with second reflow of the docs
if (kPrintingLogMod && kPrintingLogMod->level == DUMP_LAYOUT_LEVEL) {
RemoveFilesInDir(".\\");
gDumpFileNameCnt = 0;
gDumpLOFileNameCnt = 0;
}
#endif
for (uint32_t i = 0; i < mPrt->mPrintDocList.Length(); ++i) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
if (po->mDontPrint || po->mInvisible) {
continue;
}
UpdateZoomRatio(po, doSetPixelScale);
po->mPresContext->SetPageScale(po->mZoomRatio);
// Calculate scale factor from printer to screen
float printDPI = float(mPrt->mPrintDC->AppUnitsPerCSSInch()) /
float(mPrt->mPrintDC->AppUnitsPerDevPixel());
po->mPresContext->SetPrintPreviewScale(mScreenDPI / printDPI);
po->mPresShell->ReconstructFrames();
// For all views except the first one, setup the root view.
// ??? Can there be multiple po for the top-level-document?
bool documentIsTopLevel = true;
if (i != 0) {
nsSize adjSize;
bool doReturn;
nsresult rv = SetRootView(po, doReturn, documentIsTopLevel, adjSize);
MOZ_ASSERT(!documentIsTopLevel, "How could this happen?");
if (NS_FAILED(rv) || doReturn) {
return rv;
}
}
po->mPresShell->FlushPendingNotifications(Flush_Layout);
nsresult rv = UpdateSelectionAndShrinkPrintObject(po, documentIsTopLevel);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
//-------------------------------------------------------
nsresult
nsPrintEngine::SetupToPrintContent()
{
nsresult rv;
bool didReconstruction = false;
// If some new content got loaded since the initial reflow rebuild
// everything.
if (mDidLoadDataForPrinting) {
rv = ReconstructAndReflow(DoSetPixelScale());
didReconstruction = true;
NS_ENSURE_SUCCESS(rv, rv);
}
// Here is where we figure out if extra reflow for shrinking the content
// is required.
// But skip this step if we are in PrintPreview
bool ppIsShrinkToFit = mPrtPreview && mPrtPreview->mShrinkToFit;
if (mPrt->mShrinkToFit && !ppIsShrinkToFit) {
// Now look for the PO that has the smallest percent for shrink to fit
if (mPrt->mPrintDocList.Length() > 1 && mPrt->mPrintObject->mFrameType == eFrameSet) {
nsPrintObject* smallestPO = FindSmallestSTF();
NS_ASSERTION(smallestPO, "There must always be an XMost PO!");
if (smallestPO) {
// Calc the shrinkage based on the entire content area
mPrt->mShrinkRatio = smallestPO->mShrinkRatio;
}
} else {
// Single document so use the Shrink as calculated for the PO
mPrt->mShrinkRatio = mPrt->mPrintObject->mShrinkRatio;
}
if (mPrt->mShrinkRatio < 0.998f) {
rv = ReconstructAndReflow(true);
didReconstruction = true;
NS_ENSURE_SUCCESS(rv, rv);
}
#ifdef PR_LOGGING
float calcRatio = 0.0f;
if (mPrt->mPrintDocList.Length() > 1 && mPrt->mPrintObject->mFrameType == eFrameSet) {
nsPrintObject* smallestPO = FindSmallestSTF();
NS_ASSERTION(smallestPO, "There must always be an XMost PO!");
if (smallestPO) {
// Calc the shrinkage based on the entire content area
calcRatio = smallestPO->mShrinkRatio;
}
} else {
// Single document so use the Shrink as calculated for the PO
calcRatio = mPrt->mPrintObject->mShrinkRatio;
}
PR_PL(("**************************************************************************\n"));
PR_PL(("STF Ratio is: %8.5f Effective Ratio: %8.5f Diff: %8.5f\n", mPrt->mShrinkRatio, calcRatio, mPrt->mShrinkRatio-calcRatio));
PR_PL(("**************************************************************************\n"));
#endif
}
// If the frames got reconstructed and reflowed the number of pages might
// has changed.
if (didReconstruction) {
FirePrintPreviewUpdateEvent();
}
DUMP_DOC_LIST(("\nAfter Reflow------------------------------------------"));
PR_PL(("\n"));
PR_PL(("-------------------------------------------------------\n"));
PR_PL(("\n"));
CalcNumPrintablePages(mPrt->mNumPrintablePages);
PR_PL(("--- Printing %d pages\n", mPrt->mNumPrintablePages));
DUMP_DOC_TREELAYOUT;
// Print listener setup...
if (mPrt != nullptr) {
mPrt->OnStartPrinting();
}
PRUnichar* fileName = nullptr;
// check to see if we are printing to a file
bool isPrintToFile = false;
mPrt->mPrintSettings->GetPrintToFile(&isPrintToFile);
if (isPrintToFile) {
// On some platforms The BeginDocument needs to know the name of the file
// and it uses the PrintService to get it, so we need to set it into the PrintService here
mPrt->mPrintSettings->GetToFileName(&fileName);
}
PRUnichar * docTitleStr;
PRUnichar * docURLStr;
GetDisplayTitleAndURL(mPrt->mPrintObject, &docTitleStr, &docURLStr, eDocTitleDefURLDoc);
int32_t startPage = 1;
int32_t endPage = mPrt->mNumPrintablePages;
int16_t printRangeType = nsIPrintSettings::kRangeAllPages;
mPrt->mPrintSettings->GetPrintRange(&printRangeType);
if (printRangeType == nsIPrintSettings::kRangeSpecifiedPageRange) {
mPrt->mPrintSettings->GetStartPageRange(&startPage);
mPrt->mPrintSettings->GetEndPageRange(&endPage);
if (endPage > mPrt->mNumPrintablePages) {
endPage = mPrt->mNumPrintablePages;
}
}
rv = NS_OK;
// BeginDocument may pass back a FAILURE code
// i.e. On Windows, if you are printing to a file and hit "Cancel"
// to the "File Name" dialog, this comes back as an error
// Don't start printing when regression test are executed
if (!mPrt->mDebugFilePtr && mIsDoingPrinting) {
rv = mPrt->mPrintDC->BeginDocument(docTitleStr, fileName, startPage, endPage);
}
if (mIsCreatingPrintPreview) {
// Print Preview -- Pass ownership of docTitleStr and docURLStr
// to the pageSequenceFrame, to be displayed in the header
nsIPageSequenceFrame *seqFrame = mPrt->mPrintObject->mPresShell->GetPageSequenceFrame();
if (seqFrame) {
seqFrame->StartPrint(mPrt->mPrintObject->mPresContext,
mPrt->mPrintSettings, docTitleStr, docURLStr);
docTitleStr = nullptr;
docURLStr = nullptr;
}
}
if (docTitleStr) nsMemory::Free(docTitleStr);
if (docURLStr) nsMemory::Free(docURLStr);
PR_PL(("****************** Begin Document ************************\n"));
NS_ENSURE_SUCCESS(rv, rv);
// This will print the docshell document
// when it completes asynchronously in the DonePrintingPages method
// it will check to see if there are more docshells to be printed and
// then PrintDocContent will be called again.
if (mIsDoingPrinting) {
PrintDocContent(mPrt->mPrintObject, rv); // ignore return value
}
return rv;
}
//-------------------------------------------------------
// Recursively reflow each sub-doc and then calc
// all the frame locations of the sub-docs
nsresult
nsPrintEngine::ReflowDocList(nsPrintObject* aPO, bool aSetPixelScale)
{
NS_ENSURE_ARG_POINTER(aPO);
// Check to see if the subdocument's element has been hidden by the parent document
if (aPO->mParent && aPO->mParent->mPresShell) {
nsIFrame* frame = aPO->mContent ? aPO->mContent->GetPrimaryFrame() : nullptr;
if (!frame || !frame->GetStyleVisibility()->IsVisible()) {
SetPrintPO(aPO, false);
aPO->mInvisible = true;
return NS_OK;
}
}
UpdateZoomRatio(aPO, aSetPixelScale);
nsresult rv;
// Reflow the PO
rv = ReflowPrintObject(aPO);
NS_ENSURE_SUCCESS(rv, rv);
int32_t cnt = aPO->mKids.Length();
for (int32_t i=0;i<cnt;i++) {
rv = ReflowDocList(aPO->mKids[i], aSetPixelScale);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
void
nsPrintEngine::FirePrintPreviewUpdateEvent()
{
// Dispatch the event only while in PrintPreview. When printing, there is no
// listener bound to this event and therefore no need to dispatch it.
if (mIsDoingPrintPreview && !mIsDoingPrinting) {
nsCOMPtr<nsIContentViewer> cv = do_QueryInterface(mDocViewerPrint);
(new nsAsyncDOMEvent(
cv->GetDocument(), NS_LITERAL_STRING("printPreviewUpdate"), true, true)
)->RunDOMEventWhenSafe();
}
}
nsresult
nsPrintEngine::InitPrintDocConstruction(bool aHandleError)
{
nsresult rv;
rv = ReflowDocList(mPrt->mPrintObject, DoSetPixelScale());
NS_ENSURE_SUCCESS(rv, rv);
FirePrintPreviewUpdateEvent();
if (mLoadCounter == 0) {
AfterNetworkPrint(aHandleError);
}
return rv;
}
nsresult
nsPrintEngine::AfterNetworkPrint(bool aHandleError)
{
nsCOMPtr<nsIWebProgress> webProgress = do_QueryInterface(mPrt->mPrintObject->mDocShell);
webProgress->RemoveProgressListener(
static_cast<nsIWebProgressListener*>(this));
nsresult rv;
if (mIsDoingPrinting) {
rv = DocumentReadyForPrinting();
} else {
rv = FinishPrintPreview();
}
/* cleaup on failure + notify user */
if (aHandleError && NS_FAILED(rv)) {
CleanupOnFailure(rv, !mIsDoingPrinting);
}
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIWebProgressListener
NS_IMETHODIMP
nsPrintEngine::OnStateChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aStateFlags,
nsresult aStatus)
{
nsAutoCString name;
aRequest->GetName(name);
if (name.Equals("about:document-onload-blocker")) {
return NS_OK;
}
if (aStateFlags & STATE_START) {
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
++mLoadCounter;
} else if (aStateFlags & STATE_STOP) {
mDidLoadDataForPrinting = true;
--mLoadCounter;
// If all resources are loaded, then do a small timeout and if there
// are still no new requests, then another reflow.
if (mLoadCounter == 0) {
AfterNetworkPrint(true);
}
}
return NS_OK;
}
NS_IMETHODIMP
nsPrintEngine::OnProgressChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
int32_t aCurSelfProgress,
int32_t aMaxSelfProgress,
int32_t aCurTotalProgress,
int32_t aMaxTotalProgress)
{
NS_NOTREACHED("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
nsPrintEngine::OnLocationChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsIURI* aLocation,
uint32_t aFlags)
{
NS_NOTREACHED("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
nsPrintEngine::OnStatusChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
nsresult aStatus,
const PRUnichar *aMessage)
{
NS_NOTREACHED("notification excluded in AddProgressListener(...)");
return NS_OK;
}
NS_IMETHODIMP
nsPrintEngine::OnSecurityChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
uint32_t aState)
{
NS_NOTREACHED("notification excluded in AddProgressListener(...)");
return NS_OK;
}
//-------------------------------------------------------
void
nsPrintEngine::UpdateZoomRatio(nsPrintObject* aPO, bool aSetPixelScale)
{
// Here is where we set the shrinkage value into the DC
// and this is what actually makes it shrink
if (aSetPixelScale && aPO->mFrameType != eIFrame) {
float ratio;
if (mPrt->mPrintFrameType == nsIPrintSettings::kFramesAsIs || mPrt->mPrintFrameType == nsIPrintSettings::kNoFrames) {
ratio = mPrt->mShrinkRatio - 0.005f; // round down
} else {
ratio = aPO->mShrinkRatio - 0.005f; // round down
}
aPO->mZoomRatio = ratio;
} else if (!mPrt->mShrinkToFit) {
double scaling;
mPrt->mPrintSettings->GetScaling(&scaling);
aPO->mZoomRatio = float(scaling);
}
}
nsresult
nsPrintEngine::UpdateSelectionAndShrinkPrintObject(nsPrintObject* aPO,
bool aDocumentIsTopLevel)
{
nsCOMPtr<nsIPresShell> displayShell;
aPO->mDocShell->GetPresShell(getter_AddRefs(displayShell));
// Transfer Selection Ranges to the new Print PresShell
nsCOMPtr<nsISelection> selection, selectionPS;
// It's okay if there is no display shell, just skip copying the selection
if (displayShell) {
selection = displayShell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
}
selectionPS = aPO->mPresShell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
// Reset all existing selection ranges that might have been added by calling
// this function before.
if (selectionPS) {
selectionPS->RemoveAllRanges();
}
if (selection && selectionPS) {
int32_t cnt;
selection->GetRangeCount(&cnt);
int32_t inx;
for (inx = 0; inx < cnt; ++inx) {
nsCOMPtr<nsIDOMRange> range;
if (NS_SUCCEEDED(selection->GetRangeAt(inx, getter_AddRefs(range))))
selectionPS->AddRange(range);
}
}
// If we are trying to shrink the contents to fit on the page
// we must first locate the "pageContent" frame
// Then we walk the frame tree and look for the "xmost" frame
// this is the frame where the right-hand side of the frame extends
// the furthest
if (mPrt->mShrinkToFit && aDocumentIsTopLevel) {
nsIPageSequenceFrame* pageSequence = aPO->mPresShell->GetPageSequenceFrame();
NS_ENSURE_STATE(pageSequence);
pageSequence->GetSTFPercent(aPO->mShrinkRatio);
}
return NS_OK;
}
bool
nsPrintEngine::DoSetPixelScale()
{
// This is an Optimization
// If we are in PP then we already know all the shrinkage information
// so just transfer it to the PrintData and we will skip the extra shrinkage reflow
//
// doSetPixelScale tells Reflow whether to set the shrinkage value into the DC
// The first time we do not want to do this, the second time through we do
bool doSetPixelScale = false;
bool ppIsShrinkToFit = mPrtPreview && mPrtPreview->mShrinkToFit;
if (ppIsShrinkToFit) {
mPrt->mShrinkRatio = mPrtPreview->mShrinkRatio;
doSetPixelScale = true;
}
return doSetPixelScale;
}
nsIView*
nsPrintEngine::GetParentViewForRoot()
{
if (mIsCreatingPrintPreview) {
nsCOMPtr<nsIContentViewer> cv = do_QueryInterface(mDocViewerPrint);
if (cv) {
return cv->FindContainerView();
}
}
return nullptr;
}
nsresult
nsPrintEngine::SetRootView(
nsPrintObject* aPO,
bool& doReturn,
bool& documentIsTopLevel,
nsSize& adjSize
)
{
bool canCreateScrollbars = true;
nsIView* rootView;
nsIView* parentView = nullptr;
doReturn = false;
if (aPO->mParent && aPO->mParent->IsPrintable()) {
nsIFrame* frame = aPO->mContent ? aPO->mContent->GetPrimaryFrame() : nullptr;
// Without a frame, this document can't be displayed; therefore, there is no
// point to reflowing it
if (!frame) {
SetPrintPO(aPO, false);
doReturn = true;
return NS_OK;
}
//XXX If printing supported printing document hierarchies with non-constant
// zoom this would be wrong as we use the same mPrt->mPrintDC for all
// subdocuments.
adjSize = frame->GetContentRect().Size();
documentIsTopLevel = false;
// presshell exists because parent is printable
// the top nsPrintObject's widget will always have scrollbars
if (frame && frame->GetType() == nsGkAtoms::subDocumentFrame) {
nsIView* view = frame->GetView();
NS_ENSURE_TRUE(view, NS_ERROR_FAILURE);
view = view->GetFirstChild();
NS_ENSURE_TRUE(view, NS_ERROR_FAILURE);
parentView = view;
canCreateScrollbars = false;
}
} else {
nscoord pageWidth, pageHeight;
mPrt->mPrintDC->GetDeviceSurfaceDimensions(pageWidth, pageHeight);
adjSize = nsSize(pageWidth, pageHeight);
documentIsTopLevel = true;
parentView = GetParentViewForRoot();
}
if (aPO->mViewManager->GetRootView()) {
// Reuse the root view that is already on the root frame.
rootView = aPO->mViewManager->GetRootView();
// Remove it from its existing parent if necessary
aPO->mViewManager->RemoveChild(rootView);
reinterpret_cast<nsView*>(rootView)->SetParent(reinterpret_cast<nsView*>(parentView));
} else {
// Create a child window of the parent that is our "root view/window"
nsRect tbounds = nsRect(nsPoint(0, 0), adjSize);
rootView = aPO->mViewManager->CreateView(tbounds, parentView);
NS_ENSURE_TRUE(rootView, NS_ERROR_OUT_OF_MEMORY);
}
if (mIsCreatingPrintPreview && documentIsTopLevel) {
aPO->mPresContext->SetPaginatedScrolling(canCreateScrollbars);
}
// Setup hierarchical relationship in view manager
aPO->mViewManager->SetRootView(rootView);
return NS_OK;
}
// Reflow a nsPrintObject
nsresult
nsPrintEngine::ReflowPrintObject(nsPrintObject * aPO)
{
NS_ENSURE_STATE(aPO);
if (!aPO->IsPrintable()) {
return NS_OK;
}
NS_ASSERTION(!aPO->mPresContext, "Recreating prescontext");
// create the PresContext
nsPresContext::nsPresContextType type =
mIsCreatingPrintPreview ? nsPresContext::eContext_PrintPreview:
nsPresContext::eContext_Print;
nsIView* parentView =
aPO->mParent && aPO->mParent->IsPrintable() ? nullptr : GetParentViewForRoot();
aPO->mPresContext = parentView ?
new nsPresContext(aPO->mDocument, type) :
new nsRootPresContext(aPO->mDocument, type);
NS_ENSURE_TRUE(aPO->mPresContext, NS_ERROR_OUT_OF_MEMORY);
aPO->mPresContext->SetPrintSettings(mPrt->mPrintSettings);
// set the presentation context to the value in the print settings
bool printBGColors;
mPrt->mPrintSettings->GetPrintBGColors(&printBGColors);
aPO->mPresContext->SetBackgroundColorDraw(printBGColors);
mPrt->mPrintSettings->GetPrintBGImages(&printBGColors);
aPO->mPresContext->SetBackgroundImageDraw(printBGColors);
// init it with the DC
nsresult rv = aPO->mPresContext->Init(mPrt->mPrintDC);
NS_ENSURE_SUCCESS(rv, rv);
aPO->mViewManager = do_CreateInstance(kViewManagerCID, &rv);
NS_ENSURE_SUCCESS(rv,rv);
rv = aPO->mViewManager->Init(mPrt->mPrintDC);
NS_ENSURE_SUCCESS(rv,rv);
nsStyleSet* styleSet;
rv = mDocViewerPrint->CreateStyleSet(aPO->mDocument, &styleSet);
NS_ENSURE_SUCCESS(rv, rv);
rv = aPO->mDocument->CreateShell(aPO->mPresContext, aPO->mViewManager,
styleSet, getter_AddRefs(aPO->mPresShell));
if (NS_FAILED(rv)) {
delete styleSet;
return rv;
}
styleSet->EndUpdate();
// The pres shell now owns the style set object.
bool doReturn = false;;
bool documentIsTopLevel = false;
nsSize adjSize;
rv = SetRootView(aPO, doReturn, documentIsTopLevel, adjSize);
if (NS_FAILED(rv) || doReturn) {
return rv;
}
PR_PL(("In DV::ReflowPrintObject PO: %p pS: %p (%9s) Setting w,h to %d,%d\n", aPO, aPO->mPresShell.get(),
gFrameTypesStr[aPO->mFrameType], adjSize.width, adjSize.height));
// This docshell stuff is weird; will go away when we stop having multiple
// presentations per document
nsCOMPtr<nsISupports> supps(do_QueryInterface(aPO->mDocShell));
aPO->mPresContext->SetContainer(supps);
aPO->mPresShell->BeginObservingDocument();
aPO->mPresContext->SetPageSize(adjSize);
aPO->mPresContext->SetIsRootPaginatedDocument(documentIsTopLevel);
aPO->mPresContext->SetPageScale(aPO->mZoomRatio);
// Calculate scale factor from printer to screen
float printDPI = float(mPrt->mPrintDC->AppUnitsPerCSSInch()) /
float(mPrt->mPrintDC->AppUnitsPerDevPixel());
aPO->mPresContext->SetPrintPreviewScale(mScreenDPI / printDPI);
if (mIsCreatingPrintPreview && documentIsTopLevel) {
mDocViewerPrint->SetPrintPreviewPresentation(aPO->mViewManager,
aPO->mPresContext,
aPO->mPresShell);
}
rv = aPO->mPresShell->Initialize(adjSize.width, adjSize.height);
NS_ENSURE_SUCCESS(rv, rv);
NS_ASSERTION(aPO->mPresShell, "Presshell should still be here");
// Process the reflow event Initialize posted
aPO->mPresShell->FlushPendingNotifications(Flush_Layout);
rv = UpdateSelectionAndShrinkPrintObject(aPO, documentIsTopLevel);
NS_ENSURE_SUCCESS(rv, rv);
#ifdef EXTENDED_DEBUG_PRINTING
if (kPrintingLogMod && kPrintingLogMod->level == DUMP_LAYOUT_LEVEL) {
char * docStr;
char * urlStr;
GetDocTitleAndURL(aPO, docStr, urlStr);
char filename[256];
sprintf(filename, "print_dump_%d.txt", gDumpFileNameCnt++);
// Dump all the frames and view to a a file
FILE * fd = fopen(filename, "w");
if (fd) {
nsIFrame *theRootFrame =
aPO->mPresShell->FrameManager()->GetRootFrame();
fprintf(fd, "Title: %s\n", docStr?docStr:"");
fprintf(fd, "URL: %s\n", urlStr?urlStr:"");
fprintf(fd, "--------------- Frames ----------------\n");
nsRefPtr<nsRenderingContext> renderingContext;
mPrt->mPrintDocDC->CreateRenderingContext(*getter_AddRefs(renderingContext));
RootFrameList(aPO->mPresContext, fd, 0);
//DumpFrames(fd, aPO->mPresContext, renderingContext, theRootFrame, 0);
fprintf(fd, "---------------------------------------\n\n");
fprintf(fd, "--------------- Views From Root Frame----------------\n");
nsIView* v = theRootFrame->GetView();
if (v) {
v->List(fd);
} else {
printf("View is null!\n");
}
if (docShell) {
fprintf(fd, "--------------- All Views ----------------\n");
DumpViews(docShell, fd);
fprintf(fd, "---------------------------------------\n\n");
}
fclose(fd);
}
if (docStr) nsMemory::Free(docStr);
if (urlStr) nsMemory::Free(urlStr);
}
#endif
return NS_OK;
}
//-------------------------------------------------------
// Figure out how many documents and how many total pages we are printing
void
nsPrintEngine::CalcNumPrintablePages(int32_t& aNumPages)
{
aNumPages = 0;
// Count the number of printable documents
// and printable pages
for (uint32_t i=0; i<mPrt->mPrintDocList.Length(); i++) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
if (po->mPresContext && po->mPresContext->IsRootPaginatedDocument()) {
nsIPageSequenceFrame* pageSequence = po->mPresShell->GetPageSequenceFrame();
nsIFrame * seqFrame = do_QueryFrame(pageSequence);
if (seqFrame) {
nsIFrame* frame = seqFrame->GetFirstPrincipalChild();
while (frame) {
aNumPages++;
frame = frame->GetNextSibling();
}
}
}
}
}
//-----------------------------------------------------------------
//-- Done: Reflow Methods
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//-- Section: Printing Methods
//-----------------------------------------------------------------
//-------------------------------------------------------
// Called for each DocShell that needs to be printed
bool
nsPrintEngine::PrintDocContent(nsPrintObject* aPO, nsresult& aStatus)
{
NS_ASSERTION(aPO, "Pointer is null!");
aStatus = NS_OK;
if (!aPO->mHasBeenPrinted && aPO->IsPrintable()) {
aStatus = DoPrint(aPO);
return true;
}
// If |aPO->mPrintAsIs| and |aPO->mHasBeenPrinted| are true,
// the kids frames are already processed in |PrintPage|.
if (!aPO->mInvisible && !(aPO->mPrintAsIs && aPO->mHasBeenPrinted)) {
for (uint32_t i=0;i<aPO->mKids.Length();i++) {
nsPrintObject* po = aPO->mKids[i];
bool printed = PrintDocContent(po, aStatus);
if (printed || NS_FAILED(aStatus)) {
return true;
}
}
}
return false;
}
static already_AddRefed<nsIDOMNode>
GetEqualNodeInCloneTree(nsIDOMNode* aNode, nsIDocument* aDoc)
{
nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
// Selections in anonymous subtrees aren't supported.
if (content && content->IsInAnonymousSubtree()) {
return nullptr;
}
nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
NS_ENSURE_TRUE(node, nullptr);
nsTArray<int32_t> indexArray;
nsINode* current = node;
NS_ENSURE_TRUE(current, nullptr);
while (current) {
nsINode* parent = current->GetNodeParent();
if (!parent) {
break;
}
int32_t index = parent->IndexOf(current);
NS_ENSURE_TRUE(index >= 0, nullptr);
indexArray.AppendElement(index);
current = parent;
}
NS_ENSURE_TRUE(current->IsNodeOfType(nsINode::eDOCUMENT), nullptr);
current = aDoc;
for (int32_t i = indexArray.Length() - 1; i >= 0; --i) {
current = current->GetChildAt(indexArray[i]);
NS_ENSURE_TRUE(current, nullptr);
}
nsCOMPtr<nsIDOMNode> result = do_QueryInterface(current);
return result.forget();
}
static nsresult CloneRangeToSelection(nsIDOMRange* aRange,
nsIDocument* aDoc,
nsISelection* aSelection)
{
bool collapsed = false;
aRange->GetCollapsed(&collapsed);
if (collapsed) {
return NS_OK;
}
nsCOMPtr<nsIDOMNode> startContainer, endContainer;
int32_t startOffset = -1, endOffset = -1;
aRange->GetStartContainer(getter_AddRefs(startContainer));
aRange->GetStartOffset(&startOffset);
aRange->GetEndContainer(getter_AddRefs(endContainer));
aRange->GetEndOffset(&endOffset);
NS_ENSURE_STATE(startContainer && endContainer);
nsCOMPtr<nsIDOMNode> newStart = GetEqualNodeInCloneTree(startContainer, aDoc);
nsCOMPtr<nsIDOMNode> newEnd = GetEqualNodeInCloneTree(endContainer, aDoc);
NS_ENSURE_STATE(newStart && newEnd);
nsRefPtr<nsRange> range = new nsRange();
nsresult rv = range->SetStart(newStart, startOffset);
NS_ENSURE_SUCCESS(rv, rv);
rv = range->SetEnd(newEnd, endOffset);
NS_ENSURE_SUCCESS(rv, rv);
return aSelection->AddRange(range);
}
static nsresult CloneSelection(nsIDocument* aOrigDoc, nsIDocument* aDoc)
{
nsIPresShell* origShell = aOrigDoc->GetShell();
nsIPresShell* shell = aDoc->GetShell();
NS_ENSURE_STATE(origShell && shell);
nsCOMPtr<nsISelection> origSelection =
origShell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
nsCOMPtr<nsISelection> selection =
shell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
NS_ENSURE_STATE(origSelection && selection);
int32_t rangeCount = 0;
origSelection->GetRangeCount(&rangeCount);
for (int32_t i = 0; i < rangeCount; ++i) {
nsCOMPtr<nsIDOMRange> range;
origSelection->GetRangeAt(i, getter_AddRefs(range));
if (range) {
CloneRangeToSelection(range, aDoc, selection);
}
}
return NS_OK;
}
//-------------------------------------------------------
nsresult
nsPrintEngine::DoPrint(nsPrintObject * aPO)
{
PR_PL(("\n"));
PR_PL(("**************************** %s ****************************\n", gFrameTypesStr[aPO->mFrameType]));
PR_PL(("****** In DV::DoPrint PO: %p \n", aPO));
nsIPresShell* poPresShell = aPO->mPresShell;
nsPresContext* poPresContext = aPO->mPresContext;
NS_ASSERTION(poPresContext, "PrintObject has not been reflowed");
NS_ASSERTION(poPresContext->Type() != nsPresContext::eContext_PrintPreview,
"How did this context end up here?");
if (mPrt->mPrintProgressParams) {
SetDocAndURLIntoProgress(aPO, mPrt->mPrintProgressParams);
}
{
int16_t printRangeType = nsIPrintSettings::kRangeAllPages;
nsresult rv;
if (mPrt->mPrintSettings != nullptr) {
mPrt->mPrintSettings->GetPrintRange(&printRangeType);
}
// Ask the page sequence frame to print all the pages
nsIPageSequenceFrame* pageSequence = poPresShell->GetPageSequenceFrame();
NS_ASSERTION(nullptr != pageSequence, "no page sequence frame");
// We are done preparing for printing, so we can turn this off
mPrt->mPreparingForPrint = false;
// mPrt->mDebugFilePtr this is onlu non-null when compiled for debugging
if (nullptr != mPrt->mDebugFilePtr) {
#ifdef DEBUG
// output the regression test
nsIFrame* root = poPresShell->FrameManager()->GetRootFrame();
root->DumpRegressionData(poPresContext, mPrt->mDebugFilePtr, 0);
fclose(mPrt->mDebugFilePtr);
SetIsPrinting(false);
#endif
} else {
#ifdef EXTENDED_DEBUG_PRINTING
nsIFrame* rootFrame = poPresShell->FrameManager()->GetRootFrame();
if (aPO->IsPrintable()) {
char * docStr;
char * urlStr;
GetDocTitleAndURL(aPO, docStr, urlStr);
DumpLayoutData(docStr, urlStr, poPresContext, mPrt->mPrintDocDC, rootFrame, docShell, nullptr);
if (docStr) nsMemory::Free(docStr);
if (urlStr) nsMemory::Free(urlStr);
}
#endif
if (!mPrt->mPrintSettings) {
// not sure what to do here!
SetIsPrinting(false);
return NS_ERROR_FAILURE;
}
PRUnichar * docTitleStr = nullptr;
PRUnichar * docURLStr = nullptr;
GetDisplayTitleAndURL(aPO, &docTitleStr, &docURLStr, eDocTitleDefBlank);
if (nsIPrintSettings::kRangeSelection == printRangeType) {
CloneSelection(aPO->mDocument->GetOriginalDocument(), aPO->mDocument);
poPresContext->SetIsRenderingOnlySelection(true);
// temporarily creating rendering context
// which is needed to find the selection frames
nsRefPtr<nsRenderingContext> rc;
mPrt->mPrintDC->CreateRenderingContext(*getter_AddRefs(rc));
// find the starting and ending page numbers
// via the selection
nsIFrame* startFrame;
nsIFrame* endFrame;
int32_t startPageNum;
int32_t endPageNum;
nsRect startRect;
nsRect endRect;
nsCOMPtr<nsISelection> selectionPS;
selectionPS = poPresShell->GetCurrentSelection(nsISelectionController::SELECTION_NORMAL);
rv = GetPageRangeForSelection(poPresShell, poPresContext, *rc, selectionPS, pageSequence,
&startFrame, startPageNum, startRect,
&endFrame, endPageNum, endRect);
if (NS_SUCCEEDED(rv)) {
mPrt->mPrintSettings->SetStartPageRange(startPageNum);
mPrt->mPrintSettings->SetEndPageRange(endPageNum);
nsIntMargin marginTwips(0,0,0,0);
nsIntMargin unwrtMarginTwips(0,0,0,0);
mPrt->mPrintSettings->GetMarginInTwips(marginTwips);
mPrt->mPrintSettings->GetUnwriteableMarginInTwips(unwrtMarginTwips);
nsMargin totalMargin = poPresContext->CSSTwipsToAppUnits(marginTwips +
unwrtMarginTwips);
if (startPageNum == endPageNum) {
startRect.y -= totalMargin.top;
endRect.y -= totalMargin.top;
// Clip out selection regions above the top of the first page
if (startRect.y < 0) {
// Reduce height to be the height of the positive-territory
// region of original rect
startRect.height = NS_MAX(0, startRect.YMost());
startRect.y = 0;
}
if (endRect.y < 0) {
// Reduce height to be the height of the positive-territory
// region of original rect
endRect.height = NS_MAX(0, endRect.YMost());
endRect.y = 0;
}
NS_ASSERTION(endRect.y >= startRect.y,
"Selection end point should be after start point");
NS_ASSERTION(startRect.height >= 0,
"rect should have non-negative height.");
NS_ASSERTION(endRect.height >= 0,
"rect should have non-negative height.");
nscoord selectionHgt = endRect.y + endRect.height - startRect.y;
// XXX This is temporary fix for printing more than one page of a selection
pageSequence->SetSelectionHeight(startRect.y * aPO->mZoomRatio,
selectionHgt * aPO->mZoomRatio);
// calc total pages by getting calculating the selection's height
// and then dividing it by how page content frames will fit.
nscoord pageWidth, pageHeight;
mPrt->mPrintDC->GetDeviceSurfaceDimensions(pageWidth, pageHeight);
pageHeight -= totalMargin.top + totalMargin.bottom;
int32_t totalPages = NSToIntCeil(float(selectionHgt) * aPO->mZoomRatio / float(pageHeight));
pageSequence->SetTotalNumPages(totalPages);
}
}
}
nsIFrame * seqFrame = do_QueryFrame(pageSequence);
if (!seqFrame) {
SetIsPrinting(false);
if (docTitleStr) nsMemory::Free(docTitleStr);
if (docURLStr) nsMemory::Free(docURLStr);
return NS_ERROR_FAILURE;
}
mPageSeqFrame = pageSequence;
mPageSeqFrame->StartPrint(poPresContext, mPrt->mPrintSettings, docTitleStr, docURLStr);
// Schedule Page to Print
PR_PL(("Scheduling Print of PO: %p (%s) \n", aPO, gFrameTypesStr[aPO->mFrameType]));
StartPagePrintTimer(aPO);
}
}
return NS_OK;
}
//---------------------------------------------------------------------
void
nsPrintEngine::SetDocAndURLIntoProgress(nsPrintObject* aPO,
nsIPrintProgressParams* aParams)
{
NS_ASSERTION(aPO, "Must have vaild nsPrintObject");
NS_ASSERTION(aParams, "Must have vaild nsIPrintProgressParams");
if (!aPO || !aPO->mDocShell || !aParams) {
return;
}
const uint32_t kTitleLength = 64;
PRUnichar * docTitleStr;
PRUnichar * docURLStr;
GetDisplayTitleAndURL(aPO, &docTitleStr, &docURLStr, eDocTitleDefURLDoc);
// Make sure the Titles & URLS don't get too long for the progress dialog
ElipseLongString(docTitleStr, kTitleLength, false);
ElipseLongString(docURLStr, kTitleLength, true);
aParams->SetDocTitle(docTitleStr);
aParams->SetDocURL(docURLStr);
if (docTitleStr != nullptr) nsMemory::Free(docTitleStr);
if (docURLStr != nullptr) nsMemory::Free(docURLStr);
}
//---------------------------------------------------------------------
void
nsPrintEngine::ElipseLongString(PRUnichar *& aStr, const uint32_t aLen, bool aDoFront)
{
// Make sure the URLS don't get too long for the progress dialog
if (aStr && NS_strlen(aStr) > aLen) {
if (aDoFront) {
PRUnichar * ptr = &aStr[NS_strlen(aStr) - aLen + 3];
nsAutoString newStr;
newStr.AppendLiteral("...");
newStr += ptr;
nsMemory::Free(aStr);
aStr = ToNewUnicode(newStr);
} else {
nsAutoString newStr(aStr);
newStr.SetLength(aLen-3);
newStr.AppendLiteral("...");
nsMemory::Free(aStr);
aStr = ToNewUnicode(newStr);
}
}
}
static bool
DocHasPrintCallbackCanvas(nsIDocument* aDoc, void* aData)
{
if (!aDoc) {
return true;
}
Element* root = aDoc->GetRootElement();
if (!root) {
return true;
}
nsRefPtr<nsContentList> canvases = NS_GetContentList(root,
kNameSpaceID_XHTML,
NS_LITERAL_STRING("canvas"));
uint32_t canvasCount = canvases->Length(true);
for (uint32_t i = 0; i < canvasCount; ++i) {
nsCOMPtr<nsIDOMHTMLCanvasElement> canvas = do_QueryInterface(canvases->Item(i, false));
nsCOMPtr<nsIPrintCallback> printCallback;
if (canvas && NS_SUCCEEDED(canvas->GetMozPrintCallback(getter_AddRefs(printCallback))) &&
printCallback) {
// This subdocument has a print callback. Set result and return false to
// stop iteration.
*static_cast<bool*>(aData) = true;
return false;
}
}
return true;
}
static bool
DocHasPrintCallbackCanvas(nsIDocument* aDoc)
{
bool result = false;
aDoc->EnumerateSubDocuments(&DocHasPrintCallbackCanvas, static_cast<void*>(&result));
return result;
}
/**
* Checks to see if the document this print engine is associated with has any
* canvases that have a mozPrintCallback.
*/
bool
nsPrintEngine::HasPrintCallbackCanvas()
{
if (!mDocument) {
return false;
}
// First check this mDocument.
bool result = false;
DocHasPrintCallbackCanvas(mDocument, static_cast<void*>(&result));
// Also check the sub documents.
return result || DocHasPrintCallbackCanvas(mDocument);
}
//-------------------------------------------------------
bool
nsPrintEngine::PrePrintPage()
{
NS_ASSERTION(mPageSeqFrame, "mPageSeqFrame is null!");
NS_ASSERTION(mPrt, "mPrt is null!");
// Although these should NEVER be NULL
// This is added insurance, to make sure we don't crash in optimized builds
if (!mPrt || !mPageSeqFrame) {
return true; // means we are done preparing the page.
}
// Check setting to see if someone request it be cancelled
bool isCancelled = false;
mPrt->mPrintSettings->GetIsCancelled(&isCancelled);
if (isCancelled)
return true;
// Ask mPageSeqFrame if the page is ready to be printed.
// If the page doesn't get printed at all, the |done| will be |true|.
bool done = false;
nsresult rv = mPageSeqFrame->PrePrintNextPage(mPagePrintTimer, &done);
if (NS_FAILED(rv)) {
// ??? ::PrintPage doesn't set |mPrt->mIsAborted = true| if rv != NS_ERROR_ABORT,
// but I don't really understand why this should be the right thing to do?
// Shouldn't |mPrt->mIsAborted| set to true all the time if something
// wents wrong?
if (rv != NS_ERROR_ABORT) {
ShowPrintErrorDialog(rv);
mPrt->mIsAborted = true;
}
done = true;
}
return done;
}
bool
nsPrintEngine::PrintPage(nsPrintObject* aPO,
bool& aInRange)
{
NS_ASSERTION(aPO, "aPO is null!");
NS_ASSERTION(mPageSeqFrame, "mPageSeqFrame is null!");
NS_ASSERTION(mPrt, "mPrt is null!");
// Although these should NEVER be NULL
// This is added insurance, to make sure we don't crash in optimized builds
if (!mPrt || !aPO || !mPageSeqFrame) {
ShowPrintErrorDialog(NS_ERROR_FAILURE);
return true; // means we are done printing
}
PR_PL(("-----------------------------------\n"));
PR_PL(("------ In DV::PrintPage PO: %p (%s)\n", aPO, gFrameTypesStr[aPO->mFrameType]));
// Check setting to see if someone request it be cancelled
bool isCancelled = false;
mPrt->mPrintSettings->GetIsCancelled(&isCancelled);
if (isCancelled || mPrt->mIsAborted)
return true;
int32_t pageNum, numPages, endPage;
mPageSeqFrame->GetCurrentPageNum(&pageNum);
mPageSeqFrame->GetNumPages(&numPages);
bool donePrinting;
bool isDoingPrintRange;
mPageSeqFrame->IsDoingPrintRange(&isDoingPrintRange);
if (isDoingPrintRange) {
int32_t fromPage;
int32_t toPage;
mPageSeqFrame->GetPrintRange(&fromPage, &toPage);
if (fromPage > numPages) {
return true;
}
if (toPage > numPages) {
toPage = numPages;
}
PR_PL(("****** Printing Page %d printing from %d to page %d\n", pageNum, fromPage, toPage));
donePrinting = pageNum >= toPage;
aInRange = pageNum >= fromPage && pageNum <= toPage;
endPage = (toPage - fromPage)+1;
} else {
PR_PL(("****** Printing Page %d of %d page(s)\n", pageNum, numPages));
donePrinting = pageNum >= numPages;
endPage = numPages;
aInRange = true;
}
// XXX This is wrong, but the actual behavior in the presence of a print
// range sucks.
if (mPrt->mPrintFrameType == nsIPrintSettings::kEachFrameSep)
endPage = mPrt->mNumPrintablePages;
mPrt->DoOnProgressChange(++mPrt->mNumPagesPrinted, endPage, false, 0);
// Print the Page
// if a print job was cancelled externally, an EndPage or BeginPage may
// fail and the failure is passed back here.
// Returning true means we are done printing.
//
// When rv == NS_ERROR_ABORT, it means we want out of the
// print job without displaying any error messages
nsresult rv = mPageSeqFrame->PrintNextPage();
if (NS_FAILED(rv)) {
if (rv != NS_ERROR_ABORT) {
ShowPrintErrorDialog(rv);
mPrt->mIsAborted = true;
}
return true;
}
mPageSeqFrame->DoPageEnd();
return donePrinting;
}
/** ---------------------------------------------------
* Find by checking frames type
*/
nsresult
nsPrintEngine::FindSelectionBoundsWithList(nsPresContext* aPresContext,
nsRenderingContext& aRC,
nsFrameList::Enumerator& aChildFrames,
nsIFrame * aParentFrame,
nsRect& aRect,
nsIFrame *& aStartFrame,
nsRect& aStartRect,
nsIFrame *& aEndFrame,
nsRect& aEndRect)
{
NS_ASSERTION(aPresContext, "Pointer is null!");
NS_ASSERTION(aParentFrame, "Pointer is null!");
aRect += aParentFrame->GetPosition();
for (; !aChildFrames.AtEnd(); aChildFrames.Next()) {
nsIFrame* child = aChildFrames.get();
if (child->IsSelected() && child->IsVisibleForPainting()) {
nsRect r = child->GetRect();
if (aStartFrame == nullptr) {
aStartFrame = child;
aStartRect.SetRect(aRect.x + r.x, aRect.y + r.y, r.width, r.height);
} else {
aEndFrame = child;
aEndRect.SetRect(aRect.x + r.x, aRect.y + r.y, r.width, r.height);
}
}
FindSelectionBounds(aPresContext, aRC, child, aRect, aStartFrame, aStartRect, aEndFrame, aEndRect);
child = child->GetNextSibling();
}
aRect -= aParentFrame->GetPosition();
return NS_OK;
}
//-------------------------------------------------------
// Find the Frame that is XMost
nsresult
nsPrintEngine::FindSelectionBounds(nsPresContext* aPresContext,
nsRenderingContext& aRC,
nsIFrame * aParentFrame,
nsRect& aRect,
nsIFrame *& aStartFrame,
nsRect& aStartRect,
nsIFrame *& aEndFrame,
nsRect& aEndRect)
{
NS_ASSERTION(aPresContext, "Pointer is null!");
NS_ASSERTION(aParentFrame, "Pointer is null!");
// loop through named child lists
nsIFrame::ChildListIterator lists(aParentFrame);
for (; !lists.IsDone(); lists.Next()) {
nsFrameList::Enumerator childFrames(lists.CurrentList());
nsresult rv = FindSelectionBoundsWithList(aPresContext, aRC, childFrames, aParentFrame, aRect, aStartFrame, aStartRect, aEndFrame, aEndRect);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
/** ---------------------------------------------------
* This method finds the starting and ending page numbers
* of the selection and also returns rect for each where
* the x,y of the rect is relative to the very top of the
* frame tree (absolutely positioned)
*/
nsresult
nsPrintEngine::GetPageRangeForSelection(nsIPresShell * aPresShell,
nsPresContext* aPresContext,
nsRenderingContext& aRC,
nsISelection* aSelection,
nsIPageSequenceFrame* aPageSeqFrame,
nsIFrame** aStartFrame,
int32_t& aStartPageNum,
nsRect& aStartRect,
nsIFrame** aEndFrame,
int32_t& aEndPageNum,
nsRect& aEndRect)
{
NS_ASSERTION(aPresShell, "Pointer is null!");
NS_ASSERTION(aPresContext, "Pointer is null!");
NS_ASSERTION(aSelection, "Pointer is null!");
NS_ASSERTION(aPageSeqFrame, "Pointer is null!");
NS_ASSERTION(aStartFrame, "Pointer is null!");
NS_ASSERTION(aEndFrame, "Pointer is null!");
nsIFrame * seqFrame = do_QueryFrame(aPageSeqFrame);
if (!seqFrame) {
return NS_ERROR_FAILURE;
}
nsIFrame * startFrame = nullptr;
nsIFrame * endFrame = nullptr;
// start out with the sequence frame and search the entire frame tree
// capturing the starting and ending child frames of the selection
// and their rects
nsRect r = seqFrame->GetRect();
FindSelectionBounds(aPresContext, aRC, seqFrame, r,
startFrame, aStartRect, endFrame, aEndRect);
#ifdef DEBUG_rodsX
printf("Start Frame: %p\n", startFrame);
printf("End Frame: %p\n", endFrame);
#endif
// initial the page numbers here
// in case we don't find and frames
aStartPageNum = -1;
aEndPageNum = -1;
nsIFrame * startPageFrame;
nsIFrame * endPageFrame;
// check to make sure we found a starting frame
if (startFrame != nullptr) {
// Now search up the tree to find what page the
// start/ending selections frames are on
//
// Check to see if start should be same as end if
// the end frame comes back null
if (endFrame == nullptr) {
// XXX the "GetPageFrame" step could be integrated into
// the FindSelectionBounds step, but walking up to find
// the parent of a child frame isn't expensive and it makes
// FindSelectionBounds a little easier to understand
startPageFrame = nsLayoutUtils::GetPageFrame(startFrame);
endPageFrame = startPageFrame;
aEndRect = aStartRect;
} else {
startPageFrame = nsLayoutUtils::GetPageFrame(startFrame);
endPageFrame = nsLayoutUtils::GetPageFrame(endFrame);
}
} else {
return NS_ERROR_FAILURE;
}
#ifdef DEBUG_rodsX
printf("Start Page: %p\n", startPageFrame);
printf("End Page: %p\n", endPageFrame);
// dump all the pages and their pointers
{
int32_t pageNum = 1;
nsIFrame* child = seqFrame->GetFirstPrincipalChild();
while (child != nullptr) {
printf("Page: %d - %p\n", pageNum, child);
pageNum++;
child = child->GetNextSibling();
}
}
#endif
// Now that we have the page frames
// find out what the page numbers are for each frame
int32_t pageNum = 1;
nsIFrame* page = seqFrame->GetFirstPrincipalChild();
while (page != nullptr) {
if (page == startPageFrame) {
aStartPageNum = pageNum;
}
if (page == endPageFrame) {
aEndPageNum = pageNum;
}
pageNum++;
page = page->GetNextSibling();
}
#ifdef DEBUG_rodsX
printf("Start Page No: %d\n", aStartPageNum);
printf("End Page No: %d\n", aEndPageNum);
#endif
*aStartFrame = startPageFrame;
*aEndFrame = endPageFrame;
return NS_OK;
}
//-----------------------------------------------------------------
//-- Done: Printing Methods
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//-- Section: Misc Support Methods
//-----------------------------------------------------------------
//---------------------------------------------------------------------
void nsPrintEngine::SetIsPrinting(bool aIsPrinting)
{
mIsDoingPrinting = aIsPrinting;
// Calling SetIsPrinting while in print preview confuses the document viewer
// This is safe because we prevent exiting print preview while printing
if (!mIsDoingPrintPreview && mDocViewerPrint) {
mDocViewerPrint->SetIsPrinting(aIsPrinting);
}
if (mPrt && aIsPrinting) {
mPrt->mPreparingForPrint = true;
}
}
//---------------------------------------------------------------------
void nsPrintEngine::SetIsPrintPreview(bool aIsPrintPreview)
{
mIsDoingPrintPreview = aIsPrintPreview;
if (mDocViewerPrint) {
mDocViewerPrint->SetIsPrintPreview(aIsPrintPreview);
}
}
//---------------------------------------------------------------------
void
nsPrintEngine::CleanupDocTitleArray(PRUnichar**& aArray, int32_t& aCount)
{
for (int32_t i = aCount - 1; i >= 0; i--) {
nsMemory::Free(aArray[i]);
}
nsMemory::Free(aArray);
aArray = NULL;
aCount = 0;
}
//---------------------------------------------------------------------
// static
bool nsPrintEngine::HasFramesetChild(nsIContent* aContent)
{
if (!aContent) {
return false;
}
// do a breadth search across all siblings
for (nsIContent* child = aContent->GetFirstChild();
child;
child = child->GetNextSibling()) {
if (child->IsHTML(nsGkAtoms::frameset)) {
return true;
}
}
return false;
}
/** ---------------------------------------------------
* Get the Focused Frame for a documentviewer
*/
already_AddRefed<nsIDOMWindow>
nsPrintEngine::FindFocusedDOMWindow()
{
nsIFocusManager* fm = nsFocusManager::GetFocusManager();
NS_ENSURE_TRUE(fm, nullptr);
nsCOMPtr<nsPIDOMWindow> window(mDocument->GetWindow());
NS_ENSURE_TRUE(window, nullptr);
nsCOMPtr<nsPIDOMWindow> rootWindow = window->GetPrivateRoot();
NS_ENSURE_TRUE(rootWindow, nullptr);
nsPIDOMWindow* focusedWindow;
nsFocusManager::GetFocusedDescendant(rootWindow, true, &focusedWindow);
NS_ENSURE_TRUE(focusedWindow, nullptr);
if (IsWindowsInOurSubTree(focusedWindow)) {
return focusedWindow;
}
NS_IF_RELEASE(focusedWindow);
return nullptr;
}
//---------------------------------------------------------------------
bool
nsPrintEngine::IsWindowsInOurSubTree(nsPIDOMWindow * window)
{
bool found = false;
// now check to make sure it is in "our" tree of docshells
if (window) {
nsCOMPtr<nsIDocShellTreeItem> docShellAsItem =
do_QueryInterface(window->GetDocShell());
if (docShellAsItem) {
// get this DocViewer docshell
nsCOMPtr<nsIDocShell> thisDVDocShell(do_QueryReferent(mContainer));
while (!found) {
nsCOMPtr<nsIDocShell> parentDocshell(do_QueryInterface(docShellAsItem));
if (parentDocshell) {
if (parentDocshell == thisDVDocShell) {
found = true;
break;
}
} else {
break; // at top of tree
}
nsCOMPtr<nsIDocShellTreeItem> docShellParent;
docShellAsItem->GetSameTypeParent(getter_AddRefs(docShellParent));
docShellAsItem = docShellParent;
} // while
}
} // scriptobj
return found;
}
//-------------------------------------------------------
bool
nsPrintEngine::DonePrintingPages(nsPrintObject* aPO, nsresult aResult)
{
//NS_ASSERTION(aPO, "Pointer is null!");
PR_PL(("****** In DV::DonePrintingPages PO: %p (%s)\n", aPO, aPO?gFrameTypesStr[aPO->mFrameType]:""));
// If there is a pageSeqFrame, make sure there are no more printCanvas active
// that might call |Notify| on the pagePrintTimer after things are cleaned up
// and printing was marked as being done.
if (mPageSeqFrame) {
mPageSeqFrame->ResetPrintCanvasList();
}
if (aPO && !mPrt->mIsAborted) {
aPO->mHasBeenPrinted = true;
nsresult rv;
bool didPrint = PrintDocContent(mPrt->mPrintObject, rv);
if (NS_SUCCEEDED(rv) && didPrint) {
PR_PL(("****** In DV::DonePrintingPages PO: %p (%s) didPrint:%s (Not Done Printing)\n", aPO, gFrameTypesStr[aPO->mFrameType], PRT_YESNO(didPrint)));
return false;
}
}
if (NS_SUCCEEDED(aResult)) {
FirePrintCompletionEvent();
}
TurnScriptingOn(true);
SetIsPrinting(false);
// Release reference to mPagePrintTimer; the timer object destroys itself
// after this returns true
NS_IF_RELEASE(mPagePrintTimer);
return true;
}
//-------------------------------------------------------
// Recursively sets the PO items to be printed "As Is"
// from the given item down into the tree
void
nsPrintEngine::SetPrintAsIs(nsPrintObject* aPO, bool aAsIs)
{
NS_ASSERTION(aPO, "Pointer is null!");
aPO->mPrintAsIs = aAsIs;
for (uint32_t i=0;i<aPO->mKids.Length();i++) {
SetPrintAsIs(aPO->mKids[i], aAsIs);
}
}
//-------------------------------------------------------
// Given a DOMWindow it recursively finds the PO object that matches
nsPrintObject*
nsPrintEngine::FindPrintObjectByDOMWin(nsPrintObject* aPO,
nsIDOMWindow* aDOMWin)
{
NS_ASSERTION(aPO, "Pointer is null!");
// Often the CurFocused DOMWindow is passed in
// andit is valid for it to be null, so short circut
if (!aDOMWin) {
return nullptr;
}
nsCOMPtr<nsIDOMDocument> domDoc;
aDOMWin->GetDocument(getter_AddRefs(domDoc));
nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
if (aPO->mDocument && aPO->mDocument->GetOriginalDocument() == doc) {
return aPO;
}
int32_t cnt = aPO->mKids.Length();
for (int32_t i = 0; i < cnt; ++i) {
nsPrintObject* po = FindPrintObjectByDOMWin(aPO->mKids[i], aDOMWin);
if (po) {
return po;
}
}
return nullptr;
}
//-------------------------------------------------------
nsresult
nsPrintEngine::EnablePOsForPrinting()
{
// NOTE: All POs have been "turned off" for printing
// this is where we decided which POs get printed.
mPrt->mSelectedPO = nullptr;
if (mPrt->mPrintSettings == nullptr) {
return NS_ERROR_FAILURE;
}
mPrt->mPrintFrameType = nsIPrintSettings::kNoFrames;
mPrt->mPrintSettings->GetPrintFrameType(&mPrt->mPrintFrameType);
int16_t printHowEnable = nsIPrintSettings::kFrameEnableNone;
mPrt->mPrintSettings->GetHowToEnableFrameUI(&printHowEnable);
int16_t printRangeType = nsIPrintSettings::kRangeAllPages;
mPrt->mPrintSettings->GetPrintRange(&printRangeType);
PR_PL(("\n"));
PR_PL(("********* nsPrintEngine::EnablePOsForPrinting *********\n"));
PR_PL(("PrintFrameType: %s \n", gPrintFrameTypeStr[mPrt->mPrintFrameType]));
PR_PL(("HowToEnableFrameUI: %s \n", gFrameHowToEnableStr[printHowEnable]));
PR_PL(("PrintRange: %s \n", gPrintRangeStr[printRangeType]));
PR_PL(("----\n"));
// ***** This is the ultimate override *****
// if we are printing the selection (either an IFrame or selection range)
// then set the mPrintFrameType as if it were the selected frame
if (printRangeType == nsIPrintSettings::kRangeSelection) {
mPrt->mPrintFrameType = nsIPrintSettings::kSelectedFrame;
printHowEnable = nsIPrintSettings::kFrameEnableNone;
}
// This tells us that the "Frame" UI has turned off,
// so therefore there are no FrameSets/Frames/IFrames to be printed
//
// This means there are not FrameSets,
// but the document could contain an IFrame
if (printHowEnable == nsIPrintSettings::kFrameEnableNone) {
// Print all the pages or a sub range of pages
if (printRangeType == nsIPrintSettings::kRangeAllPages ||
printRangeType == nsIPrintSettings::kRangeSpecifiedPageRange) {
SetPrintPO(mPrt->mPrintObject, true);
// Set the children so they are PrinAsIs
// In this case, the children are probably IFrames
if (mPrt->mPrintObject->mKids.Length() > 0) {
for (uint32_t i=0;i<mPrt->mPrintObject->mKids.Length();i++) {
nsPrintObject* po = mPrt->mPrintObject->mKids[i];
NS_ASSERTION(po, "nsPrintObject can't be null!");
SetPrintAsIs(po);
}
// ***** Another override *****
mPrt->mPrintFrameType = nsIPrintSettings::kFramesAsIs;
}
PR_PL(("PrintFrameType: %s \n", gPrintFrameTypeStr[mPrt->mPrintFrameType]));
PR_PL(("HowToEnableFrameUI: %s \n", gFrameHowToEnableStr[printHowEnable]));
PR_PL(("PrintRange: %s \n", gPrintRangeStr[printRangeType]));
return NS_OK;
}
// This means we are either printed a selected IFrame or
// we are printing the current selection
if (printRangeType == nsIPrintSettings::kRangeSelection) {
// If the currentFocusDOMWin can'r be null if something is selected
if (mPrt->mCurrentFocusWin) {
// Find the selected IFrame
nsPrintObject * po = FindPrintObjectByDOMWin(mPrt->mPrintObject, mPrt->mCurrentFocusWin);
if (po != nullptr) {
mPrt->mSelectedPO = po;
// Makes sure all of its children are be printed "AsIs"
SetPrintAsIs(po);
// Now, only enable this POs (the selected PO) and all of its children
SetPrintPO(po, true);
// check to see if we have a range selection,
// as oppose to a insert selection
// this means if the user just clicked on the IFrame then
// there will not be a selection so we want the entire page to print
//
// XXX this is sort of a hack right here to make the page
// not try to reposition itself when printing selection
nsCOMPtr<nsIDOMWindow> domWin =
do_QueryInterface(po->mDocument->GetOriginalDocument()->GetWindow());
if (!IsThereARangeSelection(domWin)) {
printRangeType = nsIPrintSettings::kRangeAllPages;
mPrt->mPrintSettings->SetPrintRange(printRangeType);
}
PR_PL(("PrintFrameType: %s \n", gPrintFrameTypeStr[mPrt->mPrintFrameType]));
PR_PL(("HowToEnableFrameUI: %s \n", gFrameHowToEnableStr[printHowEnable]));
PR_PL(("PrintRange: %s \n", gPrintRangeStr[printRangeType]));
return NS_OK;
}
} else {
for (uint32_t i=0;i<mPrt->mPrintDocList.Length();i++) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
nsCOMPtr<nsIDOMWindow> domWin = do_GetInterface(po->mDocShell);
if (IsThereARangeSelection(domWin)) {
mPrt->mCurrentFocusWin = domWin;
SetPrintPO(po, true);
break;
}
}
return NS_OK;
}
}
}
// check to see if there is a selection when a FrameSet is present
if (printRangeType == nsIPrintSettings::kRangeSelection) {
// If the currentFocusDOMWin can'r be null if something is selected
if (mPrt->mCurrentFocusWin) {
// Find the selected IFrame
nsPrintObject * po = FindPrintObjectByDOMWin(mPrt->mPrintObject, mPrt->mCurrentFocusWin);
if (po != nullptr) {
mPrt->mSelectedPO = po;
// Makes sure all of its children are be printed "AsIs"
SetPrintAsIs(po);
// Now, only enable this POs (the selected PO) and all of its children
SetPrintPO(po, true);
// check to see if we have a range selection,
// as oppose to a insert selection
// this means if the user just clicked on the IFrame then
// there will not be a selection so we want the entire page to print
//
// XXX this is sort of a hack right here to make the page
// not try to reposition itself when printing selection
nsCOMPtr<nsIDOMWindow> domWin =
do_QueryInterface(po->mDocument->GetOriginalDocument()->GetWindow());
if (!IsThereARangeSelection(domWin)) {
printRangeType = nsIPrintSettings::kRangeAllPages;
mPrt->mPrintSettings->SetPrintRange(printRangeType);
}
PR_PL(("PrintFrameType: %s \n", gPrintFrameTypeStr[mPrt->mPrintFrameType]));
PR_PL(("HowToEnableFrameUI: %s \n", gFrameHowToEnableStr[printHowEnable]));
PR_PL(("PrintRange: %s \n", gPrintRangeStr[printRangeType]));
return NS_OK;
}
}
}
// If we are printing "AsIs" then sets all the POs to be printed as is
if (mPrt->mPrintFrameType == nsIPrintSettings::kFramesAsIs) {
SetPrintAsIs(mPrt->mPrintObject);
SetPrintPO(mPrt->mPrintObject, true);
return NS_OK;
}
// If we are printing the selected Frame then
// find that PO for that selected DOMWin and set it all of its
// children to be printed
if (mPrt->mPrintFrameType == nsIPrintSettings::kSelectedFrame) {
if ((mPrt->mIsParentAFrameSet && mPrt->mCurrentFocusWin) || mPrt->mIsIFrameSelected) {
nsPrintObject * po = FindPrintObjectByDOMWin(mPrt->mPrintObject, mPrt->mCurrentFocusWin);
if (po != nullptr) {
mPrt->mSelectedPO = po;
// NOTE: Calling this sets the "po" and
// we don't want to do this for documents that have no children,
// because then the "DoEndPage" gets called and it shouldn't
if (po->mKids.Length() > 0) {
// Makes sure that itself, and all of its children are printed "AsIs"
SetPrintAsIs(po);
}
// Now, only enable this POs (the selected PO) and all of its children
SetPrintPO(po, true);
}
}
return NS_OK;
}
// If we are print each subdoc separately,
// then don't print any of the FraneSet Docs
if (mPrt->mPrintFrameType == nsIPrintSettings::kEachFrameSep) {
SetPrintPO(mPrt->mPrintObject, true);
int32_t cnt = mPrt->mPrintDocList.Length();
for (int32_t i=0;i<cnt;i++) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
if (po->mFrameType == eFrameSet) {
po->mDontPrint = true;
}
}
}
return NS_OK;
}
//-------------------------------------------------------
// Return the nsPrintObject with that is XMost (The widest frameset frame) AND
// contains the XMost (widest) layout frame
nsPrintObject*
nsPrintEngine::FindSmallestSTF()
{
float smallestRatio = 1.0f;
nsPrintObject* smallestPO = nullptr;
for (uint32_t i=0;i<mPrt->mPrintDocList.Length();i++) {
nsPrintObject* po = mPrt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
if (po->mFrameType != eFrameSet && po->mFrameType != eIFrame) {
if (po->mShrinkRatio < smallestRatio) {
smallestRatio = po->mShrinkRatio;
smallestPO = po;
}
}
}
#ifdef EXTENDED_DEBUG_PRINTING
if (smallestPO) printf("*PO: %p Type: %d %10.3f\n", smallestPO, smallestPO->mFrameType, smallestPO->mShrinkRatio);
#endif
return smallestPO;
}
//-------------------------------------------------------
void
nsPrintEngine::TurnScriptingOn(bool aDoTurnOn)
{
if (mIsDoingPrinting && aDoTurnOn && mDocViewerPrint &&
mDocViewerPrint->GetIsPrintPreview()) {
// We don't want to turn scripting on if print preview is shown still after
// printing.
return;
}
nsPrintData* prt = mPrt;
#ifdef NS_PRINT_PREVIEW
if (!prt) {
prt = mPrtPreview;
}
#endif
if (!prt) {
return;
}
NS_ASSERTION(mDocument, "We MUST have a document.");
// First, get the script global object from the document...
for (uint32_t i=0;i<prt->mPrintDocList.Length();i++) {
nsPrintObject* po = prt->mPrintDocList.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
nsIDocument* doc = po->mDocument;
if (!doc) {
continue;
}
// get the script global object
nsIScriptGlobalObject *scriptGlobalObj = doc->GetScriptGlobalObject();
if (scriptGlobalObj) {
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(scriptGlobalObj);
NS_ASSERTION(window, "Can't get nsPIDOMWindow");
nsIScriptContext *scx = scriptGlobalObj->GetContext();
NS_WARN_IF_FALSE(scx, "Can't get nsIScriptContext");
nsresult propThere = NS_PROPTABLE_PROP_NOT_THERE;
doc->GetProperty(nsGkAtoms::scriptEnabledBeforePrintOrPreview,
&propThere);
if (aDoTurnOn) {
if (propThere != NS_PROPTABLE_PROP_NOT_THERE) {
doc->DeleteProperty(nsGkAtoms::scriptEnabledBeforePrintOrPreview);
if (scx) {
scx->SetScriptsEnabled(true, false);
}
window->ResumeTimeouts(false);
}
} else {
// Have to be careful, because people call us over and over again with
// aDoTurnOn == false. So don't set the property if it's already
// set, since in that case we'd set it to the wrong value.
if (propThere == NS_PROPTABLE_PROP_NOT_THERE) {
// Stash the current value of IsScriptEnabled on the document, so
// that layout code running in print preview doesn't get confused.
doc->SetProperty(nsGkAtoms::scriptEnabledBeforePrintOrPreview,
NS_INT32_TO_PTR(doc->IsScriptEnabled()));
if (scx) {
scx->SetScriptsEnabled(false, false);
}
window->SuspendTimeouts(1, false);
}
}
}
}
}
//-----------------------------------------------------------------
//-- Done: Misc Support Methods
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//-- Section: Finishing up or Cleaning up
//-----------------------------------------------------------------
//-----------------------------------------------------------------
void
nsPrintEngine::CloseProgressDialog(nsIWebProgressListener* aWebProgressListener)
{
if (aWebProgressListener) {
aWebProgressListener->OnStateChange(nullptr, nullptr, nsIWebProgressListener::STATE_STOP|nsIWebProgressListener::STATE_IS_DOCUMENT, NS_OK);
}
}
//-----------------------------------------------------------------
nsresult
nsPrintEngine::FinishPrintPreview()
{
nsresult rv = NS_OK;
#ifdef NS_PRINT_PREVIEW
if (!mPrt) {
/* we're already finished with print preview */
return rv;
}
rv = DocumentReadyForPrinting();
SetIsCreatingPrintPreview(false);
/* cleaup on failure + notify user */
if (NS_FAILED(rv)) {
/* cleanup done, let's fire-up an error dialog to notify the user
* what went wrong...
*/
mPrt->OnEndPrinting();
TurnScriptingOn(true);
return rv;
}
// At this point we are done preparing everything
// before it is to be created
if (mIsDoingPrintPreview && mOldPrtPreview) {
delete mOldPrtPreview;
mOldPrtPreview = nullptr;
}
mPrt->OnEndPrinting();
// PrintPreview was built using the mPrt (code reuse)
// then we assign it over
mPrtPreview = mPrt;
mPrt = nullptr;
#endif // NS_PRINT_PREVIEW
return NS_OK;
}
//-----------------------------------------------------------------
//-- Done: Finishing up or Cleaning up
//-----------------------------------------------------------------
/*=============== Timer Related Code ======================*/
nsresult
nsPrintEngine::StartPagePrintTimer(nsPrintObject* aPO)
{
if (!mPagePrintTimer) {
// Get the delay time in between the printing of each page
// this gives the user more time to press cancel
int32_t printPageDelay = 50;
mPrt->mPrintSettings->GetPrintPageDelay(&printPageDelay);
nsRefPtr<nsPagePrintTimer> timer =
new nsPagePrintTimer(this, mDocViewerPrint, printPageDelay);
timer.forget(&mPagePrintTimer);
}
return mPagePrintTimer->Start(aPO);
}
/*=============== nsIObserver Interface ======================*/
NS_IMETHODIMP
nsPrintEngine::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
nsresult rv = NS_ERROR_FAILURE;
rv = InitPrintDocConstruction(true);
if (!mIsDoingPrinting && mPrtPreview) {
mPrtPreview->OnEndPrinting();
}
return rv;
}
//---------------------------------------------------------------
//-- PLEvent Notification
//---------------------------------------------------------------
class nsPrintCompletionEvent : public nsRunnable {
public:
nsPrintCompletionEvent(nsIDocumentViewerPrint *docViewerPrint)
: mDocViewerPrint(docViewerPrint) {
NS_ASSERTION(mDocViewerPrint, "mDocViewerPrint is null.");
}
NS_IMETHOD Run() {
if (mDocViewerPrint)
mDocViewerPrint->OnDonePrinting();
return NS_OK;
}
private:
nsCOMPtr<nsIDocumentViewerPrint> mDocViewerPrint;
};
//-----------------------------------------------------------
void
nsPrintEngine::FirePrintCompletionEvent()
{
nsCOMPtr<nsIRunnable> event = new nsPrintCompletionEvent(mDocViewerPrint);
if (NS_FAILED(NS_DispatchToCurrentThread(event)))
NS_WARNING("failed to dispatch print completion event");
}
//---------------------------------------------------------------
//---------------------------------------------------------------
//-- Debug helper routines
//---------------------------------------------------------------
//---------------------------------------------------------------
#if (defined(XP_WIN) || defined(XP_OS2)) && defined(EXTENDED_DEBUG_PRINTING)
#include "windows.h"
#include "process.h"
#include "direct.h"
#define MY_FINDFIRST(a,b) FindFirstFile(a,b)
#define MY_FINDNEXT(a,b) FindNextFile(a,b)
#define ISDIR(a) (a.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
#define MY_FINDCLOSE(a) FindClose(a)
#define MY_FILENAME(a) a.cFileName
#define MY_FILESIZE(a) (a.nFileSizeHigh * MAXDWORD) + a.nFileSizeLow
int RemoveFilesInDir(const char * aDir)
{
WIN32_FIND_DATA data_ptr;
HANDLE find_handle;
char path[MAX_PATH];
strcpy(path, aDir);
// Append slash to the end of the directory names if not there
if (path[strlen(path)-1] != '\\')
strcat(path, "\\");
char findPath[MAX_PATH];
strcpy(findPath, path);
strcat(findPath, "*.*");
find_handle = MY_FINDFIRST(findPath, &data_ptr);
if (find_handle != INVALID_HANDLE_VALUE) {
do {
if (ISDIR(data_ptr)
&& (stricmp(MY_FILENAME(data_ptr),"."))
&& (stricmp(MY_FILENAME(data_ptr),".."))) {
// skip
}
else if (!ISDIR(data_ptr)) {
if (!strncmp(MY_FILENAME(data_ptr), "print_dump", 10)) {
char fileName[MAX_PATH];
strcpy(fileName, aDir);
strcat(fileName, "\\");
strcat(fileName, MY_FILENAME(data_ptr));
printf("Removing %s\n", fileName);
remove(fileName);
}
}
} while(MY_FINDNEXT(find_handle,&data_ptr));
MY_FINDCLOSE(find_handle);
}
return TRUE;
}
#endif
#ifdef EXTENDED_DEBUG_PRINTING
/** ---------------------------------------------------
* Dumps Frames for Printing
*/
static void RootFrameList(nsPresContext* aPresContext, FILE* out, int32_t aIndent)
{
if (!aPresContext || !out)
return;
nsIPresShell *shell = aPresContext->GetPresShell();
if (shell) {
nsIFrame* frame = shell->FrameManager()->GetRootFrame();
if (frame) {
frame->List(aPresContext, out, aIndent);
}
}
}
/** ---------------------------------------------------
* Dumps Frames for Printing
*/
static void DumpFrames(FILE* out,
nsPresContext* aPresContext,
nsRenderingContext * aRendContext,
nsIFrame * aFrame,
int32_t aLevel)
{
NS_ASSERTION(out, "Pointer is null!");
NS_ASSERTION(aPresContext, "Pointer is null!");
NS_ASSERTION(aRendContext, "Pointer is null!");
NS_ASSERTION(aFrame, "Pointer is null!");
nsIFrame* child = aFrame->GetFirstPrincipalChild();
while (child != nullptr) {
for (int32_t i=0;i<aLevel;i++) {
fprintf(out, " ");
}
nsAutoString tmp;
child->GetFrameName(tmp);
fputs(NS_LossyConvertUTF16toASCII(tmp).get(), out);
bool isSelected;
if (NS_SUCCEEDED(child->IsVisibleForPainting(aPresContext, *aRendContext, true, &isSelected))) {
fprintf(out, " %p %s", child, isSelected?"VIS":"UVS");
nsRect rect = child->GetRect();
fprintf(out, "[%d,%d,%d,%d] ", rect.x, rect.y, rect.width, rect.height);
fprintf(out, "v: %p ", (void*)child->GetView());
fprintf(out, "\n");
DumpFrames(out, aPresContext, aRendContext, child, aLevel+1);
child = child->GetNextSibling();
}
}
}
/** ---------------------------------------------------
* Dumps the Views from the DocShell
*/
static void
DumpViews(nsIDocShell* aDocShell, FILE* out)
{
NS_ASSERTION(aDocShell, "Pointer is null!");
NS_ASSERTION(out, "Pointer is null!");
if (nullptr != aDocShell) {
fprintf(out, "docshell=%p \n", aDocShell);
nsIPresShell* shell = nsPrintEngine::GetPresShellFor(aDocShell);
if (shell) {
nsIViewManager* vm = shell->GetViewManager();
if (vm) {
nsIView* root = vm->GetRootView();
if (root) {
root->List(out);
}
}
}
else {
fputs("null pres shell\n", out);
}
// dump the views of the sub documents
int32_t i, n;
nsCOMPtr<nsIDocShellTreeNode> docShellAsNode(do_QueryInterface(aDocShell));
docShellAsNode->GetChildCount(&n);
for (i = 0; i < n; i++) {
nsCOMPtr<nsIDocShellTreeItem> child;
docShellAsNode->GetChildAt(i, getter_AddRefs(child));
nsCOMPtr<nsIDocShell> childAsShell(do_QueryInterface(child));
if (childAsShell) {
DumpViews(childAsShell, out);
}
}
}
}
/** ---------------------------------------------------
* Dumps the Views and Frames
*/
void DumpLayoutData(char* aTitleStr,
char* aURLStr,
nsPresContext* aPresContext,
nsDeviceContext * aDC,
nsIFrame * aRootFrame,
nsIDocShekk * aDocShell,
FILE* aFD = nullptr)
{
if (!kPrintingLogMod || kPrintingLogMod->level != DUMP_LAYOUT_LEVEL) return;
if (aPresContext == nullptr || aDC == nullptr) {
return;
}
#ifdef NS_PRINT_PREVIEW
if (aPresContext->Type() == nsPresContext::eContext_PrintPreview) {
return;
}
#endif
NS_ASSERTION(aRootFrame, "Pointer is null!");
NS_ASSERTION(aDocShell, "Pointer is null!");
// Dump all the frames and view to a a file
char filename[256];
sprintf(filename, "print_dump_layout_%d.txt", gDumpLOFileNameCnt++);
FILE * fd = aFD?aFD:fopen(filename, "w");
if (fd) {
fprintf(fd, "Title: %s\n", aTitleStr?aTitleStr:"");
fprintf(fd, "URL: %s\n", aURLStr?aURLStr:"");
fprintf(fd, "--------------- Frames ----------------\n");
fprintf(fd, "--------------- Frames ----------------\n");
nsRefPtr<nsRenderingContext> renderingContext;
aDC->CreateRenderingContext(*getter_AddRefs(renderingContext));
RootFrameList(aPresContext, fd, 0);
//DumpFrames(fd, aPresContext, renderingContext, aRootFrame, 0);
fprintf(fd, "---------------------------------------\n\n");
fprintf(fd, "--------------- Views From Root Frame----------------\n");
nsIView* v = aRootFrame->GetView();
if (v) {
v->List(fd);
} else {
printf("View is null!\n");
}
if (aDocShell) {
fprintf(fd, "--------------- All Views ----------------\n");
DumpViews(aDocShell, fd);
fprintf(fd, "---------------------------------------\n\n");
}
if (aFD == nullptr) {
fclose(fd);
}
}
}
//-------------------------------------------------------------
static void DumpPrintObjectsList(nsTArray<nsPrintObject*> * aDocList)
{
if (!kPrintingLogMod || kPrintingLogMod->level != DUMP_LAYOUT_LEVEL) return;
NS_ASSERTION(aDocList, "Pointer is null!");
const char types[][3] = {"DC", "FR", "IF", "FS"};
PR_PL(("Doc List\n***************************************************\n"));
PR_PL(("T P A H PO DocShell Seq Page Root Page# Rect\n"));
int32_t cnt = aDocList->Length();
for (int32_t i=0;i<cnt;i++) {
nsPrintObject* po = aDocList->ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
nsIFrame* rootFrame = nullptr;
if (po->mPresShell) {
rootFrame = po->mPresShell->FrameManager()->GetRootFrame();
while (rootFrame != nullptr) {
nsIPageSequenceFrame * sqf = do_QueryFrame(rootFrame);
if (sqf) {
break;
}
rootFrame = rootFrame->GetFirstPrincipalChild();
}
}
PR_PL(("%s %d %d %d %p %p %p %p %p %d %d,%d,%d,%d\n", types[po->mFrameType],
po->IsPrintable(), po->mPrintAsIs, po->mHasBeenPrinted, po, po->mDocShell.get(), po->mSeqFrame,
po->mPageFrame, rootFrame, po->mPageNum, po->mRect.x, po->mRect.y, po->mRect.width, po->mRect.height));
}
}
//-------------------------------------------------------------
static void DumpPrintObjectsTree(nsPrintObject * aPO, int aLevel, FILE* aFD)
{
if (!kPrintingLogMod || kPrintingLogMod->level != DUMP_LAYOUT_LEVEL) return;
NS_ASSERTION(aPO, "Pointer is null!");
FILE * fd = aFD?aFD:stdout;
const char types[][3] = {"DC", "FR", "IF", "FS"};
if (aLevel == 0) {
fprintf(fd, "DocTree\n***************************************************\n");
fprintf(fd, "T PO DocShell Seq Page Page# Rect\n");
}
int32_t cnt = aPO->mKids.Length();
for (int32_t i=0;i<cnt;i++) {
nsPrintObject* po = aPO->mKids.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
for (int32_t k=0;k<aLevel;k++) fprintf(fd, " ");
fprintf(fd, "%s %p %p %p %p %d %d,%d,%d,%d\n", types[po->mFrameType], po, po->mDocShell.get(), po->mSeqFrame,
po->mPageFrame, po->mPageNum, po->mRect.x, po->mRect.y, po->mRect.width, po->mRect.height);
}
}
//-------------------------------------------------------------
static void GetDocTitleAndURL(nsPrintObject* aPO, char *& aDocStr, char *& aURLStr)
{
aDocStr = nullptr;
aURLStr = nullptr;
PRUnichar * docTitleStr;
PRUnichar * docURLStr;
nsPrintEngine::GetDisplayTitleAndURL(aPO,
&docTitleStr, &docURLStr,
nsPrintEngine::eDocTitleDefURLDoc);
if (docTitleStr) {
nsAutoString strDocTitle(docTitleStr);
aDocStr = ToNewCString(strDocTitle);
nsMemory::Free(docTitleStr);
}
if (docURLStr) {
nsAutoString strURL(docURLStr);
aURLStr = ToNewCString(strURL);
nsMemory::Free(docURLStr);
}
}
//-------------------------------------------------------------
static void DumpPrintObjectsTreeLayout(nsPrintObject * aPO,
nsDeviceContext * aDC,
int aLevel, FILE * aFD)
{
if (!kPrintingLogMod || kPrintingLogMod->level != DUMP_LAYOUT_LEVEL) return;
NS_ASSERTION(aPO, "Pointer is null!");
NS_ASSERTION(aDC, "Pointer is null!");
const char types[][3] = {"DC", "FR", "IF", "FS"};
FILE * fd = nullptr;
if (aLevel == 0) {
fd = fopen("tree_layout.txt", "w");
fprintf(fd, "DocTree\n***************************************************\n");
fprintf(fd, "***************************************************\n");
fprintf(fd, "T PO DocShell Seq Page Page# Rect\n");
} else {
fd = aFD;
}
if (fd) {
nsIFrame* rootFrame = nullptr;
if (aPO->mPresShell) {
rootFrame = aPO->mPresShell->FrameManager()->GetRootFrame();
}
for (int32_t k=0;k<aLevel;k++) fprintf(fd, " ");
fprintf(fd, "%s %p %p %p %p %d %d,%d,%d,%d\n", types[aPO->mFrameType], aPO, aPO->mDocShell.get(), aPO->mSeqFrame,
aPO->mPageFrame, aPO->mPageNum, aPO->mRect.x, aPO->mRect.y, aPO->mRect.width, aPO->mRect.height);
if (aPO->IsPrintable()) {
char * docStr;
char * urlStr;
GetDocTitleAndURL(aPO, docStr, urlStr);
DumpLayoutData(docStr, urlStr, aPO->mPresContext, aDC, rootFrame, aPO->mDocShell, fd);
if (docStr) nsMemory::Free(docStr);
if (urlStr) nsMemory::Free(urlStr);
}
fprintf(fd, "<***************************************************>\n");
int32_t cnt = aPO->mKids.Length();
for (int32_t i=0;i<cnt;i++) {
nsPrintObject* po = aPO->mKids.ElementAt(i);
NS_ASSERTION(po, "nsPrintObject can't be null!");
DumpPrintObjectsTreeLayout(po, aDC, aLevel+1, fd);
}
}
if (aLevel == 0 && fd) {
fclose(fd);
}
}
//-------------------------------------------------------------
static void DumpPrintObjectsListStart(const char * aStr, nsTArray<nsPrintObject*> * aDocList)
{
if (!kPrintingLogMod || kPrintingLogMod->level != DUMP_LAYOUT_LEVEL) return;
NS_ASSERTION(aStr, "Pointer is null!");
NS_ASSERTION(aDocList, "Pointer is null!");
PR_PL(("%s\n", aStr));
DumpPrintObjectsList(aDocList);
}
#define DUMP_DOC_LIST(_title) DumpPrintObjectsListStart((_title), mPrt->mPrintDocList);
#define DUMP_DOC_TREE DumpPrintObjectsTree(mPrt->mPrintObject);
#define DUMP_DOC_TREELAYOUT DumpPrintObjectsTreeLayout(mPrt->mPrintObject, mPrt->mPrintDC);
#else
#define DUMP_DOC_LIST(_title)
#define DUMP_DOC_TREE
#define DUMP_DOC_TREELAYOUT
#endif
//---------------------------------------------------------------
//---------------------------------------------------------------
//-- End of debug helper routines
//---------------------------------------------------------------
| 33.993054 | 154 | 0.634522 | [
"object"
] |
e082d5ed6efcd31d7f6b595709cc6c39dfb5b2bd | 5,199 | hpp | C++ | include/nodamushi/svd/normalized/Cpu.hpp | nodamushi/nsvd-reader | cf3a840aaac78d5791df1cf045596ec20dc03257 | [
"CC0-1.0"
] | null | null | null | include/nodamushi/svd/normalized/Cpu.hpp | nodamushi/nsvd-reader | cf3a840aaac78d5791df1cf045596ec20dc03257 | [
"CC0-1.0"
] | null | null | null | include/nodamushi/svd/normalized/Cpu.hpp | nodamushi/nsvd-reader | cf3a840aaac78d5791df1cf045596ec20dc03257 | [
"CC0-1.0"
] | null | null | null | /*!
@brief normalized CPU and SAU
@file nodamushi/svd/normalized/Cpu.hpp
*/
/*
* These codes are licensed under CC0.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
#ifndef NODAMUSHI_SVD_NORMALIZED_CPU_HPP
#define NODAMUSHI_SVD_NORMALIZED_CPU_HPP
# include <cstdint>
# include "nodamushi/svd/Endian.hpp"
# include "nodamushi/svd/SAURegionConfigProtect.hpp"
# include "nodamushi/svd/ARMCPU.hpp"
# include "nodamushi/svd/normalized/node_container.hpp"
namespace nodamushi{
namespace svd{
namespace normalized{
/**
* @brief Security Attribution Unit(SAU) region.
* @see http://www.keil.com/pack/doc/CMSIS/SVD/html/elem_cpu.html#elem_region
* @see nodamushi::svd::SAURegionsConfigRegion
*/
template<typename STRREF>struct SAURegionsConfigRegion
{
//! @brief attribute enabled
bool enabled;
//! @brief attribute name
STRREF name;
//! @brief <base> element
uint64_t base;
//! @brief <limit> element
uint64_t limit;
//! @brief <access>
SAURegionConfigProtect access;
/**
* @param T nodamushi::svd::SAURegionsConfigRegion
*/
template<typename T> SAURegionsConfigRegion(const T& s)
:enabled(s.enabled.get(true)),
name(s.name.get("")),
base(s.base.get(0)),
limit(s.limit.get(0)),
access(s.access.get(SAURegionConfigProtect{}))
{}
};
/**
* @brief Security Attribution Unit(SAU).
* @see http://www.keil.com/pack/doc/CMSIS/SVD/html/elem_cpu.html#elem_sauRegionsConfig
* @see nodamushi::svd::SAURegionConfig
*/
template<typename STRREF>struct SAURegionsConfig
{
//! @brief attribute enabled
bool enabled;
//! @brief attribute protectionWhenDisabled
SAURegionConfigProtect protectionWhenDisabled;
//! @brief <region> elements.
std::vector<SAURegionsConfigRegion<STRREF>> region;
//! @brief default constructor
SAURegionsConfig():
enabled(false),
protectionWhenDisabled(SAURegionConfigProtect{}),
region{}
{}
private:
template<typename X>friend class Cpu;
template<typename V> void init(const V& v){
if(v){
enabled = v->enabled.get(true);
protectionWhenDisabled=
v->protectionWhenDisabled.get(SAURegionConfigProtect{});
region.reserve(v->region.size());
for(const auto& ss:v->region)
region.emplace_back(ss);
}
}
};
/*!
* @brief <cpu> element
* @see http://www.keil.com/pack/doc/CMSIS/SVD/html/elem_cpu.html
* @see nodamushi::svd::Cpu
*/
template<typename STRREF>struct Cpu
{
/**
* @brief <name> element
* @see nodamushi::svd::ARMCPU
* @see get_armcpu()
*/
STRREF name;
//! @brief <revision> element
STRREF revision;
//! @brief <endian> element
Endian endian;
//! @brief <mpuPresent> element
bool mpuPresent;
//! @brief <fpuPresent> element
bool fpuPresent;
//! @brief <fpuDP> element
bool fpuDP;
//! @brief <dspPresent> element
bool dspPresent;
//! @brief <icachePresent> element
bool icachePresent;
//! @brief <dcachePresent> element
bool dcachePresent;
//! @brief <itcmPresent> element
bool itcmPresent;
//! @brief <dtcmPresent> element
bool dtcmPresent;
//! @brief <vtorPresent> element
bool vtorPresent;
//! @brief <nvicPrioBits> element
uint32_t nvicPrioBits;
//! @brief <vendorSysticConfig> element
bool vendorSystickConfig;
//! @brief <deviceNumInterrupts> element
uint32_t deviceNumInterrupts;
//! @brief <sauNumRegions> element
uint32_t sauNumRegions;
//! @brief <sauRegionsConfig> element
SAURegionsConfig<STRREF> sauRegionsConfig;
//! @brief convert name to ARMCPU enum
ARMCPU get_armcpu()const noexcept{return ::nodamushi::svd::get_cpu_type(name);}
/**
* @brief This constructor is for normalizer.
* @param V nodamushi::svd::value of <cpu>
*/
template<typename V>//V = value
Cpu(const V& v):
name(""),
revision(""),
endian(static_cast<Endian>(0)),
mpuPresent(false),
fpuPresent(false),
fpuDP(false),
dspPresent(false),
icachePresent(false),
dcachePresent(false),
itcmPresent(false),
dtcmPresent(false),
nvicPrioBits(0),
vendorSystickConfig(false),
deviceNumInterrupts(0),
sauNumRegions(0),
sauRegionsConfig()
{
if(v){
name = v->name.get("");
revision = v->revision.get("");
endian = v->endian.get(static_cast<Endian>(0));
mpuPresent = v->mpuPresent.get(false);
fpuPresent = v->fpuPresent.get(false);
fpuDP = v->fpuDP.get(false);
dspPresent = v->dspPresent.get(false);
icachePresent = v->icachePresent.get(false);
dcachePresent = v->dcachePresent.get(false);
itcmPresent = v->itcmPresent.get(false);
dtcmPresent = v->dtcmPresent.get(false);
nvicPrioBits = v->nvicPrioBits.get(0);
vendorSystickConfig = v->vendorSystickConfig.get(false);
deviceNumInterrupts = v->deviceNumInterrupts.get(0);
sauNumRegions = v->sauNumRegions.get(0);
sauRegionsConfig.init(v->sauRegionsConfig);
}
}
};
}}} // end namespace svd
#endif // NODAMUSHI_SVD_NORMALIZED_CPU_HPP
| 27.802139 | 87 | 0.677246 | [
"vector"
] |
e083f502c583986858753ff13b1039421b7e6d20 | 1,829 | cpp | C++ | main.cpp | Gabe-Jespersen/JespGen | cbd34c813868dc705b4682297e248e14078c8610 | [
"BSD-2-Clause"
] | null | null | null | main.cpp | Gabe-Jespersen/JespGen | cbd34c813868dc705b4682297e248e14078c8610 | [
"BSD-2-Clause"
] | null | null | null | main.cpp | Gabe-Jespersen/JespGen | cbd34c813868dc705b4682297e248e14078c8610 | [
"BSD-2-Clause"
] | null | null | null | /*
* =====================================================================================
*
* Filename: main.cpp
*
* Description: gaussian random number generator
*
* Version: 1.0
* Created: 11/28/2015 12:18:30 PM
* Revision: none
* Compiler: gcc
*
* Author: Gabe Jespersen (), gzackwebs@tfwno.gf
*
* =====================================================================================
*/
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <fstream>
#include "parse.h"
#include "gaussian.h"
using namespace std;
int main(int argc, char** argv)
{
srand(time(NULL));//seeding random for gaussian
vector<int> parsed = parse(argc, argv);//for storing settings
double temp;
/*
for(int i = 0; i < parsed.size(); i++)
{
cout << parsed.at(i) << endl;
}
*/
if(parsed.at(4))//if -f flag was used for file output
{
ofstream outputFile;
outputFile.open("output.txt");//opening file
for(int i = 0; i < parsed.at(2); i++)//for every number
{
temp = gaussian(parsed.at(0),parsed.at(1));//generate a random gaussian number
if(parsed.at(3))//if -p flag
{
temp = round(temp);//round
}
outputFile << temp << endl;//append temp to file, followed by newline
}
outputFile.close();
}
else
{
for(int i = 0; i < parsed.at(2); i++)//same as last time
{
temp = gaussian(parsed.at(0),parsed.at(1));
if(parsed.at(3))
{
temp = round(temp);
}
cout << temp << endl;//just outputting here instead of to file
}
}
return 0;
}
| 23.448718 | 90 | 0.472389 | [
"vector"
] |
e084147deb761cf729964212be6da48e236bd762 | 5,301 | cpp | C++ | src/mbgl/renderer/painter_line.cpp | tamaskenez/mapbox-gl-native-cmake | 169e6412fd880278a0fb080826609d305e6d500b | [
"BSD-2-Clause"
] | 1 | 2015-07-01T21:59:13.000Z | 2015-07-01T21:59:13.000Z | src/mbgl/renderer/painter_line.cpp | tamaskenez/mapbox-gl-native-cmake | 169e6412fd880278a0fb080826609d305e6d500b | [
"BSD-2-Clause"
] | null | null | null | src/mbgl/renderer/painter_line.cpp | tamaskenez/mapbox-gl-native-cmake | 169e6412fd880278a0fb080826609d305e6d500b | [
"BSD-2-Clause"
] | null | null | null | #include <mbgl/renderer/painter.hpp>
#include <mbgl/renderer/line_bucket.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/map/tile_id.hpp>
#include <mbgl/shader/line_shader.hpp>
#include <mbgl/shader/linesdf_shader.hpp>
#include <mbgl/shader/linepattern_shader.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
#include <mbgl/geometry/line_atlas.hpp>
using namespace mbgl;
void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const TileID& id, const mat4 &matrix) {
// Abort early.
if (pass == RenderPass::Opaque) return;
config.stencilTest = true;
config.depthTest = true;
config.depthMask = GL_FALSE;
const auto &properties = layer_desc.getProperties<LineProperties>();
const auto &layout = bucket.layout;
// the distance over which the line edge fades out.
// Retina devices need a smaller distance to avoid aliasing.
float antialiasing = 1 / state.getPixelRatio();
float blur = properties.blur + antialiasing;
float edgeWidth = properties.width / 2.0;
float inset = -1;
float offset = 0;
float shift = 0;
if (properties.gap_width != 0) {
inset = properties.gap_width / 2.0 + antialiasing * 0.5;
edgeWidth = properties.width;
// shift outer lines half a pixel towards the middle to eliminate the crack
offset = inset - antialiasing / 2.0;
}
float outset = offset + edgeWidth + antialiasing / 2.0 + shift;
Color color = properties.color;
color[0] *= properties.opacity;
color[1] *= properties.opacity;
color[2] *= properties.opacity;
color[3] *= properties.opacity;
float ratio = state.getPixelRatio();
mat4 vtxMatrix = translatedMatrix(matrix, properties.translate, id, properties.translateAnchor);
config.depthRange = { strata, 1.0f };
if (properties.dash_array.from.size()) {
useProgram(linesdfShader->program);
linesdfShader->u_matrix = vtxMatrix;
linesdfShader->u_exmatrix = extrudeMatrix;
linesdfShader->u_linewidth = {{ outset, inset }};
linesdfShader->u_ratio = ratio;
linesdfShader->u_blur = blur;
linesdfShader->u_color = color;
LinePatternPos posA = lineAtlas->getDashPosition(properties.dash_array.from, layout.cap == CapType::Round);
LinePatternPos posB = lineAtlas->getDashPosition(properties.dash_array.to, layout.cap == CapType::Round);
lineAtlas->bind();
float patternratio = std::pow(2.0, std::floor(std::log2(state.getScale())) - id.z) / 8.0 * id.overscaling;
float scaleXA = patternratio / posA.width / properties.dash_line_width / properties.dash_array.fromScale;
float scaleYA = -posA.height / 2.0;
float scaleXB = patternratio / posB.width / properties.dash_line_width / properties.dash_array.toScale;
float scaleYB = -posB.height / 2.0;
linesdfShader->u_patternscale_a = {{ scaleXA, scaleYA }};
linesdfShader->u_tex_y_a = posA.y;
linesdfShader->u_patternscale_b = {{ scaleXB, scaleYB }};
linesdfShader->u_tex_y_b = posB.y;
linesdfShader->u_image = 0;
linesdfShader->u_sdfgamma = lineAtlas->width / (properties.dash_line_width * std::min(posA.width, posB.width) * 256.0 * state.getPixelRatio()) / 2;
linesdfShader->u_mix = properties.dash_array.t;
bucket.drawLineSDF(*linesdfShader);
} else if (properties.image.from.size()) {
SpriteAtlasPosition imagePosA = spriteAtlas->getPosition(properties.image.from, true);
SpriteAtlasPosition imagePosB = spriteAtlas->getPosition(properties.image.to, true);
float factor = 8.0 / std::pow(2, state.getIntegerZoom() - id.z) * id.overscaling;
useProgram(linepatternShader->program);
linepatternShader->u_matrix = vtxMatrix;
linepatternShader->u_exmatrix = extrudeMatrix;
linepatternShader->u_linewidth = {{ outset, inset }};
linepatternShader->u_ratio = ratio;
linepatternShader->u_blur = blur;
linepatternShader->u_pattern_size_a = {{imagePosA.size[0] * factor * properties.image.fromScale, imagePosA.size[1]}};
linepatternShader->u_pattern_tl_a = imagePosA.tl;
linepatternShader->u_pattern_br_a = imagePosA.br;
linepatternShader->u_pattern_size_b = {{imagePosB.size[0] * factor * properties.image.toScale, imagePosB.size[1]}};
linepatternShader->u_pattern_tl_b = imagePosB.tl;
linepatternShader->u_pattern_br_b = imagePosB.br;
linepatternShader->u_fade = properties.image.t;
linepatternShader->u_opacity = properties.opacity;
MBGL_CHECK_ERROR(glActiveTexture(GL_TEXTURE0));
spriteAtlas->bind(true);
config.depthRange = { strata + strata_epsilon, 1.0f }; // may or may not matter
bucket.drawLinePatterns(*linepatternShader);
} else {
useProgram(lineShader->program);
lineShader->u_matrix = vtxMatrix;
lineShader->u_exmatrix = extrudeMatrix;
lineShader->u_linewidth = {{ outset, inset }};
lineShader->u_ratio = ratio;
lineShader->u_blur = blur;
lineShader->u_color = color;
bucket.drawLines(*lineShader);
}
}
| 40.159091 | 155 | 0.683456 | [
"geometry"
] |
e08fbbc115e79fe8893cc4795025f1e808d25762 | 1,682 | hpp | C++ | src/Intensive/EnvScalarQuantities.hpp | glmcr/NPGTOS | 6b7dee9bb0e8b84c187a1a8ce9cda756c0ce75e3 | [
"MIT"
] | 1 | 2020-05-25T01:16:03.000Z | 2020-05-25T01:16:03.000Z | src/Intensive/EnvScalarQuantities.hpp | glmcr/NPGTOS | 6b7dee9bb0e8b84c187a1a8ce9cda756c0ce75e3 | [
"MIT"
] | null | null | null | src/Intensive/EnvScalarQuantities.hpp | glmcr/NPGTOS | 6b7dee9bb0e8b84c187a1a8ce9cda756c0ce75e3 | [
"MIT"
] | null | null | null | #ifndef _NPGTOSIntensiveEnvScalarQuantities_hpp
#define _NPGTOSIntensiveEnvScalarQuantities_hpp
//---
#include "NPGTOS.hpp"
#include "Core/Core.hpp"
#include "Core/Constants.hpp"
#include "Core/ScalarQuantity.hpp"
#include "Intensive/Intensive.hpp"
//---
using namespace NPGTOS;
//---
class Intensive::EnvScalarQuantities {
private :
protected :
//--- We can consider here that pressure and temperature
// are averages values in a thermodynamic entity.
Core::ScalarQuantity pressure; //--- a.k.a. thermodynamic pressure here equal everywhere
// in a thermodynamic entity i.e. grad(pressure)== 0,0,0 vector.
Core::ScalarQuantity temperature; //--- Equal everywhere in a thermodynamic entity
// i.e. grad(temperature)== (0,0,0) vector.
virtual inline EnvScalarQuantities& init(); // final;
public :
EnvScalarQuantities();
//~ScalarQuantities();
virtual inline Core::ScalarQuantity* const pressureQ() const final;
virtual inline Core::ScalarQuantity* const temperatureQ() const final;
};
//---
Intensive::EnvScalarQuantities& Intensive::EnvScalarQuantities::init() {
Core::Constants::STD_PRESSURE.copyToSQDest(this->pressure);
Core::Constants::STD_TEMPERATURE.copyToSQDest(this->temperature);
return *this;
}
//---
inline Core::ScalarQuantity*
const Intensive::EnvScalarQuantities::
pressureQ() const { return (Core::ScalarQuantity*) &this->pressure; }
//---
inline Core::ScalarQuantity*
const Intensive::EnvScalarQuantities::
temperatureQ() const { return (Core::ScalarQuantity*) &this->temperature; }
#endif
| 27.57377 | 104 | 0.686088 | [
"vector"
] |
e098d43c517d77d7829e2bd29dfa0236fefba6bd | 959 | cpp | C++ | advanced/1048.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | advanced/1048.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | advanced/1048.cpp | Gongyihang/PAT | 7425be22b0a844fb7171560e034fd7a867680b49 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <map>
#include <set>
using namespace std;
int main()
{
int N, M;
scanf("%d %d", &N, &M);
vector<int> v;
int coin;
for (int i = 0; i < N; i++)
{
scanf("%d", &coin);
v.push_back(coin);
}
sort(v.begin(), v.end());
int v1 = 0, v2 = 0;
int flag = 0;
for (int i = N - 1; i >= 0; i--)
{
if (!flag)
{
for (int j = 0; j < N; j++)
{
v2 = v[i];
if (v[j] == (M - v2) && j < i)
{
v1 = v[j];
printf("%d %d\n", v1, v2);
flag = 1;
break;
}
}
}
else
{
break;
}
}
if (!flag)
{
printf("No Solution");
}
system("pause");
return 0;
} | 16.824561 | 46 | 0.342023 | [
"vector"
] |
e0992f440f1c7eb2f30d9928b14052125d4d7ca6 | 5,120 | hpp | C++ | Core/Device.hpp | GlynnJKW/Stratum | ddc55796f3207fe3df23c455c6304cb72aebcb02 | [
"MIT"
] | null | null | null | Core/Device.hpp | GlynnJKW/Stratum | ddc55796f3207fe3df23c455c6304cb72aebcb02 | [
"MIT"
] | null | null | null | Core/Device.hpp | GlynnJKW/Stratum | ddc55796f3207fe3df23c455c6304cb72aebcb02 | [
"MIT"
] | null | null | null | #pragma once
#include <list>
#include <utility>
#include <Core/DescriptorSet.hpp>
#include <Core/CommandBuffer.hpp>
#include <Core/Instance.hpp>
#include <Util/Util.hpp>
class CommandBuffer;
class Fence;
class Window;
struct DeviceMemoryAllocation {
VkDeviceMemory mDeviceMemory;
VkDeviceSize mOffset;
VkDeviceSize mSize;
uint32_t mMemoryType;
void* mMapped;
std::string mTag;
};
class Device {
public:
struct FrameContext {
std::vector<std::shared_ptr<Semaphore>> mSemaphores; // semaphores that signal when this frame is done
std::vector<std::shared_ptr<Fence>> mFences; // fences that signal when this frame is done
std::list<std::pair<Buffer*, uint32_t>> mTempBuffers;
std::unordered_map<VkDescriptorSetLayout, std::list<std::pair<DescriptorSet*, uint32_t>>> mTempDescriptorSets;
std::vector<Buffer*> mTempBuffersInUse;
std::vector<DescriptorSet*> mTempDescriptorSetsInUse;
Device* mDevice;
inline FrameContext() : mFences({}), mSemaphores({}), mTempBuffers({}), mTempDescriptorSets({}), mTempBuffersInUse({}), mTempDescriptorSetsInUse({}) {};
ENGINE_EXPORT ~FrameContext();
ENGINE_EXPORT void Reset();
};
ENGINE_EXPORT static bool FindQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface, uint32_t& graphicsFamily, uint32_t& presentFamily);
ENGINE_EXPORT ~Device();
ENGINE_EXPORT DeviceMemoryAllocation AllocateMemory(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags properties, const std::string& tag);
ENGINE_EXPORT void FreeMemory(const DeviceMemoryAllocation& allocation);
ENGINE_EXPORT Buffer* GetTempBuffer(const std::string& name, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties);
ENGINE_EXPORT DescriptorSet* GetTempDescriptorSet(const std::string& name, VkDescriptorSetLayout layout);
ENGINE_EXPORT std::shared_ptr<CommandBuffer> GetCommandBuffer(const std::string& name = "Command Buffer");
ENGINE_EXPORT std::shared_ptr<Fence> Execute(std::shared_ptr<CommandBuffer> commandBuffer, bool frameContext = true);
ENGINE_EXPORT void Flush();
ENGINE_EXPORT void SetObjectName(void* object, const std::string& name, VkObjectType type) const;
ENGINE_EXPORT VkSampleCountFlagBits GetMaxUsableSampleCount();
inline VkPhysicalDevice PhysicalDevice() const { return mPhysicalDevice; }
inline uint32_t PhysicalDeviceIndex() const { return mPhysicalDeviceIndex; }
inline VkQueue GraphicsQueue() const { return mGraphicsQueue; };
inline VkQueue PresentQueue() const { return mPresentQueue; };
inline uint32_t GraphicsQueueFamily() const { return mGraphicsQueueFamily; };
inline uint32_t PresentQueueFamily() const { return mPresentQueueFamily; };
inline uint32_t DescriptorSetCount() const { return mDescriptorSetCount; };
inline uint32_t MaxFramesInFlight() const { return mInstance->MaxFramesInFlight(); }
inline uint32_t FrameContextIndex() const { return mFrameContextIndex; }
inline FrameContext* CurrentFrameContext() { return &mFrameContexts[mFrameContextIndex]; }
inline const VkPhysicalDeviceLimits& Limits() const { return mLimits; }
inline ::Instance* Instance() const { return mInstance; }
inline VkPipelineCache PipelineCache() const { return mPipelineCache; }
inline operator VkDevice() const { return mDevice; }
private:
struct Allocation {
void* mMapped;
VkDeviceMemory mMemory;
VkDeviceSize mSize;
// <offset, size>
std::list<std::pair<VkDeviceSize, VkDeviceSize>> mAvailable;
std::list<DeviceMemoryAllocation> mAllocations;
ENGINE_EXPORT bool SubAllocate(const VkMemoryRequirements& requirements, DeviceMemoryAllocation& allocation, const std::string& tag);
ENGINE_EXPORT void Deallocate(const DeviceMemoryAllocation& allocation);
};
friend class DescriptorSet;
friend class CommandBuffer;
friend class ::Instance;
ENGINE_EXPORT Device(::Instance* instance, VkPhysicalDevice physicalDevice, uint32_t physicalDeviceIndex, uint32_t graphicsQueue, uint32_t presentQueue, const std::set<std::string>& deviceExtensions, std::vector<const char*> validationLayers);
::Instance* mInstance;
uint32_t mFrameContextIndex; // assigned by mInstance
FrameContext* mFrameContexts;
std::unordered_map<uint32_t, std::vector<Allocation>> mMemoryAllocations;
VkPhysicalDeviceLimits mLimits;
uint32_t mMaxMSAASamples;
uint32_t mPhysicalDeviceIndex;
VkPhysicalDevice mPhysicalDevice;
VkDevice mDevice;
VkPipelineCache mPipelineCache;
uint32_t mGraphicsQueueFamily;
uint32_t mPresentQueueFamily;
VkQueue mGraphicsQueue;
VkQueue mPresentQueue;
VkDescriptorPool mDescriptorPool;
uint32_t mDescriptorSetCount;
std::mutex mTmpDescriptorSetMutex;
std::mutex mTmpBufferMutex;
std::mutex mDescriptorPoolMutex;
std::mutex mCommandPoolMutex;
std::mutex mMemoryMutex;
std::unordered_map<std::thread::id, VkCommandPool> mCommandPools;
std::unordered_map<VkCommandPool, std::queue<std::shared_ptr<CommandBuffer>>> mCommandBuffers;
#ifdef ENABLE_DEBUG_LAYERS
PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
#endif
}; | 38.496241 | 244 | 0.801758 | [
"object",
"vector"
] |
e099a5cc6b0dbc5b360ce870dc3aca045eb1b44e | 2,842 | cpp | C++ | src/Editor/ImGuiRenderer.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | 2 | 2022-02-08T13:16:01.000Z | 2022-02-28T18:21:35.000Z | src/Editor/ImGuiRenderer.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | null | null | null | src/Editor/ImGuiRenderer.cpp | matey-99/MistEngine | 1a60f98da6b9331b3249f995e2b2566449ce0187 | [
"MIT"
] | null | null | null | #include "ImGuiRenderer.h"
#include "Scene/SceneSerializer.h"
ImGuiRenderer::ImGuiRenderer()
{
}
void ImGuiRenderer::Setup(GLFWwindow* window, const char* glsl_version, Ref<Scene> scene)
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
m_IO = &ImGui::GetIO(); (void)m_IO;
m_IO->ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
m_IO->ConfigFlags |= ImGuiConfigFlags_DockingEnable;
m_IO->ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
m_IO->WantCaptureMouse = true;
m_IO->WantCaptureKeyboard = true;
ImGui::StyleColorsDark();
ImGuiStyle& style = ImGui::GetStyle();
if (m_IO->ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
m_Scene = scene;
m_Editor = Editor::GetInstance();
m_Editor->Initialize(m_Scene);
}
void ImGuiRenderer::Render()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuizmo::BeginFrame();
ImGui::DockSpaceOverViewport(ImGui::GetMainViewport());
ImGui::Begin("Camera");
ImGui::Text("Position: x = %f, y = %f, z = %f", m_Scene->GetCamera()->Position.x, m_Scene->GetCamera()->Position.y, m_Scene->GetCamera()->Position.z);
ImGui::Text("Rotation: yaw = %f, pitch = %f", m_Scene->GetCamera()->Yaw, m_Scene->GetCamera()->Pitch);
ImGui::DragFloat("Movement speed", &m_Scene->GetCamera()->MovementSpeed);
ImGui::End();
ImGui::Begin("Toolbar");
if (ImGui::Button("Translate"))
m_Editor->SetGizmoOperation(ImGuizmo::OPERATION::TRANSLATE);
ImGui::SameLine();
if (ImGui::Button("Rotate"))
m_Editor->SetGizmoOperation(ImGuizmo::OPERATION::ROTATE);
ImGui::SameLine();
if (ImGui::Button("Scale"))
m_Editor->SetGizmoOperation(ImGuizmo::OPERATION::SCALE);
std::string buttonText = m_Editor->IsPlayMode() ? "Exit" : "Play";
ImGui::SameLine();
if (ImGui::Button(buttonText.c_str()))
m_Editor->ManagePlayMode();
ImGui::End();
m_Editor->Render();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void ImGuiRenderer::EndFrame()
{
if (m_IO->ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
}
void ImGuiRenderer::CleanUp()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void ImGuiRenderer::ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset);
}
| 28.707071 | 154 | 0.6886 | [
"render"
] |
e09bc0a0cc6895655c56ea2d7170f1a49d9fa2d3 | 100 | cc | C++ | prob05/calculate_avg.cc | Jocruiser/Jocruiser | 14cfbdd7c2f914cc4b3e2592a597edbdb82dd6a5 | [
"MIT"
] | null | null | null | prob05/calculate_avg.cc | Jocruiser/Jocruiser | 14cfbdd7c2f914cc4b3e2592a597edbdb82dd6a5 | [
"MIT"
] | null | null | null | prob05/calculate_avg.cc | Jocruiser/Jocruiser | 14cfbdd7c2f914cc4b3e2592a597edbdb82dd6a5 | [
"MIT"
] | null | null | null | #include <vector>
double CalculateAvg(std::vector<double>& input) {
// Complete this function.
}
| 16.666667 | 49 | 0.71 | [
"vector"
] |
e0a3983962ecbba7cf7dbd62a18c28d7ed0ce691 | 1,722 | cc | C++ | matlab-gui/widgets/checkbox.cc | Curab7/matlab | b30430b8e1b44453c1c9328f8cdafb88cdd3a38b | [
"Apache-2.0"
] | null | null | null | matlab-gui/widgets/checkbox.cc | Curab7/matlab | b30430b8e1b44453c1c9328f8cdafb88cdd3a38b | [
"Apache-2.0"
] | null | null | null | matlab-gui/widgets/checkbox.cc | Curab7/matlab | b30430b8e1b44453c1c9328f8cdafb88cdd3a38b | [
"Apache-2.0"
] | 7 | 2019-07-08T00:55:05.000Z | 2019-07-16T14:12:29.000Z | #include "CheckBox.h"
#include "widget-helper.h"
#include "registry.h"
CheckBox::CheckBox(const FunctionCallbackInfo<Value>& args)
: QCheckBox(GetTargetWidget())
{
INIT_OBJECT(args);
GET(std::string, text);
GET(Local<Function>, onclick);
GET_IF(bool, init_val, false);
this->setText(text.c_str());
auto sz = GetCurrentLayout().width();
sz += this->size().width() + 20;
GetCurrentLayout().setWidth(sz);
this->setGeometry(QRect(sz, 530, 160, 22));
text_ = text;
onclick_ = onclick;
setChecked(init_val);
connect(this, SIGNAL(clicked(bool)), this, SLOT(ClickCallback()));
isolate_ = isolate;
context_ = isolate->GetCurrentContext();
js_self_ = args.GetReturnValue().Get()->ToObject(context_).ToLocalChecked();
js_self_->Set(MakeStr(isolate, "onclick_func"), (onclick));
}
void CheckBox::ClickCallback() {
js_self_ = v8pp::class_<CheckBox>::find_object(isolate_, this);
Local<Boolean> arg1 = Boolean::New(isolate_, int(this->isChecked()));
Local<Value> argv[] = { arg1 };
onclick_ = Local<Function>::Cast(js_self_->Get(MakeStr(isolate_, "onclick_func")));
onclick_->CallAsFunction(isolate_->GetCurrentContext(), js_self_, 1, argv);
}
Local<FunctionTemplate> CheckBox::me_class_;
v8pp::class_<CheckBox>* CheckBox::self_class_ = nullptr;
void CheckBox::Init(Local<Object> mod, V8Shell* shell)
{
self_class_ = new
v8pp::class_<CheckBox>(shell->GetIsolate());
self_class_
->ctor<const FunctionCallbackInfo<Value>&>()
.set("text", &CheckBox::text_)
.set("onclick", &CheckBox::onclick_);
mod->Set(MakeStr(shell->GetIsolate(), "Checkbox"), self_class_->js_function_template()->GetFunction(shell->GetIsolate()->GetCurrentContext()).ToLocalChecked());
} | 30.210526 | 162 | 0.705575 | [
"object"
] |
e0a50f08927fb03eb1a49713595ea261b493ab3b | 321 | cpp | C++ | BOJ/11727.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | BOJ/11727.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | BOJ/11727.cpp | ReinforceIII/Algorithm | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | [
"MIT"
] | null | null | null | /* 11727 2xn 타일링2 */
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int memo[10001];
int main() {
int n;
cin>>n;
memo[0] = 1;
memo[1] = 1;
for(int i=2; i<=n; i++) {
memo[i] = memo[i-1] + 2*memo[i-2];
memo[i]%=10007;
}
cout<<memo[n];
return 0;
} | 15.285714 | 38 | 0.560748 | [
"vector"
] |
e0a8f0bf2b8c34f19a3016e246349a3289680ee0 | 7,578 | cc | C++ | func/tf/image.cc | jchesterpivotal/Faasm | d4e25baf0c69df7eea8614de3759792748f7b9d4 | [
"Apache-2.0"
] | 1 | 2020-04-21T07:33:42.000Z | 2020-04-21T07:33:42.000Z | func/tf/image.cc | TNTtian/Faasm | 377f4235063a7834724cc750697d3e0280d4a581 | [
"Apache-2.0"
] | 4 | 2020-02-03T18:54:32.000Z | 2020-05-13T18:28:28.000Z | func/tf/image.cc | TNTtian/Faasm | 377f4235063a7834724cc750697d3e0280d4a581 | [
"Apache-2.0"
] | null | null | null | #include "image.h"
#include <faasm/time.h>
#include <faasm/input.h>
#include <faasm/faasm.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
#ifndef __wasm__
#include <emulator/emulator.h>
#endif
#include "absl/memory/memory.h"
#include "get_top_n.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/optional_debug_tools.h"
#include "tensorflow/lite/profiling/profiler.h"
#include "tensorflow/lite/string_util.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
namespace tflite {
namespace label_image {
using TfLiteDelegatePtr = tflite::Interpreter::TfLiteDelegatePtr;
using TfLiteDelegatePtrMap = std::map<std::string, TfLiteDelegatePtr>;
// Takes a file name, and loads a list of labels from it, one per line, and
// returns a vector of the strings. It pads with empty strings so the length
// of the result is a multiple of 16, because our model expects that.
TfLiteStatus ReadLabelsFile(const string &file_name,
std::vector<string> *result,
size_t *found_label_count) {
std::ifstream file(file_name);
if (!file) {
printf("Labels file %s not found\n", file_name.c_str());
return kTfLiteError;
}
result->clear();
string line;
while (std::getline(file, line)) {
result->push_back(line);
}
*found_label_count = result->size();
const int padding = 16;
while (result->size() % padding) {
result->emplace_back();
}
return kTfLiteOk;
}
}
}
FAASM_MAIN_FUNC() {
#ifdef __wasm__
std::string dataDir = "faasm://tfdata/";
#else
std::string dataDir = "/usr/local/code/faasm/func/tf/data/";
setEmulatorUser("tf");
#endif
int loopCount = 1;
int warmupLoops = 0;
int nResults = 5;
std::string imagePath = dataDir + "grace_hopper.bmp";
std::string labelsPath = dataDir + "labels.txt";
std::string modelKey = "mobilenet_v1";
std::unique_ptr<tflite::FlatBufferModel> model;
std::unique_ptr<tflite::Interpreter> interpreter;
const size_t modelSize = 16900760;
FAASM_PROF_START(modelRead)
#ifdef __wasm__
// With wasm we can read directly to a pointer from shared state
uint8_t *modelBytes = faasmReadStatePtr(modelKey.c_str(), modelSize);
#else
auto modelBytes = new uint8_t[modelSize];
faasmReadState(modelKey.c_str(), modelBytes, modelSize);
#endif
FAASM_PROF_END(modelRead)
FAASM_PROF_START(modelBuild)
model = tflite::FlatBufferModel::BuildFromBuffer(reinterpret_cast<char *>(modelBytes), modelSize);
if (!model) {
printf("\nFailed to load model from key %s\n", modelKey.c_str());
exit(-1);
}
printf("Loaded model %s\n", modelKey.c_str());
model->error_reporter();
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);
if (!interpreter) {
printf("Failed to construct interpreter\n");
exit(-1);
}
interpreter->UseNNAPI(false);
interpreter->SetAllowFp16PrecisionForFp32(false);
interpreter->SetNumThreads(1);
FAASM_PROF_END(modelBuild)
FAASM_PROF_START(imgRead)
int image_width = 224;
int image_height = 224;
int image_channels = 3;
printf("Reading in image %s\n", imagePath.c_str());
std::vector<uint8_t> in = tflite::label_image::read_bmp(
imagePath.c_str(),
&image_width,
&image_height,
&image_channels
);
printf("Finished reading in image %s\n", imagePath.c_str());
printf("Got w, h, c: %i, %i, %i\n", image_width, image_height, image_channels);
FAASM_PROF_END(imgRead)
FAASM_PROF_START(tensors)
int input = interpreter->inputs()[0];
const std::vector<int> inputs = interpreter->inputs();
printf("Allocating tensors\n");
if (interpreter->AllocateTensors() != kTfLiteOk) {
printf("Failed to allocate tensors!\n");
}
printf("Finished allocating tensors\n");
// get input dimension from the input tensor metadata
// assuming one input only
TfLiteIntArray *dims = interpreter->tensor(input)->dims;
int wanted_height = dims->data[1];
int wanted_width = dims->data[2];
int wanted_channels = dims->data[3];
FAASM_PROF_END(tensors)
FAASM_PROF_START(imgResize)
tflite::label_image::resize(
interpreter->typed_tensor<float>(input),
in.data(),
image_height,
image_width,
image_channels,
wanted_height,
wanted_width,
wanted_channels
);
FAASM_PROF_END(imgResize)
FAASM_PROF_START(interpreterLoops)
if (loopCount > 1) {
for (int i = 0; i < warmupLoops; i++) {
if (interpreter->Invoke() != kTfLiteOk) {
printf("Failed to invoke tflite!\n");
}
}
}
printf("Invoking interpreter in a loop\n");
for (int i = 0; i < loopCount; i++) {
printf("Interpreter invoke %i\n", i);
if (interpreter->Invoke() != kTfLiteOk) {
printf("Failed to invoke tflite!\n");
}
}
FAASM_PROF_END(interpreterLoops)
FAASM_PROF_START(outputPrep)
printf("Finished invoking\n");
std::vector<int> outputs = interpreter->outputs();
unsigned long outputsSize = outputs.size();
if (outputsSize == 0) {
printf("Empty result from interpreter\n");
exit(1);
}
int output = outputs[0];
TfLiteIntArray *output_dims = interpreter->tensor(output)->dims;
// assume output dims to be something like (1, 1, ... ,size)
const float threshold = 0.001f;
std::vector<std::pair<float, int>> top_results;
auto output_size = output_dims->data[output_dims->size - 1];
tflite::label_image::get_top_n<float>(
interpreter->typed_output_tensor<float>(0),
output_size,
nResults,
threshold,
&top_results,
true
);
if (top_results.empty()) {
printf("No top results found\n");
exit(1);
} else {
printf("Found %li top results\n", top_results.size());
}
FAASM_PROF_END(outputPrep)
FAASM_PROF_START(labelsRead)
std::vector<std::string> labels;
size_t label_count;
if (tflite::label_image::ReadLabelsFile(
labelsPath.c_str(),
&labels,
&label_count
) != kTfLiteOk) {
printf("Failed reading labels file: %s\n", labelsPath.c_str());
exit(-1);
}
std::string outputStr;
for (const auto &result : top_results) {
const float confidence = result.first;
const int index = result.second;
printf("%f: %i %s\n", confidence, index, labels[index].c_str());
outputStr += std::to_string(confidence) + ": " + std::to_string(index) + " " + labels[index] + "\n";
}
faasm::setStringOutput(outputStr.c_str());
FAASM_PROF_END(labelsRead)
#ifndef __wasm__
delete[] modelBytes;
#endif
return 0;
}
| 28.704545 | 108 | 0.622724 | [
"vector",
"model"
] |
e0ac0299d9eafcc95b7ff1c847456c541345217a | 47,476 | cpp | C++ | src/TextRange.cpp | TimoKunze/RichTextBoxControl | 7bc1c30ce836e96cdb085e5fbaa6ccf1734d1e3f | [
"MIT"
] | 4 | 2018-04-23T07:25:15.000Z | 2020-12-03T05:52:38.000Z | src/TextRange.cpp | TimoKunze/RichTextBoxControl | 7bc1c30ce836e96cdb085e5fbaa6ccf1734d1e3f | [
"MIT"
] | null | null | null | src/TextRange.cpp | TimoKunze/RichTextBoxControl | 7bc1c30ce836e96cdb085e5fbaa6ccf1734d1e3f | [
"MIT"
] | 2 | 2019-07-21T11:12:34.000Z | 2022-01-31T01:11:45.000Z | // TextRange.cpp: A wrapper for a range of text.
#include "stdafx.h"
#include "TextRange.h"
#include "ClassFactory.h"
//////////////////////////////////////////////////////////////////////
// implementation of ISupportErrorInfo
STDMETHODIMP TextRange::InterfaceSupportsErrorInfo(REFIID interfaceToCheck)
{
if(InlineIsEqualGUID(IID_IRichTextRange, interfaceToCheck)) {
return S_OK;
}
return S_FALSE;
}
// implementation of ISupportErrorInfo
//////////////////////////////////////////////////////////////////////
HRESULT CALLBACK TextRange::QueryITextRangeInterface(LPVOID pThis, REFIID queriedInterface, LPVOID* ppImplementation, DWORD_PTR /*cookie*/)
{
ATLASSERT_POINTER(ppImplementation, LPVOID);
if(!ppImplementation) {
return E_POINTER;
}
if(InlineIsEqualGUID(__uuidof(ITextRange), queriedInterface) || InlineIsEqualGUID(__uuidof(ITextRange2), queriedInterface)) {
TextRange* pTextRange = reinterpret_cast<TextRange*>(pThis);
return pTextRange->properties.pTextRange->QueryInterface(queriedInterface, ppImplementation);
}
*ppImplementation = NULL;
return E_NOINTERFACE;
}
TextRange::Properties::~Properties()
{
if(pOwnerRTB) {
pOwnerRTB->Release();
pOwnerRTB = NULL;
}
if(pTextRange) {
pTextRange->Release();
pTextRange = NULL;
}
}
HWND TextRange::Properties::GetRTBHWnd(void)
{
ATLASSUME(pOwnerRTB);
OLE_HANDLE handle = NULL;
pOwnerRTB->get_hWnd(&handle);
return static_cast<HWND>(LongToHandle(handle));
}
void TextRange::Attach(ITextRange* pTextRange)
{
if(properties.pTextRange) {
properties.pTextRange->Release();
properties.pTextRange = NULL;
}
if(pTextRange) {
//pTextRange->QueryInterface(IID_PPV_ARGS(&properties.pTextRange));
properties.pTextRange = pTextRange;
properties.pTextRange->AddRef();
}
}
void TextRange::Detach(void)
{
if(properties.pTextRange) {
properties.pTextRange->Release();
properties.pTextRange = NULL;
}
}
void TextRange::SetOwner(RichTextBox* pOwner)
{
if(properties.pOwnerRTB) {
properties.pOwnerRTB->Release();
}
properties.pOwnerRTB = pOwner;
if(properties.pOwnerRTB) {
properties.pOwnerRTB->AddRef();
}
}
STDMETHODIMP TextRange::get_CanEdit(BooleanPropertyValueConstants* pValue)
{
ATLASSERT_POINTER(pValue, BooleanPropertyValueConstants);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
LONG canEdit = tomFalse;
hr = properties.pTextRange->CanEdit(&canEdit);
*pValue = static_cast<BooleanPropertyValueConstants>(canEdit);
}
return hr;
}
STDMETHODIMP TextRange::get_EmbeddedObject(IRichOLEObject** ppOLEObject)
{
ATLASSERT_POINTER(ppOLEObject, IRichOLEObject*);
if(!ppOLEObject) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComPtr<IUnknown> pObject = NULL;
hr = properties.pTextRange->GetEmbeddedObject(&pObject);
if(pObject) {
CComQIPtr<IOleObject> pOleObject = pObject;
CComPtr<ITextRange> pTextRangeClone = NULL;
properties.pTextRange->GetDuplicate(&pTextRangeClone);
ClassFactory::InitOLEObject(pTextRangeClone, pOleObject, properties.pOwnerRTB, IID_IRichOLEObject, reinterpret_cast<LPUNKNOWN*>(ppOLEObject));
} else {
*ppOLEObject = NULL;
}
}
return hr;
}
STDMETHODIMP TextRange::get_FirstChar(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetChar(pValue);
}
return hr;
}
STDMETHODIMP TextRange::put_FirstChar(LONG newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetChar(newValue);
}
return hr;
}
STDMETHODIMP TextRange::get_Font(IRichTextFont** ppTextFont)
{
ATLASSERT_POINTER(ppTextFont, IRichTextFont*);
if(!ppTextFont) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComPtr<ITextFont> pFont = NULL;
hr = properties.pTextRange->GetFont(&pFont);
ClassFactory::InitTextFont(pFont, IID_IRichTextFont, reinterpret_cast<LPUNKNOWN*>(ppTextFont));
}
return hr;
}
STDMETHODIMP TextRange::put_Font(IRichTextFont* pNewTextFont)
{
if(pNewTextFont) {
CComPtr<ITextFont> pFont = NULL;
if(SUCCEEDED(pNewTextFont->QueryInterface(__uuidof(ITextFont), reinterpret_cast<LPVOID*>(&pFont)))) {
if(properties.pTextRange) {
return properties.pTextRange->SetFont(pFont);
} else {
return E_FAIL;
}
}
}
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
STDMETHODIMP TextRange::get_Paragraph(IRichTextParagraph** ppTextParagraph)
{
ATLASSERT_POINTER(ppTextParagraph, IRichTextParagraph*);
if(!ppTextParagraph) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComPtr<ITextPara> pParagraph = NULL;
hr = properties.pTextRange->GetPara(&pParagraph);
ClassFactory::InitTextParagraph(pParagraph, IID_IRichTextParagraph, reinterpret_cast<LPUNKNOWN*>(ppTextParagraph));
}
return hr;
}
STDMETHODIMP TextRange::put_Paragraph(IRichTextParagraph* pNewTextParagraph)
{
if(pNewTextParagraph) {
CComPtr<ITextPara> pParagraph = NULL;
if(SUCCEEDED(pNewTextParagraph->QueryInterface(__uuidof(ITextPara), reinterpret_cast<LPVOID*>(&pParagraph)))) {
if(properties.pTextRange) {
return properties.pTextRange->SetPara(pParagraph);
} else {
return E_FAIL;
}
}
}
// invalid value - raise VB runtime error 380
return MAKE_HRESULT(1, FACILITY_WINDOWS | FACILITY_DISPATCH, 380);
}
STDMETHODIMP TextRange::get_RangeEnd(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetEnd(pValue);
}
return hr;
}
STDMETHODIMP TextRange::put_RangeEnd(LONG newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetEnd(newValue);
}
return hr;
}
STDMETHODIMP TextRange::get_RangeLength(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
LONG start = 0;
LONG end = 0;
hr = properties.pTextRange->GetStart(&start);
if(SUCCEEDED(hr)) {
hr = properties.pTextRange->GetEnd(&end);
if(SUCCEEDED(hr)) {
*pValue = end - start;
}
}
}
return hr;
}
STDMETHODIMP TextRange::get_RangeStart(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetStart(pValue);
}
return hr;
}
STDMETHODIMP TextRange::put_RangeStart(LONG newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetStart(newValue);
}
return hr;
}
STDMETHODIMP TextRange::get_RichText(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
VARIANT v;
VariantClear(&v);
IUnknown* pDataObjectUnknown = NULL;
v.ppunkVal = &pDataObjectUnknown;
v.vt = VT_UNKNOWN | VT_BYREF;
hr = properties.pTextRange->Copy(&v);
if(v.vt == (VT_UNKNOWN | VT_BYREF) && pDataObjectUnknown) {
CComQIPtr<IDataObject> pDataObject = pDataObjectUnknown;
if(pDataObject) {
FORMATETC format = {static_cast<CLIPFORMAT>(RegisterClipboardFormat(CF_RTF)), NULL, DVASPECT_CONTENT, -1, 0};
format.tymed = TYMED_HGLOBAL;
STGMEDIUM storageMedium = {0};
hr = pDataObject->GetData(&format, &storageMedium);
if(storageMedium.tymed & TYMED_HGLOBAL) {
LPSTR pText = reinterpret_cast<LPSTR>(GlobalLock(storageMedium.hGlobal));
*pValue = _bstr_t(pText).Detach();
GlobalUnlock(storageMedium.hGlobal);
}
ReleaseStgMedium(&storageMedium);
}
} else {
hr = E_FAIL;
}
VariantClear(&v);
}
return hr;
}
STDMETHODIMP TextRange::put_RichText(BSTR newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComObject<SourceOLEDataObject>* pOLEDataObjectObj = NULL;
CComObject<SourceOLEDataObject>::CreateInstance(&pOLEDataObjectObj);
pOLEDataObjectObj->AddRef();
//pOLEDataObjectObj->SetOwner(NULL);
CComQIPtr<IDataObject> pDataObject = pOLEDataObjectObj;
pOLEDataObjectObj->Release();
if(pDataObject) {
FORMATETC format = {static_cast<CLIPFORMAT>(RegisterClipboardFormat(CF_RTF)), NULL, DVASPECT_CONTENT, -1, 0};
STGMEDIUM storageMedium = {0};
format.tymed = storageMedium.tymed = TYMED_HGLOBAL;
int textSize = _bstr_t(newValue).length() * sizeof(CHAR);
storageMedium.hGlobal = GlobalAlloc(GPTR, textSize + sizeof(CHAR));
if(storageMedium.hGlobal) {
LPSTR pText = reinterpret_cast<LPSTR>(GlobalLock(storageMedium.hGlobal));
CopyMemory(pText, CW2A(newValue), textSize);
GlobalUnlock(storageMedium.hGlobal);
hr = pDataObject->SetData(&format, &storageMedium, TRUE);
if(SUCCEEDED(hr)) {
VARIANT v;
VariantClear(&v);
v.punkVal = pDataObject.Detach();
v.vt = VT_UNKNOWN;
hr = properties.pTextRange->Paste(&v, format.cfFormat);
VariantClear(&v);
}
}
}
}
return hr;
}
STDMETHODIMP TextRange::get_StoryLength(LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetStoryLength(pValue);
}
return hr;
}
STDMETHODIMP TextRange::get_StoryType(StoryTypeConstants* pValue)
{
ATLASSERT_POINTER(pValue, StoryTypeConstants);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
long type = tomUnknownStory;
hr = properties.pTextRange->GetStoryType(&type);
*pValue = static_cast<StoryTypeConstants>(type);
}
return hr;
}
STDMETHODIMP TextRange::get_SubRanges(IRichTextSubRanges** ppSubRanges)
{
ATLASSERT_POINTER(ppSubRanges, IRichTextSubRanges*);
if(!ppSubRanges) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComPtr<ITextRange> pTextRangeClone = NULL;
properties.pTextRange->GetDuplicate(&pTextRangeClone);
ClassFactory::InitTextSubRanges(pTextRangeClone, properties.pOwnerRTB, IID_IRichTextSubRanges, reinterpret_cast<LPUNKNOWN*>(ppSubRanges));
}
return hr;
}
STDMETHODIMP TextRange::get_Text(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetText(pValue);
}
return hr;
}
STDMETHODIMP TextRange::put_Text(BSTR newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetText(newValue);
}
return hr;
}
STDMETHODIMP TextRange::get_UnitIndex(UnitConstants unit, LONG* pValue)
{
ATLASSERT_POINTER(pValue, LONG);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->GetIndex(unit, pValue);
}
return hr;
}
STDMETHODIMP TextRange::get_URL(BSTR* pValue)
{
ATLASSERT_POINTER(pValue, BSTR);
if(!pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange2> pTextRange2 = properties.pTextRange;
if(pTextRange2) {
hr = pTextRange2->GetURL(pValue);
} else {
hr = E_NOINTERFACE;
}
}
return hr;
}
STDMETHODIMP TextRange::put_URL(BSTR newValue)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange2> pTextRange2 = properties.pTextRange;
if(pTextRange2) {
if(newValue && SysStringLen(newValue) > 0) {
LPTSTR pURL;
#ifdef UNICODE
pURL = OLE2W(newValue);
#else
COLE2T converter(newValue);
pURL = converter;
#endif
CString tmp = pURL;
if(tmp.GetAt(0) != TEXT('\"')) {
tmp = TEXT('\"') + tmp;
}
if(tmp.GetAt(tmp.GetLength() - 1) != TEXT('\"')) {
tmp = tmp + TEXT('\"');
}
BSTR v = tmp.AllocSysString();
hr = pTextRange2->SetURL(v);
SysFreeString(v);
} else {
hr = pTextRange2->SetURL(NULL);
}
} else {
hr = E_NOINTERFACE;
}
}
return hr;
}
STDMETHODIMP TextRange::BuildDownMath(BuildUpMathConstants flags, VARIANT_BOOL* pDidAnyChanges)
{
ATLASSERT_POINTER(pDidAnyChanges, VARIANT_BOOL);
if(!pDidAnyChanges) {
return E_POINTER;
}
ATLASSERT(properties.pTextRange);
if(!properties.pTextRange) {
return CO_E_RELEASED;
}
*pDidAnyChanges = VARIANT_FALSE;
CComQIPtr<ITextRange2> pTextRange2 = properties.pTextRange;
if(pTextRange2) {
HRESULT hr = pTextRange2->Linearize(flags);
if(hr == NOERROR) {
*pDidAnyChanges = VARIANT_TRUE;
hr = S_OK;
} else if(hr == S_FALSE) {
hr = S_OK;
}
return hr;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP TextRange::BuildUpMath(BuildUpMathConstants flags, VARIANT_BOOL* pDidAnyChanges)
{
ATLASSERT_POINTER(pDidAnyChanges, VARIANT_BOOL);
if(!pDidAnyChanges) {
return E_POINTER;
}
ATLASSERT(properties.pTextRange);
if(!properties.pTextRange) {
return CO_E_RELEASED;
}
*pDidAnyChanges = VARIANT_FALSE;
CComQIPtr<ITextRange2> pTextRange2 = properties.pTextRange;
if(pTextRange2) {
HRESULT hr = pTextRange2->BuildUpMath(flags);
if(hr == NOERROR) {
*pDidAnyChanges = VARIANT_TRUE;
hr = S_OK;
} else if(hr == S_FALSE) {
hr = S_OK;
}
return hr;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP TextRange::CanPaste(IOLEDataObject* pOLEDataObject/* = NULL*/, LONG formatID/* = 0*/, VARIANT_BOOL* pCanPaste/* = NULL*/)
{
ATLASSERT_POINTER(pCanPaste, VARIANT_BOOL);
if(!pCanPaste) {
return E_POINTER;
}
if(formatID == 0xffffbf01) {
formatID = RegisterClipboardFormat(CF_RTF);
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
LONG canPaste = tomFalse;
BOOL useFallback = TRUE;
if(pOLEDataObject) {
CComQIPtr<IDataObject> pDataObject = pOLEDataObject;
if(pDataObject) {
useFallback = FALSE;
VARIANT v;
VariantClear(&v);
pDataObject->QueryInterface(IID_PPV_ARGS(&v.punkVal));
v.vt = VT_UNKNOWN;
hr = properties.pTextRange->CanPaste(&v, formatID, &canPaste);
VariantClear(&v);
}
}
if(useFallback) {
hr = properties.pTextRange->CanPaste(NULL, formatID, &canPaste);
}
if(SUCCEEDED(hr)) {
// there does not seem to be a difference between hr and canPaste
*pCanPaste = BOOL2VARIANTBOOL(hr == S_OK);
hr = S_OK;
}
}
return hr;
}
STDMETHODIMP TextRange::ChangeCase(CaseConstants newCase)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->ChangeCase(newCase);
}
return hr;
}
STDMETHODIMP TextRange::Clone(IRichTextRange** ppClone)
{
ATLASSERT_POINTER(ppClone, IRichTextRange*);
if(!ppClone) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
*ppClone = NULL;
if(properties.pTextRange) {
CComPtr<ITextRange> pRange = NULL;
hr = properties.pTextRange->GetDuplicate(&pRange);
ClassFactory::InitTextRange(pRange, properties.pOwnerRTB, IID_IRichTextRange, reinterpret_cast<LPUNKNOWN*>(ppClone));
}
return hr;
}
STDMETHODIMP TextRange::Collapse(VARIANT_BOOL collapseToStart/* = VARIANT_TRUE*/, VARIANT_BOOL* pSucceeded/* = NULL*/)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->Collapse(VARIANTBOOL2BOOL(collapseToStart) ? tomStart : tomEnd);
*pSucceeded = BOOL2VARIANTBOOL(SUCCEEDED(hr));
hr = S_OK;
}
return hr;
}
STDMETHODIMP TextRange::ContainsRange(IRichTextRange* pCompareAgainst, VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pCompareAgainst, IRichTextRange);
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pCompareAgainst || !pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange> pRange = pCompareAgainst;
LONG contains = tomFalse;
hr = pRange->InRange(properties.pTextRange, &contains);
*pValue = BOOL2VARIANTBOOL(contains == tomTrue);
}
return hr;
}
STDMETHODIMP TextRange::Copy(VARIANT* pOLEDataObject/* = NULL*/, VARIANT_BOOL* pSucceeded/* = NULL*/)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
if(pOLEDataObject && pOLEDataObject->vt == (VT_DISPATCH | VT_BYREF)) {
VARIANT v;
VariantClear(&v);
IUnknown* pDataObjectUnknown = NULL;
v.ppunkVal = &pDataObjectUnknown;
v.vt = VT_UNKNOWN | VT_BYREF;
hr = properties.pTextRange->Copy(&v);
if(v.vt == (VT_UNKNOWN | VT_BYREF) && pDataObjectUnknown) {
CComQIPtr<IDataObject> pDataObject = pDataObjectUnknown;
ClassFactory::InitOLEDataObject(pDataObject, IID_IOLEDataObject, reinterpret_cast<LPUNKNOWN*>(pOLEDataObject->ppdispVal));
}
VariantClear(&v);
} else {
hr = properties.pTextRange->Copy(NULL);
}
*pSucceeded = BOOL2VARIANTBOOL(SUCCEEDED(hr));
hr = S_OK;
}
return hr;
}
STDMETHODIMP TextRange::CopyRichTextFromTextRange(IRichTextRange* pSourceObject, VARIANT_BOOL* pSucceeded)
{
ATLASSERT_POINTER(pSourceObject, IRichTextRange);
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSourceObject || !pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange> pSourceRange = pSourceObject;
if(pSourceRange) {
CComPtr<ITextRange> pSourceFormattedText = NULL;
hr = pSourceRange->GetFormattedText(&pSourceFormattedText);
if(SUCCEEDED(hr)) {
hr = properties.pTextRange->SetFormattedText(pSourceFormattedText);
}
}
*pSucceeded = BOOL2VARIANTBOOL(SUCCEEDED(hr));
}
return hr;
}
STDMETHODIMP TextRange::Cut(VARIANT* pOLEDataObject/* = NULL*/, VARIANT_BOOL* pSucceeded/* = NULL*/)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
if(pOLEDataObject && pOLEDataObject->vt == (VT_DISPATCH | VT_BYREF)) {
VARIANT v;
VariantClear(&v);
IUnknown* pDataObjectUnknown = NULL;
v.ppunkVal = &pDataObjectUnknown;
v.vt = VT_UNKNOWN | VT_BYREF;
hr = properties.pTextRange->Cut(&v);
if(v.vt == (VT_UNKNOWN | VT_BYREF) && pDataObjectUnknown) {
CComQIPtr<IDataObject> pDataObject = pDataObjectUnknown;
ClassFactory::InitOLEDataObject(pDataObject, IID_IOLEDataObject, reinterpret_cast<LPUNKNOWN*>(pOLEDataObject->ppdispVal));
}
VariantClear(&v);
} else {
hr = properties.pTextRange->Copy(NULL);
}
*pSucceeded = BOOL2VARIANTBOOL(SUCCEEDED(hr));
hr = S_OK;
}
return hr;
}
STDMETHODIMP TextRange::Delete(UnitConstants unit/* = uCharacter*/, LONG count/* = 0*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->Delete(unit, count, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::Equals(IRichTextRange* pCompareAgainst, VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pCompareAgainst, IRichTextRange);
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pCompareAgainst || !pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange> pRange = pCompareAgainst;
LONG equal = tomFalse;
hr = properties.pTextRange->IsEqual(pRange, &equal);
*pValue = BOOL2VARIANTBOOL(equal == tomTrue);
}
return hr;
}
STDMETHODIMP TextRange::EqualsStory(IRichTextRange* pCompareAgainst, VARIANT_BOOL* pValue)
{
ATLASSERT_POINTER(pCompareAgainst, IRichTextRange);
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pCompareAgainst || !pValue) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
CComQIPtr<ITextRange> pRange = pCompareAgainst;
LONG equal = tomFalse;
hr = properties.pTextRange->InStory(pRange, &equal);
*pValue = BOOL2VARIANTBOOL(equal == tomTrue);
}
return hr;
}
STDMETHODIMP TextRange::ExpandToUnit(UnitConstants unit, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->Expand(unit, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::FindText(BSTR searchFor, SearchDirectionConstants searchDirectionAndMaxCharsToPass/* = sdForward*/, SearchModeConstants searchMode/* = smDefault*/, MoveRangeBoundariesConstants moveRangeBoundaries/* = mrbMoveBoth*/, LONG* pLengthMatched/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
switch(moveRangeBoundaries) {
case mrbMoveBoth:
hr = properties.pTextRange->FindText(searchFor, searchDirectionAndMaxCharsToPass, searchMode, pLengthMatched);
break;
case mrbMoveStartOnly:
hr = properties.pTextRange->FindTextStart(searchFor, searchDirectionAndMaxCharsToPass, searchMode, pLengthMatched);
break;
case mrbMoveEndOnly:
hr = properties.pTextRange->FindTextEnd(searchFor, searchDirectionAndMaxCharsToPass, searchMode, pLengthMatched);
break;
}
}
return hr;
}
STDMETHODIMP TextRange::GetEndPosition(HorizontalPositionConstants horizontalPosition, VerticalPositionConstants verticalPosition, RangePositionConstants flags, OLE_XPOS_PIXELS* pX, OLE_YPOS_PIXELS* pY, VARIANT_BOOL* pSucceeded)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
long type = tomEnd | horizontalPosition | verticalPosition | flags;
hr = properties.pTextRange->GetPoint(type, pX, pY);
// NOTE: hr will be S_FALSE if the coordinates are not within the client rectangle and tomAllowOffClient has not been specified.
*pSucceeded = BOOL2VARIANTBOOL(hr == S_OK);
// Don't set hr to S_OK, so that S_FALSE can be distinguished from a real error.
}
return hr;
}
STDMETHODIMP TextRange::GetStartPosition(HorizontalPositionConstants horizontalPosition, VerticalPositionConstants verticalPosition, RangePositionConstants flags, OLE_XPOS_PIXELS* pX, OLE_YPOS_PIXELS* pY, VARIANT_BOOL* pSucceeded)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
long type = tomStart | horizontalPosition | verticalPosition | flags;
hr = properties.pTextRange->GetPoint(type, pX, pY);
// NOTE: hr will be S_FALSE if the coordinates are not within the client rectangle and tomAllowOffClient has not been specified.
*pSucceeded = BOOL2VARIANTBOOL(hr == S_OK);
// Don't set hr to S_OK, so that S_FALSE can be distinguished from a real error.
}
return hr;
}
STDMETHODIMP TextRange::IsWithinTable(VARIANT* pTable/* = NULL*/, VARIANT* pTableRow/* = NULL*/, VARIANT* pTableCell/* = NULL*/, VARIANT_BOOL* pValue/* = NULL*/)
{
ATLASSERT_POINTER(pValue, VARIANT_BOOL);
if(!pValue) {
return E_POINTER;
}
ATLASSERT(properties.pTextRange);
if(!properties.pTextRange) {
return CO_E_RELEASED;
}
*pValue = VARIANT_FALSE;
LONG rangeStart = -1;
LONG rangeEnd = -1;
properties.pTextRange->GetStart(&rangeStart);
properties.pTextRange->GetEnd(&rangeEnd);
CComPtr<ITextRange> pTableTextRange = NULL;
HRESULT hr = properties.pTextRange->GetDuplicate(&pTableTextRange);
if(FAILED(hr)) {
return hr;
}
LONG startOfTable = -1;
LONG endOfTable = -1;
LONG start = -1;
pTableTextRange->GetStart(&start);
LONG previousStart = start;
BOOL mayTryToGetBoundary = FALSE;
// unfortunately this will walk into nested tables
while(pTableTextRange->Move(tomCell, -1, NULL) == S_OK) {
pTableTextRange->GetStart(&start);
if(start == previousStart) {
break;
}
mayTryToGetBoundary = TRUE;
previousStart = start;
}
if(!mayTryToGetBoundary) {
// maybe the range start is within the first cell, so go one forward and then back again to check this
if(pTableTextRange->Move(tomCell, 1, NULL) == S_OK) {
pTableTextRange->Move(tomCell, -1, NULL);
mayTryToGetBoundary = TRUE;
} else {
// maybe the range start is equal to the table start
// TODO: Probably this won't work if the first cell contains a nested table.
pTableTextRange->SetStart(rangeStart + 1);
// it might be better to just set mayTryToGetBoundary to TRUE here
if(pTableTextRange->Move(tomCell, 1, NULL) == S_OK) {
pTableTextRange->Move(tomCell, -1, NULL);
mayTryToGetBoundary = TRUE;
}
}
}
if(mayTryToGetBoundary) {
// Here we should at least be in the table's first row.
HRESULT hr2 = pTableTextRange->StartOf(tomRow, tomExtend, NULL);
if(hr2 == S_OK) {
// everything looks fine
pTableTextRange->GetStart(&startOfTable);
} else if(hr2 == S_FALSE) {
// this happens for instance if we are in cell 2 and there is a nested table in the first cell
pTableTextRange->GetStart(&start);
// NOTE: This trick seems to work even if there are multiple levels of nested tables in the first cell.
pTableTextRange->SetStart(start - 1);
if(pTableTextRange->StartOf(tomRow, tomExtend, NULL) == S_OK) {
pTableTextRange->GetStart(&startOfTable);
}
}
}
if(startOfTable >= 0) {
// We have the start of the table now and it seems quite reliable. Find the table's end now.
pTableTextRange->SetStart(rangeEnd);
start = rangeEnd;
previousStart = start - 1;
mayTryToGetBoundary = FALSE;
// unfortunately this will walk into nested tables
while(pTableTextRange->Move(tomCell, 1, NULL) == S_OK) {
pTableTextRange->GetStart(&start);
if(start == previousStart) {
break;
}
// EndOf will fail if we already are at the end
pTableTextRange->SetEnd(previousStart);
mayTryToGetBoundary = TRUE;
previousStart = start;
}
if(!mayTryToGetBoundary) {
// maybe the range end is within the last cell
if(pTableTextRange->Move(tomCell, -1, NULL) == S_OK) {
pTableTextRange->Move(tomCell, 1, NULL);
mayTryToGetBoundary = TRUE;
} else {
// maybe the range end is equal to the table end
pTableTextRange->SetStart(rangeEnd - 1);
if(pTableTextRange->Move(tomCell, -1, NULL) == S_OK) {
pTableTextRange->Move(tomCell, 1, NULL);
mayTryToGetBoundary = TRUE;
}
}
}
if(mayTryToGetBoundary) {
// unfortunately the loop would walk out of the nested table, so check the nesting levels
LONG ourNestingLevel = -1;
CComPtr<ITextRange> pDuplicate = NULL;
if(SUCCEEDED(pTableTextRange->GetDuplicate(&pDuplicate)) && SUCCEEDED(pDuplicate->SetStart(startOfTable))) {
CComPtr<IRichTable> pOurTable = ClassFactory::InitTable(pDuplicate, properties.pOwnerRTB);
pOurTable->get_NestingLevel(&ourNestingLevel);
do {
hr = pTableTextRange->EndOf(tomRow, tomExtend, NULL);
if(hr == S_OK) {
pDuplicate = NULL;
if(SUCCEEDED(pTableTextRange->GetDuplicate(&pDuplicate)) && SUCCEEDED(pDuplicate->Collapse(tomEnd))) {
CComPtr<IRichTable> pTableOfEnd = ClassFactory::InitTable(pDuplicate, properties.pOwnerRTB);
LONG endNestingLevel = -1;
pTableOfEnd->get_NestingLevel(&endNestingLevel);
if(endNestingLevel >= ourNestingLevel) {
pTableTextRange->GetEnd(&endOfTable);
pTableTextRange->SetEnd(endOfTable + 1);
} else {
// we're in a nested table and we've already been in the last row
pTableTextRange->GetEnd(&endOfTable);
hr = S_FALSE;
}
} else {
hr = E_FAIL;
endOfTable = -1;
}
}
} while(hr == S_OK);
}
}
}
if(startOfTable >= 0 && endOfTable >= 0) {
*pValue = VARIANT_TRUE;
pTableTextRange->SetStart(startOfTable);
pTableTextRange->SetEnd(endOfTable);
} else {
pTableTextRange = NULL;
}
CComPtr<ITextRange> pRowTextRange = NULL;
if(pTableTextRange && ((pTableRow && pTableRow->vt == (VT_DISPATCH | VT_BYREF)) || (pTableCell && pTableCell->vt == (VT_DISPATCH | VT_BYREF)))) {
// now search for the table row
hr = pTableTextRange->GetDuplicate(&pRowTextRange);
if(FAILED(hr)) {
return hr;
}
// start with the first row
LONG startOfNextRowCandidate = startOfTable;
BOOL foundRow = FALSE;
do {
// set the cursor to the current row
pRowTextRange->SetStart(startOfNextRowCandidate);
pRowTextRange->SetEnd(startOfNextRowCandidate);
hr = pRowTextRange->EndOf(tomRow, tomExtend, NULL);
if(hr == S_OK) {
// this has been a row, retrieve the position at which the next row would start
pRowTextRange->GetEnd(&startOfNextRowCandidate);
if(startOfNextRowCandidate <= endOfTable) {
// we're still inside the table, so count this row
LONG rowStart = 0;
LONG rowEnd = 0;
pRowTextRange->GetStart(&rowStart);
pRowTextRange->GetEnd(&rowEnd);
if(rowStart <= rangeStart && rangeStart <= rowEnd) {
foundRow = (rowStart <= rangeEnd && rangeEnd <= rowEnd);
if(foundRow) {
pRowTextRange->SetStart(rowStart);
pRowTextRange->SetEnd(rowEnd);
}
break;
}
}
if(startOfNextRowCandidate >= endOfTable) {
// we reached the end of the table
break;
}
} else {
// this has not been a row, so don't count it and stop
break;
}
} while(!foundRow);
if(!foundRow) {
pRowTextRange = NULL;
}
}
CComPtr<ITextRange> pCellTextRange = NULL;
if(pTableTextRange && pRowTextRange && pTableCell && pTableCell->vt == (VT_DISPATCH | VT_BYREF)) {
// now search for the table cell
hr = pRowTextRange->GetDuplicate(&pCellTextRange);
if(FAILED(hr)) {
return hr;
}
LONG rowStart = 0;
LONG rowEnd = 0;
pRowTextRange->GetStart(&rowStart);
pRowTextRange->GetEnd(&rowEnd);
// NOTE: StartOf(tomCell, tomExtend) and EndOf(tomCell, tomExtend) do not really work on Windows 7.
// start with the first cell
BOOL foundCell = FALSE;
LONG cellStart = rowStart + 2;
LONG cellEnd = cellStart;
LONG startOfNextCellCandidate = 0;
do {
// set the cursor to the current cell
pCellTextRange->SetStart(cellStart);
pCellTextRange->SetEnd(cellEnd);
// move one cell ahead
hr = pCellTextRange->Move(tomCell, 1, NULL);
if(hr == S_OK) {
// the start of the next cell minus one is the end of the current cell
pCellTextRange->GetStart(&startOfNextCellCandidate);
cellEnd = startOfNextCellCandidate - 1;
if(startOfNextCellCandidate < rowEnd) {
// we're still inside the row, so count this cell
if(cellStart <= rangeStart && rangeStart <= cellEnd) {
foundCell = (cellStart <= rangeEnd && rangeEnd <= cellEnd);
if(foundCell) {
pCellTextRange->SetStart(cellStart);
pCellTextRange->SetEnd(cellEnd);
}
}
}
if(startOfNextCellCandidate >= rowEnd) {
// we reached the end of the row
break;
}
} else {
// this has not been a cell, so don't count it and stop
break;
}
if(!foundCell) {
// prepare for next cell
cellStart = startOfNextCellCandidate;
cellEnd = cellStart;
}
} while(!foundCell);
if(!foundCell) {
pCellTextRange = NULL;
}
}
if(pTableTextRange && pTable && pTable->vt == (VT_DISPATCH | VT_BYREF)) {
ClassFactory::InitTable(pTableTextRange, properties.pOwnerRTB, IID_IRichTable, reinterpret_cast<LPUNKNOWN*>(pTable->ppdispVal));
}
if(pTableTextRange && pRowTextRange && pTableRow && pTableRow->vt == (VT_DISPATCH | VT_BYREF)) {
ClassFactory::InitTableRow(pTableTextRange, pRowTextRange, properties.pOwnerRTB, IID_IRichTableRow, reinterpret_cast<LPUNKNOWN*>(pTableRow->ppdispVal));
}
if(pTableTextRange && pRowTextRange && pCellTextRange && pTableCell && pTableCell->vt == (VT_DISPATCH | VT_BYREF)) {
ClassFactory::InitTableCell(pTableTextRange, pRowTextRange, pCellTextRange, properties.pOwnerRTB, IID_IRichTableCell, reinterpret_cast<LPUNKNOWN*>(pTableCell->ppdispVal));
}
return S_OK;
}
STDMETHODIMP TextRange::MoveEndByUnit(UnitConstants unit, LONG count, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveEnd(unit, count, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveEndToPosition(OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, VARIANT_BOOL doNotMoveStart)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetPoint(x, y, tomEnd, (VARIANTBOOL2BOOL(doNotMoveStart) ? tomExtend : tomMove));
}
return hr;
}
STDMETHODIMP TextRange::MoveEndToEndOfUnit(UnitConstants unit, VARIANT_BOOL doNotMoveStart, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->EndOf(unit, (VARIANTBOOL2BOOL(doNotMoveStart) ? tomExtend : tomMove), pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveEndUntil(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveEndUntil(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveEndWhile(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveEndWhile(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveInsertionPointByUnit(UnitConstants unit, LONG count, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->Move(unit, count, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveInsertionPointUntil(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveUntil(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveInsertionPointWhile(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveWhile(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveStartByUnit(UnitConstants unit, LONG count, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveStart(unit, count, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveStartToPosition(OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y, VARIANT_BOOL doNotMoveEnd)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetPoint(x, y, tomStart, (VARIANTBOOL2BOOL(doNotMoveEnd) ? tomExtend : tomMove));
}
return hr;
}
STDMETHODIMP TextRange::MoveStartToStartOfUnit(UnitConstants unit, VARIANT_BOOL doNotMoveEnd, LONG* pDelta)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->StartOf(unit, (VARIANTBOOL2BOOL(doNotMoveEnd) ? tomExtend : tomMove), pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveStartUntil(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveStartUntil(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveStartWhile(VARIANT* pCharacterSet, LONG maximumCharactersToPass/* = tomForward*/, LONG* pDelta/* = NULL*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->MoveStartWhile(pCharacterSet, maximumCharactersToPass, pDelta);
}
return hr;
}
STDMETHODIMP TextRange::MoveToUnitIndex(UnitConstants unit, LONG index, VARIANT_BOOL setRangeToEntireUnit/* = VARIANT_FALSE*/, VARIANT_BOOL* pSucceeded/* = NULL*/)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetIndex(unit, index, (VARIANTBOOL2BOOL(setRangeToEntireUnit) ? tomExtend : tomMove));
*pSucceeded = BOOL2VARIANTBOOL(hr == S_OK);
hr = S_OK;
}
return hr;
}
STDMETHODIMP TextRange::Paste(IOLEDataObject* pOLEDataObject/* = NULL*/, LONG formatID/* = 0*/, VARIANT_BOOL* pSucceeded/* = NULL*/)
{
ATLASSERT_POINTER(pSucceeded, VARIANT_BOOL);
if(!pSucceeded) {
return E_POINTER;
}
if(formatID == 0xffffbf01) {
formatID = RegisterClipboardFormat(CF_RTF);
}
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
BOOL useFallback = TRUE;
if(pOLEDataObject) {
CComQIPtr<IDataObject> pDataObject = pOLEDataObject;
if(pDataObject) {
useFallback = FALSE;
VARIANT v;
VariantInit(&v);
pDataObject->QueryInterface(IID_PPV_ARGS(&v.punkVal));
v.vt = VT_UNKNOWN;
hr = properties.pTextRange->Paste(&v, formatID);
VariantClear(&v);
}
}
if(useFallback) {
hr = properties.pTextRange->Paste(NULL, formatID);
}
*pSucceeded = BOOL2VARIANTBOOL(SUCCEEDED(hr));
hr = S_OK;
}
return hr;
}
STDMETHODIMP TextRange::ReplaceWithTable(LONG columnCount, LONG rowCount, VARIANT_BOOL allowIndividualCellStyles/* = VARIANT_TRUE*/, SHORT borderSize/* = 0*/, HAlignmentConstants horizontalRowAlignment/* = halLeft*/, VAlignmentConstants verticalCellAlignment/* = valCenter*/, LONG rowIndent/* = -1*/, LONG columnWidth/* = -1*/, LONG horizontalCellMargin/* = -1*/, LONG rowHeight/* = -1*/, IRichTable** ppAddedTable/* = NULL*/)
{
ATLASSERT_POINTER(ppAddedTable, IRichTable*);
if(!ppAddedTable) {
return E_POINTER;
}
if(columnCount <= 0 || rowCount <= 0 || borderSize < -1 || rowIndent < -1 || columnWidth < -1 || horizontalCellMargin < -1 || rowHeight < -1) {
return E_INVALIDARG;
}
if(horizontalRowAlignment < halLeft || horizontalRowAlignment > halRight) {
return E_INVALIDARG;
}
if(verticalCellAlignment < valTop || verticalCellAlignment > valBottom) {
return E_INVALIDARG;
}
*ppAddedTable = NULL;
HWND hWndRTB = properties.GetRTBHWnd();
ATLASSERT(IsWindow(hWndRTB));
LONG twipsPerPixelX = 15;
LONG twipsPerPixelY = 15;
HDC hDCRTB = GetDC(hWndRTB);
if(hDCRTB) {
twipsPerPixelX = 1440 / GetDeviceCaps(hDCRTB, LOGPIXELSX);
twipsPerPixelY = 1440 / GetDeviceCaps(hDCRTB, LOGPIXELSY);
ReleaseDC(hWndRTB, hDCRTB);
}
if(rowIndent == -1) {
rowIndent = twipsPerPixelX * 35 / 10;
}
if(horizontalCellMargin == -1) {
horizontalCellMargin = twipsPerPixelX * 48 / 10;
}
if(borderSize == -1) {
borderSize = static_cast<SHORT>(twipsPerPixelX);
}
BOOL useFallback = TRUE;
LONG rangeStart = 0;
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
properties.pTextRange->GetStart(&rangeStart);
CComQIPtr<ITextRange2> pTextRange2 = properties.pTextRange;
if(pTextRange2) {
// auto-fit can be:
// 0 - disabled
// 1 - enabled, may be overridden by fixed width specifications
#if FALSE
// Does not work well, e.g. the column width is too wide for autoFit=1 and the cell properties are not applied.
// Also it always returns E_INVALIDARG if the MDIWordpad sample is maximized (both windows - doc and frame).
long autoFit = (columnWidth == -1 ? 1 : 0);
hr = pTextRange2->InsertTable(columnCount, rowCount, autoFit);
/*CAtlString s;
s.Format(_T("0x%X"), hr);
MessageBox(NULL, s, _T("InsertTable"), MB_OK);*/
if(SUCCEEDED(hr)) {
useFallback = FALSE;
ATLASSERT(FALSE);
CComPtr<ITextRow> pTextRow = NULL;
if(SUCCEEDED(pTextRange2->GetRow(&pTextRow))) {
if(VARIANTBOOL2BOOL(allowIndividualCellStyles)) {
// does not seem to work anyway, it has no effect
pTextRow->SetCellCountCache(columnCount);
}
pTextRow->SetAlignment(static_cast<LONG>(horizontalRowAlignment));
pTextRow->SetCellMargin(horizontalCellMargin);
pTextRow->SetIndent(rowIndent);
pTextRow->SetHeight(rowHeight);
pTextRow->SetCellIndex(0);
pTextRow->SetCellWidth(columnWidth);
pTextRow->SetCellAlignment(verticalCellAlignment);
pTextRow->SetCellBorderWidths(borderSize, borderSize, borderSize, borderSize);
LONG backColor1 = RGB(255, 255, 255);
CComPtr<ITextFont> pTextFont = NULL;
if(SUCCEEDED(pTextRange2->GetFont(&pTextFont))) {
pTextFont->GetBackColor(&backColor1);
}
pTextRow->SetCellColorBack(backColor1);
if(FAILED(pTextRow->Apply(rowCount, tomRowApplyDefault))) {
ATLASSERT(FALSE && "ITextRow::Apply failed");
}
} else {
ATLASSERT(FALSE && "ITextRange2::GetRow failed");
}
}
#endif
}
if(useFallback) {
// try EM_INSERTTABLE
hr = E_NOINTERFACE;
if(hWndRTB) {
if(columnWidth == -1) {
// emulate auto-fit
SCROLLINFO scrollInfo = {0};
scrollInfo.cbSize = sizeof(SCROLLINFO);
scrollInfo.fMask = SIF_ALL;
GetScrollInfo(hWndRTB, SB_HORZ, &scrollInfo);
int width = scrollInfo.nMax - scrollInfo.nMin;
columnWidth = (twipsPerPixelX * width - rowIndent) / columnCount;
}
TABLEROWPARMS rowParams = {0};
rowParams.cbRow = sizeof(TABLEROWPARMS);
rowParams.cbCell = sizeof(TABLECELLPARMS);
properties.pTextRange->GetStart(&rowParams.cpStartRow);
rowParams.cCell = static_cast<BYTE>(columnCount);
rowParams.cRow = static_cast<BYTE>(rowCount);
switch(horizontalRowAlignment) {
case halLeft:
rowParams.nAlignment = PFA_LEFT;
break;
case halCenter:
rowParams.nAlignment = PFA_CENTER;
break;
case halRight:
rowParams.nAlignment = PFA_RIGHT;
break;
}
rowParams.dxCellMargin = horizontalCellMargin;
rowParams.dxIndent = rowIndent;
rowParams.dyHeight = (rowHeight <= 0 ? 0 : rowHeight);
rowParams.fIdentCells = !VARIANTBOOL2BOOL(allowIndividualCellStyles);
if(rowParams.fIdentCells) {
TABLECELLPARMS cellParams = {0};
cellParams.dxWidth = columnWidth;
cellParams.nVertAlign = static_cast<WORD>(verticalCellAlignment);
cellParams.dxBrdrLeft = borderSize;
cellParams.dxBrdrRight = borderSize;
cellParams.dyBrdrTop = borderSize;
cellParams.dyBrdrBottom = borderSize;
CComPtr<ITextFont> pTextFont = NULL;
if(SUCCEEDED(properties.pTextRange->GetFont(&pTextFont))) {
pTextFont->GetBackColor(reinterpret_cast<LONG*>(&cellParams.crBackPat));
} else {
cellParams.crBackPat = RGB(255, 255, 255);
}
hr = static_cast<HRESULT>(SendMessage(hWndRTB, EM_INSERTTABLE, reinterpret_cast<WPARAM>(&rowParams), reinterpret_cast<LPARAM>(&cellParams)));
if(hr == E_INVALIDARG) {
// might be Windows XP
/*rowParams.cbRow -= 2 * sizeof(long);
hr = static_cast<HRESULT>(SendMessage(hWndRTB, EM_INSERTTABLE, reinterpret_cast<WPARAM>(&rowParams), reinterpret_cast<LPARAM>(&cellParams)));*/
}
} else {
TABLECELLPARMS* pCellParams = reinterpret_cast<TABLECELLPARMS*>(HeapAlloc(GetProcessHeap(), 0, columnCount * sizeof(TABLECELLPARMS)));
if(pCellParams) {
ZeroMemory(pCellParams, columnCount * sizeof(TABLECELLPARMS));
for(int col = 0; col < columnCount; ++col) {
pCellParams[col].dxWidth = columnWidth;
pCellParams[col].nVertAlign = static_cast<WORD>(verticalCellAlignment);
pCellParams[col].dxBrdrLeft = borderSize;
pCellParams[col].dxBrdrRight = borderSize;
pCellParams[col].dyBrdrTop = borderSize;
pCellParams[col].dyBrdrBottom = borderSize;
CComPtr<ITextFont> pTextFont = NULL;
if(SUCCEEDED(properties.pTextRange->GetFont(&pTextFont))) {
pTextFont->GetBackColor(reinterpret_cast<LONG*>(&pCellParams[col].crBackPat));
} else {
pCellParams[col].crBackPat = RGB(255, 255, 255);
}
}
hr = static_cast<HRESULT>(SendMessage(hWndRTB, EM_INSERTTABLE, reinterpret_cast<WPARAM>(&rowParams), reinterpret_cast<LPARAM>(pCellParams)));
if(hr == E_INVALIDARG) {
// might be Windows XP
/*rowParams.cbRow -= 2 * sizeof(long);
hr = static_cast<HRESULT>(SendMessage(hWndRTB, EM_INSERTTABLE, reinterpret_cast<WPARAM>(&rowParams), reinterpret_cast<LPARAM>(pCellParams)));*/
}
HeapFree(GetProcessHeap(), 0, pCellParams);
} else {
hr = E_OUTOFMEMORY;
}
}
/*if(SUCCEEDED(hr)) {
useFallback = FALSE;
}*/
}
}
}
/*if(useFallback && hWndRTB) {
// NOTE: This fallback probably won't work for nested tables.
LPSTR pTmp = new CHAR[70];
if(columnWidth == -1) {
// \trautofit control word does not seem to work, so emulate it
SCROLLINFO scrollInfo = {0};
scrollInfo.cbSize = sizeof(SCROLLINFO);
scrollInfo.fMask = SIF_ALL;
GetScrollInfo(hWndRTB, SB_HORZ, &scrollInfo);
int width = scrollInfo.nMax - scrollInfo.nMin;
columnWidth = (twipsPerPixelX * width - rowIndent) / columnCount;
}
CAtlStringA rawRichText = "{\\rtf1\\ansi\r\n\\uc1";
for(LONG row = 1; row <= rowCount; ++row) {
// row properties
rawRichText += "\\trowd";
if(pTmp && _itoa_s(horizontalCellMargin, pTmp, 70, 10) == 0) {
rawRichText += "\\trgaph";
rawRichText += pTmp;
} else {
rawRichText += "\\trgaph72";
}
switch(horizontalRowAlignment) {
case halLeft:
rawRichText += "\\trql";
break;
case halCenter:
rawRichText += "\\trqc";
break;
case halRight:
rawRichText += "\\trqr";
break;
}
if(pTmp && _itoa_s(rowIndent, pTmp, 70, 10) == 0) {
rawRichText += "\\trleft";
rawRichText += pTmp;
} else {
rawRichText += "\\trleft0";
}
if(rowHeight > 0 && pTmp) {
if(_itoa_s(rowHeight, pTmp, 70, 10) == 0) {
rawRichText += "\\trrh";
rawRichText += pTmp;
}
}
if(pTmp && _itoa_s(horizontalCellMargin, pTmp, 70, 10) == 0) {
rawRichText += "\\trpaddl";
rawRichText += pTmp;
rawRichText += "\\trpaddr";
rawRichText += pTmp;
} else {
rawRichText += "\\trpaddl72\\trpaddr72";
}
rawRichText += "\\trpaddfl3\\trpaddfr3\r\n";
for(LONG column = 1; column <= columnCount; ++column) {
switch(verticalCellAlignment) {
case valTop:
rawRichText += "\\clvertalt";
break;
case valCenter:
rawRichText += "\\clvertalc";
break;
case valBottom:
rawRichText += "\\clvertalb";
break;
}
// cell borders and cell width
if(borderSize > 0 && pTmp && _itoa_s(borderSize, pTmp, 70, 10) == 0) {
rawRichText += "\\clbrdrl\\brdrw";
rawRichText += pTmp;
rawRichText += "\\brdrs\\clbrdrt\\brdrw";
rawRichText += pTmp;
rawRichText += "\\brdrs\\clbrdrr\\brdrw";
rawRichText += pTmp;
rawRichText += "\\brdrs\\clbrdrb\\brdrw";
rawRichText += pTmp;
rawRichText += "\\brdrs";
} else {
rawRichText += "\\clbrdrl\\brdrw0\\brdrs\\clbrdrt\\brdrw0\\brdrs\\clbrdrr\\brdrw0\\brdrs\\clbrdrb\\brdrw0\\brdrs";
}
if(pTmp && _itoa_s(rowIndent + (column * columnWidth), pTmp, 70, 10) == 0) {
rawRichText += " \\cellx";
rawRichText += pTmp;
}
}
rawRichText += "\\pard\\intbl";
for(LONG column = 1; column <= columnCount; ++column) {
// end of cell
rawRichText += "\\cell";
}
// end of row
rawRichText += "\\row";
if(row == rowCount) {
rawRichText += "\r\n";
}
}
rawRichText += "}\r\n";
if(pTmp) {
SECUREFREE(pTmp);
}
SETTEXTEX options = {0};
options.flags = ST_SELECTION | ST_KEEPUNDO;
options.codepage = 0xFFFFFFFF;
LPCSTR pBuffer = rawRichText;
if(SendMessage(hWndRTB, EM_SETTEXTEX, reinterpret_cast<WPARAM>(&options), reinterpret_cast<LPARAM>(pBuffer))) {
hr = S_OK;
} else {
hr = E_FAIL;
}
// keep the object alive until after EM_SETTEXTEX
rawRichText = "";
}*/
if(SUCCEEDED(hr)) {
CComPtr<ITextRange> pTextRange = NULL;
properties.pTextRange->GetDuplicate(&pTextRange);
pTextRange->SetStart(rangeStart);
ClassFactory::InitTable(pTextRange, properties.pOwnerRTB, IID_IRichTable, reinterpret_cast<LPUNKNOWN*>(ppAddedTable));
}
return hr;
}
STDMETHODIMP TextRange::ScrollIntoView(ScrollIntoViewConstants flags/* = sivScrollRangeStartToTop*/)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->ScrollIntoView(flags);
}
return hr;
}
STDMETHODIMP TextRange::Select(void)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->Select();
}
return hr;
}
STDMETHODIMP TextRange::SetStartAndEnd(LONG anchorEnd, LONG activeEnd)
{
HRESULT hr = E_FAIL;
if(properties.pTextRange) {
hr = properties.pTextRange->SetRange(anchorEnd, activeEnd);
}
return hr;
} | 29.6725 | 426 | 0.706883 | [
"object"
] |
e0addaca48e349c6d1cc88802a5ef0a842c0c1f7 | 504 | cc | C++ | src/app/riscv-test-config.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | 6 | 2019-02-07T18:22:17.000Z | 2021-11-05T01:43:09.000Z | src/app/riscv-test-config.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | null | null | null | src/app/riscv-test-config.cc | csail-csg/riscv-meta | 4258e8e8784ad2fb2bc77f9d867fe762f86561aa | [
"BSD-3-Clause"
] | 2 | 2018-02-06T13:26:41.000Z | 2020-12-06T09:46:16.000Z | //
// riscv-test-config.cc
//
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include <string>
#include <memory>
#include <vector>
#include <deque>
#include <map>
#include "riscv-config-parser.h"
#include "riscv-config.h"
int main(int argc, const char * argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s <configfile>\n", argv[0]);
exit(1);
}
riscv_config cfg;
cfg.read(argv[1]);
printf("%s", cfg.to_string().c_str());
return 0;
}
| 15.272727 | 55 | 0.652778 | [
"vector"
] |
e0b928e19412d1dca54c1208c6dde5946d0d6855 | 2,190 | hpp | C++ | examples/Particles/SpacebattleDemo.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | examples/Particles/SpacebattleDemo.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | examples/Particles/SpacebattleDemo.hpp | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | #pragma once
#ifndef NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP
#define NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Graphics/ParticleStruct.hpp>
#include <Nazara/Graphics/SkyboxBackground.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Platform/EventHandler.hpp>
#include <NDK/Entity.hpp>
#include <NDK/State.hpp>
#include <vector>
#include "Common.hpp"
class SpacebattleExample : public ParticleDemo
{
public:
SpacebattleExample(ExampleShared& sharedData);
~SpacebattleExample() = default;
void Enter(Ndk::StateMachine& fsm) override;
void Leave(Ndk::StateMachine& fsm) override;
bool Update(Ndk::StateMachine& fsm, float elapsedTime) override;
private:
void CreateSpaceShip();
void CreateTurret();
void OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event);
struct Turret
{
Nz::ModelRef baseModel;
Nz::ModelRef cannonModel;
Nz::ModelRef cannonBaseModel;
Nz::ModelRef rotatingBaseModel;
Ndk::EntityHandle baseEntity;
Ndk::EntityHandle cannonAnchorEntity;
Ndk::EntityHandle cannonEntity;
Ndk::EntityHandle cannonBaseEntity;
Ndk::EntityHandle rotatingBaseEntity;
};
Turret m_turret;
float m_introTimer;
float m_spaceshipSpawnCounter;
float m_turretBaseRotation;
float m_turretCannonBaseRotation;
float m_turretShootTimer;
Nz::ModelRef m_spaceshipModel;
Nz::ModelRef m_spacestationModel;
Nz::Music m_ambientMusic;
Nz::ParticleDeclarationRef m_torpedoDeclaration;
Nz::ParticleRendererRef m_laserBeamRenderer;
Nz::Sound m_turretFireSound;
Nz::Sound m_turretReloadSound;
Nz::SkyboxBackground m_skybox;
Ndk::EntityHandle m_introText;
Ndk::EntityHandle m_spaceshipTemplate;
Ndk::EntityHandle m_spacestationEntity;
Ndk::ParticleGroupComponentHandle m_fireGroup;
Ndk::ParticleGroupComponentHandle m_smokeGroup;
Ndk::ParticleGroupComponentHandle m_torpedoGroup;
NazaraSlot(Nz::EventHandler, OnMouseMoved, m_onMouseMoved);
};
#endif // NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP
| 30.416667 | 104 | 0.79589 | [
"vector",
"model"
] |
e0bd195ed0d70fd3c9f936db1dfcb2750e639b01 | 3,136 | cpp | C++ | userrecognizer_window.cpp | moonmedtwo/MyEyes | d64719863e559779389603233686f30b0bf50199 | [
"MIT"
] | 1 | 2019-05-05T01:13:59.000Z | 2019-05-05T01:13:59.000Z | userrecognizer_window.cpp | moonmedtwo/MyEyes | d64719863e559779389603233686f30b0bf50199 | [
"MIT"
] | null | null | null | userrecognizer_window.cpp | moonmedtwo/MyEyes | d64719863e559779389603233686f30b0bf50199 | [
"MIT"
] | null | null | null | #include "userrecognizer_window.h"
#include "ui_userRecognizer_window.h"
/*
* @brief: parse cloud list from QStringList
*/
void
UserRecognizer_Window::update_cloud_list(const QStringList &list, const QString &root)
{
if(list.size() > 0)
{
cloud_list_.clear();
for(int i = 0; i < list.size(); ++i)
{
std::string s_root = root.toStdString();
QString path = list.at(i);
std::string s_path = path.toStdString();
if(s_root.back() != '/')
{
s_root += '/';
}
cloud_list_.push_back(s_root + s_path);
}
}
}
/*
* @brief: render point cloud to UI
*/
void
UserRecognizer_Window::renderCloud(const std::string &path)
{
if(!viewer_started_)
{
viewer_.reset(new pcl::visualization::PCLVisualizer("model_vis",false));
ui->qvtkWidget->SetRenderWindow(viewer_->getRenderWindow());
// viewer_->setupInteractor(ui->qvtkWidget->GetInteractor(),\
// ui->qvtkWidget->GetRenderWindow());
viewer_->addCoordinateSystem(0.1,"coordinateAxis",0);
viewer_started_ = true;
}
pcl::PCDReader reader;
CloudPtr cloud(new Cloud);
reader.read(path,*cloud);
if(cloud->points.size() <= 0)
return;
viewer_->removeAllPointClouds();
viewer_->addPointCloud(cloud,"cloud",0);
viewer_->resetCameraViewpoint("cloud");
viewer_->resetCamera();
ui->qvtkWidget->update();
}
/*
* @brief: filter all files related to pointcloud in dir
* @brief: add files to cloud_list_ with update_cloud_list()
*/
void
UserRecognizer_Window::filterCloudinDir(QDir &dir)
{
dir.setNameFilters(QStringList("*.pcd"));
dir.setFilter(QDir::Files);
dir.setSorting(QDir::Name);
update_cloud_list(dir.entryList(),dir.path());
}
/*
* @brief: update private member variables
* @brief: and UI when model_dir_ changes
*/
void
UserRecognizer_Window::updateModelDir(const std::string &dir)
{
// Update private variable
std::cout << __FUNCTION__ << " " << model_dir_ << std::endl;
model_dir_ = dir;
// Convert to QString
QString dir_path(QString::fromStdString(model_dir_));
ui->label_modelPath->setText(dir_path);
{
QDir curDir(dir_path);
filterCloudinDir(curDir);
}
if(cloud_list_.size() > 0)
{
renderCloud(cloud_list_[0]);
}
}
UserRecognizer_Window::UserRecognizer_Window(QWidget *parent,const std::string &model_dir) :
QDialog(parent),
ui(new Ui::UserRecognizer_Window),
model_dir_(model_dir)
{
ui->setupUi(this);
updateModelDir(model_dir_);
}
UserRecognizer_Window::~UserRecognizer_Window()
{
delete ui;
}
void UserRecognizer_Window::on_pushButton_chooseModel_clicked()
{
QString dir =
QFileDialog::getExistingDirectory(this, tr("Open Directory"),
DATABASE_ROOT,
QFileDialog::ShowDirsOnly |
QFileDialog::DontResolveSymlinks);
updateModelDir(dir.toStdString());
}
| 26.352941 | 92 | 0.618941 | [
"render"
] |
e0c47a8bcdfc4c099cce60cb3a38017b8e70a741 | 659 | cpp | C++ | intro_vectors.cpp | pysogge/cpp_script_projects | 58578106ed0f33cc60de11df8eb4886fc3595797 | [
"MIT"
] | 1 | 2022-03-10T15:24:36.000Z | 2022-03-10T15:24:36.000Z | intro_vectors.cpp | pysogge/cpp_script_projects | 58578106ed0f33cc60de11df8eb4886fc3595797 | [
"MIT"
] | null | null | null | intro_vectors.cpp | pysogge/cpp_script_projects | 58578106ed0f33cc60de11df8eb4886fc3595797 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, q;
int k, val;
int indexI, indexJ;
// cin >> n >> q;
scanf("%d %d", &n, &q);
vector< vector<int> > a(n);
for(int i = 0; i < n; i++){
cin >> k;
vector<int> b(k);
for(int j = 0; j < k; j++){
cin >> val;
b[j] = val;
// cout << val << "->" << b[j] << endl;
// b.push_back(val) not working
}
a[i] = b;
}
for(int m = 0; m < q; m++){
cin >> indexI >> indexJ;
cout << a[indexI][indexJ] << endl;
}
return 0;
} | 18.828571 | 51 | 0.38088 | [
"vector"
] |
e0c68a3b4655bc400633a1b10bc3adab46b73880 | 2,283 | cpp | C++ | twitPick/src/TwitterParser.cpp | rlunaro/twitPick | 91a8be4dde7bbca1bbe39f7fe8e36cf90e88338f | [
"Apache-2.0"
] | null | null | null | twitPick/src/TwitterParser.cpp | rlunaro/twitPick | 91a8be4dde7bbca1bbe39f7fe8e36cf90e88338f | [
"Apache-2.0"
] | null | null | null | twitPick/src/TwitterParser.cpp | rlunaro/twitPick | 91a8be4dde7bbca1bbe39f7fe8e36cf90e88338f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Raul Luna
*
* 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.
*
*/
/*
* TwitterParser.cpp
*
* rluna
* Dec 27, 2018
*
*/
#include <TwitterParser.h>
TwitterParser::TwitterParser( std::string statusesLine )
{
parse( statusesLine );
}
void TwitterParser::parse( std::string statusesLine )
{
// traverse all the status
auto twitterJson = nlohmann::json::parse( statusesLine );
statuses.clear();
for( nlohmann::json statusLine : twitterJson["statuses"] )
{
TwitterStatus status;
status = parseSingleStatus( statusLine );
statuses.push_back( status );
}
statusesIt = statuses.begin();
}
TwitterStatus TwitterParser::parseSingleStatus( nlohmann::json statusLine )
{
TwitterStatus status;
status.createdAt = statusLine["created_at"];
status.id = statusLine["id_str"];
status.text = statusLine["full_text"];
status.source = statusLine["source"];
status.retweetCount = statusLine["retweet_count"];
status.lang = statusLine["lang"];
status.user = parseSingleUser( statusLine["user"] );
return status;
} // parseSingleStatus
TwitterUser TwitterParser::parseSingleUser( nlohmann::json userLine )
{
TwitterUser user;
user.id = userLine["id_str"];
user.name = userLine["name"];
user.screenName = userLine["screen_name"];
user.followersCount = userLine["followers_count"];
user.lang = userLine["lang"];
return user;
} // parseSingleUser
std::vector<TwitterStatus> TwitterParser::getStatuses()
{
return statuses;
}
bool TwitterParser::isNextStatus() const
{
return statusesIt != statuses.end();
}
TwitterStatus TwitterParser::next()
{
TwitterStatus nextStatus = *statusesIt;
statusesIt++;
return nextStatus;
}
| 24.287234 | 75 | 0.696452 | [
"vector"
] |
e0c81f87315340b596df0fd67a0f8365ccdb1cb2 | 1,584 | hpp | C++ | spotify_stream/src/drm/widevine_session.hpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | 2 | 2020-06-07T16:47:20.000Z | 2021-03-20T10:41:34.000Z | spotify_stream/src/drm/widevine_session.hpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | spotify_stream/src/drm/widevine_session.hpp | Yanick-Salzmann/carpi | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | [
"Apache-2.0"
] | null | null | null | #ifndef CARPI_WIDEVINE_SESSION_HPP
#define CARPI_WIDEVINE_SESSION_HPP
#include <string>
#include <vector>
#include "../cdm/content_decryption_module.hpp"
#include <common_utils/log.hpp>
#include <net_utils/http_client.hpp>
#include <cstdint>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <uuid/uuid.h>
namespace carpi::spotify::drm {
class WidevineAdapter;
class WidevineSession {
LOGGER;
net::http_client _client{};
std::string _session_id{};
std::string _license_server_url{};
std::string _access_token{};
std::condition_variable _license_event{};
std::mutex _license_lock;
bool _has_license = false;
WidevineAdapter *_adapter = nullptr;
void forward_license_request(const std::vector<uint8_t> &data);
public:
explicit WidevineSession(WidevineAdapter *adapter, std::string session_id, std::string license_server_url, std::string access_token) :
_adapter{adapter},
_session_id{std::move(session_id)},
_license_server_url{std::move(license_server_url)},
_access_token{std::move(access_token)} {
}
void on_license_updated();
void handle_message(cdm::MessageType message_type, const std::vector<uint8_t> &data);
void wait_for_license();
void decrypt_sample(uuid_t key_id, const void* iv, std::size_t iv_size, const void* encrypted, std::size_t encrypted_size, std::vector<uint8_t>& decrypted);
};
}
#endif //CARPI_WIDEVINE_SESSION_HPP
| 28.8 | 164 | 0.684975 | [
"vector"
] |
e0cb77517b1a0db9cfbfd4d797213beb714d7f7d | 5,392 | cpp | C++ | src/modules/packetio/memory/dpdk/pool_allocator.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/modules/packetio/memory/dpdk/pool_allocator.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/modules/packetio/memory/dpdk/pool_allocator.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | #include <memory>
#include <numeric>
#include "lwip/pbuf.h"
#include "core/op_core.h"
#include "packetio/drivers/dpdk/dpdk.h"
#include "packetio/drivers/dpdk/model/port_info.hpp"
#include "packetio/memory/dpdk/memp.h"
#include "packetio/memory/dpdk/pool_allocator.hpp"
namespace openperf::packetio::dpdk {
/*
* Per the DPDK documentation, cache size should be a divisor of pool
* size. However, since the optimal pool size is a Mersenne number,
* nice multiples of 2 tend to be wasteful. This table specifies the
* cache size to use for various pool sizes in order to minimize wasted
* pool elements.
*/
#if RTE_MEMPOOL_CACHE_MAX_SIZE < 512
#error "RTE_MEMPOOL_CACHE_MAX_SIZE must be at least 512"
#endif
#if RTE_MBUF_PRIV_ALIGN != MEM_ALIGNMENT
#error "RTE_MBUF_PRIV_ALIGN and lwip's MEM_ALIGNMENT msut be equal"
#endif
static struct cache_size_map
{
uint32_t nb_mbufs;
uint32_t cache_size;
} packetio_cache_size_map[] = {
{63, 9}, /* 63 % 9 == 0 */
{127, 21}, /* 127 % 21 == 1 (127 is prime) */
{255, 51}, /* 255 % 51 == 0 */
{511, 73}, /* 511 % 73 == 0 */
{1023, 341}, /* 1023 % 341 == 0 */
{2047, 341}, /* 2047 % 341 == 1 */
{4095, 455}, /* 4095 % 455 == 0 */
{8191, 455}, /* 8191 % 455 == 1 (8191 is prime) */
{16383, 455}, /* 16383 % 455 == 3 */
{32767, 504}, /* 32767 % 504 == 7 */
{65535, 508}, /* 65535 % 508 == 3 */
{131071, 510}, /* 131071 % 510 == 1 (131071 is prime) */
};
__attribute__((const)) static uint32_t get_cache_size(uint32_t nb_mbufs)
{
for (size_t i = 0; i < op_count_of(packetio_cache_size_map); i++) {
if (packetio_cache_size_map[i].nb_mbufs == nb_mbufs) {
return (packetio_cache_size_map[i].cache_size);
}
}
return (RTE_MEMPOOL_CACHE_MAX_SIZE);
}
/*
* Convert nb_mbufs to a Mersenne number, as those are the
* most efficient size for mempools. If our input is already a
* power of 2, return input - 1 instead of doubling the size.
*/
__attribute__((const)) static uint32_t pool_size_adjust(uint32_t nb_mbufs)
{
return (rte_is_power_of_2(nb_mbufs) ? nb_mbufs - 1
: rte_align32pow2(nb_mbufs) - 1);
}
static void log_mempool(const struct rte_mempool* mpool)
{
OP_LOG(OP_LOG_DEBUG,
"%s: %u, %u byte mbufs on NUMA socket %d\n",
mpool->name,
mpool->size,
rte_pktmbuf_data_room_size((struct rte_mempool*)mpool),
mpool->socket_id);
}
static rte_mempool* create_pbuf_mempool(
const char* name, size_t size, bool cached, bool direct, int socket_id)
{
static_assert(PBUF_PRIVATE_SIZE >= sizeof(struct pbuf));
size_t nb_mbufs = op_min(131072, pool_size_adjust(op_max(1024U, size)));
rte_mempool* mp =
rte_pktmbuf_pool_create_by_ops(name,
nb_mbufs,
cached ? get_cache_size(nb_mbufs) : 0,
PBUF_PRIVATE_SIZE,
direct ? PBUF_POOL_BUFSIZE : 0,
socket_id,
"stack");
if (!mp) {
throw std::runtime_error(std::string("Could not allocate mempool = ")
+ name);
}
log_mempool(mp);
return (mp);
}
pool_allocator::pool_allocator(const std::vector<model::port_info>& info,
const std::map<int, queue::count>& q_counts)
{
/* Base default pool size on the number and types of ports on each NUMA node
*/
for (auto i = 0U; i < RTE_MAX_NUMA_NODES; i++) {
auto sum = std::accumulate(
begin(info),
end(info),
0,
[&](unsigned lhs, const model::port_info& rhs) {
const auto& cursor = q_counts.find(rhs.id());
if (cursor == q_counts.end() || rhs.socket_id() != i) {
return (lhs);
}
return (lhs + (cursor->second.rx * rhs.rx_desc_count())
+ (cursor->second.tx * rhs.tx_desc_count()));
});
if (sum) {
/*
* Create both a ref/rom and default mempool for each NUMA node with
* ports Note: we only use a map for the rom/ref pools for symmetry.
* We never actually need to look them up.
*/
std::array<char, RTE_MEMPOOL_NAMESIZE> name_buf;
snprintf(name_buf.data(),
RTE_MEMPOOL_NAMESIZE,
memp_ref_rom_mempool_fmt,
i);
m_ref_rom_mpools.emplace(
i,
create_pbuf_mempool(
name_buf.data(), MEMP_NUM_PBUF, false, false, i));
snprintf(name_buf.data(),
RTE_MEMPOOL_NAMESIZE,
memp_default_mempool_fmt,
i);
m_default_mpools.emplace(
i, create_pbuf_mempool(name_buf.data(), sum, true, true, i));
}
}
};
rte_mempool* pool_allocator::rx_mempool(unsigned socket_id) const
{
assert(socket_id <= RTE_MAX_NUMA_NODES);
auto found = m_default_mpools.find(socket_id);
return (found == m_default_mpools.end() ? nullptr : found->second.get());
}
} // namespace openperf::packetio::dpdk
| 33.91195 | 80 | 0.567322 | [
"vector",
"model"
] |
e0cb94175066c636c7883b999b53989d6024d334 | 6,161 | cpp | C++ | modules/wechat_qrcode/src/zxing/common/bitarray.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/wechat_qrcode/src/zxing/common/bitarray.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/wechat_qrcode/src/zxing/common/bitarray.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Tencent is pleased to support the open source community by making WeChat QRCode available.
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Modified from ZXing. Copyright ZXing authors.
// Licensed under the Apache License, Version 2.0 (the "License").
#include "../../precomp.hpp"
#include "bitarray.hpp"
using zxing::ArrayRef;
using zxing::BitArray;
using zxing::ErrorHandler;
using zxing::Ref;
BitArray::BitArray(int size_) : size(size_), bits(size_), nextSets(size_), nextUnSets(size_) {}
void BitArray::setUnchar(int i, unsigned char newBits) { bits[i] = newBits; }
bool BitArray::isRange(int start, int end, bool value, ErrorHandler &err_handler) {
if (end < start) {
err_handler = IllegalArgumentErrorHandler("isRange");
return false;
}
if (start < 0 || end >= bits->size()) {
err_handler = IllegalArgumentErrorHandler("isRange");
return false;
}
if (end == start) {
return true; // empty range matches
}
bool startBool = bits[start] != (unsigned char)0;
int end2 = start;
if (startBool) {
end2 = getNextUnset(start);
} else {
end2 = getNextSet(start);
}
if (startBool == value) {
if (end2 < end) {
return false;
}
} else {
return false;
}
return true;
}
void BitArray::reverse() {
bool *rowBits = getRowBoolPtr();
bool tempBit;
for (int i = 0; i < size / 2; i++) {
tempBit = rowBits[i];
rowBits[i] = rowBits[size - i - 1];
rowBits[size - i - 1] = tempBit;
}
}
void BitArray::initAllNextSets() {
bool *rowBits = getRowBoolPtr();
int *nextSetArray = nextSets->data();
int *nextUnsetArray = nextUnSets->data();
// Init the last one
if (rowBits[size - 1]) {
nextSetArray[size - 1] = size - 1;
nextUnsetArray[size - 1] = size;
} else {
nextUnsetArray[size - 1] = size - 1;
nextSetArray[size - 1] = size;
}
// do inits
for (int i = size - 2; i >= 0; i--) {
if (rowBits[i]) {
nextSetArray[i] = i;
nextUnsetArray[i] = nextUnsetArray[i + 1];
} else {
nextUnsetArray[i] = i;
nextSetArray[i] = nextSetArray[i + 1];
}
}
}
void BitArray::initAllNextSetsFromCounters(std::vector<int> counters) {
bool *rowBits = getRowBoolPtr();
bool isWhite = rowBits[0];
int c = 0;
int offset = 0;
int count = 0;
int prevCount = 0;
int currCount = 0;
int _size = counters.size();
int *nextSetArray = nextSets->data();
int *nextUnsetArray = nextUnSets->data();
// int* countersArray = counters.data();
int *countersArray = &counters[0];
while (c < _size) {
currCount = countersArray[c];
count += currCount;
if (isWhite) {
for (int i = 0; i < currCount; i++) {
offset = prevCount + i;
nextSetArray[offset] = prevCount + i;
nextUnsetArray[offset] = count;
}
} else {
for (int i = 0; i < currCount; i++) {
offset = prevCount + i;
nextSetArray[offset] = count;
nextUnsetArray[offset] = prevCount + i;
}
}
isWhite = !isWhite;
prevCount += currCount;
c++;
}
}
int BitArray::getNextSet(int from) {
if (from >= size) {
return size;
}
return nextSets[from];
}
int BitArray::getNextUnset(int from) {
if (from >= size) {
return size;
}
return nextUnSets[from];
}
BitArray::~BitArray() {}
int BitArray::getSize() const { return size; }
void BitArray::clear() {
int max = bits->size();
for (int i = 0; i < max; i++) {
bits[i] = 0;
}
}
BitArray::Reverse::Reverse(Ref<BitArray> array_) : array(array_) { array->reverse(); }
BitArray::Reverse::~Reverse() { array->reverse(); }
void BitArray::appendBit(bool value) {
ArrayRef<unsigned char> newBits(size + 1);
for (int i = 0; i < size; i++) {
newBits[i] = bits[i];
}
bits = newBits;
if (value) {
set(size);
}
++size;
}
int BitArray::getSizeInBytes() const { return size; }
// Appends the least-significant bits, from value, in order from
// most-significant to least-significant. For example, appending 6 bits
// from 0x000001E will append the bits 0, 1, 1, 1, 1, 0 in that order.
void BitArray::appendBits(int value, int numBits, ErrorHandler &err_handler) {
if (numBits < 0 || numBits > 32) {
err_handler = IllegalArgumentErrorHandler("Number of bits must be between 0 and 32");
return;
}
ArrayRef<unsigned char> newBits(size + numBits);
for (int i = 0; i < size; i++) newBits[i] = bits[i];
bits = newBits;
for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {
if (((value >> (numBitsLeft - 1)) & 0x01) == 1) {
set(size);
}
++size;
}
return;
}
void BitArray::appendBitArray(const BitArray &array) {
ArrayRef<unsigned char> newBits(size + array.getSize());
for (int i = 0; i < size; ++i) {
newBits[i] = bits[i];
}
bits = newBits;
for (int i = 0; i < array.getSize(); ++i) {
if (array.get(i)) {
set(size);
}
++size;
}
}
void BitArray::toBytes(int bitOffset, ArrayRef<int> &array, int offset, int numBytes) {
for (int i = 0; i < numBytes; i++) {
int theByte = 0;
if (get(bitOffset)) {
theByte = 1;
}
bitOffset++;
array[offset + i] = theByte;
}
}
void BitArray::bitXOR(const BitArray &other, ErrorHandler &err_handler) {
if (size != other.size) {
err_handler = IllegalArgumentErrorHandler("Sizes don't match");
return;
}
for (int i = 0; i < bits->size(); i++) {
bits[i] = bits[i] == other.bits[i] ? 0 : 1;
}
}
| 26.32906 | 95 | 0.566466 | [
"vector"
] |
e0cf75c2360316aab6948642c5db979403b095ee | 1,580 | cpp | C++ | tests/test-hash/test-hash.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 19 | 2016-06-18T02:03:56.000Z | 2022-02-23T17:26:32.000Z | tests/test-hash/test-hash.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 43 | 2017-03-09T07:32:12.000Z | 2022-03-23T20:18:35.000Z | tests/test-hash/test-hash.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 5 | 2019-11-14T22:24:02.000Z | 2021-09-07T18:27:21.000Z | // Description: test HumHash class.
#include <iostream>
#include "HumHash.h"
#include "HumNum.h"
using namespace hum;
int main(int argc, char** argv) {
HumHash myhash;
myhash.setValue("LO", "N", "vis", "3");
cout << "VALUE for vis = " << myhash.getValue("LO", "N", "vis") << endl;
cout << "VALUE for vis = " << myhash.getValue("LO:N:vis") << endl;
// myhash.deleteValue("LO:N:vis");
cout << "VALUE for vis = " << myhash.getValue("LO:N:vis") << endl;
cout << "INTVALUE for vis = " << myhash.getValueInt("LO:N:vis") << endl;
cout << "DOES vis exist? " << myhash.isDefined("LO:N:vis") << endl;
cout << "DOES x exist? " << myhash.isDefined("LO:N:x") << endl;
cout << "VALUE for x = \"" << myhash.getValue("LO", "N", "x")
<< "\"" << endl;
cout << "DOES x exist? " << myhash.isDefined("LO:N:x") << endl;
vector<string> keys = myhash.getKeys("LO", "N");
for (int i=0; i<keys.size(); i++) {
cout << "KEY " << i << ": " << keys[i] << endl;
}
// HumNum n("4/5");
HumNum n(5,4);
cout << "NEW NUMBER IS " << n << endl;
myhash.setValue("global", n);
myhash.setValue("", "global", n);
myhash.setValue("", "", "global", n);
cout << "global = " << myhash.getValueFraction("global") << endl;
cout << ":global = " << myhash.getValueFraction("", "global") << endl;
cout << "::global = " << myhash.getValueFraction("", "", "global") << endl;
cout << "int value = " << myhash.getValueInt("", "", "global") << endl;
cout << "int float = " << myhash.getValueFloat("", "", "global") << endl;
return 0;
}
| 36.744186 | 78 | 0.544304 | [
"vector"
] |
e0d5c82f62ae0e668dafeb179d0455e9bb907245 | 2,028 | cpp | C++ | UtinniCore/swg/ui/utinni_command_parser.cpp | ptklatt/Utinni | db69278c9f35464242f4e9d62b1ea9587c7ec60f | [
"MIT"
] | 8 | 2020-10-30T02:44:59.000Z | 2022-03-24T03:14:05.000Z | UtinniCore/swg/ui/utinni_command_parser.cpp | ModTheGalaxy/Utinni | 6fc118d7d80667a6e12864fc5fffe5782eaacd58 | [
"MIT"
] | 2 | 2021-01-12T00:47:23.000Z | 2021-03-20T21:02:25.000Z | UtinniCore/swg/ui/utinni_command_parser.cpp | ModTheGalaxy/Utinni | 6fc118d7d80667a6e12864fc5fffe5782eaacd58 | [
"MIT"
] | 7 | 2020-11-13T23:11:27.000Z | 2021-07-04T12:19:45.000Z | /**
* MIT License
*
* Copyright (c) 2020 Philip Klatt
*
* 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 "utinni_command_parser.h"
namespace utinni
{
static const CommandParser::CommandData commands[] =
{
{"test1", 0, "", "Test Command 1"},
{"test2", 0, "", "Test Command 2"}
};
UtinniCommandParser::UtinniCommandParser() : CommandParser("utinni", 0, "...", "Utinni related commands.", nullptr)
{
for (const auto& command : commands)
{
addSubCommand(swg_new<CommandParser>(command, this));
}
}
bool UtinniCommandParser::performParsing(const int64_t& userId, const std::vector<swg::WString>& args, const wchar_t* originalCommand, const wchar_t* result, const CommandParser* node)
{
auto& cmd = args[0];
if (cmd == "test1")
{
utility::showMessageBox("1");
return true;
}
swg::WString test2 = "test2";
if (cmd == test2)
{
utility::showMessageBox("2");
return true;
}
return false;
}
}
| 30.727273 | 184 | 0.699211 | [
"vector"
] |
e0da517c34a39337c2e8b599131f7fd9fbedba5c | 27,996 | cxx | C++ | ParaViewCore/VTKExtensions/SIL/vtkSubsetInclusionLattice.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | ParaViewCore/VTKExtensions/SIL/vtkSubsetInclusionLattice.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | ParaViewCore/VTKExtensions/SIL/vtkSubsetInclusionLattice.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-03-13T03:35:01.000Z | 2021-03-13T03:35:01.000Z | /*=========================================================================
Program: ParaView
Module: vtkSubsetInclusionLattice.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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.
=========================================================================*/
#include "vtkSubsetInclusionLattice.h"
#include "vtkCommand.h"
#include "vtkInformation.h"
#include "vtkInformationObjectBaseKey.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include <cassert>
#include <map>
#include <set>
#include <sstream>
#include <vtk_pugixml.h>
#include <vtksys/SystemTools.hxx>
//=============================================================================
/**
* Namespace of various pugi::xml_tree_walker subclasses
*/
//=============================================================================
namespace Walkers
{
/**
* This is a xml_tree_walker that walks the subtree setting
* `state` for every node it visits.
*
* If the node is `Node`, this simply updates the `state` attribute.
* If the node is `ref:link`, it calls `vtkInternals::SetSelectionState` on
* the linked node.
* If the node is `ref:rev-link`, it calls `vtkInternals::UpdateState` on the
* linked node.
*/
template <class T>
class SetState : public pugi::xml_tree_walker
{
T* Parent;
vtkSubsetInclusionLattice::SelectionStates State;
public:
SetState(T* parent, vtkSubsetInclusionLattice::SelectionStates state)
: Parent(parent)
, State(state)
{
}
bool for_each(pugi::xml_node& node) override
{
if (strcmp(node.name(), "Node") == 0)
{
auto attr = node.attribute("state");
if (attr && attr.as_int() != this->State)
{
attr.set_value(this->State);
this->Parent->TriggerSelectionChanged(node.attribute("uid").as_int());
}
}
else if (strcmp(node.name(), "ref:link") == 0)
{
this->Parent->SetSelectionState(
node.attribute("uid").as_int(), this->State == vtkSubsetInclusionLattice::Selected, false);
}
else if (strcmp(node.name(), "ref:rev-link") == 0)
{
this->Parent->UpdateState(node.attribute("uid").as_int());
}
return true;
}
void operator=(const SetState&) = delete;
};
/**
* A tree walker that walks the subtree clearing the "explicit_state" attribute.
*/
class ClearExplicit : public pugi::xml_tree_walker
{
public:
bool for_each(pugi::xml_node& node) override
{
node.remove_attribute("explicit_state");
return true;
}
void operator=(const ClearExplicit&) = delete;
};
/**
* A walker to build a selection-path map comprising of status for all leaf nodes.
*
* @section DefineSelection How to define selection
*
* I have not been able to decide which is the best way to define the selection.
* Is the user interested in preserving the state for a non-leaf node he toggled
* or the resolved leaves? If former, we need to preserve the order in which the
* operations happen too. For now, I am leaving towards the easiest i.e. the
* leaf node status.
*/
class SerializeSelection : public pugi::xml_tree_walker
{
std::map<std::string, bool>& Selection;
std::string path(const pugi::xml_node node) const
{
if (!node)
{
return std::string();
}
assert(strcmp(node.name(), "Node") == 0);
if (strcmp(node.attribute("name").value(), "SIL") == 0)
{
return std::string();
}
return this->path(node.parent()) + "/" + node.attribute("name").value();
}
public:
SerializeSelection(std::map<std::string, bool>& sel)
: Selection(sel)
{
}
bool for_each(pugi::xml_node& node) override
{
if (node && strcmp(node.name(), "Node") == 0 && !node.child("Node") && !node.child("ref:link"))
{
this->Selection[this->path(node)] =
node.attribute("state").as_int() == vtkSubsetInclusionLattice::Selected;
}
return true;
}
void operator=(const SerializeSelection&) = delete;
};
/**
* A walker that walks the tree and offsets all uids by a fixed amount.
*/
class OffsetUid : public pugi::xml_tree_walker
{
int Offset;
public:
OffsetUid(int offset)
: Offset(offset)
{
}
bool for_each(pugi::xml_node& node) override
{
auto attr = node.attribute("uid");
attr.set_value(this->Offset + attr.as_int());
return true;
}
void operator=(const OffsetUid&) = delete;
};
/**
* Given a map of old ids to new ids, updates all uid references in the tree
* that use the old ids to use the new ids instead.
*/
class UpdateIds : public pugi::xml_tree_walker
{
const std::map<int, int>& Map;
public:
UpdateIds(const std::map<int, int>& amap)
: Map(amap)
{
}
bool for_each(pugi::xml_node& node) override
{
auto attr = node.attribute("uid");
auto iter = this->Map.find(attr.as_int());
if (iter != this->Map.end())
{
attr.set_value(iter->second);
}
return true;
}
void operator=(const UpdateIds&) = delete;
};
/**
* A walker that cleans up uids in the tree by reassigning
* the ids for all nodes. Useful to keep the uids from increasing
* too much as trees are merged, for example.
*/
class ReassignUids : public pugi::xml_tree_walker
{
int& NextUID;
std::map<int, int> IdsMap;
public:
ReassignUids(int& nextuid)
: NextUID(nextuid)
{
}
bool for_each(pugi::xml_node& node) override
{
auto attr = node.attribute("uid");
auto iter = this->IdsMap.find(attr.as_int());
if (attr && iter == this->IdsMap.end())
{
const int newid = this->NextUID++;
this->IdsMap[attr.as_int()] = newid;
attr.set_value(newid);
}
else if (attr)
{
attr.set_value(iter->second);
}
return true;
}
void operator=(const ReassignUids&) = delete;
};
}
//=============================================================================
class vtkSubsetInclusionLattice::vtkInternals
{
int NextUID;
pugi::xml_document Document;
vtkSubsetInclusionLattice* Parent;
public:
vtkInternals(vtkSubsetInclusionLattice* self)
: NextUID(0)
, Parent(self)
{
this->Initialize();
}
void Initialize()
{
this->Document.load_string("<Node name='SIL' version='1.0' uid='0' next_uid='1' state='0' />");
this->NextUID = 1;
}
std::string Serialize() const
{
std::ostringstream str;
this->Document.save(str);
return str.str();
}
bool Deserialize(const char* data, vtkSubsetInclusionLattice* self)
{
pugi::xml_document document;
if (!document.load_string(data))
{
// leave state untouched.
return false;
}
if (document.child("Node"))
{
this->Document.reset(document);
this->NextUID = this->Document.first_child().attribute("next_uid").as_int();
self->Modified();
return true;
}
return false;
}
vtkSubsetInclusionLattice::SelectionType GetSelection() const
{
vtkSubsetInclusionLattice::SelectionType selection;
Walkers::SerializeSelection walker(selection);
this->Document.first_child().traverse(walker);
return selection;
}
pugi::xml_node Find(int uid) const
{
if (uid < 0)
{
return pugi::xml_node();
}
return this->Document.find_node([=](const pugi::xml_node& node) {
return strcmp(node.name(), "Node") == 0 && node.attribute("uid").as_int() == uid;
});
}
pugi::xml_node GetRoot() const { return this->Document.first_child(); }
pugi::xml_node Find(const char* xpath) const { return this->Document.select_node(xpath).node(); }
int GetNextUID()
{
int next = this->NextUID++;
this->Document.first_child().attribute("next_uid").set_value(this->NextUID);
return next;
}
void Print(ostream& os, vtkIndent indent)
{
std::ostringstream str;
str << indent;
this->Document.save(os, str.str().c_str());
}
bool SetSelectionState(int id, bool value, bool isexplicit = false)
{
auto node = this->Find(id);
return node ? this->SetSelectionState(node, value, isexplicit) : false;
}
bool SetSelectionState(pugi::xml_node node, bool value, bool isexplicit = false)
{
if (!node)
{
return false;
}
const vtkSubsetInclusionLattice::SelectionStates state =
value ? vtkSubsetInclusionLattice::Selected : vtkSubsetInclusionLattice::NotSelected;
auto state_attr = node.attribute("state");
// since node's state has been modified, ensure none of its children are
// flagged as `explicit_state`.
Walkers::ClearExplicit clearExplicit;
node.traverse(clearExplicit);
node.remove_attribute("explicit_state");
if (isexplicit)
{
node.append_attribute("explicit_state").set_value(state);
}
if (state_attr.as_int() != state)
{
state_attr.set_value(state);
// notify that the node's selection state has changed.
this->Parent->TriggerSelectionChanged(node.attribute("uid").as_int());
// navigate down the tree and update state for all children.
// this will walk through `ref:link`.
Walkers::SetState<vtkSubsetInclusionLattice::vtkInternals> setState(this, state);
node.traverse(setState);
// navigate up and update state.
this->UpdateState(node.parent());
return true; // state changed.
}
return false; // state not changed.
}
void UpdateState(int id) { this->UpdateState(this->Find(id)); }
void UpdateState(pugi::xml_node node)
{
while (node)
{
auto state = this->GetStateFromImmediateChildren(node);
if (node.attribute("state").as_int() == state)
{
// nothing to do. changing node's state has no effect on node.
break;
}
node.attribute("state").set_value(state);
// notify that the node's selection state has changed.
this->Parent->TriggerSelectionChanged(node.attribute("uid").as_int());
node = node.parent();
}
}
vtkSubsetInclusionLattice::SelectionStates GetSelectionState(int id) const
{
return this->GetSelectionState(this->Find(id));
}
vtkSubsetInclusionLattice::SelectionStates GetSelectionState(const pugi::xml_node node) const
{
switch (node.attribute("state").as_int())
{
case vtkSubsetInclusionLattice::Selected:
return vtkSubsetInclusionLattice::Selected;
case vtkSubsetInclusionLattice::PartiallySelected:
return vtkSubsetInclusionLattice::PartiallySelected;
case vtkSubsetInclusionLattice::NotSelected:
default:
return vtkSubsetInclusionLattice::NotSelected;
}
}
static std::string ConvertXPath(const std::string& simplePath)
{
bool startsWithSep;
auto parts = vtkInternals::SplitString(simplePath, startsWithSep);
std::ostringstream stream;
stream << "/Node[@name='SIL']";
for (size_t cc = 0; cc < parts.size(); ++cc)
{
if (parts[cc].size() == 0)
{
stream << "/";
}
else
{
stream << "/Node[@name='" << parts[cc].c_str() << "']";
}
}
return stream.str();
}
void Merge(const std::string& state)
{
pugi::xml_document other;
if (!other.load_string(state.c_str()))
{
return;
}
// make all uid in `other` unique. this is necessary to avoid conflicts with
// ids in `this`.
Walkers::OffsetUid walker(this->NextUID);
other.traverse(walker);
// key: id in `other`, value: id in `this`.
std::map<int, int> merged_ids;
this->MergeNodes(merged_ids, this->Document.first_child(), other.first_child());
// now iterate and update all merged ids.
Walkers::UpdateIds walker2(merged_ids);
this->Document.traverse(walker2);
// now merge all duplicate "ref:link" and "ref:rev-link" nodes.
this->CleanDuplicateLinks(this->Document.first_child());
// now let's cleanup uids.
this->NextUID = 0;
Walkers::ReassignUids walker3(this->NextUID);
this->Document.traverse(walker3);
this->Document.first_child().attribute("next_uid").set_value(this->NextUID);
}
void TriggerSelectionChanged(int id)
{
if (id >= 0)
{
this->Parent->TriggerSelectionChanged(id);
}
}
private:
int GetState(const pugi::xml_node node) const
{
if (node && strcmp(node.name(), "Node") == 0)
{
return node.attribute("state").as_int();
}
else if (node && strcmp(node.name(), "ref:link") == 0)
{
return this->GetState(this->Find(node.attribute("uid").as_int()));
}
return vtkSubsetInclusionLattice::NotSelected;
}
vtkSubsetInclusionLattice::SelectionStates GetStateFromImmediateChildren(
const pugi::xml_node node) const
{
using vtkSIL = vtkSubsetInclusionLattice;
int selected_count = 0;
int notselected_count = 0;
int children_count = 0;
for (auto child : node.children())
{
int child_state;
if (strcmp(child.name(), "Node") == 0 || strcmp(child.name(), "ref:link") == 0)
{
children_count++;
child_state = this->GetState(child);
switch (child_state)
{
case vtkSIL::NotSelected:
notselected_count++;
break;
case vtkSIL::Selected:
selected_count++;
break;
case vtkSIL::PartiallySelected:
return vtkSIL::PartiallySelected;
}
if (selected_count > 0 && notselected_count > 0)
{
return vtkSIL::PartiallySelected;
}
}
}
if (selected_count == children_count)
{
return vtkSIL::Selected;
}
else if (notselected_count == children_count)
{
return vtkSIL::NotSelected;
}
return vtkSIL::PartiallySelected;
}
void MergeNodes(
std::map<int, int>& merged_ids, pugi::xml_node self, const pugi::xml_node other) const
{
merged_ids[other.attribute("uid").as_int()] = self.attribute("uid").as_int();
std::map<std::string, pugi::xml_node> selfChildrenMap;
for (auto node : self.children("Node"))
{
selfChildrenMap[node.attribute("name").value()] = node;
}
for (auto onode : other.children("Node"))
{
std::string name = onode.attribute("name").value();
auto iter = selfChildrenMap.find(name);
if (iter != selfChildrenMap.end())
{
this->MergeNodes(merged_ids, iter->second, onode);
}
else
{
self.append_copy(onode);
}
}
// links, we just append. we'll squash duplicates later.
for (auto onode : other.children("ref:link"))
{
self.append_copy(onode);
}
for (auto onode : other.children("ref:rev-link"))
{
self.append_copy(onode);
}
}
void CleanDuplicateLinks(pugi::xml_node self) const
{
for (auto node : self.children("Node"))
{
this->CleanDuplicateLinks(node);
}
std::set<int> seen_ids;
std::vector<pugi::xml_node> to_remove;
for (auto node : self.children("ref:link"))
{
int uid = node.attribute("uid").as_int();
if (seen_ids.find(uid) != seen_ids.end())
{
to_remove.push_back(node);
}
seen_ids.insert(uid);
}
seen_ids.clear();
for (auto node : self.children("ref:rev-link"))
{
int uid = node.attribute("uid").as_int();
if (seen_ids.find(uid) != seen_ids.end())
{
to_remove.push_back(node);
}
seen_ids.insert(uid);
}
for (auto node : to_remove)
{
self.remove_child(node);
}
}
// We don't use vtksys::SystemTools since it doesn't handle "//foo" correctly.
static std::vector<std::string> SplitString(const std::string& str, bool& startsWithSep)
{
std::vector<std::string> ret;
size_t pos = 0, posPrev = 0;
while ((pos = str.find('/', posPrev)) != std::string::npos)
{
if (pos == 0)
{
startsWithSep = true;
}
else
{
size_t len = pos - posPrev;
if (len > 0)
{
ret.push_back(str.substr(posPrev, len));
}
else
{
ret.push_back(std::string());
}
}
posPrev = pos + 1;
}
if (posPrev < str.size())
{
ret.push_back(str.substr(posPrev));
}
return ret;
}
};
vtkStandardNewMacro(vtkSubsetInclusionLattice);
vtkInformationKeyMacro(vtkSubsetInclusionLattice, SUBSET_INCLUSION_LATTICE, ObjectBase);
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice::vtkSubsetInclusionLattice()
: Internals(new vtkSubsetInclusionLattice::vtkInternals(this))
{
}
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice::~vtkSubsetInclusionLattice()
{
delete this->Internals;
this->Internals = nullptr;
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::Initialize()
{
vtkInternals& internals = (*this->Internals);
internals.Initialize();
this->Modified();
}
//----------------------------------------------------------------------------
std::string vtkSubsetInclusionLattice::Serialize() const
{
const vtkInternals& internals = (*this->Internals);
return internals.Serialize();
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Deserialize(const std::string& data)
{
vtkInternals& internals = (*this->Internals);
return internals.Deserialize(data.c_str(), this);
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Deserialize(const char* data)
{
vtkInternals& internals = (*this->Internals);
return internals.Deserialize(data, this);
}
//----------------------------------------------------------------------------
int vtkSubsetInclusionLattice::AddNode(const char* name, int parent)
{
vtkInternals& internals = (*this->Internals);
auto node = internals.Find(parent);
if (!node)
{
vtkErrorMacro("Invalid `parent` specified: " << parent);
return -1;
}
auto child = node.append_child("Node");
int uid = internals.GetNextUID();
child.append_attribute("name").set_value(name);
child.append_attribute("uid").set_value(uid);
child.append_attribute("state").set_value(0);
this->Modified();
return uid;
}
//----------------------------------------------------------------------------
int vtkSubsetInclusionLattice::AddNodeAtPath(const char* path)
{
if (path == nullptr || path[0] == 0)
{
return -1;
}
const int id = this->FindNode(path);
if (id != -1)
{
// path already exists.
return id;
}
std::string spath(path);
// confirm that path is full-qualified.
// i.e. starts with `/` and no `//`.
if (spath[0] != '/' || spath.find("//") != std::string::npos)
{
return -1;
}
bool modified = false;
vtkInternals& internals = (*this->Internals);
auto node = internals.Find(static_cast<int>(0));
// iterate component-by-component and then add nodes as needed.
spath.erase(0, 1); // remove leading '/'.
const auto components = vtksys::SystemTools::SplitString(spath);
for (const std::string& part : components)
{
pugi::xml_node nchild;
for (auto child : node.children("Node"))
{
auto attr = child.attribute("name");
if (attr && part == attr.value())
{
nchild = child;
break;
}
}
if (!nchild)
{
nchild = node.append_child("Node");
nchild.append_attribute("name").set_value(part.c_str());
nchild.append_attribute("uid").set_value(internals.GetNextUID());
nchild.append_attribute("state").set_value(0);
modified = true;
}
node = nchild;
}
if (modified)
{
this->Modified();
}
return node.attribute("uid").as_int();
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::AddCrossLink(int src, int dst)
{
vtkInternals& internals = (*this->Internals);
auto srcnode = internals.Find(src);
if (!srcnode)
{
vtkErrorMacro("Invalid `src` specified: " << src);
return false;
}
auto dstnode = internals.Find(dst);
if (!dstnode)
{
vtkErrorMacro("Invalid `dst` specified: " << dst);
return false;
}
auto ref = srcnode.append_child("ref:link");
ref.append_attribute("uid").set_value(dst);
auto rref = dstnode.append_child("ref:rev-link");
rref.append_attribute("uid").set_value(src);
this->Modified();
return true;
}
//----------------------------------------------------------------------------
int vtkSubsetInclusionLattice::FindNode(const char* spath) const
{
if (!spath)
{
return -1;
}
std::string convertedxpath = vtkInternals::ConvertXPath(spath);
const vtkInternals& internals = (*this->Internals);
auto srcnode = internals.Find(convertedxpath.c_str());
if (!srcnode)
{
return -1;
}
return srcnode.attribute("uid").as_int();
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Select(int node)
{
vtkInternals& internals = (*this->Internals);
return internals.SetSelectionState(node, true, true);
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Deselect(int node)
{
vtkInternals& internals = (*this->Internals);
return internals.SetSelectionState(node, false, true);
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::ClearSelections()
{
vtkInternals& internals = (*this->Internals);
internals.SetSelectionState(0, false, false);
}
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice::SelectionStates vtkSubsetInclusionLattice::GetSelectionState(
int node) const
{
const vtkInternals& internals = (*this->Internals);
return node >= 0 ? internals.GetSelectionState(node) : NotSelected;
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Select(const char* path)
{
// `AddNodeAtPath` doesn't add a new node if one already exists.
return this->Select(this->AddNodeAtPath(path));
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::Deselect(const char* path)
{
// `AddNodeAtPath` doesn't add a new node if one already exists.
return this->Deselect(this->AddNodeAtPath(path));
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::SelectAll(const char* spath)
{
std::string convertedxpath = vtkInternals::ConvertXPath(spath);
vtkInternals& internals = (*this->Internals);
auto root = internals.GetRoot();
bool retval = false;
for (auto xnode : root.select_nodes(convertedxpath.c_str()))
{
retval = internals.SetSelectionState(xnode.node(), true, true) || retval;
}
return retval;
}
//----------------------------------------------------------------------------
bool vtkSubsetInclusionLattice::DeselectAll(const char* spath)
{
std::string convertedxpath = vtkInternals::ConvertXPath(spath);
vtkInternals& internals = (*this->Internals);
auto root = internals.GetRoot();
bool retval = false;
for (auto xnode : root.select_nodes(convertedxpath.c_str()))
{
retval = internals.SetSelectionState(xnode.node(), false, true) || retval;
}
return retval;
}
//----------------------------------------------------------------------------
std::vector<int> vtkSubsetInclusionLattice::GetChildren(int node) const
{
std::vector<int> retval;
vtkInternals& internals = (*this->Internals);
auto xmlNode = internals.Find(node);
for (auto child : xmlNode.children("Node"))
{
retval.push_back(child.attribute("uid").as_int());
}
return retval;
}
//----------------------------------------------------------------------------
int vtkSubsetInclusionLattice::GetParent(int node, int* childIndex) const
{
int retval = -1;
if (childIndex)
{
*childIndex = -1;
}
vtkInternals& internals = (*this->Internals);
if (auto xmlNode = internals.Find(node))
{
if (auto parentNode = xmlNode.parent())
{
retval = parentNode.attribute("uid").as_int();
if (childIndex)
{
*childIndex = 0;
for (auto child : parentNode.children("Node"))
{
if (child == xmlNode)
{
break;
}
++(*childIndex);
}
}
}
}
return retval;
}
//----------------------------------------------------------------------------
const char* vtkSubsetInclusionLattice::GetNodeName(int node) const
{
vtkInternals& internals = (*this->Internals);
if (auto xmlNode = internals.Find(node))
{
return xmlNode.attribute("name").value();
}
return nullptr;
}
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice::SelectionType vtkSubsetInclusionLattice::GetSelection() const
{
return this->Internals->GetSelection();
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::SetSelection(
const vtkSubsetInclusionLattice::SelectionType& selection)
{
vtkInternals& internals = (*this->Internals);
internals.SetSelectionState(0, NotSelected, /*explicit=*/false);
for (auto s : selection)
{
if (s.second)
{
this->Select(s.first.c_str());
}
else
{
this->Deselect(s.first.c_str());
}
}
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::TriggerSelectionChanged(int node)
{
this->InvokeEvent(vtkCommand::StateChangedEvent, &node);
this->SelectionChangeTime.Modified();
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::Modified()
{
this->Superclass::Modified();
this->SelectionChangeTime.Modified();
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::DeepCopy(const vtkSubsetInclusionLattice* other)
{
if (other)
{
this->Deserialize(other->Serialize());
}
else
{
this->Initialize();
}
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::Merge(const std::string& other)
{
this->Internals->Merge(other);
this->Modified();
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::Merge(const vtkSubsetInclusionLattice* other)
{
this->Internals->Merge(other->Serialize());
}
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice* vtkSubsetInclusionLattice::GetSIL(vtkInformation* info)
{
return info ? vtkSubsetInclusionLattice::SafeDownCast(info->Get(SUBSET_INCLUSION_LATTICE()))
: nullptr;
}
//----------------------------------------------------------------------------
vtkSubsetInclusionLattice* vtkSubsetInclusionLattice::GetSIL(vtkInformationVector* v, int i)
{
return vtkSubsetInclusionLattice::GetSIL(v->GetInformationObject(i));
}
//----------------------------------------------------------------------------
vtkSmartPointer<vtkSubsetInclusionLattice> vtkSubsetInclusionLattice::Clone(
const vtkSubsetInclusionLattice* other)
{
if (other)
{
vtkSmartPointer<vtkSubsetInclusionLattice> clone;
clone.TakeReference(other->NewInstance());
clone->DeepCopy(other);
}
return nullptr;
}
//----------------------------------------------------------------------------
void vtkSubsetInclusionLattice::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
vtkInternals& internals = (*this->Internals);
internals.Print(os, vtkIndent().GetNextIndent());
}
| 27.473994 | 99 | 0.588084 | [
"vector"
] |
e0e06beb71ba7c0a662fe9e6db7fc86e2294ba0b | 11,266 | cpp | C++ | CTN_05_Hardware_3D_DirectX/src/Testing.cpp | TheUnicum/CTN_05_Hardware_3D_DirectX | 39940fb0466ff5b419d7f7c4cf55ee1f90784baa | [
"Apache-2.0"
] | null | null | null | CTN_05_Hardware_3D_DirectX/src/Testing.cpp | TheUnicum/CTN_05_Hardware_3D_DirectX | 39940fb0466ff5b419d7f7c4cf55ee1f90784baa | [
"Apache-2.0"
] | null | null | null | CTN_05_Hardware_3D_DirectX/src/Testing.cpp | TheUnicum/CTN_05_Hardware_3D_DirectX | 39940fb0466ff5b419d7f7c4cf55ee1f90784baa | [
"Apache-2.0"
] | null | null | null | #include "DynamicConstant.h"
#include "LayoutCodex.h"
#include "Vertex.h"
#include "Graphics.h"
#include "Window.h"
#include <cstring>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Material.h"
#include "Mesh.h"
#include "Testing.h"
#include "ChiliXM.h"
#include <algorithm>
#include <array>
#include "BindableCommon.h"
#include "RenderTarget.h"
#include "Surface.h"
#include "cnpy.h"
namespace dx = DirectX;
void TestNumpy()
{
auto v = std::vector{ 0,1,2,4,5,6 };
cnpy::npy_save("test.npy", v.data(), { 3,2 });
}
void TestDynamicMeshLoading()
{
using namespace Dvtx;
Assimp::Importer imp;
const auto pScene = imp.ReadFile("Models\\brick_wall\\brick_wall.obj",
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_ConvertToLeftHanded |
aiProcess_GenNormals |
aiProcess_CalcTangentSpace
);
auto layout = VertexLayout{}
.Append(VertexLayout::Position3D)
.Append(VertexLayout::Normal)
.Append(VertexLayout::Tangent)
.Append(VertexLayout::Bitangent)
.Append(VertexLayout::Texture2D);
VertexBuffer buf{ std::move(layout),*pScene->mMeshes[0] };
for (auto i = 0ull, end = buf.Size(); i < end; i++)
{
const auto a = buf[i].Attr<VertexLayout::Position3D>();
const auto b = buf[i].Attr<VertexLayout::Normal>();
const auto c = buf[i].Attr<VertexLayout::Tangent>();
const auto d = buf[i].Attr<VertexLayout::Bitangent>();
const auto e = buf[i].Attr<VertexLayout::Texture2D>();
}
}
void TestMaterialSystemLoading(Graphics& gfx)
{
std::string path = "src\\Models\\brick_wall\\brick_wall.obj";
Assimp::Importer imp;
const auto pScene = imp.ReadFile(path,
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_ConvertToLeftHanded |
aiProcess_GenNormals |
aiProcess_CalcTangentSpace
);
Material mat{ gfx,*pScene->mMaterials[1],path };
Mesh mesh{ gfx,mat,*pScene->mMeshes[0] };
}
void TestScaleMatrixTranslation()
{
auto tlMat = DirectX::XMMatrixTranslation(20.f, 30.f, 40.f);
tlMat = ScaleTranslation(tlMat, 0.1f);
dx::XMFLOAT4X4 f4;
dx::XMStoreFloat4x4(&f4, tlMat);
auto etl = ExtractTranslation(f4);
assert(etl.x == 2.f && etl.y == 3.f && etl.z == 4.f);
}
void TestDynamicConstant()
{
using namespace std::string_literals;
// data roundtrip tests
{
Dcb::RawLayout s;
s.Add<Dcb::Struct>("butts"s);
s["butts"s].Add<Dcb::Float3>("pubes"s);
s["butts"s].Add<Dcb::Float>("dank"s);
s.Add<Dcb::Float>("woot"s);
s.Add<Dcb::Array>("arr"s);
s["arr"s].Set<Dcb::Struct>(4);
s["arr"s].T().Add<Dcb::Float3>("twerk"s);
s["arr"s].T().Add<Dcb::Array>("werk"s);
s["arr"s].T()["werk"s].Set<Dcb::Float>(6);
s["arr"s].T().Add<Dcb::Array>("meta"s);
s["arr"s].T()["meta"s].Set<Dcb::Array>(6);
s["arr"s].T()["meta"s].T().Set<Dcb::Matrix>(4);
s["arr"s].T().Add<Dcb::Bool>("booler");
// fails: duplicate symbol name
// s.Add<Dcb::Bool>( "arr"s );
// fails: bad symbol name
//s.Add<Dcb::Bool>( "69man" );
auto b = Dcb::Buffer(std::move(s));
// fails to compile: conversion not in type map
//b["woot"s] = "#"s;
const auto sig = b.GetRootLayoutElement().GetSignature();
{
auto exp = 42.0f;
b["woot"s] = exp;
float act = b["woot"s];
assert(act == exp);
}
{
auto exp = 420.0f;
b["butts"s]["dank"s] = exp;
float act = b["butts"s]["dank"s];
assert(act == exp);
}
{
auto exp = 111.0f;
b["arr"s][2]["werk"s][5] = exp;
float act = b["arr"s][2]["werk"s][5];
assert(act == exp);
}
{
auto exp = DirectX::XMFLOAT3{ 69.0f,0.0f,0.0f };
b["butts"s]["pubes"s] = exp;
dx::XMFLOAT3 act = b["butts"s]["pubes"s];
assert(!std::memcmp(&exp, &act, sizeof(DirectX::XMFLOAT3)));
}
{
DirectX::XMFLOAT4X4 exp;
dx::XMStoreFloat4x4(
&exp,
dx::XMMatrixIdentity()
);
b["arr"s][2]["meta"s][5][3] = exp;
dx::XMFLOAT4X4 act = b["arr"s][2]["meta"s][5][3];
assert(!std::memcmp(&exp, &act, sizeof(DirectX::XMFLOAT4X4)));
}
{
auto exp = true;
b["arr"s][2]["booler"s] = exp;
bool act = b["arr"s][2]["booler"s];
assert(act == exp);
}
{
auto exp = false;
b["arr"s][2]["booler"s] = exp;
bool act = b["arr"s][2]["booler"s];
assert(act == exp);
}
// exists
{
assert(b["butts"s]["pubes"s].Exists());
assert(!b["butts"s]["fubar"s].Exists());
if (auto ref = b["butts"s]["pubes"s]; ref.Exists())
{
dx::XMFLOAT3 f = ref;
assert(f.x == 69.0f);
}
}
// set if exists
{
assert(b["butts"s]["pubes"s].SetIfExists(dx::XMFLOAT3{ 1.0f,2.0f,3.0f }));
auto& f3 = static_cast<const dx::XMFLOAT3&>(b["butts"s]["pubes"s]);
assert(f3.x == 1.0f && f3.y == 2.0f && f3.z == 3.0f);
assert(!b["butts"s]["phubar"s].SetIfExists(dx::XMFLOAT3{ 2.0f,2.0f,7.0f }));
}
const auto& cb = b;
{
dx::XMFLOAT4X4 act = cb["arr"s][2]["meta"s][5][3];
assert(act._11 == 1.0f);
}
// this doesn't compile: buffer is const
// cb["arr"][2]["booler"] = true;
// static_cast<bool&>(cb["arr"][2]["booler"]) = true;
// this fails assertion: array out of bounds
// cb["arr"s][200];
}
// size test array of arrays
{
Dcb::RawLayout s;
s.Add<Dcb::Array>("arr");
s["arr"].Set<Dcb::Array>(6);
s["arr"].T().Set<Dcb::Matrix>(4);
auto b = Dcb::Buffer(std::move(s));
auto act = b.GetSizeInBytes();
assert(act == 16u * 4u * 4u * 6u);
}
// size test array of floats
{
Dcb::RawLayout s;
s.Add<Dcb::Array>("arr");
s["arr"].Set<Dcb::Float>(16);
auto b = Dcb::Buffer(std::move(s));
auto act = b.GetSizeInBytes();
assert(act == 256u);
}
// size test array of structs with padding
{
Dcb::RawLayout s;
s.Add<Dcb::Array>("arr");
s["arr"].Set<Dcb::Struct>(6);
s["arr"s].T().Add<Dcb::Float2>("a");
s["arr"].T().Add<Dcb::Float3>("b"s);
auto b = Dcb::Buffer(std::move(s));
auto act = b.GetSizeInBytes();
assert(act == 16u * 2u * 6u);
}
// size test array of primitive that needs padding
{
Dcb::RawLayout s;
s.Add<Dcb::Array>("arr");
s["arr"].Set<Dcb::Float3>(6);
auto b = Dcb::Buffer(std::move(s));
auto act = b.GetSizeInBytes();
assert(act == 16u * 6u);
}
// testing CookedLayout
{
Dcb::RawLayout s;
s.Add<Dcb::Array>("arr");
s["arr"].Set<Dcb::Float3>(6);
auto cooked = Dcb::LayoutCodex::Resolve(std::move(s));
// raw is cleared after donating
s.Add<Dcb::Float>("arr");
// fails to compile, cooked returns const&
// cooked["arr"].Add<Dcb::Float>("buttman");
auto b1 = Dcb::Buffer(cooked);
b1["arr"][0] = dx::XMFLOAT3{ 69.0f,0.0f,0.0f };
auto b2 = Dcb::Buffer(cooked);
b2["arr"][0] = dx::XMFLOAT3{ 420.0f,0.0f,0.0f };
assert(static_cast<dx::XMFLOAT3>(b1["arr"][0]).x == 69.0f);
assert(static_cast<dx::XMFLOAT3>(b2["arr"][0]).x == 420.0f);
}
// specific testing scenario (packing error)
{
Dcb::RawLayout pscLayout;
pscLayout.Add<Dcb::Float3>("materialColor");
pscLayout.Add<Dcb::Float3>("specularColor");
pscLayout.Add<Dcb::Float>("specularWeight");
pscLayout.Add<Dcb::Float>("specularGloss");
auto cooked = Dcb::LayoutCodex::Resolve(std::move(pscLayout));
assert(cooked.GetSizeInBytes() == 48u);
}
// array non-packing
{
Dcb::RawLayout pscLayout;
pscLayout.Add<Dcb::Array>("arr");
pscLayout["arr"].Set<Dcb::Float>(10);
auto cooked = Dcb::LayoutCodex::Resolve(std::move(pscLayout));
assert(cooked.GetSizeInBytes() == 160u);
}
// array of struct w/ padding
{
Dcb::RawLayout pscLayout;
pscLayout.Add<Dcb::Array>("arr");
pscLayout["arr"].Set<Dcb::Struct>(10);
pscLayout["arr"].T().Add<Dcb::Float3>("x");
pscLayout["arr"].T().Add<Dcb::Float2>("y");
auto cooked = Dcb::LayoutCodex::Resolve(std::move(pscLayout));
assert(cooked.GetSizeInBytes() == 320u);
}
// testing pointer stuff
{
Dcb::RawLayout s;
s.Add<Dcb::Struct>("butts"s);
s["butts"s].Add<Dcb::Float3>("pubes"s);
s["butts"s].Add<Dcb::Float>("dank"s);
auto b = Dcb::Buffer(std::move(s));
const auto exp = 696969.6969f;
b["butts"s]["dank"s] = 696969.6969f;
assert((float&)b["butts"s]["dank"s] == exp);
assert(*(float*)&b["butts"s]["dank"s] == exp);
const auto exp2 = 42.424242f;
*(float*)&b["butts"s]["dank"s] = exp2;
assert((float&)b["butts"s]["dank"s] == exp2);
}
// specific testing scenario (packing error)
{
Dcb::RawLayout lay;
lay.Add<Dcb::Bool>("normalMapEnabled");
lay.Add<Dcb::Bool>("specularMapEnabled");
lay.Add<Dcb::Bool>("hasGlossMap");
lay.Add<Dcb::Float>("specularPower");
lay.Add<Dcb::Float3>("specularColor");
lay.Add<Dcb::Float>("specularMapWeight");
auto buf = Dcb::Buffer(std::move(lay));
assert(buf.GetSizeInBytes() == 32u);
}
// specific testing scenario (array packing issues gimme a tissue)
{
const int maxRadius = 7;
const int nCoef = maxRadius * 2 + 1;
Dcb::RawLayout l;
l.Add<Dcb::Integer>("nTaps");
l.Add<Dcb::Array>("coefficients");
l["coefficients"].Set<Dcb::Float>(nCoef);
Dcb::Buffer buf{ std::move(l) };
// assert proper amount of memory allocated
assert(buf.GetSizeInBytes() == (nCoef + 1) * 4 * 4);
// assert array empty
{
const char* begin = reinterpret_cast<char*>((int*)&buf["nTaps"]);
assert(std::all_of(begin, begin + buf.GetSizeInBytes(), [](char c) {return c == 0; }));
}
// assert sparse float storage
{
for (int i = 0; i < nCoef; i++)
{
buf["coefficients"][i] = 6.9f;
}
const auto begin = reinterpret_cast<std::array<float, 4>*>((float*)&buf["coefficients"][0]);
const auto end = begin + nCoef;
assert(std::all_of(begin, end, [](const auto& arr)
{
return arr[0] == 6.9f && arr[1] == 0.0f && arr[2] == 0.0f && arr[3] == 0.0f;
}));
}
}
}
void D3DTestScratchPad(Window& wnd)
{
namespace dx = DirectX;
using namespace Dvtx;
const auto RenderWithVS = [&gfx = wnd.Gfx()](const std::string& vsName)
{
const auto bitop = Bind::Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY::D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
const auto layout = VertexLayout{}
.Append(VertexLayout::Position2D)
.Append(VertexLayout::Float3Color);
VertexBuffer vb(layout, 3);
vb[0].Attr<VertexLayout::Position2D>() = dx::XMFLOAT2{ 0.0f,0.5f };
vb[0].Attr<VertexLayout::Float3Color>() = dx::XMFLOAT3{ 1.0f,0.0f,0.0f };
vb[1].Attr<VertexLayout::Position2D>() = dx::XMFLOAT2{ 0.5f,-0.5f };
vb[1].Attr<VertexLayout::Float3Color>() = dx::XMFLOAT3{ 0.0f,1.0f,0.0f };
vb[2].Attr<VertexLayout::Position2D>() = dx::XMFLOAT2{ -0.5f,-0.5f };
vb[2].Attr<VertexLayout::Float3Color>() = dx::XMFLOAT3{ 0.0f,0.0f,1.0f };
const auto bivb = Bind::VertexBuffer::Resolve(gfx, "##?", vb);
const std::vector<unsigned short> idx = { 0,1,2 };
const auto biidx = Bind::IndexBuffer::Resolve(gfx, "##?", idx);
const auto bips = Bind::PixelShader::Resolve(gfx, "ShaderBins\\Test_PS.cso");
const auto bivs = Bind::VertexShader::Resolve(gfx, "ShaderBins\\" + vsName);
const auto bilay = Bind::InputLayout::Resolve(gfx, layout, *bivs);
auto rt = Bind::ShaderInputRenderTarget{ gfx,1280,720,0 };
biidx->Bind(gfx);
bivb->Bind(gfx);
bitop->Bind(gfx);
bips->Bind(gfx);
bivs->Bind(gfx);
bilay->Bind(gfx);
rt.Clear(gfx, { 0.0f,0.0f,0.0f,1.0f });
rt.BindAsBuffer(gfx);
gfx.DrawIndexed(biidx->GetCount());
gfx.GetTarget()->BindAsBuffer(gfx);
rt.ToSurface(gfx).Save("Test_" + vsName + ".png");
};
RenderWithVS("Test2_VS.cso");
RenderWithVS("Test1_VS.cso");
}
| 28.739796 | 115 | 0.626576 | [
"mesh",
"vector"
] |
e0e317076d0b773a3aa8bc57d1521a4988cb7e63 | 13,236 | cc | C++ | arcane/extras/NumericalModel/src/Numerics/LinearSolver/HypreSolverImpl/HypreLinearSolver.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 16 | 2021-09-20T12:37:01.000Z | 2022-03-18T09:19:14.000Z | arcane/extras/NumericalModel/src/Numerics/LinearSolver/HypreSolverImpl/HypreLinearSolver.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 66 | 2021-09-17T13:49:39.000Z | 2022-03-30T16:24:07.000Z | arcane/extras/NumericalModel/src/Numerics/LinearSolver/HypreSolverImpl/HypreLinearSolver.cc | cedricga91/framework | 143eeccb5bf375df4a3f11b888681f84f60380c6 | [
"Apache-2.0"
] | 11 | 2021-09-27T16:48:55.000Z | 2022-03-23T19:06:56.000Z | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
#include "Utils/Utils.h"
#include <arcane/ArcaneVersion.h>
#include <HYPRE_utilities.h>
#include "_hypre_utilities.h" // pour HYPRE_ERROR_CONV
#include <HYPRE.h>
#include <HYPRE_parcsr_mv.h>
#include <HYPRE_IJ_mv.h>
#include <HYPRE_parcsr_ls.h>
#include <HYPRE_parcsr_mv.h>
#include "Numerics/LinearSolver/ILinearSystemVisitor.h"
#include "Numerics/LinearSolver/ILinearSystemBuilder.h"
#include "Numerics/LinearSolver/ILinearSystem.h"
#include "Numerics/LinearSolver/ILinearSolver.h"
#include "Numerics/LinearSolver/HypreSolverImpl/HypreLinearSystem.h"
#include "Numerics/LinearSolver/HypreSolverImpl/HypreLinearSolver.h"
#include "Numerics/LinearSolver/HypreSolverImpl/HypreInternal.h"
#ifdef _MPI
#define MPICH_SKIP_MPICXX 1
#include "mpi.h"
#endif
using namespace Arcane;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
HypreLinearSolver::
HypreLinearSolver(const ServiceBuildInfo & sbi)
: ArcaneHypreSolverObject(sbi)
, m_system_is_built(false)
, m_system_is_locked(false)
{
m_system = NULL;
m_builder = NULL;
}
/*---------------------------------------------------------------------------*/
HypreLinearSolver::
~HypreLinearSolver()
{
freeLinearSystem();
}
/*---------------------------------------------------------------------------*/
void HypreLinearSolver::setLinearSystemBuilder(ILinearSystemBuilder * builder)
{
m_builder = builder;
}
/*---------------------------------------------------------------------------*/
void HypreLinearSolver::init()
{
freeLinearSystem();
updateLinearSystem();
if (m_builder == NULL)
fatal() << "LinearSystemBuilder must be set before initializing LinearSolver";
m_builder->connect(m_system);
m_builder->init();
}
/*---------------------------------------------------------------------------*/
void HypreLinearSolver::start()
{
updateLinearSystem() ;
m_system->start();
}
/*---------------------------------------------------------------------------*/
void
HypreLinearSolver::
updateLinearSystem()
{
if (m_system==NULL)
{
m_system = new HypreLinearSystem(this);
m_system->init();
}
}
/*---------------------------------------------------------------------------*/
void
HypreLinearSolver::
freeLinearSystem()
{
delete m_system;
m_system = NULL;
m_system_is_built = false ;
m_system_is_locked = false ;
}
/*---------------------------------------------------------------------------*/
ILinearSystem *
HypreLinearSolver::
getLinearSystem()
{
updateLinearSystem();
return m_system ;
}
/*---------------------------------------------------------------------------*/
bool
HypreLinearSolver::
buildLinearSystem()
{
bool flag = m_system->accept(m_builder) ;
m_system_is_built = true ;
m_system_is_locked = false ;
return flag ;
}
/*---------------------------------------------------------------------------*/
bool
HypreLinearSolver::
getSolution()
{
return m_builder->commitSolution(m_system) ;
}
/*---------------------------------------------------------------------------*/
bool HypreLinearSolver::solve()
{
// Macro "pratique" en attendant de trouver mieux
#ifdef VALUESTRING
#error Already defined macro VALUESTRING
#endif
#define VALUESTRING(option) ((option).enumValues()->nameOfValue((option)(),""))
// Construction du système linéaire à résoudre au format
// Le builder connait la strcuture interne garce au visiteur de l'init
if(!m_system_is_built)
{
fatal()<<"Linear system is not built, buildLinearSystem() should be call first" ;
m_system->accept(m_builder) ;
}
if(m_system_is_locked)
fatal()<<"Error : try to solve a system already solved once without having been modified since" ;
HYPRE_Solver solver;
HYPRE_Solver preconditioner;
// acces aux fonctions du preconditionneur
HYPRE_PtrToParSolverFcn precond_solve_function = NULL;
HYPRE_PtrToParSolverFcn precond_setup_function = NULL;
int (*precond_destroy_function)(HYPRE_Solver) = NULL;
switch (options()->preconditioner())
{
case HypreOptionTypes::NoPC:
// precond_destroy_function = NULL;
break;
case HypreOptionTypes::AMGPC:
checkError("Hypre AMG preconditioner",HYPRE_BoomerAMGCreate(&preconditioner));
precond_solve_function = HYPRE_BoomerAMGSolve;
precond_setup_function = HYPRE_BoomerAMGSetup;
precond_destroy_function = HYPRE_BoomerAMGDestroy;
break;
case HypreOptionTypes::ParaSailsPC:
checkError("Hypre ParaSails preconditioner",HYPRE_ParaSailsCreate(MPI_COMM_WORLD,&preconditioner));
precond_solve_function = HYPRE_ParaSailsSolve;
precond_setup_function = HYPRE_ParaSailsSetup;
precond_destroy_function = HYPRE_ParaSailsDestroy;
break;
case HypreOptionTypes::EuclidPC:
checkError("Hypre Euclid preconditioner",HYPRE_EuclidCreate(MPI_COMM_WORLD,&preconditioner));
precond_solve_function = HYPRE_EuclidSolve;
precond_setup_function = HYPRE_EuclidSetup;
precond_destroy_function = HYPRE_EuclidDestroy;
break;
default:
fatal() << "Undefined Hypre preconditioner option";
}
// acces aux fonctions du solveur
int (*solver_set_logging_function)(HYPRE_Solver,int) = NULL;
int (*solver_set_print_level_function)(HYPRE_Solver,int) = NULL;
int (*solver_set_tol_function)(HYPRE_Solver,double) = NULL;
int (*solver_set_precond_function)(HYPRE_Solver,HYPRE_PtrToParSolverFcn,HYPRE_PtrToParSolverFcn,HYPRE_Solver) = NULL;
int (*solver_setup_function)(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector) = NULL;
int (*solver_solve_function)(HYPRE_Solver,HYPRE_ParCSRMatrix,HYPRE_ParVector,HYPRE_ParVector) = NULL;
int (*solver_get_num_iterations_function)(HYPRE_Solver,int*) = NULL;
int (*solver_get_final_relative_residual_function)(HYPRE_Solver,double*) = NULL;
int (*solver_destroy_function)(HYPRE_Solver) = NULL;
switch (options()->solver())
{
case HypreOptionTypes::AMG:
checkError("Hypre AMG solver",HYPRE_BoomerAMGCreate(&solver));
if (options()->verbose())
checkError("Hypre AMG SetDebugFlag",HYPRE_BoomerAMGSetDebugFlag(solver,1));
checkError("Hypre AMG solver SetMaxIter",HYPRE_BoomerAMGSetMaxIter(solver,options()->numIterationsMax()));
solver_set_logging_function = HYPRE_BoomerAMGSetLogging;
solver_set_print_level_function = HYPRE_BoomerAMGSetPrintLevel;
solver_set_tol_function = HYPRE_BoomerAMGSetTol;
// solver_set_precond_function = NULL;
solver_setup_function = HYPRE_BoomerAMGSetup;
solver_solve_function = HYPRE_BoomerAMGSolve;
solver_get_num_iterations_function = HYPRE_BoomerAMGGetNumIterations;
solver_get_final_relative_residual_function = HYPRE_BoomerAMGGetFinalRelativeResidualNorm;
solver_destroy_function = HYPRE_BoomerAMGDestroy;
break;
case HypreOptionTypes::GMRES:
checkError("Hypre GMRES solver",HYPRE_ParCSRGMRESCreate(MPI_COMM_WORLD,&solver));
checkError("Hypre GMRES solver SetMaxIter",HYPRE_ParCSRGMRESSetMaxIter(solver,options()->numIterationsMax()));
solver_set_logging_function = HYPRE_ParCSRGMRESSetLogging;
solver_set_print_level_function = HYPRE_ParCSRGMRESSetPrintLevel;
solver_set_tol_function = HYPRE_ParCSRGMRESSetTol;
solver_set_precond_function = HYPRE_ParCSRGMRESSetPrecond;
solver_setup_function = HYPRE_ParCSRGMRESSetup;
solver_solve_function = HYPRE_ParCSRGMRESSolve;
solver_get_num_iterations_function = HYPRE_ParCSRGMRESGetNumIterations;
solver_get_final_relative_residual_function = HYPRE_ParCSRGMRESGetFinalRelativeResidualNorm;
solver_destroy_function = HYPRE_ParCSRGMRESDestroy;
break;
case HypreOptionTypes::BiCGStab:
checkError("Hypre BiCGStab solver",HYPRE_ParCSRBiCGSTABCreate(MPI_COMM_WORLD,&solver));
checkError("Hypre BiCGStab solver SetMaxIter",HYPRE_ParCSRBiCGSTABSetMaxIter(solver,options()->numIterationsMax()));
solver_set_logging_function = HYPRE_ParCSRBiCGSTABSetLogging;
solver_set_print_level_function = HYPRE_ParCSRBiCGSTABSetPrintLevel;
solver_set_tol_function = HYPRE_ParCSRBiCGSTABSetTol;
solver_set_precond_function = HYPRE_ParCSRBiCGSTABSetPrecond;
solver_setup_function = HYPRE_ParCSRBiCGSTABSetup;
solver_solve_function = HYPRE_ParCSRBiCGSTABSolve;
solver_get_num_iterations_function = HYPRE_ParCSRBiCGSTABGetNumIterations;
solver_get_final_relative_residual_function = HYPRE_ParCSRBiCGSTABGetFinalRelativeResidualNorm;
solver_destroy_function = HYPRE_ParCSRBiCGSTABDestroy;
break;
case HypreOptionTypes::Hybrid:
checkError("Hypre Hybrid solver",HYPRE_ParCSRHybridCreate(&solver));
// checkError("Hypre Hybrid solver SetSolverType",HYPRE_ParCSRHybridSetSolverType(solver,1)); // PCG
checkError("Hypre Hybrid solver SetSolverType",HYPRE_ParCSRHybridSetSolverType(solver,2)); // GMRES
// checkError("Hypre Hybrid solver SetSolverType",HYPRE_ParCSRHybridSetSolverType(solver,3)); // BiCGSTab
checkError("Hypre Hybrid solver SetDiagMaxIter",HYPRE_ParCSRHybridSetDSCGMaxIter(solver,options()->numIterationsMax()));
checkError("Hypre Hybrid solver SetPCMaxIter",HYPRE_ParCSRHybridSetPCGMaxIter(solver,options()->numIterationsMax()));
solver_set_logging_function = HYPRE_ParCSRHybridSetLogging;
solver_set_print_level_function = HYPRE_ParCSRHybridSetPrintLevel;
solver_set_tol_function = HYPRE_ParCSRHybridSetTol;
solver_set_precond_function = NULL; // HYPRE_ParCSRHybridSetPrecond; // SegFault si utilise un préconditionneur !
solver_setup_function = HYPRE_ParCSRHybridSetup;
solver_solve_function = HYPRE_ParCSRHybridSolve;
solver_get_num_iterations_function = HYPRE_ParCSRHybridGetNumIterations;
solver_get_final_relative_residual_function = HYPRE_ParCSRHybridGetFinalRelativeResidualNorm;
solver_destroy_function = HYPRE_ParCSRHybridDestroy;
break;
default:
fatal() << "Undefined solver option";
}
if (solver_set_precond_function)
{
if (precond_solve_function)
{
checkError("Hypre "+VALUESTRING(options()->solver)+" solver SetPreconditioner",(*solver_set_precond_function)(solver,precond_solve_function,precond_setup_function,preconditioner));
}
}
else
{
if (precond_solve_function)
{
fatal() << "Hypre " << VALUESTRING(options()->solver) << " solver cannot accept preconditioner";
}
}
checkError("Hypre "+VALUESTRING(options()->solver)+" solver SetStopCriteria",(*solver_set_tol_function)(solver,options()->stopCriteriaValue()));
if (options()->verbose())
{
checkError("Hypre "+VALUESTRING(options()->solver)+" solver Setlogging",(*solver_set_print_level_function)(solver,1));
checkError("Hypre "+VALUESTRING(options()->solver)+" solver SetPrintLevel",(*solver_set_print_level_function)(solver,3));
}
HYPRE_ParCSRMatrix A;
HYPRE_ParVector b, x;
checkError("Hypre Matrix GetObject",HYPRE_IJMatrixGetObject(m_system->m_internal->m_ij_matrix, (void **) &A));
checkError("Hypre RHS Vector GetObject",HYPRE_IJVectorGetObject(m_system->m_internal->m_bij_vector, (void **) &b));
checkError("Hypre Unknown Vector GetObject",HYPRE_IJVectorGetObject(m_system->m_internal->m_xij_vector, (void **) &x));
checkError("Hypre "+VALUESTRING(options()->solver)+" solver Setup",(*solver_setup_function)(solver, A, b, x));
m_status.succeeded = ((*solver_solve_function)(solver, A, b, x) == 0);
checkError("Hypre "+VALUESTRING(options()->solver)+" solver GetNumIterations",(*solver_get_num_iterations_function)(solver,&m_status.iteration_count));
checkError("Hypre "+VALUESTRING(options()->solver)+" solver GetFinalResidual",(*solver_get_final_relative_residual_function)(solver,&m_status.residual));
checkError("Hypre "+VALUESTRING(options()->solver)+" solver Destroy",(*solver_destroy_function)(solver));
if (precond_destroy_function)
checkError("Hypre "+VALUESTRING(options()->preconditioner)+" preconditioner Destroy",(*precond_destroy_function)(preconditioner));
//lock linear system to prevent from solving it twice without changing it
m_system_is_locked = true ;
return m_status.succeeded;
#undef VALUESTRING
}
/*---------------------------------------------------------------------------*/
void HypreLinearSolver::end()
{
//m_builder->end();
m_system->end() ;
freeLinearSystem();
m_system_is_built = false ;
}
/*---------------------------------------------------------------------------*/
void HypreLinearSolver::checkError(const String & msg, int ierr, int skipError) const
{
if (ierr != 0 and (ierr & ~skipError) != 0)
{
char hypre_error_msg[256];
HYPRE_DescribeError(ierr,hypre_error_msg);
fatal() << msg << " failed : " << hypre_error_msg << "[code=" << ierr << "]";
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_REGISTER_SERVICE_HYPRESOLVER(HypreSolver,HypreLinearSolver);
| 38.815249 | 190 | 0.68767 | [
"vector"
] |
e0ee0805d684b013bdb7fd36cb83ff605397dce3 | 3,173 | cpp | C++ | src/editStereoList.cpp | morynicz/ace-of-space | cb1983e58b52d704854f79b230eeba8ac261d954 | [
"MIT"
] | null | null | null | src/editStereoList.cpp | morynicz/ace-of-space | cb1983e58b52d704854f79b230eeba8ac261d954 | [
"MIT"
] | null | null | null | src/editStereoList.cpp | morynicz/ace-of-space | cb1983e58b52d704854f79b230eeba8ac261d954 | [
"MIT"
] | null | null | null | /*
* editStereoList.cpp
*
* Created on: 3 Jan 2015
* Author: link
*/
#include <boost/program_options.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <list>
#include "ConvenienceFunctions.hpp"
#include "StorageFunctions.hpp"
const int USER_TRIGGERED_EXIT = 0;
void parseCommandline(const int& argc,
char** argv,
std::string& input,
std::string& output)
{
boost::program_options::options_description desc;
desc.add_options()("help,h", "this help message")(
"input,i",
boost::program_options::value<std::string>(),
"input directory containing imageList.xml")(
"output,o",
boost::program_options::value<std::string>(),
"output directory to which purged imageList.xml will be written");
boost::program_options::variables_map vm;
boost::program_options::store(
boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
throw USER_TRIGGERED_EXIT;
}
if (vm.count("output"))
{
output = vm["output"].as<std::string>();
}
if (vm.count("input"))
{
input = vm["input"].as<std::string>();
}
}
int main(int argc, char** argv)
{
std::string input, output;
parseCommandline(argc, argv, input, output);
cv::Size imageSize, chessboardSize;
double sideLength;
std::list<std::pair<cv::Mat, cv::Mat>> imageList;
loadImageList(input, imageSize, chessboardSize, sideLength, imageList);
cv::Mat display(imageSize.height, imageSize.width * 2, CV_8UC3);
cv::Rect leftRoi(cv::Point(imageSize.width, 0), imageSize);
cv::Rect rightRoi(cv::Point(0, 0), imageSize);
std::cerr << imageSize << std::endl;
std::cerr << display.size() << std::endl;
std::cerr << leftRoi << std::endl;
std::cerr << rightRoi << std::endl;
cv::namedWindow("main", cv::WINDOW_NORMAL);
char c = ' ';
auto bIt = imageList.begin();
int cnt = 0;
do
{
cv::Mat left = display(leftRoi);
cv::Mat right = display(rightRoi);
cv::Mat gLeft, gRight;
std::vector<cv::Point2f> leftCorners, rightCorners;
((std::pair<cv::Mat, cv::Mat>)*bIt).first.copyTo(gLeft);
((std::pair<cv::Mat, cv::Mat>)*bIt).second.copyTo(gRight);
bool leftFound =
cv::findChessboardCorners(gLeft, chessboardSize, leftCorners);
cv::cvtColor(gLeft, left, cv::COLOR_BGR2GRAY);
cv::drawChessboardCorners(left, chessboardSize, leftCorners, leftFound);
bool rightFound =
cv::findChessboardCorners(gRight, chessboardSize, rightCorners);
cv::cvtColor(gRight, right, cv::COLOR_BGR2GRAY);
cv::drawChessboardCorners(right, chessboardSize, rightCorners, rightFound);
cv::imshow("main", display);
c = cv::waitKey(0);
if ('d' == c)
{
bIt = imageList.erase(bIt);
continue;
}
++bIt;
std::cerr << cnt++ << std::endl;
} while (imageList.end() != bIt && 'q' != c);
saveImageList(output, imageSize, chessboardSize, sideLength, imageList);
}
| 27.119658 | 79 | 0.650804 | [
"vector"
] |
e0f4462c8d9e30a1061fd810e178fd30f833200c | 7,055 | hpp | C++ | include/ghex/structured/cubed_sphere/transform.hpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | null | null | null | include/ghex/structured/cubed_sphere/transform.hpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | 4 | 2019-12-11T10:22:25.000Z | 2021-12-20T13:50:20.000Z | include/ghex/structured/cubed_sphere/transform.hpp | fthaler/GHEX | ead3699e3ed3aa60c5f18225d4d6f8dcf3412cf9 | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2020, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef INCLUDED_GHEX_STRUCTURED_CUBED_SPHERE_TRANSFORM_HPP
#define INCLUDED_GHEX_STRUCTURED_CUBED_SPHERE_TRANSFORM_HPP
#include <array>
namespace gridtools {
namespace ghex {
namespace structured {
namespace cubed_sphere {
// cubed sphere tiles and coordinate system
//
// +----------+
// | (2)|
// | x ∧ |
// | | |
// | y<--+ |
// +----------+----------+----------+----------+
// | +-->y (4)| (0)| (1)| +-->y (3)|
// | | | ∧ y | ∧ y | | |
// | ∨ x | | | | | ∨ x |
// | | +-->x | +-->x | |
// +----------+----------+----------+----------+
// | (5)|
// | ∧ y |
// | | |
// | +-->x |
// +----------+
/** @brief affine transform matrix for tile coordinate transforms */
struct transform {
std::array<int,4> m_rotation;
std::array<int,2> m_translation;
std::array<int,2> m_offset;
constexpr bool switched_xy() const noexcept {return m_rotation[0]==0;}
constexpr bool reversed_x() const noexcept {
return switched_xy() ? (m_rotation[1]==-1) : (m_rotation[0]==-1);
}
constexpr bool reversed_y() const noexcept {
return switched_xy() ? (m_rotation[2]==-1) : (m_rotation[3]==-1);
}
/** @brief transform tile coordinates
* @param x x coordinate
* @param y y coordinate
* @param c number of cells along the cube edges
* @return transformed coordinate array */
constexpr std::array<int,2> operator()(int x, int y, int c) const noexcept {
return { m_rotation[0]*x + m_rotation[1]*y + m_translation[0]*c + m_offset[0],
m_rotation[2]*x + m_rotation[3]*y + m_translation[1]*c + m_offset[1]};
}
};
// neighbor tiles, order: -x,+x,-y,+y
static constexpr std::array<std::array<int,4>,6> tile_lu = {
std::array<int,4>{4,1,5,2}, // 0
std::array<int,4>{0,3,5,2}, // 1
std::array<int,4>{0,3,1,4}, // 2
std::array<int,4>{2,5,1,4}, // 3
std::array<int,4>{2,5,3,0}, // 4
std::array<int,4>{4,1,3,0} // 5
};
static constexpr transform identity_transform = {{1,0,0,1},{0,0},{0,0}};
// transform of tile coordinates to neighbor tile coordinates, order -x,+x,-y,+y
static constexpr std::array<std::array<transform,4>,6> transform_lu = {
std::array<transform,4>{
transform{{ 0,-1, 1, 0},{ 1, 1},{-1, 0}},
transform{{ 1, 0, 0, 1},{-1, 0},{ 0, 0}},
transform{{ 1, 0, 0, 1},{ 0, 1},{ 0, 0}},
transform{{ 0, 1,-1, 0},{-1, 1},{ 0,-1}}},
std::array<transform,4>{
transform{{ 1, 0, 0, 1},{ 1, 0},{ 0, 0}},
transform{{ 0,-1, 1, 0},{ 1,-1},{-1, 0}},
transform{{ 0, 1,-1, 0},{ 1, 1},{ 0,-1}},
transform{{ 1, 0, 0, 1},{ 0,-1},{ 0, 0}}},
std::array<transform,4>{
transform{{ 0,-1, 1, 0},{ 1, 1},{-1, 0}},
transform{{ 1, 0, 0, 1},{-1, 0},{ 0, 0}},
transform{{ 1, 0, 0, 1},{ 0, 1},{ 0, 0}},
transform{{ 0, 1,-1, 0},{-1, 1},{ 0,-1}}},
std::array<transform,4>{
transform{{ 1, 0, 0, 1},{ 1, 0},{ 0, 0}},
transform{{ 0,-1, 1, 0},{ 1,-1},{-1, 0}},
transform{{ 0, 1,-1, 0},{ 1, 1},{ 0,-1}},
transform{{ 1, 0, 0, 1},{ 0,-1},{ 0, 0}}},
std::array<transform,4>{
transform{{ 0,-1, 1, 0},{ 1, 1},{-1, 0}},
transform{{ 1, 0, 0, 1},{-1, 0},{ 0, 0}},
transform{{ 1, 0, 0, 1},{ 0, 1},{ 0, 0}},
transform{{ 0, 1,-1, 0},{-1, 1},{ 0,-1}}},
std::array<transform,4>{
transform{{ 1, 0, 0, 1},{ 1, 0},{ 0, 0}},
transform{{ 0,-1, 1, 0},{ 1,-1},{-1, 0}},
transform{{ 0, 1,-1, 0},{ 1, 1},{ 0,-1}},
transform{{ 1, 0, 0, 1},{ 0,-1},{ 0, 0}}}
};
// inverse transform: neigbhor tile coordinates to this tile coordinates
static constexpr std::array<std::array<transform,4>,6> inverse_transform_lu = {
std::array<transform,4>{
transform_lu[4][3],
transform_lu[1][0],
transform_lu[5][3],
transform_lu[2][0]},
std::array<transform,4>{
transform_lu[0][1],
transform_lu[3][2],
transform_lu[5][1],
transform_lu[2][2]},
std::array<transform,4>{
transform_lu[0][3],
transform_lu[3][0],
transform_lu[1][3],
transform_lu[4][0]},
std::array<transform,4>{
transform_lu[2][1],
transform_lu[5][2],
transform_lu[1][1],
transform_lu[4][2]},
std::array<transform,4>{
transform_lu[2][3],
transform_lu[5][0],
transform_lu[3][3],
transform_lu[0][0]},
std::array<transform,4>{
transform_lu[4][1],
transform_lu[1][2],
transform_lu[3][1],
transform_lu[0][2]}
};
} // namespace cubed_sphere
} // namespace structured
} // namespace ghex
} // namespace gridtools
#endif // INCLUDED_GHEX_STRUCTURED_CUBED_SPHERE_TRANSFORM_HPP
| 47.348993 | 103 | 0.361446 | [
"transform"
] |
e0f48726123d95bbb00f6f117d50113897d99c30 | 45,840 | cpp | C++ | src/generator.cpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | 3 | 2021-02-28T12:52:43.000Z | 2021-12-31T00:12:48.000Z | src/generator.cpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | null | null | null | src/generator.cpp | AggroBird/propane | 83134d11f6a90798db8937761ab707d95c520f1b | [
"MIT"
] | null | null | null | #include "propane_generator.hpp"
#include "generation.hpp"
#include "errors.hpp"
#include "utility.hpp"
#define VALIDATE(errc, expr, ...) ENSURE_WITH_META(errc, this->get_meta(), expr, propane::generator_exception, __VA_ARGS__)
#define VALIDATE_IDENTIFIER(str) VALIDATE(ERRC::GNR_INVALID_IDENTIFIER, propane::is_identifier(str), \
"Invalid identifier: '%'", str)
#define VALIDATE_PARAM_COUNT(num) VALIDATE(ERRC::GNR_PARAMETER_OVERFLOW, size_t(num) <= method_parameter_max, \
"Method parameter count exceeds maximum (%/%)", num, method_parameter_max)
#define VALIDATE_INIT_COUNT(num) VALIDATE(ERRC::GNR_INITIALIZER_OVERFLOW, size_t(num) <= global_initializer_max, \
"Constant initializer count exceeds maximum (%/%)", num, global_initializer_max)
#define VALIDATE_INDEX_RANGE(idx, max) VALIDATE(ERRC::GNR_INDEX_OUT_OF_RANGE, size_t(idx) < size_t(max), \
"% out of range (%/%)", get_index_type_name(idx), size_t(idx), max)
#define VALIDATE_ARRAY_LENGTH(len) VALIDATE(ERRC::GNR_ARRAY_LENGTH_ZERO, (len) != 0, \
"Array length cannot be zero")
#define VALIDATE_INDEX_VALUE(idx) VALIDATE(ERRC::GNR_INVALID_INDEX, size_t(idx) != size_t(invalid_index), \
"Invalid index provided")
#define VALIDATE_OFFSET_VALUE(empty) VALIDATE(ERRC::GNR_EMPTY_OFFSET, empty, \
"Empty offset sequence provided")
#define VALIDATE_IDENTIFIER_TYPE(expr, lhs_type, rhs_type, name) VALIDATE(ERRC::GNR_IDENTIFIER_TYPE_MISMATCH, expr, \
"Declaration of % '%' collides with previous % declaration", lhs_type, name, rhs_type)
#define VALIDATE_NONVOID(type) VALIDATE(ERRC::GNR_INVALID_VOID_TYPE, (type) != propane::type_idx::voidtype, \
"Void type is not valid as a parameter or field type")
#define VALIDATE_TYPE_DEC(expr, type_name, type_meta) VALIDATE(ERRC::GNR_TYPE_REDECLARATION, expr, \
"Type '%' has already been declared (see %)", type_name, type_meta)
#define VALIDATE_METHOD_DEC(expr, method_name, method_meta) VALIDATE(ERRC::GNR_METHOD_REDECLARATION, expr, \
"Method '%' has already been declared (see %)", method_name, method_meta)
#define VALIDATE_GLOBAL_DEC(expr, global_name) VALIDATE(ERRC::GNR_GLOBAL_REDECLARATION, expr, \
"Global '%' has already been declared", global_name)
#define VALIDATE_FIELD_DEC(expr, field_name, type_name, type_meta) VALIDATE(ERRC::GNR_FIELD_REDECLARATION, expr, \
"Field '%' has already been declared (see declaration for '%' at %)", field_name, type_name, type_meta)
#define VALIDATE_STACK_DEC(expr, method_meta) VALIDATE(ERRC::GNR_STACK_REDECLARATION, expr, \
"Stack for method '%' has already been set", method_meta)
#define VALIDATE_LABEL_DEC(expr, label_name) VALIDATE(ERRC::GNR_LABEL_REDECLARATION, expr, \
"Label '%' has already been defined", label_name)
#define VALIDATE_LABEL_DEF(expr, label_name) VALIDATE(ERRC::GNR_LABEL_UNDEFINED, expr, \
"Undefined label '%'", label_name)
#define VALIDATE_RET_VAL(expr, method_name, method_meta) VALIDATE(ERRC::GNR_INVALID_RET_VAL, expr, \
"Method return value does not match declaration (see declaration for '%' at %)", method_name, method_meta)
#define VALIDATE_STACK_INDEX(idx, max) VALIDATE(ERRC::GNR_STACK_OUT_OF_RANGE, size_t(idx) < size_t(max), \
"Stack index out of range (%/%)", size_t(idx), max)
#define VALIDATE_PARAM_INDEX(idx, max) VALIDATE(ERRC::GNR_PARAM_OUT_OF_RANGE, size_t(idx) < size_t(max), \
"Parameter index out of range (%/%)", size_t(idx), max)
#define VALIDATE_NONCONST(expr) VALIDATE(ERRC::GNR_INVALID_CONSTANT, expr, \
"Constant is not valid as left-hand side operand")
#define VALIDATE_HAS_RETURNED(expr, method_name, method_meta) VALIDATE(ERRC::GNR_MISSING_RET_VAL, expr, \
"Method is expecting a return value (see declaration for '%' at %)", method_name, method_meta)
#define VALIDATE_INDEX(id, max) { VALIDATE_INDEX_VALUE(id); VALIDATE_INDEX_RANGE(id, max); }
#define VALIDATE_TYPE(id, max) { VALIDATE_INDEX(id, max); VALIDATE_NONVOID(id); }
#define VALIDATE_TYPES(set, max) { for(const auto& id : set) { VALIDATE_INDEX(id, max); VALIDATE_NONVOID(id); } }
#define VALIDATE_INDICES(set, max) { for(const auto& id : set) { VALIDATE_INDEX(id, max); } }
namespace propane
{
static constexpr size_t method_parameter_max = 256;
static constexpr size_t global_initializer_max = 65536;
class generator_impl final : public gen_intermediate_data
{
public:
NOCOPY_CLASS_DEFAULT(generator_impl);
~generator_impl();
inline name_idx emplace_identifier(string_view identifier)
{
if (auto find = database.find(identifier))
{
return find.key;
}
else
{
return database.emplace(identifier, lookup_idx::make_identifier()).key;
}
}
void define_data(lookup_type lookup, type_idx type, name_idx name, span<const constant> values)
{
VALIDATE_INDEX(name, database.size());
VALIDATE_INDEX(type, types.size());
VALIDATE_INIT_COUNT(values.size());
auto find = database[name];
VALIDATE_GLOBAL_DEC(find->lookup != lookup_type::global && find->lookup != lookup_type::constant, find.name);
VALIDATE_IDENTIFIER_TYPE(find->lookup == lookup_type::identifier, lookup_type::identifier, find->lookup, find.name);
// Validate values
for (const auto& it : values)
{
const type_idx init_type = type_idx(it.header.index());
if (init_type == type_idx::voidtype)
VALIDATE_INDEX(it.payload.global, database.size())
else
ASSERT(init_type <= propane::type_idx::vptr, "")
}
auto& table = get_data_table(lookup);
const index_t idx = index_t(table.info.size());
// Upgrade to global
*find = lookup_idx(lookup, idx);
table.info.push_back(field(name, type, table.data.size()));
append_bytecode(table.data, uint16_t(values.size()));
for (const auto& it : values)
{
const type_idx init_type = type_idx(it.header.index());
if (init_type == type_idx::voidtype)
{
// Constant identifier
append_bytecode(table.data, uint8_t(init_type));
append_bytecode(table.data, it.payload.global);
}
else
{
// Encoded constant
append_bytecode(table.data, uint8_t(init_type));
if (init_type != type_idx::vptr)
{
append_constant(table.data, it);
}
}
}
}
inline gen_data_table& get_data_table(lookup_type type)
{
switch (type)
{
case lookup_type::global: return globals;
case lookup_type::constant: return constants;
}
ASSERT(false, "Invalid lookup type");
return globals;
}
// Writer objects, get released in the deconstructor or in finalize
indexed_vector<type_idx, generator::type_writer*> type_writers;
indexed_vector<method_idx, generator::method_writer*> method_writers;
// Meta index for the current intermediate (0 if defined)
meta_idx meta_index = meta_idx::invalid;
index_t line_number = 0;
vector<uint8_t> keybuf;
inline file_meta get_meta() const
{
return file_meta(metatable[meta_index].name, line_number);
}
void append_constant(vector<uint8_t>& buf, address addr)
{
switch (type_idx(addr.header.index()))
{
case type_idx::i8: append_bytecode(buf, addr.payload.i8); break;
case type_idx::u8: append_bytecode(buf, addr.payload.u8); break;
case type_idx::i16: append_bytecode(buf, addr.payload.i16); break;
case type_idx::u16: append_bytecode(buf, addr.payload.u16); break;
case type_idx::i32: append_bytecode(buf, addr.payload.i32); break;
case type_idx::u32: append_bytecode(buf, addr.payload.u32); break;
case type_idx::i64: append_bytecode(buf, addr.payload.i64); break;
case type_idx::u64: append_bytecode(buf, addr.payload.u64); break;
case type_idx::f32: append_bytecode(buf, addr.payload.f32); break;
case type_idx::f64: append_bytecode(buf, addr.payload.f64); break;
case type_idx::vptr: append_bytecode(buf, addr.payload.vptr); break;
default: ASSERT(false, "Invalid type index provided");
}
}
};
class type_writer_impl final : public gen_type
{
public:
NOCOPY_CLASS_DEFAULT(type_writer_impl, generator_impl&, name_idx name, type_idx index, bool is_union);
~type_writer_impl();
generator_impl& gen;
inline file_meta get_meta() const
{
return gen.get_meta();
}
};
class method_writer_impl final : public gen_method
{
public:
NOCOPY_CLASS_DEFAULT(method_writer_impl, generator_impl&, name_idx name, method_idx index, signature_idx signature);
~method_writer_impl();
// Lookup tables, to prevent duplicate indices
unordered_map<method_idx, index_t> call_lookup;
unordered_map<name_idx, index_t> global_lookup;
unordered_map<offset_idx, index_t> offset_index_lookup;
// Labels
unordered_map<label_idx, size_t> label_locations;
unordered_map<label_idx, vector<size_t>> unresolved_branches;
database<index_t, label_idx> named_labels;
indexed_vector<label_idx, index_t> label_declarations; // Unnamed labels will be added to the declarations list as 'invalid_index'
size_t parameter_count = 0;
size_t last_return = 0;
bool expects_return_value = false;
generator_impl& gen;
inline type_idx get_type(address addr) const
{
const index_t idx = addr.header.index();
switch (addr.header.type())
{
case address_type::stackvar:
{
ASSERT(is_valid_index(stackvars, idx), "Index out of range");
return stackvars[idx].type;
}
case address_type::parameter:
{
const auto& sig = gen.signatures[signature];
ASSERT(is_valid_index(sig.parameters, idx), "Index out of range");
return sig.parameters[idx].type;
}
case address_type::global:
{
ASSERT(gen.globals.info.is_valid_index(global_idx(idx)), "Index out of range");
return gen.globals.info[global_idx(idx)].type;
}
case address_type::constant:
{
ASSERT(gen.constants.info.is_valid_index(global_idx(idx)), "Index out of range");
return gen.constants.info[global_idx(idx)].type;
}
}
return type_idx::invalid;
}
void resolve_labels()
{
// Fetch all labels that have been referenced by a branch
map<size_t, vector<label_idx>> write_labels;
for (auto& branch : unresolved_branches)
{
auto label = label_locations.find(branch.first);
if (label == label_locations.end())
{
// Label location not known
const auto label_name_index = label_declarations[branch.first];
if (label_name_index == invalid_index)
{
VALIDATE_LABEL_DEF(false, size_t(branch.first));
}
else
{
VALIDATE_LABEL_DEF(false, named_labels[label_name_index].name);
}
}
write_labels[label->second].push_back(label->first);
}
// Export labels
labels.reserve(write_labels.size());
for (auto& label : write_labels)
{
for (auto& branch_index : label.second)
{
auto locations = unresolved_branches.find(branch_index);
for (auto& offset : locations->second)
{
*reinterpret_cast<size_t*>(bytecode.data() + offset) = label.first;
}
}
if (label.first >= bytecode.size())
{
const bool expected = !gen.signatures[signature].has_return_value();
VALIDATE_RET_VAL(expected, gen.database[name].name, gen.make_meta(index));
write_ret();
}
labels.push_back(label.first);
}
}
inline void append_bytecode(const void* ptr, size_t len)
{
const uint8_t* bptr = reinterpret_cast<const uint8_t*>(ptr);
bytecode.insert(bytecode.end(), bptr, bptr + len);
}
template<typename value_t> inline void append_bytecode(const value_t& val)
{
static_assert(std::is_trivial_v<value_t> && !std::is_same_v<string_view, value_t>, "Type must be trivially copyable");
append_bytecode(&val, sizeof(value_t));
}
void write_subcode_zero()
{
append_bytecode(subcode(0));
}
bool validate_address(address addr) const
{
switch (addr.header.type())
{
case address_type::stackvar:
{
if (addr.header.index() != address_header_constants::index_max)
{
VALIDATE_STACK_INDEX(addr.header.index(), stackvars.size());
}
}
break;
case address_type::parameter:
{
VALIDATE_PARAM_INDEX(addr.header.index(), parameter_count);
}
break;
case address_type::constant:
{
VALIDATE_NONCONST(false);
}
break;
}
return true;
}
bool validate_operand(address addr) const
{
if (addr.header.type() == address_type::constant)
{
return true;
}
return validate_address(addr);
}
bool validate_operands(span<const address> args) const
{
for (const auto& it : args)
{
if (!validate_operand(it))
{
return false;
}
}
return true;
}
void write_address(address addr)
{
address_data_t data(0);
data.header = addr.header;
switch (addr.header.type())
{
case address_type::stackvar:
{
if (addr.header.index() == address_header_constants::index_max)
{
data.header.set_index(address_header_constants::index_max);
}
}
break;
case address_type::global:
{
const name_idx global_name = (name_idx)addr.header.index();
auto find = global_lookup.find(global_name);
if (find == global_lookup.end())
{
// New global
const index_t idx = index_t(globals.size());
global_lookup.emplace(global_name, idx);
globals.push_back(global_name);
data.header.set_index(idx);
}
else
{
data.header.set_index(index_t(find->second));
}
}
break;
}
switch (addr.header.modifier())
{
case address_modifier::none: break;
case address_modifier::direct_field:
case address_modifier::indirect_field:
{
const offset_idx field = addr.payload.field;
auto find = offset_index_lookup.find(field);
if (find == offset_index_lookup.end())
{
// New offset
const index_t idx = index_t(offsets.size());
offset_index_lookup.emplace(field, idx);
offsets.push_back(field);
data.field = (offset_idx)idx;
}
else
{
data.field = (offset_idx)find->second;
}
}
break;
case address_modifier::subscript:
{
data.offset = addr.payload.offset;
}
break;
}
append_bytecode(data);
}
void write_operand(address addr)
{
if (addr.header.type() == address_type::constant)
{
append_bytecode(addr.header);
gen.append_constant(bytecode, addr);
return;
}
write_address(addr);
}
void write_label(label_idx label)
{
auto branch = unresolved_branches.find(label);
vector<size_t>& list = branch == unresolved_branches.end() ? unresolved_branches.emplace(label, vector<size_t>()).first->second : branch->second;
list.push_back(bytecode.size());
append_bytecode(size_t(0));
}
void write_expression(opcode op, address lhs)
{
if (validate_address(lhs))
{
append_bytecode(op);
write_address(lhs);
}
}
void write_expression(opcode op, address lhs, address rhs)
{
if (validate_address(lhs) && validate_operand(rhs))
{
append_bytecode(op);
write_address(lhs);
write_operand(rhs);
}
}
void write_sub_expression(opcode op, address lhs)
{
if (validate_address(lhs))
{
append_bytecode(op);
write_subcode_zero();
write_address(lhs);
}
}
void write_sub_expression(opcode op, address lhs, address rhs)
{
if (validate_address(lhs) && validate_operand(rhs))
{
append_bytecode(op);
write_subcode_zero();
write_address(lhs);
write_operand(rhs);
}
}
void write_branch(opcode op, label_idx label)
{
VALIDATE_INDEX(label, label_declarations.size());
append_bytecode(op);
write_label(label);
}
void write_branch(opcode op, label_idx label, address lhs)
{
VALIDATE_INDEX(label, label_declarations.size());
if (validate_address(lhs))
{
append_bytecode(op);
write_label(label);
write_subcode_zero();
write_address(lhs);
}
}
void write_branch(opcode op, label_idx label, address lhs, address rhs)
{
VALIDATE_INDEX(label, label_declarations.size());
if (validate_address(lhs) && validate_operand(rhs))
{
append_bytecode(op);
write_label(label);
write_subcode_zero();
write_address(lhs);
write_operand(rhs);
}
}
void write_sw(address addr, span<const label_idx> labels)
{
VALIDATE_ARRAY_LENGTH(labels.size());
VALIDATE_INDICES(labels, label_declarations.size());
if (validate_address(addr))
{
append_bytecode(opcode::sw);
write_address(addr);
append_bytecode(uint32_t(labels.size()));
for (auto it : labels)
{
write_label(it);
}
}
}
void write_call(method_idx method, span<const address> args)
{
VALIDATE_INDEX(method, gen.methods.size());
VALIDATE_PARAM_COUNT(args.size());
if (validate_operands(args))
{
append_bytecode(opcode::call);
index_t idx;
auto find = call_lookup.find(method);
if (find == call_lookup.end())
{
idx = index_t(calls.size());
calls.push_back(method);
call_lookup.emplace(method, idx);
}
else
{
idx = find->second;
}
append_bytecode(idx);
append_bytecode(uint8_t(args.size()));
for (const auto& it : args)
{
write_subcode_zero();
write_operand(it);
}
}
}
void write_callv(address addr, span<const address> args)
{
VALIDATE_PARAM_COUNT(args.size());
if (validate_address(addr) && validate_operands(args))
{
append_bytecode(opcode::callv);
write_address(addr);
append_bytecode(uint8_t(args.size()));
for (const auto& it : args)
{
write_subcode_zero();
write_operand(it);
}
}
}
void write_ret()
{
const bool expected = !gen.signatures[signature].has_return_value();
VALIDATE_RET_VAL(expected, gen.database[name].name, gen.make_meta(index));
append_bytecode(opcode::ret);
last_return = bytecode.size();
}
void write_retv(address addr)
{
const bool expected = gen.signatures[signature].has_return_value();
VALIDATE_RET_VAL(expected, gen.database[name].name, gen.make_meta(index));
if (validate_operand(addr))
{
append_bytecode(opcode::retv);
write_subcode_zero();
write_operand(addr);
}
last_return = bytecode.size();
}
void write_dump(address addr)
{
if (validate_operand(addr))
{
append_bytecode(opcode::dump);
write_operand(addr);
}
}
inline file_meta get_meta() const
{
return gen.get_meta();
}
};
// Types
type_writer_impl::type_writer_impl(generator_impl& gen, name_idx name, type_idx index, bool is_union) :
gen_type(name, index),
gen(gen)
{
flags |= extended_flags::is_defined;
if (is_union) flags |= type_flags::is_union;
meta.index = gen.meta_index;
meta.line_number = gen.line_number;
}
type_writer_impl::~type_writer_impl()
{
}
generator::type_writer::type_writer(generator_impl& gen, name_idx name, type_idx index, bool is_union) :
handle(gen, name, index, is_union)
{
}
generator::type_writer::~type_writer()
{
}
name_idx generator::type_writer::name() const
{
return self().name;
}
type_idx generator::type_writer::index() const
{
return self().index;
}
void generator::type_writer::declare_field(type_idx type, name_idx name)
{
auto& writer = self();
auto& gen = writer.gen;
VALIDATE_TYPE(type, gen.types.size());
VALIDATE_INDEX(name, gen.database.size());
bool is_defined = false;
for (auto& f : writer.fields)
{
VALIDATE_FIELD_DEC(name != f.name, gen.database[name].name, gen.database[writer.name].name, gen.make_meta(writer.index));
}
writer.fields.push_back(field(name, type));
}
void generator::type_writer::declare_field(type_idx type, string_view name)
{
auto& writer = self();
auto& gen = writer.gen;
VALIDATE_IDENTIFIER(name);
VALIDATE_TYPE(type, gen.types.size());
return declare_field(type, gen.emplace_identifier(name));
}
span<const field> generator::type_writer::fields() const
{
return self().fields;
}
void generator::type_writer::finalize()
{
auto& writer = self();
auto& gen = writer.gen;
auto& dst = gen.types[writer.index];
auto& src = writer;
// Copy over pointer and array types (they get assigned by the generator)
ASSERT(src.pointer_type == type_idx::invalid, "Pointer type index is not valid here");
ASSERT(src.array_types.empty(), "Array type indices are not valid here");
src.pointer_type = dst.pointer_type;
std::swap(src.array_types, dst.array_types);
dst = std::move(src);
gen.type_writers[writer.index] = nullptr;
delete this;
}
// Methods
method_writer_impl::method_writer_impl(generator_impl& gen, name_idx name, method_idx index, signature_idx signature) :
gen_method(name, index),
gen(gen)
{
flags |= extended_flags::is_defined;
this->signature = signature;
const auto& sig = gen.signatures[signature];
this->parameter_count = sig.parameters.size();
this->expects_return_value = sig.has_return_value();
meta.index = gen.meta_index;
meta.line_number = gen.line_number;
}
method_writer_impl::~method_writer_impl()
{
}
generator::method_writer::method_writer(class generator_impl& gen, name_idx name, method_idx index, signature_idx signature) :
handle(gen, name, index, signature)
{
}
generator::method_writer::~method_writer()
{
}
name_idx generator::method_writer::name() const
{
return self().name;
}
method_idx generator::method_writer::index() const
{
return self().index;
}
void generator::method_writer::push(span<const type_idx> types)
{
auto& writer = self();
VALIDATE_TYPES(types, writer.gen.types.size());
writer.stackvars.reserve(writer.stackvars.size() + types.size());
for (auto it : types)
{
writer.stackvars.push_back(stackvar(it));
}
}
span<const stackvar> generator::method_writer::stack() const
{
return self().stackvars;
}
label_idx generator::method_writer::declare_label(string_view label_name)
{
VALIDATE_IDENTIFIER(label_name);
auto& writer = self();
auto find = writer.named_labels.find(label_name);
if (!find)
{
// New named label
const label_idx next = label_idx(writer.label_declarations.size());
writer.label_declarations.push_back(writer.named_labels.emplace(label_name, next).key);
return next;
}
return *find;
}
label_idx generator::method_writer::declare_label()
{
auto& writer = self();
// New unnamed label
const label_idx next = label_idx(writer.label_declarations.size());
writer.label_declarations.push_back(invalid_index);
return next;
}
void generator::method_writer::write_label(label_idx label)
{
auto& writer = self();
VALIDATE_INDEX(label, writer.label_declarations.size());
const auto find = writer.label_locations.find(label);
if (find != writer.label_locations.end())
{
const auto label_name_index = writer.label_declarations[label];
if (label_name_index == invalid_index)
{
VALIDATE_LABEL_DEC(false, size_t(label));
}
else
{
VALIDATE_LABEL_DEC(false, writer.named_labels[label_name_index].name);
}
}
writer.label_locations.emplace(label, writer.bytecode.size());
}
void generator::method_writer::write_noop()
{
self().append_bytecode(opcode::noop);
}
void generator::method_writer::write_set(address lhs, address rhs)
{
self().write_sub_expression(opcode::set, lhs, rhs);
}
void generator::method_writer::write_conv(address lhs, address rhs)
{
self().write_sub_expression(opcode::conv, lhs, rhs);
}
void generator::method_writer::write_not(address lhs)
{
self().write_sub_expression(opcode::ari_not, lhs);
}
void generator::method_writer::write_neg(address lhs)
{
self().write_sub_expression(opcode::ari_neg, lhs);
}
void generator::method_writer::write_mul(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_mul, lhs, rhs);
}
void generator::method_writer::write_div(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_div, lhs, rhs);
}
void generator::method_writer::write_mod(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_mod, lhs, rhs);
}
void generator::method_writer::write_add(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_add, lhs, rhs);
}
void generator::method_writer::write_sub(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_sub, lhs, rhs);
}
void generator::method_writer::write_lsh(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_lsh, lhs, rhs);
}
void generator::method_writer::write_rsh(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_rsh, lhs, rhs);
}
void generator::method_writer::write_and(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_and, lhs, rhs);
}
void generator::method_writer::write_xor(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_xor, lhs, rhs);
}
void generator::method_writer::write_or(address lhs, address rhs)
{
self().write_sub_expression(opcode::ari_or, lhs, rhs);
}
void generator::method_writer::write_padd(address lhs, address rhs)
{
self().write_sub_expression(opcode::padd, lhs, rhs);
}
void generator::method_writer::write_psub(address lhs, address rhs)
{
self().write_sub_expression(opcode::psub, lhs, rhs);
}
void generator::method_writer::write_pdif(address lhs, address rhs)
{
self().write_expression(opcode::pdif, lhs, rhs);
}
void generator::method_writer::write_cmp(address lhs, address rhs)
{
self().write_sub_expression(opcode::cmp, lhs, rhs);
}
void generator::method_writer::write_ceq(address lhs, address rhs)
{
self().write_sub_expression(opcode::ceq, lhs, rhs);
}
void generator::method_writer::write_cne(address lhs, address rhs)
{
self().write_sub_expression(opcode::cne, lhs, rhs);
}
void generator::method_writer::write_cgt(address lhs, address rhs)
{
self().write_sub_expression(opcode::cgt, lhs, rhs);
}
void generator::method_writer::write_cge(address lhs, address rhs)
{
self().write_sub_expression(opcode::cge, lhs, rhs);
}
void generator::method_writer::write_clt(address lhs, address rhs)
{
self().write_sub_expression(opcode::clt, lhs, rhs);
}
void generator::method_writer::write_cle(address lhs, address rhs)
{
self().write_sub_expression(opcode::cle, lhs, rhs);
}
void generator::method_writer::write_cze(address addr)
{
self().write_sub_expression(opcode::cze, addr);
}
void generator::method_writer::write_cnz(address addr)
{
self().write_sub_expression(opcode::cnz, addr);
}
void generator::method_writer::write_br(label_idx label)
{
self().write_branch(opcode::br, label);
}
void generator::method_writer::write_beq(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::beq, label, lhs, rhs);
}
void generator::method_writer::write_bne(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::bne, label, lhs, rhs);
}
void generator::method_writer::write_bgt(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::bgt, label, lhs, rhs);
}
void generator::method_writer::write_bge(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::bge, label, lhs, rhs);
}
void generator::method_writer::write_blt(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::blt, label, lhs, rhs);
}
void generator::method_writer::write_ble(label_idx label, address lhs, address rhs)
{
self().write_branch(opcode::ble, label, lhs, rhs);
}
void generator::method_writer::write_bze(label_idx label, address lhs)
{
self().write_branch(opcode::bze, label, lhs);
}
void generator::method_writer::write_bnz(label_idx label, address lhs)
{
self().write_branch(opcode::bnz, label, lhs);
}
void generator::method_writer::write_sw(address addr, span<const label_idx> labels)
{
self().write_sw(addr, labels);
}
void generator::method_writer::write_call(method_idx method, span<const address> args)
{
self().write_call(method, args);
}
void generator::method_writer::write_callv(address addr, span<const address> args)
{
self().write_callv(addr, args);
}
void generator::method_writer::write_ret()
{
self().write_ret();
}
void generator::method_writer::write_retv(address addr)
{
self().write_retv(addr);
}
void generator::method_writer::write_dump(address addr)
{
self().write_dump(addr);
}
void generator::method_writer::finalize()
{
auto& writer = self();
auto& gen = writer.gen;
// Ensure the method has returned a value
if (writer.expects_return_value)
{
VALIDATE_HAS_RETURNED(!writer.bytecode.empty() && writer.last_return == writer.bytecode.size(), gen.database[writer.name].name, gen.make_meta(writer.index));
}
writer.resolve_labels();
gen.methods[writer.index] = std::move(writer);
gen.method_writers[writer.index] = nullptr;
delete this;
}
// Generator
generator_impl::generator_impl()
{
initialize_base_types();
keybuf.reserve(32);
}
generator_impl::~generator_impl()
{
for (auto& it : type_writers)
{
if (it) delete it;
}
for (auto& it : method_writers)
{
if (it) delete it;
}
}
generator::generator()
{
}
generator::generator(string_view name)
{
auto& gen = self();
gen.initialize_base_types();
gen.meta_index = gen.metatable.emplace(name);
}
generator::~generator()
{
}
name_idx generator::make_identifier(string_view name)
{
VALIDATE_IDENTIFIER(name);
return self().emplace_identifier(name);
}
signature_idx generator::make_signature(type_idx return_type, span<const type_idx> parameter_types)
{
auto& gen = self();
VALIDATE_INDEX(return_type, gen.types.size());
VALIDATE_TYPES(parameter_types, gen.types.size());
VALIDATE_PARAM_COUNT(parameter_types.size());
make_key(return_type, parameter_types, gen.keybuf);
auto find = gen.signature_lookup.find(gen.keybuf);
if (find == gen.signature_lookup.end())
{
const signature_idx index = signature_idx(gen.signatures.size());
gen_signature sig;
sig.index = index;
sig.return_type = return_type;
sig.parameters.reserve(parameter_types.size());
for (auto it : parameter_types)
{
sig.parameters.push_back(stackvar(it));
}
gen.signature_lookup.emplace(gen.keybuf, index);
gen.signatures.push_back(std::move(sig));
return index;
}
else
{
return find->second;
}
}
offset_idx generator::make_offset(type_idx type, span<const name_idx> fields)
{
auto& gen = self();
VALIDATE_INDEX(type, gen.types.size());
VALIDATE_INDICES(fields, gen.database.size());
VALIDATE_OFFSET_VALUE(!fields.empty());
make_key(type, fields, gen.keybuf);
auto find = gen.offset_lookup.find(gen.keybuf);
if (find == gen.offset_lookup.end())
{
// New offset
block<name_idx> field_indices(fields.data(), fields.size());
gen_field_address addr(type, std::move(field_indices));
const offset_idx index = offset_idx(gen.offsets.size());
gen.offsets.push_back(std::move(addr));
gen.offset_lookup.emplace(gen.keybuf, index);
return index;
}
else
{
return find->second;
}
}
offset_idx generator::append_offset(offset_idx offset, span<const name_idx> fields)
{
auto& gen = self();
VALIDATE_INDEX(offset, gen.offsets.size());
VALIDATE_INDICES(fields, gen.database.size());
VALIDATE_OFFSET_VALUE(!fields.empty());
const auto& base = gen.offsets[offset];
gen.keybuf.clear();
append_key(gen.keybuf, base.name.object_type);
for (size_t i = 0; i < base.name.field_names.size(); i++)
{
append_key(gen.keybuf, base.name.field_names[i]);
}
for (size_t i = 0; i < fields.size(); i++)
{
append_key(gen.keybuf, fields[i]);
}
auto find = gen.offset_lookup.find(gen.keybuf);
if (find == gen.offset_lookup.end())
{
block<name_idx> field_indices(base.name.field_names.size() + fields.size());
name_idx* dst = field_indices.data();
for (size_t i = 0; i < base.name.field_names.size(); i++)
*dst++ = base.name.field_names[i];
for (size_t i = 0; i < fields.size(); i++)
*dst++ = fields[i];
gen_field_address addr(base.name.object_type, std::move(field_indices));
const offset_idx index = offset_idx(gen.offsets.size());
gen.offsets.push_back(std::move(addr));
gen.offset_lookup.emplace(gen.keybuf, index);
return index;
}
else
{
return find->second;
}
}
void generator::define_global(name_idx name, bool is_constant, type_idx type, span<const constant> values)
{
self().define_data(is_constant ? lookup_type::constant : lookup_type::global, type, name, values);
}
type_idx generator::declare_type(name_idx name)
{
auto& gen = self();
VALIDATE_INDEX(name, gen.database.size());
auto find = gen.database[name];
if (find->lookup == lookup_type::identifier)
{
// New type
const type_idx index = type_idx(gen.types.size());
*find = index;
gen.types.push_back(gen_type(name, index));
gen.type_writers.resize(gen.types.size());
return index;
}
else
{
VALIDATE_IDENTIFIER_TYPE(find->lookup == lookup_type::type, lookup_type::type, find->lookup, gen.database[name].name);
// Type already exists
return find->type;
}
}
generator::type_writer& generator::define_type(type_idx type, bool is_union)
{
auto& gen = self();
VALIDATE_INDEX(type, gen.types.size());
auto& dst = gen.types[type];
VALIDATE_TYPE_DEC(!dst.is_defined(), gen.database[dst.name].name, gen.make_meta(dst.index));
dst.meta.index = gen.meta_index;
dst.meta.line_number = gen.line_number;
generator::type_writer*& writer = gen.type_writers[type];
if (!writer)
{
writer = new generator::type_writer(gen, dst.name, dst.index, is_union);
}
return *writer;
}
type_idx generator::declare_pointer_type(type_idx base_type)
{
auto& gen = self();
VALIDATE_INDEX(base_type, gen.types.size());
auto& type = gen.types[base_type];
if (type.pointer_type == type_idx::invalid)
{
// New pointer type
const type_idx idx = type_idx(gen.types.size());
gen_type generate_type(name_idx::invalid, idx);
generate_type.make_pointer(base_type);
generate_type.flags |= extended_flags::is_defined;
type.pointer_type = idx;
gen.types.push_back(std::move(generate_type));
return idx;
}
// Existing pointer type
return type.pointer_type;
}
type_idx generator::declare_array_type(type_idx base_type, size_t array_size)
{
auto& gen = self();
VALIDATE_INDEX(base_type, gen.types.size());
VALIDATE_ARRAY_LENGTH(array_size);
auto& type = gen.types[base_type];
auto find = type.array_types.find(array_size);
if (find == type.array_types.end())
{
// New array type
const type_idx idx = type_idx(gen.types.size());
gen_type generate_type(name_idx::invalid, idx);
generate_type.make_array(base_type, array_size);
generate_type.flags |= extended_flags::is_defined;
type.array_types.emplace(array_size, idx);
gen.types.push_back(std::move(generate_type));
return idx;
}
// Existing array type
return find->second;
}
type_idx generator::declare_signature_type(signature_idx signature)
{
auto& gen = self();
VALIDATE_INDEX(signature, gen.signatures.size());
gen_signature& sig = gen.signatures[signature];
if (sig.signature_type == type_idx::invalid)
{
// New signature type
const type_idx idx = type_idx(gen.types.size());
gen_type generate_type(name_idx::invalid, idx);
generate_type.make_signature(signature);
generate_type.flags |= extended_flags::is_defined;
sig.signature_type = idx;
gen.types.push_back(std::move(generate_type));
return idx;
}
// Existing signature type
return sig.signature_type;
}
method_idx generator::declare_method(name_idx name)
{
auto& gen = self();
VALIDATE_INDEX(name, gen.database.size());
auto find = gen.database[name];
if (find->lookup == lookup_type::identifier)
{
// New method
const method_idx index = method_idx(gen.methods.size());
*find = index;
gen.methods.push_back(gen_method(name, index));
gen.method_writers.resize(gen.methods.size());
return index;
}
else
{
VALIDATE_IDENTIFIER_TYPE(find->lookup == lookup_type::method, lookup_type::method, find->lookup, gen.database[name].name);
// Existing method
return find->method;
}
}
generator::method_writer& generator::define_method(method_idx method, signature_idx signature)
{
auto& gen = self();
VALIDATE_INDEX(method, gen.methods.size());
VALIDATE_INDEX(signature, gen.signatures.size());
auto& dst = gen.methods[method];
VALIDATE_METHOD_DEC(!dst.is_defined(), gen.database[dst.name].name, gen.make_meta(dst.index));
dst.meta.index = gen.meta_index;
dst.meta.line_number = gen.line_number;
generator::method_writer*& writer = gen.method_writers[method];
if (!writer)
{
writer = new generator::method_writer(gen, dst.name, dst.index, signature);
}
return *writer;
}
void generator::set_line_number(index_t line_number) noexcept
{
self().line_number = line_number;
}
intermediate generator::finalize()
{
auto& gen = self();
// Finalize can throw
// Finalize cleans up the writer and sets itself null in the array
for (auto& it : gen.type_writers)
{
if (it) it->finalize();
}
for (auto& it : gen.method_writers)
{
if (it) it->finalize();
}
intermediate result;
gen_intermediate_data::serialize(result, gen);
return result;
}
file_meta generator::type_writer::get_meta() const
{
return self().gen.get_meta();
}
file_meta generator::method_writer::get_meta() const
{
return self().gen.get_meta();
}
file_meta generator::get_meta() const
{
return self().get_meta();
}
} | 33.980726 | 169 | 0.575545 | [
"vector"
] |
804082ad721ed14e643097bc02a95accbd473cc4 | 22,919 | cpp | C++ | src/Pegasus/Provider/ClientCIMOMHandleRep.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/Pegasus/Provider/ClientCIMOMHandleRep.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/Pegasus/Provider/ClientCIMOMHandleRep.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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 <Pegasus/Common/Constants.h>
#include <Pegasus/Common/Thread.h>
#include <Pegasus/Common/Tracer.h>
#include <Pegasus/ProviderManager2/AutoPThreadSecurity.h>
#include "ClientCIMOMHandleRep.h"
PEGASUS_NAMESPACE_BEGIN
static void deleteContentLanguage(void* data)
{
ContentLanguageList* cl = static_cast<ContentLanguageList*>(data);
delete cl;
}
/**
This class is used to prevent concurrent access to a non-reentrant
CIMClient object.
*/
class ClientCIMOMHandleAccessController
{
public:
ClientCIMOMHandleAccessController(Mutex& lock)
: _lock(lock)
{
try
{
// assume default client timeout
if (!_lock.timed_lock(PEGASUS_DEFAULT_CLIENT_TIMEOUT_MILLISECONDS))
{
throw CIMException(CIM_ERR_ACCESS_DENIED, MessageLoaderParms(
"Provider.CIMOMHandle.CIMOMHANDLE_TIMEOUT",
"Timeout waiting for CIMOMHandle"));
}
}
catch (Exception& e)
{
PEG_TRACE((TRC_CIMOM_HANDLE, Tracer::LEVEL2,
"Unexpected Exception: %s",
(const char*)e.getMessage().getCString()));
throw;
}
catch (...)
{
PEG_TRACE_CSTRING(TRC_CIMOM_HANDLE, Tracer::LEVEL2,
"Unexpected exception");
throw;
}
}
~ClientCIMOMHandleAccessController()
{
// Must not throw an exception from a destructor
try
{
_lock.unlock();
}
catch (Exception& e)
{
PEG_TRACE((TRC_CIMOM_HANDLE, Tracer::LEVEL2,
"Ignoring Exception: %s",
(const char*)e.getMessage().getCString()));
}
catch (...)
{
PEG_TRACE_CSTRING(TRC_CIMOM_HANDLE, Tracer::LEVEL2,
"Ignoring unknown exception");
}
}
private:
// Unimplemented constructors and assignment operator
ClientCIMOMHandleAccessController();
ClientCIMOMHandleAccessController(const ClientCIMOMHandleAccessController&);
ClientCIMOMHandleAccessController& operator=(
const ClientCIMOMHandleAccessController&);
Mutex& _lock;
};
/**
The ClientCIMOMHandleSetup class encapsulates the logic to set up the
CIMClient object state based on a specified OperationContext. The
original CIMClient state is restored by the destructor. Only one
ClientCIMOMHandleSetup object may operate on a given CIMClient object
at a time. Use of the ClientCIMOMHandleAccessController class is
recommend to control access to CIMClient objects.
*/
class ClientCIMOMHandleSetup
{
public:
ClientCIMOMHandleSetup(
CIMClientRep*& client,
const OperationContext& context)
{
//
// Initialize the CIMClient object if necessary
//
if (client == 0)
{
PEG_TRACE_CSTRING(TRC_CIMOM_HANDLE, Tracer::LEVEL3,
"Creating CIMClient connection");
client = new CIMClientRep();
//
// If connection fails, we need to make sure that subsequent
// calls will try to connect again.
//
try
{
client->connectLocalBinary();
}
catch(...)
{
delete client;
client = 0;
throw;
}
}
_client = client;
//
// If the caller specified a timeout value in the OperationContext,
// set it in the CIMClient object.
//
_origTimeout = client->getTimeout();
if (context.contains(TimeoutContainer::NAME))
{
TimeoutContainer t_cntr = (TimeoutContainer)
context.get(TimeoutContainer::NAME);
client->setTimeout(t_cntr.getTimeOut());
}
//
// If the caller specified an Accept-Language in the
// OperationContext, set it in the CIMClient object.
//
_origAcceptLanguages = client->getRequestAcceptLanguages();
if (context.contains(AcceptLanguageListContainer::NAME))
{
AcceptLanguageListContainer al_cntr = (AcceptLanguageListContainer)
context.get(AcceptLanguageListContainer::NAME);
_client->setRequestAcceptLanguages(al_cntr.getLanguages());
}
else
{
// No AcceptLanguageListContainer in OperationContext; try
// getting the AcceptLanguageList from the current thread
AcceptLanguageList* al = Thread::getLanguages();
if (al != NULL)
{
_client->setRequestAcceptLanguages(*al);
}
}
//
// If the caller specified a Content-Language in the
// OperationContext, set it in the CIMClient object.
//
_origContentLanguages = client->getRequestContentLanguages();
if (context.contains(ContentLanguageListContainer::NAME))
{
ContentLanguageListContainer cl_cntr =
(ContentLanguageListContainer)context.get(
ContentLanguageListContainer::NAME);
_client->setRequestContentLanguages(cl_cntr.getLanguages());
}
}
~ClientCIMOMHandleSetup()
{
// Must not throw an exception from a destructor
try
{
//
// If the response has a Content-Language then save it into
// thread-specific storage
//
if (_client->getResponseContentLanguages().size() > 0)
{
Thread* curThrd = Thread::getCurrent();
if (curThrd != NULL)
{
// deletes the old tsd and creates a new one
curThrd->put_tsd(TSD_CIMOM_HANDLE_CONTENT_LANGUAGES,
deleteContentLanguage,
sizeof(ContentLanguageList*),
new ContentLanguageList(
_client->getResponseContentLanguages()));
}
}
//
// Reset CIMClient timeout value and languages to original values
//
_client->setTimeout(_origTimeout);
_client->setRequestAcceptLanguages(_origAcceptLanguages);
_client->setRequestContentLanguages(_origContentLanguages);
}
catch (Exception& e)
{
PEG_TRACE((TRC_CIMOM_HANDLE, Tracer::LEVEL1,
"Ignoring Exception: %s",
(const char*)e.getMessage().getCString()));
}
catch (...)
{
PEG_TRACE_CSTRING(TRC_CIMOM_HANDLE, Tracer::LEVEL1,
"Ignoring unknown exception");
}
}
private:
// Unimplemented constructors and assignment operator
ClientCIMOMHandleSetup();
ClientCIMOMHandleSetup(const ClientCIMOMHandleSetup&);
ClientCIMOMHandleSetup& operator=(const ClientCIMOMHandleSetup&);
CIMClientRep* _client;
Uint32 _origTimeout;
AcceptLanguageList _origAcceptLanguages;
ContentLanguageList _origContentLanguages;
};
//
// ClientCIMOMHandleRep
//
ClientCIMOMHandleRep::ClientCIMOMHandleRep()
: _client(0)
{
}
ClientCIMOMHandleRep::~ClientCIMOMHandleRep()
{
if (_client != 0)
{
// Must not throw an exception from a destructor
try
{
_client->disconnect();
}
catch (...)
{
// Ignore disconnect exceptions
}
delete _client;
}
}
//
// CIM Operations
//
CIMClass ClientCIMOMHandleRep::getClass(
const OperationContext & context,
const CIMNamespaceName& nameSpace,
const CIMName& className,
Boolean localOnly,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::getClass");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->getClass(
nameSpace,
className,
localOnly,
includeQualifiers,
includeClassOrigin,
propertyList);
}
Array<CIMClass> ClientCIMOMHandleRep::enumerateClasses(
const OperationContext & context,
const CIMNamespaceName& nameSpace,
const CIMName& className,
Boolean deepInheritance,
Boolean localOnly,
Boolean includeQualifiers,
Boolean includeClassOrigin)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::enumerateClasses");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->enumerateClasses(
nameSpace,
className,
deepInheritance,
localOnly,
includeQualifiers,
includeClassOrigin);
}
Array<CIMName> ClientCIMOMHandleRep::enumerateClassNames(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMName& className,
Boolean deepInheritance)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::enumerateClassNames");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->enumerateClassNames(
nameSpace,
className,
deepInheritance);
}
void ClientCIMOMHandleRep::createClass(
const OperationContext & context,
const CIMNamespaceName& nameSpace,
const CIMClass& newClass)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::createClass");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->createClass(
nameSpace,
newClass);
PEG_METHOD_EXIT();
}
void ClientCIMOMHandleRep::modifyClass(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMClass& modifiedClass)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::modifyClass");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->modifyClass(
nameSpace,
modifiedClass);
PEG_METHOD_EXIT();
}
void ClientCIMOMHandleRep::deleteClass(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::deleteClass");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->deleteClass(
nameSpace,
className);
PEG_METHOD_EXIT();
}
CIMResponseData ClientCIMOMHandleRep::getInstance(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& instanceName,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::getInstance");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->getInstance(
nameSpace,
instanceName,
false, // localOnly
includeQualifiers,
includeClassOrigin,
propertyList);
}
CIMResponseData ClientCIMOMHandleRep::enumerateInstances(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMName& className,
Boolean deepInheritance,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::enumerateInstances");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->enumerateInstances(
nameSpace,
className,
deepInheritance,
false, // localOnly
includeQualifiers,
includeClassOrigin,
propertyList);
}
CIMResponseData ClientCIMOMHandleRep::enumerateInstanceNames(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMName& className)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::enumerateInstanceNames");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->enumerateInstanceNames(
nameSpace,
className);
}
CIMObjectPath ClientCIMOMHandleRep::createInstance(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMInstance& newInstance)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::createInstance");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->createInstance(
nameSpace,
newInstance);
}
void ClientCIMOMHandleRep::modifyInstance(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMInstance& modifiedInstance,
Boolean includeQualifiers,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::modifyInstance");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->modifyInstance(
nameSpace,
modifiedInstance,
includeQualifiers,
propertyList);
PEG_METHOD_EXIT();
}
void ClientCIMOMHandleRep::deleteInstance(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& instanceName)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::deleteInstance");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->deleteInstance(
nameSpace,
instanceName);
PEG_METHOD_EXIT();
}
CIMResponseData ClientCIMOMHandleRep::execQuery(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const String& queryLanguage,
const String& query)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::execQuery");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->execQuery(
nameSpace,
queryLanguage,
query);
}
CIMResponseData ClientCIMOMHandleRep::associators(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& objectName,
const CIMName& assocClass,
const CIMName& resultClass,
const String& role,
const String& resultRole,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::associators");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->associators(
nameSpace,
objectName,
assocClass,
resultClass,
role,
resultRole,
includeQualifiers,
includeClassOrigin,
propertyList);
}
CIMResponseData ClientCIMOMHandleRep::associatorNames(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& objectName,
const CIMName& assocClass,
const CIMName& resultClass,
const String& role,
const String& resultRole)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::associatorNames");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->associatorNames(
nameSpace,
objectName,
assocClass,
resultClass,
role,
resultRole);
}
CIMResponseData ClientCIMOMHandleRep::references(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role,
Boolean includeQualifiers,
Boolean includeClassOrigin,
const CIMPropertyList& propertyList)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::references");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->references(
nameSpace,
objectName,
resultClass,
role,
includeQualifiers,
includeClassOrigin,
propertyList);
}
CIMResponseData ClientCIMOMHandleRep::referenceNames(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& objectName,
const CIMName& resultClass,
const String& role)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE,
"ClientCIMOMHandleRep::referenceNames");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->referenceNames(
nameSpace,
objectName,
resultClass,
role);
}
CIMValue ClientCIMOMHandleRep::getProperty(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& instanceName,
const CIMName& propertyName)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::getProperty");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->getProperty(
nameSpace,
instanceName,
propertyName);
}
void ClientCIMOMHandleRep::setProperty(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& instanceName,
const CIMName& propertyName,
const CIMValue& newValue)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::setProperty");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
_client->setProperty(
nameSpace,
instanceName,
propertyName,
newValue);
PEG_METHOD_EXIT();
}
CIMValue ClientCIMOMHandleRep::invokeMethod(
const OperationContext & context,
const CIMNamespaceName &nameSpace,
const CIMObjectPath& instanceName,
const CIMName& methodName,
const Array<CIMParamValue>& inParameters,
Array<CIMParamValue>& outParameters)
{
PEG_METHOD_ENTER(TRC_CIMOM_HANDLE, "ClientCIMOMHandleRep::invokeMethod");
AutoPThreadSecurity revPthreadSec(context, true);
ClientCIMOMHandleAccessController access(_clientMutex);
ClientCIMOMHandleSetup setup(_client, context);
PEG_METHOD_EXIT();
return _client->invokeMethod(
nameSpace,
instanceName,
methodName,
inParameters,
outParameters);
}
//
// Other public methods
//
#ifdef PEGASUS_USE_EXPERIMENTAL_INTERFACES
OperationContext ClientCIMOMHandleRep::getResponseContext()
{
OperationContext ctx;
Thread* curThrd = Thread::getCurrent();
if (curThrd == NULL)
{
ctx.insert(ContentLanguageListContainer(ContentLanguageList()));
}
else
{
ContentLanguageList* contentLangs = (ContentLanguageList*)
curThrd->reference_tsd(TSD_CIMOM_HANDLE_CONTENT_LANGUAGES);
curThrd->dereference_tsd();
if (contentLangs == NULL)
{
ctx.insert(ContentLanguageListContainer(ContentLanguageList()));
}
else
{
ctx.insert(ContentLanguageListContainer(*contentLangs));
// delete the old tsd to free the memory
curThrd->delete_tsd(TSD_CIMOM_HANDLE_CONTENT_LANGUAGES);
}
}
return ctx;
}
#endif
PEGASUS_NAMESPACE_END
| 29.687824 | 80 | 0.676033 | [
"object"
] |
80432c01c0c2b3b68239d9a5dc2fdb0cf9e0110e | 1,175 | hpp | C++ | map/track.hpp | Polas/omim | 03558b418b338f506fbf3aa72ddf15187a2005ee | [
"Apache-2.0"
] | 1 | 2020-11-10T01:13:12.000Z | 2020-11-10T01:13:12.000Z | map/track.hpp | Polas/omim | 03558b418b338f506fbf3aa72ddf15187a2005ee | [
"Apache-2.0"
] | 1 | 2018-11-26T15:44:46.000Z | 2018-11-27T10:55:36.000Z | map/track.hpp | Polas/omim | 03558b418b338f506fbf3aa72ddf15187a2005ee | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "kml/types.hpp"
#include "drape_frontend/user_marks_provider.hpp"
#include <string>
class Track : public df::UserLineMark
{
using Base = df::UserLineMark;
public:
explicit Track(kml::TrackData && data);
kml::MarkGroupId GetGroupId() const override { return m_groupID; }
bool IsDirty() const override { return m_isDirty; }
void ResetChanges() const override { m_isDirty = false; }
kml::TrackData const & GetData() const { return m_data; }
std::string GetName() const;
m2::RectD GetLimitRect() const;
double GetLengthMeters() const;
int GetMinZoom() const override { return 1; }
df::DepthLayer GetDepthLayer() const override;
size_t GetLayerCount() const override;
dp::Color GetColor(size_t layerIndex) const override;
float GetWidth(size_t layerIndex) const override;
float GetDepth(size_t layerIndex) const override;
std::vector<m2::PointD> GetPoints() const override;
std::vector<geometry::PointWithAltitude> const & GetPointsWithAltitudes() const;
void Attach(kml::MarkGroupId groupId);
void Detach();
private:
kml::TrackData m_data;
kml::MarkGroupId m_groupID;
mutable bool m_isDirty = true;
};
| 27.325581 | 82 | 0.737872 | [
"geometry",
"vector"
] |
80477d1644381c55dad8c5c8de23a7c4fb06855e | 6,434 | hpp | C++ | third_party/omr/compiler/compile/OMRMethod.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/compile/OMRMethod.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/compile/OMRMethod.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef OMR_METHOD_INCL
#define OMR_METHOD_INCL
/*
* The following #define and typedef must appear before any #includes in this file
*/
#ifndef OMR_METHOD_CONNECTOR
#define OMR_METHOD_CONNECTOR
namespace OMR { class Method; }
namespace OMR { typedef OMR::Method MethodConnector; }
#endif
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include "codegen/RecognizedMethods.hpp"
#include "env/TRMemory.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "infra/Annotations.hpp"
class TR_OpaqueClassBlock;
class TR_ResolvedMethod;
namespace TR { class Compilation; }
// Method indexes
//
class mcount_t {
private:
uint32_t _value;
mcount_t(uint32_t value) : _value(value) {}
public:
mcount_t() : _value(0) {}
mcount_t(const mcount_t &other) : _value(other._value) {}
static mcount_t valueOf(uint16_t value){ return mcount_t((uint32_t)value); }
static mcount_t valueOf(uint32_t value){ return mcount_t((uint32_t)value); }
static mcount_t valueOf(int32_t value) { return mcount_t((uint32_t)value); }
bool operator >= (mcount_t other) const { return _value >= other._value; }
bool operator > (mcount_t other) const { return _value > other._value; }
bool operator <= (mcount_t other) const { return _value <= other._value; }
bool operator == (mcount_t other) const { return _value == other._value; }
bool operator != (mcount_t other) const { return _value != other._value; }
mcount_t operator + (int32_t increment) const { return mcount_t(_value + increment); }
uint32_t value() const { return _value; }
};
#define JITTED_METHOD_INDEX (mcount_t::valueOf((uint32_t)0)) // Index of the top-level method being compiled
#define MAX_CALLER_INDEX (mcount_t::valueOf((uint32_t)INT_MAX)) // Could be UINT_MAX, in theory, but let's avoid corner cases until that day comes when we need 3 billion caller indexes
class TR_MethodParameterIterator
{
public:
TR_ALLOC(TR_Memory::Method)
virtual TR::DataType getDataType() = 0;
virtual TR_OpaqueClassBlock * getOpaqueClass() = 0; // if getDataType() == TR::Aggregate
virtual bool isArray() = 0; // refines getOpaqueClass
virtual bool isClass() = 0; // refines getOpaqueClass
virtual char * getUnresolvedJavaClassSignature(uint32_t&)=0;
virtual bool atEnd() = 0;
virtual void advanceCursor() = 0;
protected:
TR_MethodParameterIterator(TR::Compilation& comp) : _comp(comp) { }
TR::Compilation & _comp;
};
typedef struct TR_AOTMethodInfo
{
TR_ResolvedMethod *resolvedMethod;
int32_t cpIndex;
} TR_AOTMethodInfo;
namespace OMR
{
class Method
{
public:
TR_ALLOC(TR_Memory::Method);
enum Type {J9, Test, JitBuilder};
virtual TR::DataType parmType(uint32_t parmNumber); // returns the type of the parmNumber'th parameter (0-based)
virtual bool isConstructor(); // returns true if this method is object constructor.
virtual TR::ILOpCodes directCallOpCode();
virtual TR::ILOpCodes indirectCallOpCode();
virtual TR::DataType returnType();
virtual uint32_t returnTypeWidth();
virtual bool returnTypeIsUnsigned();
virtual TR::ILOpCodes returnOpCode();
virtual const char *signature(TR_Memory *, TR_AllocationKind = heapAlloc);
virtual uint16_t classNameLength();
virtual uint16_t nameLength();
virtual uint16_t signatureLength();
virtual char *classNameChars(); // returns the utf8 of the class that this method is in.
virtual char *nameChars(); // returns the utf8 of the method name
virtual char *signatureChars(); // returns the utf8 of the signature
bool isJ9() { return _typeOfMethod == J9; }
Type methodType() { return _typeOfMethod; }
Method(Type t = J9) : _typeOfMethod(t) { _recognizedMethod = _mandatoryRecognizedMethod = TR::unknownMethod; }
// --------------------------------------------------------------------------
// J9
virtual uint32_t numberOfExplicitParameters();
virtual bool isArchetypeSpecimen(){ return false; }
virtual void setArchetypeSpecimen(bool b = true);
virtual bool isUnsafeWithObjectArg(TR::Compilation * = NULL);
virtual bool isUnsafeCAS(TR::Compilation * = NULL);
virtual bool isBigDecimalMethod (TR::Compilation * = NULL);
virtual bool isBigDecimalConvertersMethod (TR::Compilation * = NULL);
virtual bool isFinalInObject();
virtual TR_MethodParameterIterator *getParameterIterator(TR::Compilation&, TR_ResolvedMethod * = NULL);
// ---------------------------------------------------------------------------
// Use this for optional logic that takes advantage of known information about a particular method
//
TR::RecognizedMethod getRecognizedMethod() { return _recognizedMethod; }
// Use this for logic where failing to recognize a method leads to bugs
//
TR::RecognizedMethod getMandatoryRecognizedMethod() { return _mandatoryRecognizedMethod; }
void setRecognizedMethod(TR::RecognizedMethod rm) { _recognizedMethod = rm; }
void setMandatoryRecognizedMethod(TR::RecognizedMethod rm) { _mandatoryRecognizedMethod = rm; }
private:
TR::RecognizedMethod _recognizedMethod;
TR::RecognizedMethod _mandatoryRecognizedMethod;
Type _typeOfMethod;
};
}
#endif
| 35.744444 | 184 | 0.698788 | [
"object"
] |
8052b0433db62889b2e184e50149f460e6e9c975 | 4,061 | cpp | C++ | Portable/zoolib/PullPush_SeparatedValues.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 13 | 2015-01-28T21:05:09.000Z | 2021-11-03T22:21:11.000Z | Portable/zoolib/PullPush_SeparatedValues.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | null | null | null | Portable/zoolib/PullPush_SeparatedValues.cpp | ElectricMagic/zoolib_cxx | cb3ccfde931b3989cd420fa093153204a7899805 | [
"MIT"
] | 4 | 2018-11-16T08:33:33.000Z | 2021-12-11T19:40:46.000Z | // Copyright (c) 2018 Andrew Green. MIT License. http://www.zoolib.org
#include "zoolib/PullPush_SeparatedValues.h"
#include "zoolib/ParseException.h"
#include "zoolib/Unicode.h" // For operator+=
#include "zoolib/ChanW_UTF.h"
#include "zoolib/ZMACRO_foreach.h"
#include <vector>
namespace ZooLib {
//using namespace Util_Chan_UTF_Operators;
using namespace PullPush;
using std::string;
using std::vector;
// =================================================================================================
#pragma mark - Static parsing functions
static
vector<string8> spReadValues(const ChanR_UTF& iChanR, UTF32 iSeparator_Value, UTF32 iTerminator_Line)
{
vector<string8> result;
string8 curValue;
for (bool gotAny = false; /*no test*/; gotAny = true)
{
if (NotQ<UTF32> theCPQ = sQRead(iChanR))
{
if (gotAny)
result.push_back(curValue);
break;
}
else if (*theCPQ == iTerminator_Line)
{
result.push_back(curValue);
break;
}
else if (*theCPQ == iSeparator_Value)
{
result.push_back(curValue);
curValue.clear();
}
else
{
curValue += *theCPQ;
}
}
return result;
}
// =================================================================================================
#pragma mark - Pull_SeparatedValues_Options
Pull_SeparatedValues_Options::Pull_SeparatedValues_Options(
UTF32 iSeparator_Value, UTF32 iTerminator_Line)
: fSeparator_Value(iSeparator_Value)
, fTerminator_Line(iTerminator_Line)
{}
// =================================================================================================
#pragma mark -
bool sPull_SeparatedValues_Push_PPT(const ChanR_UTF& iChanR,
const Pull_SeparatedValues_Options& iOptions,
const ChanW_PPT& iChanW)
{
const vector<string8> theNames =
spReadValues(iChanR, iOptions.fSeparator_Value, iOptions.fTerminator_Line);
if (theNames.empty())
return false;
sPush_Start_Seq(iChanW);
for (;;)
{
const vector<string8> theValues =
spReadValues(iChanR, iOptions.fSeparator_Value, iOptions.fTerminator_Line);
if (theValues.empty())
{
sPush_End(iChanW);
return true;
}
sPush_Start_Map(iChanW);
for (size_t xx = 0; xx < theNames.size() && xx < theValues.size(); ++xx)
sPush(theNames[xx], theValues[xx], iChanW);
sPush_End(iChanW);
}
}
bool sPull_SeparatedValues_Push_PPT(const ChanR_UTF& iChanR,
UTF32 iSeparator_Value, UTF32 iTerminator_Line,
const ChanW_PPT& iChanW)
{
return sPull_SeparatedValues_Push_PPT(iChanR,
Pull_SeparatedValues_Options(iSeparator_Value, iTerminator_Line),
iChanW);
}
// =================================================================================================
#pragma mark - Push_SeparatedValues_Options
Push_SeparatedValues_Options::Push_SeparatedValues_Options(
UTF32 iSeparator_Value, UTF32 iTerminator_Line)
: fSeparator_Value(iSeparator_Value)
, fTerminator_Line(iTerminator_Line)
{}
// =================================================================================================
#pragma mark -
bool sPull_PPT_Push_SeparatedValues(const ChanR_PPT& iChanR,
const Push_SeparatedValues_Options& iOptions,
const ChanW_UTF& iChanW)
{
ZQ<PPT> theStartQ = sQRead(iChanR);
if (not theStartQ)
return false;
if (not sIsStart_Seq(*theStartQ))
sThrow_ParseException("Expected Start_Seq");
for (;;)
{
ZQ<PPT> theQ = sQRead(iChanR);
if (not theQ)
sThrow_ParseException("Expected PPT");
if (not sIsStart_Seq(*theQ))
{
if (sIsEnd(*theQ))
break;
sThrow_ParseException("Expected End of document, or start of line");
}
for (bool isFirst = true; /*no test*/; isFirst = false)
{
ZQ<PPT> theQ = sQEReadPPTOrEnd(iChanR);
if (not theQ)
{
sEWrite(iChanW, iOptions.fTerminator_Line);
break;
}
if (not isFirst)
sEWrite(iChanW, iOptions.fSeparator_Value);
if (ZQ<string8> theStringQ = theQ->QGet<string8>())
sEWrite(iChanW, *theStringQ);
else
{
sEWrite(iChanW, "???");
if (sIsStart(*theQ))
sSkip_Node(iChanR, 1);
}
}
}
return true;
}
} // namespace ZooLib
| 24.172619 | 101 | 0.629155 | [
"vector"
] |
805ad52c094ff16ced7c1a6181e57f03ab226a4e | 23,092 | cc | C++ | quantizer.cc | TiKevin83/pik | 56e644f3b7530ea9faeaa32f315329cc98604c2b | [
"Apache-2.0"
] | null | null | null | quantizer.cc | TiKevin83/pik | 56e644f3b7530ea9faeaa32f315329cc98604c2b | [
"Apache-2.0"
] | null | null | null | quantizer.cc | TiKevin83/pik | 56e644f3b7530ea9faeaa32f315329cc98604c2b | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "quantizer.h"
#include <stdio.h>
#include <algorithm>
#include <sstream>
#include <vector>
#define PROFILER_ENABLED 1
#include "arch_specific.h"
#include "cache_aligned.h"
#include "common.h"
#include "compiler_specific.h"
#include "dct.h"
#include "entropy_coder.h"
#include "profiler.h"
#include "simd/simd.h"
namespace pik {
static const int kDefaultQuant = 64;
// kQuantWeights[3 * k_zz + c] is the relative weight of the k_zz coefficient
// (in the zig-zag order) in component c. Higher weights correspond to finer
// quantization intervals and more bits spent in encoding.
const double *GetQuantWeights() {
static double kQuantWeights[kNumQuantTables * 192] = {
// Default weights
4.3141203228013438,
0.83740203419092563,
0.51137522717087869,
8.736834574015262,
0.7776397194427076,
0.13442931289541543,
6.3379346742508131,
0.70692883300525067,
0.12368899522321172,
1.7679749651060572,
0.65347325775644483,
0.23333737574436145,
4.1820889419933449,
0.61826473894479117,
0.16390510194206945,
3.321466890319678,
0.50605143545289055,
0.1042338362877393,
2.2121858502448699,
0.39737454618364199,
0.039923519117012793,
1.5048430743835741,
0.44253191996134272,
0.081069424968966131,
2.4362778754556715,
0.43257013459329918,
0.074344935656858804,
1.1783892036481227,
0.30224131501589768,
0.035528575800878801,
1.3283725533453592,
0.22521680805375197,
0.081862698246215573,
1.5580768395244231,
0.25349576252750305,
0.11241739107306357,
1.1384409237139839,
0.32444867301666058,
0.069356620702463886,
1.1693363410240802,
0.22720605247313719,
0.072073951417197107,
0.76754319201101462,
0.21674064978995528,
0.049027879973039395,
0.64727928422122272,
0.18328656176888211,
0.063889525390303029,
1.1045513421611661,
0.21585103511079337,
0.074571320833125856,
1.4832095549023419,
0.24363059692829409,
0.046613553523984899,
1.5262612594710887,
0.2658115196632741,
0.095593946920371917,
1.2583542418439091,
0.20278784329053368,
0.10198656903794691,
0.42008027458003649,
0.12917105983800514,
0.10283606990457778,
1.2115017196865743,
0.12382691731111502,
0.1118578524826251,
1.0284671621456556,
0.13754624577284763,
0.065629383999491628,
1.2151126659170599,
0.20578654159697155,
0.067402764565903606,
1.3360284442899479,
0.18668594655278073,
0.056478124053817289,
1.3941851810988457,
0.18141839274334995,
0.069418113786006708,
1.0857335532257077,
0.14874461747004106,
0.071432726113976608,
0.49362766892933202,
0.10020854148621977,
0.027582794969484382,
0.65702715944968204,
0.096304882733300276,
0.091792356939215544,
0.32829090137286626,
0.076386710316435236,
0.012417922327300664,
0.83052927891064143,
0.15665165444878068,
0.043896269389724109,
1.0434079920710564,
0.21053548494276011,
0.046276756365166177,
1.2094211085965179,
0.16230067189998562,
0.066730255542867128,
0.24506686179103726,
0.11717160108133351,
0.071165909610693245,
0.5961782045984203,
0.10906846987703636,
0.1074957435127179,
0.37538159142202759,
0.071397660203107588,
0.050158510029965957,
0.28792379690718628,
0.088841068516194235,
0.032875806394252971,
0.56685852046049934,
0.16199207885726091,
0.070272384862404516,
0.60238104605220288,
0.13140304193241348,
0.036894168984050693,
0.43756449773263967,
0.10538224819307006,
0.061117235994783574,
1.445481349271859,
0.11056598177328424,
0.10550134542793914,
0.62668250672205428,
0.1363109543481357,
0.090595671257557658,
0.93212201984338217,
0.091816676840817527,
0.065804682083453414,
0.77349681213167532,
0.094966685329228195,
0.046235492735370469,
0.43544066126588366,
0.14585995730471052,
0.13016576971130089,
0.53449533631624657,
0.16736010700087711,
0.11194695994990535,
0.66297724883130826,
0.13362584923010118,
0.027664198156865393,
1.37558530050399797,
0.19032544668628112,
0.06550400570919304,
0.65627644060647694,
0.18257594324102225,
0.02736150102783333,
0.69658722851847443,
0.16019921330041217,
0.03928658926666367,
0.60383586256890809,
0.25321132092045168,
0.03265559675305111,
0.83693327158281239,
0.14504128077517850,
0.02099986490870039,
0.89483155160749195,
0.19135027758942161,
0.05451133366516921,
1.01079312492116169,
0.18828293699332641,
0.02114328476201841,
0.61433852336830252,
0.18195885412296919,
0.04756213156467592,
0.85359113948742638,
0.17833895130867813,
0.06022307525778426,
0.19690151314535168,
0.14519022078866697,
0.02011343570768113,
0.68009239530229870,
0.17833653288483989,
0.05546182646799611,
0.25124318417438091,
0.13437112957798944,
0.04817602415230767,
0.76255544979395051,
0.13009719708974776,
0.04122936655509454,
0.80566896654017395,
0.13810327055412253,
0.05703495243404272,
0.42317017460668760,
0.12932494829955105,
0.05788307678117844,
0.88814332926268424,
0.14743472727149085,
0.03950479954925656,
0.42966332525140621,
0.14234967223268227,
0.04663425547477144,
// Weights for HQ mode
5.97098671763256839,
1.69761990929546780,
0.53853771332792444,
3.14253990320328125,
0.78664853390117273,
0.17190174775266073,
3.21440032329272363,
0.79324113975890986,
0.19073348746478294,
2.31877876078626644,
1.20331026659435092,
0.18068627495819625,
2.66138348593645846,
1.27976364845854129,
0.14314257421962365,
2.05669558255116414,
0.67193542643511317,
0.12976541962082244,
1.89568467702556931,
0.87684508464905198,
0.13840382703261955,
1.87183877378106178,
0.87332866827360733,
0.13886642497406188,
1.81376345075241852,
0.90546493291290131,
0.12640806528419762,
1.38659706271567829,
0.67357513728317564,
0.10046114149393238,
1.43970070343494916,
0.64960619501539618,
0.10434852182815810,
1.64121019910504962,
0.67261342673313418,
0.12842635952387660,
1.46477538313861277,
0.70021253533295424,
0.10903159857162095,
1.52923458157991998,
0.69961592005489026,
0.09710617072173894,
1.40023384922801197,
0.68455392518694513,
0.07908914182002977,
1.33839402167055588,
0.69211618315286805,
0.09308446231558251,
1.43643407833087378,
0.69628390114558059,
0.08386075776976390,
1.42012129383485530,
0.65847070005190744,
0.09890816230765243,
1.68161355944399049,
0.71866143043615716,
0.09940258437481214,
1.56772586225783828,
0.67160483088794198,
0.09466185289417853,
1.36510921600277535,
0.62401571586763904,
0.08236434651134468,
1.03208101627848747,
0.59120245407886063,
0.05912383931246348,
1.69702527326663510,
0.68535225222980134,
0.09623784903161817,
1.53252814802078419,
0.72569260047525008,
0.08106185965616462,
1.40794482088634898,
0.68347344254745312,
0.09180649324754615,
0.98409717572352373,
0.66630217832243899,
0.08752033959765924,
1.41539698889807042,
0.51216510866872778,
0.06712898051010259,
0.95856947616046384,
0.50258164653939053,
0.05876841963372925,
0.82585586314858783,
0.60553389435339600,
0.05851610562550572,
1.32551190883622838,
0.52116816325598003,
0.05776704204017307,
1.42525227948613864,
0.66451111078322889,
0.09029381536978218,
1.61480964386399450,
0.58319461600661016,
0.08374152456688765,
1.36272444106781343,
0.56725685656994129,
0.07447525932711950,
1.23016114633190843,
0.54560308162655557,
0.06244568047577013,
1.02531080328291346,
0.51073378680450165,
0.05900332401163505,
0.79645147162795993,
0.48279035076704235,
0.05942394100369194,
1.10224441792333505,
0.51399854683593382,
0.06488521108420610,
1.32841168654714181,
0.55615524649126835,
0.09305414673745493,
1.58130787393576955,
0.52228127315219441,
0.09462056731598355,
1.32305080787503493,
0.56539808782479895,
0.08967000072418904,
1.60940316666871319,
0.60902893903479105,
0.08559545911151349,
1.15852808153812559,
0.57532339125302434,
0.07594769254966900,
1.41422670295622654,
0.51208334668238098,
0.08262610724104018,
1.50123574147011585,
0.61420516049012464,
0.08996506605454008,
1.43030813640267751,
0.52583680560641410,
0.07164827618952087,
1.66786924477306031,
0.56912874262481383,
0.06055826950374100,
1.01687835220554090,
0.53050807292462376,
0.06116745665900101,
1.53314369451989063,
0.58806280311474168,
0.10622593889251969,
1.13915364970228650,
0.51607666905695815,
0.09892489416863132,
1.20062442282843995,
0.62042257791036048,
0.07859956608053299,
1.57803627072360175,
0.56412252798799212,
0.08054184901244756,
1.45092323858166239,
0.52681964760491928,
0.07837902068062400,
1.54334806766566768,
0.52727572293349534,
0.08728601353049063,
1.39711767258527320,
0.57393681796751261,
0.07930505691716441,
0.78158104550004404,
0.60390867209622334,
0.07462500390508715,
1.81436012692921311,
0.54071907903714811,
0.07981141132875894,
0.78511966383388032,
0.55016303699852442,
0.07926565080862039,
1.15182975200692361,
0.56361259875118574,
0.09215829949648185,
0.92065100803555544,
0.56635179840667760,
0.10282781177064568,
1.22537108443054898,
0.54603239891514965,
0.08249748895287572,
1.57458694038461045,
0.53538377686685823,
0.07811475203273252,
1.30320516365488825,
0.46393811087230996,
0.09657913185935441,
0.94422674464538836,
0.46159976390783986,
0.09834404184403754,
1.43973209699300408,
0.46356335670292936,
0.07601385475613358,
};
return &kQuantWeights[0];
}
const float* NewDequantMatrices() {
float* table = static_cast<float*>(
CacheAligned::Allocate(kNumQuantTables * 192 * sizeof(float)));
for (int id = 0; id < kNumQuantTables; ++id) {
for (int idx = 0; idx < 192; ++idx) {
int c = idx % 3;
int k_zz = idx / 3;
int k = kNaturalCoeffOrder[k_zz];
float idct_scale = kIDCTScales[k % 8] * kIDCTScales[k / 8] / 64.0f;
double weight = GetQuantWeights()[id * 192 + idx];
if (weight < 0.02) {
weight = 0.02;
}
table[id * 192 + c * 64 + k] = idct_scale / weight;
}
}
return table;
}
// Returns aligned memory.
const float* DequantMatrix(int id) {
static const float* const kDequantMatrix = NewDequantMatrices();
return &kDequantMatrix[id * 192];
}
ImageD ComputeBlockDistanceQForm(const double lambda,
const float* PIK_RESTRICT scales) {
ImageD A = Identity<double>(64);
for (int ky = 0, k = 0; ky < 8; ++ky) {
for (int kx = 0; kx < 8; ++kx, ++k) {
const float scale =
kRecipIDCTScales[kx] * kRecipIDCTScales[ky] / scales[k];
A.Row(k)[k] *= scale * scale;
}
}
for (int i = 0; i < 8; ++i) {
const double scale_i = kRecipIDCTScales[i];
for (int k = 0; k < 8; ++k) {
const double sign_k = (k % 2 == 0 ? 1.0 : -1.0);
const double scale_k = kRecipIDCTScales[k];
const double scale_ik = scale_i * scale_k / scales[8 * i + k];
const double scale_ki = scale_i * scale_k / scales[8 * k + i];
for (int l = 0; l < 8; ++l) {
const double sign_l = (l % 2 == 0 ? 1.0 : -1.0);
const double scale_l = kRecipIDCTScales[l];
const double scale_il = scale_i * scale_l / scales[8 * i + l];
const double scale_li = scale_i * scale_l / scales[8 * l + i];
A.Row(8 * i + k)[8 * i + l] +=
(1.0 + sign_k * sign_l) * lambda * scale_ik * scale_il;
A.Row(8 * k + i)[8 * l + i] +=
(1.0 + sign_k * sign_l) * lambda * scale_ki * scale_li;
}
}
}
return A;
}
Quantizer::Quantizer(int template_id, int quant_xsize, int quant_ysize)
: quant_xsize_(quant_xsize),
quant_ysize_(quant_ysize),
template_id_(template_id),
global_scale_(kGlobalScaleDenom / kDefaultQuant),
quant_patch_(kDefaultQuant),
quant_dc_(kDefaultQuant),
quant_img_ac_(quant_xsize_, quant_ysize_),
initialized_(false) {
FillImage(kDefaultQuant, &quant_img_ac_);
if (template_id == kQuantHQ) {
memcpy(zero_bias_, kZeroBiasHQ, sizeof(kZeroBiasHQ));
} else {
memcpy(zero_bias_, kZeroBiasDefault, sizeof(kZeroBiasDefault));
}
}
const float* Quantizer::DequantMatrix() const {
return pik::DequantMatrix(template_id_);
}
void Quantizer::GetQuantField(float* quant_dc, ImageF* qf) {
const float scale = Scale();
*quant_dc = scale * quant_dc_;
*qf = ImageF(quant_xsize_, quant_ysize_);
for (size_t y = 0; y < quant_ysize_; ++y) {
for (size_t x = 0; x < quant_xsize_; ++x) {
qf->Row(y)[x] = scale * quant_img_ac_.Row(y)[x];
}
}
}
std::string Quantizer::Encode(PikImageSizeInfo* info) const {
std::stringstream ss;
ss << std::string(1, (global_scale_ - 1) >> 8);
ss << std::string(1, (global_scale_ - 1) & 0xff);
ss << std::string(1, quant_patch_ - 1);
ss << std::string(1, quant_dc_ - 1);
if (info) {
info->total_size += 4;
}
return ss.str();
}
bool Quantizer::Decode(BitReader* br) {
global_scale_ = br->ReadBits(8) << 8;
global_scale_ += br->ReadBits(8) + 1;
quant_patch_ = br->ReadBits(8) + 1;
quant_dc_ = br->ReadBits(8) + 1;
inv_global_scale_ = kGlobalScaleDenom * 1.0 / global_scale_;
inv_quant_dc_ = inv_global_scale_ / quant_dc_;
inv_quant_patch_ = inv_global_scale_ / quant_patch_;
initialized_ = true;
return true;
}
void Quantizer::DumpQuantizationMap() const {
printf("Global scale: %d (%.7f)\nDC quant: %d\n", global_scale_,
global_scale_ * 1.0 / kGlobalScaleDenom, quant_dc_);
printf("AC quantization Map:\n");
for (size_t y = 0; y < quant_img_ac_.ysize(); ++y) {
for (size_t x = 0; x < quant_img_ac_.xsize(); ++x) {
printf(" %3d", quant_img_ac_.Row(y)[x]);
}
printf("\n");
}
}
Image3S QuantizeCoeffs(const Image3F& in, const Quantizer& quantizer) {
PROFILER_FUNC;
const size_t block_xsize = in.xsize() / 64;
const size_t block_ysize = in.ysize();
Image3S out(block_xsize * 64, block_ysize);
for (int c = 0; c < 3; ++c) {
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = in.PlaneRow(c, block_y);
int16_t* PIK_RESTRICT row_out = out.PlaneRow(c, block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float* PIK_RESTRICT block_in = &row_in[block_x * 64];
int16_t* PIK_RESTRICT block_out = &row_out[block_x * 64];
quantizer.QuantizeBlock(block_x, block_y, c, block_in, block_out);
}
}
}
return out;
}
// Returns DC only; "in" is 1x64 blocks.
Image3S QuantizeCoeffsDC(const Image3F& in, const Quantizer& quantizer) {
const size_t block_xsize = in.xsize() / 64;
const size_t block_ysize = in.ysize();
Image3S out(block_xsize, block_ysize);
for (int c = 0; c < 3; ++c) {
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = in.PlaneRow(c, block_y);
int16_t* PIK_RESTRICT row_out = out.PlaneRow(c, block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float* PIK_RESTRICT block_in = &row_in[block_x * 64];
row_out[block_x] =
quantizer.QuantizeBlockDC(block_x, block_y, c, block_in);
}
}
}
return out;
}
// Superceded by QuantizeRoundtrip and DequantizeCoeffsT.
Image3F DequantizeCoeffs(const Image3S& in, const Quantizer& quantizer) {
PROFILER_FUNC;
const int block_xsize = in.xsize() / 64;
const int block_ysize = in.ysize();
Image3F out(block_xsize * 64, block_ysize);
const float inv_quant_dc = quantizer.inv_quant_dc();
const float* PIK_RESTRICT kDequantMatrix = quantizer.DequantMatrix();
const int16_t* all_block_in[3];
float* all_block_out[3];
for (int by = 0; by < block_ysize; ++by) {
for (int c = 0; c < 3; ++c) {
all_block_in[c] = in.PlaneRow(c, by);
all_block_out[c] = out.PlaneRow(c, by);
}
for (int bx = 0; bx < block_xsize; ++bx) {
const float inv_quant_ac = quantizer.inv_quant_ac(bx, by);
const int offset = bx * 64;
for (int c = 0; c < 3; ++c) {
const int16_t* PIK_RESTRICT block_in = all_block_in[c] + offset;
const float* PIK_RESTRICT muls = &kDequantMatrix[c * 64];
float* PIK_RESTRICT block_out = all_block_out[c] + offset;
for (int k = 0; k < 64; ++k) {
block_out[k] = block_in[k] * (muls[k] * inv_quant_ac);
}
block_out[0] = block_in[0] * (muls[0] * inv_quant_dc);
}
}
}
return out;
}
ImageF QuantizeRoundtrip(const Quantizer& quantizer, int c,
const ImageF& coeffs) {
const size_t block_xsize = coeffs.xsize() / 64;
const size_t block_ysize = coeffs.ysize();
ImageF out(coeffs.xsize(), coeffs.ysize());
const float inv_quant_dc = quantizer.inv_quant_dc();
const float* PIK_RESTRICT kDequantMatrix = &quantizer.DequantMatrix()[c * 64];
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = coeffs.ConstRow(block_y);
float* PIK_RESTRICT row_out = out.Row(block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float inv_quant_ac = quantizer.inv_quant_ac(block_x, block_y);
const float* PIK_RESTRICT block_in = &row_in[block_x * 64];
float* PIK_RESTRICT block_out = &row_out[block_x * 64];
int16_t qblock[64];
quantizer.QuantizeBlock(block_x, block_y, c, block_in, qblock);
block_out[0] = qblock[0] * (kDequantMatrix[0] * inv_quant_dc);
for (int k = 1; k < 64; ++k) {
block_out[k] = qblock[k] * (kDequantMatrix[k] * inv_quant_ac);
}
}
}
return out;
}
ImageF QuantizeRoundtripExtract189(const Quantizer& quantizer, int c,
const ImageF& coeffs) {
const size_t block_xsize = coeffs.xsize() / 64;
const size_t block_ysize = coeffs.ysize();
ImageF out(4 * block_xsize, block_ysize);
const float* PIK_RESTRICT kDequantMatrix = &quantizer.DequantMatrix()[c * 64];
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = coeffs.ConstRow(block_y);
float* PIK_RESTRICT row_out = out.Row(block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float inv_quant_ac = quantizer.inv_quant_ac(block_x, block_y);
const float* PIK_RESTRICT block_in = &row_in[block_x * 64];
float* PIK_RESTRICT block_out = &row_out[block_x * 4];
int16_t qblock[64];
quantizer.QuantizeBlock2x2(block_x, block_y, c, block_in, qblock);
block_out[1] = qblock[1] * (kDequantMatrix[1] * inv_quant_ac);
block_out[2] = qblock[8] * (kDequantMatrix[8] * inv_quant_ac);
block_out[3] = qblock[9] * (kDequantMatrix[9] * inv_quant_ac);
}
}
return out;
}
ImageF QuantizeRoundtripExtractDC(const Quantizer& quantizer, int c,
const ImageF& coeffs) {
// All coordinates are blocks.
const int block_xsize = coeffs.xsize() / 64;
const int block_ysize = coeffs.ysize();
ImageF out(block_xsize, block_ysize);
const float mul =
quantizer.DequantMatrix()[c * 64] * quantizer.inv_quant_dc();
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = coeffs.ConstRow(block_y);
float* PIK_RESTRICT row_out = out.Row(block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float* PIK_RESTRICT block_in = &row_in[block_x * 64];
row_out[block_x] =
quantizer.QuantizeBlockDC(block_x, block_y, c, block_in) * mul;
}
}
return out;
}
ImageF QuantizeRoundtripDC(const Quantizer& quantizer, int c,
const ImageF& dc) {
// All coordinates are blocks.
const int block_xsize = dc.xsize();
const int block_ysize = dc.ysize();
ImageF out(block_xsize, block_ysize);
const float mul =
quantizer.DequantMatrix()[c * 64] * quantizer.inv_quant_dc();
for (size_t block_y = 0; block_y < block_ysize; ++block_y) {
const float* PIK_RESTRICT row_in = dc.ConstRow(block_y);
float* PIK_RESTRICT row_out = out.Row(block_y);
for (size_t block_x = 0; block_x < block_xsize; ++block_x) {
const float* PIK_RESTRICT block_in = row_in + block_x;
row_out[block_x] =
quantizer.QuantizeBlockDC(block_x, block_y, c, block_in) * mul;
}
}
return out;
}
Image3F QuantizeRoundtrip(const Quantizer& quantizer, const Image3F& coeffs) {
return Image3F(QuantizeRoundtrip(quantizer, 0, coeffs.Plane(0)),
QuantizeRoundtrip(quantizer, 1, coeffs.Plane(1)),
QuantizeRoundtrip(quantizer, 2, coeffs.Plane(2)));
}
Image3F QuantizeRoundtripExtract189(const Quantizer& quantizer,
const Image3F& coeffs) {
return Image3F(QuantizeRoundtripExtract189(quantizer, 0, coeffs.Plane(0)),
QuantizeRoundtripExtract189(quantizer, 1, coeffs.Plane(1)),
QuantizeRoundtripExtract189(quantizer, 2, coeffs.Plane(2)));
}
Image3F QuantizeRoundtripExtractDC(const Quantizer& quantizer,
const Image3F& coeffs) {
return Image3F(QuantizeRoundtripExtractDC(quantizer, 0, coeffs.Plane(0)),
QuantizeRoundtripExtractDC(quantizer, 1, coeffs.Plane(1)),
QuantizeRoundtripExtractDC(quantizer, 2, coeffs.Plane(2)));
}
Image3F QuantizeRoundtripDC(const Quantizer& quantizer, const Image3F& coeffs) {
return Image3F(QuantizeRoundtripDC(quantizer, 0, coeffs.Plane(0)),
QuantizeRoundtripDC(quantizer, 1, coeffs.Plane(1)),
QuantizeRoundtripDC(quantizer, 2, coeffs.Plane(2)));
}
} // namespace pik
| 30.871658 | 80 | 0.679369 | [
"vector",
"3d"
] |
805d51f5f5ed41916f03c88075e4aa29622a079d | 4,803 | cc | C++ | google/cloud/bigtable/tests/table_sample_rows_integration_test.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 299 | 2019-01-31T12:17:56.000Z | 2022-03-30T15:46:15.000Z | google/cloud/bigtable/tests/table_sample_rows_integration_test.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 6,560 | 2019-01-29T03:15:15.000Z | 2022-03-31T23:58:48.000Z | google/cloud/bigtable/tests/table_sample_rows_integration_test.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | 253 | 2019-02-07T01:18:13.000Z | 2022-03-30T17:21:10.000Z | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/client_options.h"
#include "google/cloud/bigtable/data_client.h"
#include "google/cloud/bigtable/mutations.h"
#include "google/cloud/bigtable/row_key_sample.h"
#include "google/cloud/bigtable/table.h"
#include "google/cloud/bigtable/testing/table_integration_test.h"
#include "google/cloud/testing_util/integration_test.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <chrono>
#include <memory>
#include <ostream>
#include <string>
#include <vector>
namespace google {
namespace cloud {
namespace bigtable {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
using ::google::cloud::bigtable::testing::TableTestEnvironment;
using ::testing::IsEmpty;
Table GetTable() {
return Table(MakeDataClient(TableTestEnvironment::project_id(),
TableTestEnvironment::instance_id()),
TableTestEnvironment::table_id());
}
void VerifySamples(StatusOr<std::vector<RowKeySample>> samples) {
ASSERT_STATUS_OK(samples);
// It is somewhat hard to verify that the values returned here are correct.
// We cannot check the specific values, not even the format, of the row keys
// because Cloud Bigtable might return an empty row key (for "end of table"),
// and it might return row keys that have never been written to.
// All we can check is that this is not empty, and that the offsets are in
// ascending order.
ASSERT_THAT(*samples, Not(IsEmpty()));
std::int64_t previous = 0;
for (auto const& s : *samples) {
EXPECT_LE(previous, s.offset_bytes);
previous = s.offset_bytes;
}
// At least one of the samples should have non-zero offset:
auto last = samples->back();
EXPECT_LT(0, last.offset_bytes);
}
class SampleRowsIntegrationTest
: public ::google::cloud::testing_util::IntegrationTest {
public:
static void SetUpTestSuite() {
// Create kBatchSize * kBatchCount rows. Use a special client with tracing
// disabled because it simply generates too much data.
auto table =
Table(MakeDataClient(TableTestEnvironment::project_id(),
TableTestEnvironment::instance_id(),
Options{}.set<TracingComponentsOption>({"rpc"})),
TableTestEnvironment::table_id());
int constexpr kBatchCount = 10;
int constexpr kBatchSize = 5000;
int constexpr kColumnCount = 10;
std::string const family = "family1";
int row_id = 0;
for (int batch = 0; batch != kBatchCount; ++batch) {
BulkMutation bulk;
for (int row = 0; row != kBatchSize; ++row) {
std::ostringstream os;
os << "row:" << std::setw(9) << std::setfill('0') << row_id;
// Build a mutation that creates 10 columns.
SingleRowMutation mutation(os.str());
for (int col = 0; col != kColumnCount; ++col) {
std::string column_id = "c" + std::to_string(col);
std::string value = column_id + "#" + os.str();
mutation.emplace_back(SetCell(family, std::move(column_id),
std::chrono::milliseconds(0),
std::move(value)));
}
bulk.emplace_back(std::move(mutation));
++row_id;
}
auto failures = table.BulkApply(std::move(bulk));
ASSERT_THAT(failures, IsEmpty());
}
}
};
TEST_F(SampleRowsIntegrationTest, Synchronous) {
auto table = GetTable();
VerifySamples(table.SampleRows());
};
TEST_F(SampleRowsIntegrationTest, Asynchronous) {
auto table = GetTable();
auto fut = table.AsyncSampleRows();
// Block until the asynchronous operation completes. This is not what one
// would do in a real application (the synchronous API is better in that
// case), but we need to wait before checking the results.
VerifySamples(fut.get());
};
} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace bigtable
} // namespace cloud
} // namespace google
int main(int argc, char* argv[]) {
::testing::InitGoogleMock(&argc, argv);
(void)::testing::AddGlobalTestEnvironment(
new google::cloud::bigtable::testing::TableTestEnvironment);
return RUN_ALL_TESTS();
}
| 35.316176 | 79 | 0.681866 | [
"vector"
] |
806739434023af8e3e9608bb079e6aece368aaf3 | 6,171 | cpp | C++ | StudyWatch_SDK_healthwearableApp/Source/sdk/src/bcm_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | 2 | 2019-03-11T15:24:51.000Z | 2022-03-07T09:42:05.000Z | StudyWatch_SDK_healthwearableApp/Source/sdk/src/bcm_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | null | null | null | StudyWatch_SDK_healthwearableApp/Source/sdk/src/bcm_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | 1 | 2021-03-16T08:26:05.000Z | 2021-03-16T08:26:05.000Z | #include "bcm_application.hpp"
bcm_application::~bcm_application(void) {
}
bcm_application::bcm_application(watch *sdk) :
m2m2_application(sdk),
bcm_stream(M2M2_ADDR_MED_BCM_STREAM, this) {}
/*!
\brief Fetches a human-readable string describing the application.
*/
std::string bcm_application::get_name(void) {
return "BCM application";
}
/*!
\brief Fetches the address of the application.
*/
M2M2_ADDR_ENUM_t bcm_application::get_address(void) {
return M2M2_ADDR_MED_BCM;
}
ret::sdk_status bcm_application::set_dft_num(uint32_t dft_num) {
m2m2_pkt<bcm_app_set_dft_num_t> pkt(this->get_address());
pkt.payload.command = M2M2_BCM_APP_CMD_SET_DFT_NUM_REQ;
pkt.payload.status = APP_COMMON_STATUS_OK;
pkt.payload.dftnum = dft_num;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
return ret::SDK_ERR;
}
ret::sdk_status bcm_application::enable_or_disable_sweep_frequency(bool enable) {
m2m2_pkt<m2m2_bcm_app_sweep_freq_resp_t> pkt(this->get_address());
if (enable)
pkt.payload.command = M2M2_BCM_APP_CMD_SWEEP_FREQ_ENABLE_REQ;
else
pkt.payload.command = M2M2_BCM_APP_CMD_SWEEP_FREQ_DISABLE_REQ;
pkt.payload.status = APP_COMMON_STATUS_OK;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
return ret::SDK_ERR;
}
ret::sdk_status bcm_application::set_hsrtia_cal(uint16_t value)
{
m2m2_pkt<bcm_app_hs_rtia_sel_t> pkt(this->get_address());
pkt.payload.command = M2M2_BCM_APP_CMD_SET_HS_RTIA_CAL_REQ;
pkt.payload.status = APP_COMMON_STATUS_OK;
pkt.payload.hsritasel = value;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
return ret::SDK_ERR;
}
/*!
\brief Read from a set of BCM LCFGs.
This function takes a vector of addresses to read, and returns a vector of
(field, value) pairs which contain the addresses and values read.
\note If an invalid list of addresses is given (i.e. an empty list), or an
error occured on the device, a vector of size 1 with a (address, value) pair
of 0 is returned.
\note The SDK does not perform any validation on the correctness of the addresses
given.
\see ppg_application::lcfg_write
\see ppg_application::load_lcfg
*/
std::vector<std::pair<uint8_t, uint32_t>> bcm_application::lcfg_read(
std::vector<uint8_t> addresses //!< A vector of lcfg addresses to be read.
) {
if (addresses.size() == 0) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> { {0, 0}};
}
// Assemble this packet the old school way to fill out the variable-length list of lcfg operations
uint16_t pkt_size = (offsetof(m2m2_hdr_t, data)) + offsetof(bcm_app_lcfg_op_hdr_t, ops) +
addresses.size() * sizeof(bcm_app_lcfg_op_t);
std::vector<uint8_t> pkt(pkt_size);
m2m2_hdr_t *p_hdr = (m2m2_hdr_t *)&pkt[0];
bcm_app_lcfg_op_hdr_t *p_ops_hdr = (bcm_app_lcfg_op_hdr_t *)&p_hdr->data[0];
bcm_app_lcfg_op_t *p_ops = (bcm_app_lcfg_op_t *)&p_ops_hdr->ops[0];
p_hdr->length = pkt_size;
p_ops_hdr->command = M2M2_APP_COMMON_CMD_READ_LCFG_REQ;
p_ops_hdr->num_ops = addresses.size();
for (unsigned int i = 0; i < addresses.size(); i++) {
p_ops[i].field = addresses[i];
p_ops[i].value = 0x0000;
}
auto resp = this->sync_send(pkt);
std::vector<std::pair<uint8_t, uint32_t>> ret_vals;
p_hdr = (m2m2_hdr_t *)&resp[0];
p_ops_hdr = (bcm_app_lcfg_op_hdr_t *)&p_hdr->data[0];
if (p_ops_hdr->status != M2M2_APP_COMMON_STATUS_OK) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> { {0, 0}};
}
p_ops = (bcm_app_lcfg_op_t *)&p_ops_hdr->ops[0];
for (unsigned int i = 0; i < p_ops_hdr->num_ops; i++) {
std::pair<uint8_t, uint32_t> v;
v.first = p_ops[i].field;
v.second = p_ops[i].value;
ret_vals.push_back(v);
}
return ret_vals;
}
/*!
\brief Write to a set of lcfgs.
This function takes a vector of (field, value) pairs to write, and returns
a vector of (field, value) pairs which contain the field and values written.
\note If an invalid list of addresses is given (i.e. an empty list), or an
error occured on the device, a vector of size 1 with a (address, value) pair
of 0 is returned.
\note The SDK does not perform any validation on the correctness of the addresses
or values given.
\see ppg_application::lcfg_read
\see ppg_application::load_lcfg
*/
std::vector<std::pair<uint8_t, uint32_t>> bcm_application::lcfg_write(
std::vector<std::pair<uint8_t, uint32_t>> addr_vals //!< A vector of lcfg (field,value) pairs to be written.
) {
if (addr_vals.size() == 0) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> { {0, 0}};
}
// Assemble this packet the old school way to fill out the variable-length list of register operations
uint16_t pkt_size = offsetof(m2m2_hdr_t, data)
+ offsetof(bcm_app_lcfg_op_hdr_t, ops)
+ addr_vals.size() * sizeof(bcm_app_lcfg_op_t);
std::vector<uint8_t> pkt(pkt_size);
m2m2_hdr_t *p_hdr = (m2m2_hdr_t *)&pkt[0];
bcm_app_lcfg_op_hdr_t *p_ops_hdr = (bcm_app_lcfg_op_hdr_t *)&p_hdr->data[0];
bcm_app_lcfg_op_t *p_ops = (bcm_app_lcfg_op_t *)&p_ops_hdr->ops[0];
p_hdr->length = pkt_size;
p_ops_hdr->command = M2M2_APP_COMMON_CMD_WRITE_LCFG_REQ;
p_ops_hdr->num_ops = addr_vals.size();
for (unsigned int i = 0; i < addr_vals.size(); i++) {
p_ops[i].field = addr_vals[i].first;
p_ops[i].value = addr_vals[i].second;
}
auto resp = this->sync_send(pkt);
std::vector<std::pair<uint8_t, uint32_t>> ret_vals;
p_hdr = (m2m2_hdr_t *)&resp[0];
p_ops_hdr = (bcm_app_lcfg_op_hdr_t *)&p_hdr->data[0];
if (p_ops_hdr->status != M2M2_APP_COMMON_STATUS_OK) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> { {0, 0}};
}
p_ops = (bcm_app_lcfg_op_t *)&p_ops_hdr->ops[0];
for (unsigned int i = 0; i < p_ops_hdr->num_ops; i++) {
std::pair<uint8_t, uint32_t> v;
v.first = p_ops[i].field;
v.second = p_ops[i].value;
ret_vals.push_back(v);
}
return ret_vals;
}
| 34.093923 | 109 | 0.720305 | [
"vector"
] |
806b831e9cd3bc38219fedd0a42728911da79a59 | 55,848 | cpp | C++ | Deep Down/Motor2D/j1EntityFactory.cpp | Sandruski/Deep-Down-Game | 7987e0c92b42c11f55a9ceff44dae91993e26ee7 | [
"MIT"
] | null | null | null | Deep Down/Motor2D/j1EntityFactory.cpp | Sandruski/Deep-Down-Game | 7987e0c92b42c11f55a9ceff44dae91993e26ee7 | [
"MIT"
] | null | null | null | Deep Down/Motor2D/j1EntityFactory.cpp | Sandruski/Deep-Down-Game | 7987e0c92b42c11f55a9ceff44dae91993e26ee7 | [
"MIT"
] | 4 | 2017-12-17T17:02:15.000Z | 2018-12-12T22:14:30.000Z | #include "p2Defs.h"
#include "p2Log.h"
#include "j1Module.h"
#include "j1App.h"
#include "j1EntityFactory.h"
#include "j1Render.h"
#include "Entity.h"
#include "Imp.h"
#include "CatPeasant.h"
#include "Monkey.h"
#include "Cat.h"
#include "j1Textures.h"
#include "j1Scene.h"
#include "j1Map.h"
#include "j1Pathfinding.h"
#include "j1Collision.h"
#include "j1Gui.h"
#include "j1FadeToBlack.h"
#include "j1Menu.h"
#define SPAWN_MARGIN 50
j1EntityFactory::j1EntityFactory()
{
name.create("entities");
for (uint i = 0; i < MAX_ENTITIES; ++i)
entities[i] = nullptr;
}
// Destructor
j1EntityFactory::~j1EntityFactory()
{
}
bool j1EntityFactory::Awake(pugi::xml_node& config) {
bool ret = true;
pugi::xml_node node = config.child("spritesheets").child("spritesheet");
// Load texture paths
CatPeasant_spritesheet = node.attribute("name").as_string();
node = node.next_sibling("spritesheet");
Monkey_spritesheet = node.attribute("name").as_string();
node = node.next_sibling("spritesheet");
Imp_spritesheet = node.attribute("name").as_string();
node = node.next_sibling("spritesheet");
Player_spritesheet = node.attribute("name").as_string();
node = node.next_sibling("spritesheet");
Cat_spritesheet = node.attribute("name").as_string();
//_load_texture_paths
//PLAYER
pugi::xml_node general_node = config.child("types").child("player").child("general");
pugi::xml_node actual_node;
actual_node = general_node.child("coll_offset");
player.coll_offset = { actual_node.attribute("x").as_int(), actual_node.attribute("y").as_int(), actual_node.attribute("w").as_int(), actual_node.attribute("h").as_int() };
player.gravity = general_node.child("gravity").attribute("value").as_float();
actual_node = general_node.child("speed");
player.speed = { actual_node.attribute("x").as_float(), actual_node.attribute("y").as_float() };
player.check_collision_offset = general_node.child("check_collision").attribute("offset").as_uint();
// Load animations
pugi::xml_node animations_node = config.child("types").child("player").child("animations");
//idle
node = animations_node.child("idle");
player.idle.speed = node.attribute("speed").as_float();
player.idle.loop = node.attribute("loop").as_bool();
player.coll_size = { node.child("frame").attribute("w").as_int(), node.child("frame").attribute("h").as_int() };
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//idle2
node = animations_node.child("idle2");
player.idle2.speed = node.attribute("speed").as_float();
player.idle2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.idle2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//forward
node = animations_node.child("forward");
player.forward.speed = node.attribute("speed").as_float();
player.forward.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.forward.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//backward
node = animations_node.child("backward");
player.backward.speed = node.attribute("speed").as_float();
player.backward.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.backward.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//crouch
node = animations_node.child("crouch");
player.crouch.speed = node.attribute("speed").as_float();
player.crouch.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.crouch.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//crouch2
node = animations_node.child("crouch2");
player.crouch2.speed = node.attribute("speed").as_float();
player.crouch2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.crouch2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//shot
node = animations_node.child("shot");
player.shot.speed = node.attribute("speed").as_float();
player.shot.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.shot.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//shot2
node = animations_node.child("shot2");
player.shot2.speed = node.attribute("speed").as_float();
player.shot2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.shot2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//crouchShot
node = animations_node.child("crouchShot");
player.crouchShot.speed = node.attribute("speed").as_float();
player.crouchShot.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.crouchShot.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//crouchShot2
node = animations_node.child("crouchShot2");
player.crouchShot2.speed = node.attribute("speed").as_float();
player.crouchShot2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.crouchShot2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//jump
node = animations_node.child("jump");
player.jump.speed = node.attribute("speed").as_float();
player.jump.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.jump.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//jump2
node = animations_node.child("jump2");
player.jump2.speed = node.attribute("speed").as_float();
player.jump2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.jump2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//punished
node = animations_node.child("punished");
player.punished.speed = node.attribute("speed").as_float();
player.punished.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.punished.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//punished2
node = animations_node.child("punished2");
player.punished2.speed = node.attribute("speed").as_float();
player.punished2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.punished2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//dash
node = animations_node.child("dash");
player.dash.speed = node.attribute("speed").as_float();
player.dash.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.dash.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//dash2
node = animations_node.child("dash2");
player.dash2.speed = node.attribute("speed").as_float();
player.dash2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.dash2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//firstAttack
node = animations_node.child("firstAttack");
player.firstAttack.speed = node.attribute("speed").as_float();
player.firstAttack.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.firstAttack.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//firstAttack2
node = animations_node.child("firstAttack2");
player.firstAttack2.speed = node.attribute("speed").as_float();
player.firstAttack2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.firstAttack2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//secondAttack
node = animations_node.child("secondAttack");
player.secondAttack.speed = node.attribute("speed").as_float();
player.secondAttack.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.secondAttack.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//secondAttack2
node = animations_node.child("secondAttack2");
player.secondAttack2.speed = node.attribute("speed").as_float();
player.secondAttack2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.secondAttack2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//thirdAttack
node = animations_node.child("thirdAttack");
player.thirdAttack.speed = node.attribute("speed").as_float();
player.thirdAttack.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.thirdAttack.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//thirdAttack2
node = animations_node.child("thirdAttack2");
player.thirdAttack2.speed = node.attribute("speed").as_float();
player.thirdAttack2.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
player.thirdAttack2.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//_load_animations
//_PLAYER
// IMP
general_node = config.child("types").child("imp").child("general");
actual_node = general_node.child("coll_offset");
imp.coll_offset = { actual_node.attribute("x").as_int(), actual_node.attribute("y").as_int(), actual_node.attribute("w").as_int(), actual_node.attribute("h").as_int() };
imp.lives = general_node.child("lives").attribute("value").as_int();
actual_node = general_node.child("pathfinding_affect_area");
imp.enemy_pathfinding_affect_area = { actual_node.child("enemy").attribute("x").as_int(), actual_node.child("enemy").attribute("y").as_int(),actual_node.child("enemy").attribute("w").as_int(),actual_node.child("enemy").attribute("h").as_int() };
imp.player_pathfinding_affect_area = { actual_node.child("player").attribute("x").as_int(), actual_node.child("player").attribute("y").as_int(),actual_node.child("player").attribute("w").as_int(),actual_node.child("player").attribute("h").as_int() };
actual_node = general_node.child("pathfinding_speed");
imp.pathfinding_slow_speed = actual_node.attribute("slow").as_float();
imp.pathfinding_normal_speed = actual_node.attribute("normal").as_float();
imp.pathfinding_fast_speed = actual_node.attribute("fast").as_float();
imp.min_distance_to_pathfind = general_node.child("min_distance_to_pathfind").attribute("value").as_int();
imp.min_distance_to_shoot = general_node.child("min_distance_to_shoot").attribute("value").as_int();
imp.distance_to_player = general_node.child("distance_to_player").attribute("value").as_int();
imp.seconds_to_wait = general_node.child("seconds_to_wait").attribute("value").as_int();
imp.scene1_pathfinding_start = general_node.child("scene1_pathfinding_start").attribute("x").as_int();
imp.particle_speed = { general_node.child("particle_speed").attribute("x").as_float(), general_node.child("particle_speed").attribute("y").as_float() };
imp.hurt_fx = general_node.child("hurt_fx").attribute("value").as_uint();
// Load animations
animations_node = config.child("types").child("imp").child("animations");
//r_shield_idle
node = animations_node.child("r_shield_idle");
imp.r_shield_idle.speed = node.attribute("speed").as_float();
imp.r_shield_idle.loop = node.attribute("loop").as_bool();
imp.coll_size = { node.child("frame").attribute("w").as_int(), node.child("frame").attribute("h").as_int() };
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.r_shield_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_shield_idle
node = animations_node.child("l_shield_idle");
imp.l_shield_idle.speed = node.attribute("speed").as_float();
imp.l_shield_idle.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.l_shield_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_shield_hurt
node = animations_node.child("r_shield_hurt");
imp.r_shield_hurt.speed = node.attribute("speed").as_float();
imp.r_shield_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.r_shield_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_shield_hurt
node = animations_node.child("l_shield_hurt");
imp.l_shield_hurt.speed = node.attribute("speed").as_float();
imp.l_shield_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.l_shield_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_jump
node = animations_node.child("r_jump");
imp.r_jump.speed = node.attribute("speed").as_float();
imp.r_jump.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.r_jump.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_jump
node = animations_node.child("l_jump");
imp.l_jump.speed = node.attribute("speed").as_float();
imp.l_jump.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.l_jump.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_throw_bomb
node = animations_node.child("r_throw_bomb");
imp.r_throw_bomb.speed = node.attribute("speed").as_float();
imp.r_throw_bomb.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.r_throw_bomb.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_throw_bomb
node = animations_node.child("l_throw_bomb");
imp.l_throw_bomb.speed = node.attribute("speed").as_float();
imp.l_throw_bomb.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.l_throw_bomb.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_shield_walk
node = animations_node.child("r_shield_walk");
imp.r_shield_walk.speed = node.attribute("speed").as_float();
imp.r_shield_walk.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.r_shield_walk.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_shield_walk
node = animations_node.child("l_shield_walk");
imp.l_shield_walk.speed = node.attribute("speed").as_float();
imp.l_shield_walk.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.l_shield_walk.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//invisible
node = animations_node.child("invisible");
imp.invisible.speed = node.attribute("speed").as_float();
imp.invisible.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
imp.invisible.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//_load_animations
//_IMP
// MONKEY
general_node = config.child("types").child("monkey").child("general");
actual_node = general_node.child("coll_offset");
monkey.coll_offset = { actual_node.attribute("x").as_int(), actual_node.attribute("y").as_int(), actual_node.attribute("w").as_int(), actual_node.attribute("h").as_int() };
monkey.lives = general_node.child("lives").attribute("value").as_int();
actual_node = general_node.child("pathfinding_affect_area");
monkey.enemy_pathfinding_affect_area = { actual_node.child("enemy").attribute("x").as_int(), actual_node.child("enemy").attribute("y").as_int(),actual_node.child("enemy").attribute("w").as_int(),actual_node.child("enemy").attribute("h").as_int() };
monkey.player_pathfinding_affect_area = { actual_node.child("player").attribute("x").as_int(), actual_node.child("player").attribute("y").as_int(),actual_node.child("player").attribute("w").as_int(),actual_node.child("player").attribute("h").as_int() };
actual_node = general_node.child("pathfinding_speed");
monkey.pathfinding_slow_speed = actual_node.attribute("slow").as_float();
monkey.pathfinding_normal_speed = actual_node.attribute("normal").as_float();
monkey.min_distance_to_hit = general_node.child("min_distance_to_hit").attribute("value").as_int();
monkey.distance_to_player = general_node.child("distance_to_player").attribute("value").as_int();
monkey.particle_speed = { general_node.child("particle_speed").attribute("x").as_float(), general_node.child("particle_speed").attribute("y").as_float() };
monkey.hurt_fx = general_node.child("hurt_fx").attribute("value").as_uint();
// Load animations
animations_node = config.child("types").child("monkey").child("animations");
//r_idle
node = animations_node.child("r_idle");
monkey.r_idle.speed = node.attribute("speed").as_float();
monkey.r_idle.loop = node.attribute("loop").as_bool();
monkey.coll_size = { node.child("frame").attribute("w").as_int(), node.child("frame").attribute("h").as_int() };
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.r_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_idle
node = animations_node.child("l_idle");
monkey.l_idle.speed = node.attribute("speed").as_float();
monkey.l_idle.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.l_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_hurt
node = animations_node.child("r_hurt");
monkey.r_hurt.speed = node.attribute("speed").as_float();
monkey.r_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.r_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_hurt
node = animations_node.child("l_hurt");
monkey.l_hurt.speed = node.attribute("speed").as_float();
monkey.l_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.l_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_hit
node = animations_node.child("r_hit");
monkey.r_hit.speed = node.attribute("speed").as_float();
monkey.r_hit.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.r_hit.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_hit
node = animations_node.child("l_hit");
monkey.l_hit.speed = node.attribute("speed").as_float();
monkey.l_hit.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
monkey.l_hit.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//_load_animations
//_MONKEY
// CAT PEASANT
general_node = config.child("types").child("cat_peasant").child("general");
actual_node = general_node.child("coll_offset");
catPeasant.coll_offset = { actual_node.attribute("x").as_int(), actual_node.attribute("y").as_int(), actual_node.attribute("w").as_int(), actual_node.attribute("h").as_int() };
catPeasant.lives = general_node.child("lives").attribute("value").as_int();
catPeasant.pathfinding_normal_speed = general_node.child("pathfinding_speed").attribute("normal").as_float();
catPeasant.min_distance_to_shoot = general_node.child("min_distance_to_shoot").attribute("value").as_int();
catPeasant.distance_to_player = general_node.child("distance_to_player").attribute("value").as_int();
catPeasant.seconds_to_wait = general_node.child("seconds_to_wait").attribute("value").as_int();
catPeasant.particle_speed = { general_node.child("particle_speed").attribute("x").as_float(), general_node.child("particle_speed").attribute("y").as_float() };
catPeasant.hurt_fx = general_node.child("hurt_fx").attribute("value").as_uint();
// Load animations
animations_node = config.child("types").child("cat_peasant").child("animations");
//r_idle
node = animations_node.child("r_idle");
catPeasant.r_idle.speed = node.attribute("speed").as_float();
catPeasant.r_idle.loop = node.attribute("loop").as_bool();
catPeasant.coll_size = { node.child("frame").attribute("w").as_int(), node.child("frame").attribute("h").as_int() };
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_idle
node = animations_node.child("l_idle");
catPeasant.l_idle.speed = node.attribute("speed").as_float();
catPeasant.l_idle.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_idle_no_staff
node = animations_node.child("r_idle_no_staff");
catPeasant.r_idle_no_staff.speed = node.attribute("speed").as_float();
catPeasant.r_idle_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_idle_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_idle_no_staff
node = animations_node.child("l_idle_no_staff");
catPeasant.l_idle_no_staff.speed = node.attribute("speed").as_float();
catPeasant.l_idle_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_idle_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_hurt
node = animations_node.child("r_hurt");
catPeasant.r_hurt.speed = node.attribute("speed").as_float();
catPeasant.r_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_hurt
node = animations_node.child("l_hurt");
catPeasant.l_hurt.speed = node.attribute("speed").as_float();
catPeasant.l_hurt.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_hurt.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_hurt_no_staff
node = animations_node.child("r_hurt_no_staff");
catPeasant.r_hurt_no_staff.speed = node.attribute("speed").as_float();
catPeasant.r_hurt_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_hurt_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_hurt_no_staff
node = animations_node.child("l_hurt_no_staff");
catPeasant.l_hurt_no_staff.speed = node.attribute("speed").as_float();
catPeasant.l_hurt_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_hurt_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_dead
node = animations_node.child("r_dead");
catPeasant.r_dead.speed = node.attribute("speed").as_float();
catPeasant.r_dead.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_dead.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_dead
node = animations_node.child("l_dead");
catPeasant.l_dead.speed = node.attribute("speed").as_float();
catPeasant.l_dead.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_dead.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_dead_no_staff
node = animations_node.child("r_dead_no_staff");
catPeasant.r_dead_no_staff.speed = node.attribute("speed").as_float();
catPeasant.r_dead_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_dead_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_dead_no_staff
node = animations_node.child("l_dead_no_staff");
catPeasant.l_dead_no_staff.speed = node.attribute("speed").as_float();
catPeasant.l_dead_no_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_dead_no_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_throw_staff
node = animations_node.child("r_throw_staff");
catPeasant.r_throw_staff.speed = node.attribute("speed").as_float();
catPeasant.r_throw_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.r_throw_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_throw_staff
node = animations_node.child("l_throw_staff");
catPeasant.l_throw_staff.speed = node.attribute("speed").as_float();
catPeasant.l_throw_staff.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
catPeasant.l_throw_staff.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//_load_animations
//_CAT_PEASANT
// CAT
general_node = config.child("types").child("cat").child("general");
actual_node = general_node.child("coll_offset");
cat.coll_offset = { actual_node.attribute("x").as_int(), actual_node.attribute("y").as_int(), actual_node.attribute("w").as_int(), actual_node.attribute("h").as_int() };
// Load animations
animations_node = config.child("types").child("cat").child("animations");
//r_idle
node = animations_node.child("r_idle");
cat.r_idle.speed = node.attribute("speed").as_float();
cat.r_idle.loop = node.attribute("loop").as_bool();
cat.coll_size = { node.child("frame").attribute("w").as_int(), node.child("frame").attribute("h").as_int() };
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_idle
node = animations_node.child("l_idle");
cat.l_idle.speed = node.attribute("speed").as_float();
cat.l_idle.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_idle.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_going_ZZZ
node = animations_node.child("r_going_ZZZ");
cat.r_going_ZZZ.speed = node.attribute("speed").as_float();
cat.r_going_ZZZ.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_going_ZZZ.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_going_ZZZ
node = animations_node.child("l_going_ZZZ");
cat.l_going_ZZZ.speed = node.attribute("speed").as_float();
cat.l_going_ZZZ.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_going_ZZZ.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_ZZZ
node = animations_node.child("r_ZZZ");
cat.r_ZZZ.speed = node.attribute("speed").as_float();
cat.r_ZZZ.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_ZZZ.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_ZZZ
node = animations_node.child("l_ZZZ");
cat.l_ZZZ.speed = node.attribute("speed").as_float();
cat.l_ZZZ.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_ZZZ.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_waking_up
node = animations_node.child("r_waking_up");
cat.r_waking_up.speed = node.attribute("speed").as_float();
cat.r_waking_up.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_waking_up.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_waking_up
node = animations_node.child("l_waking_up");
cat.l_waking_up.speed = node.attribute("speed").as_float();
cat.l_waking_up.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_waking_up.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_to_crouch
node = animations_node.child("r_to_crouch");
cat.r_to_crouch.speed = node.attribute("speed").as_float();
cat.r_to_crouch.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_to_crouch.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_to_crouch
node = animations_node.child("l_to_crouch");
cat.l_to_crouch.speed = node.attribute("speed").as_float();
cat.l_to_crouch.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_to_crouch.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_crouch
node = animations_node.child("r_crouch");
cat.r_crouch.speed = node.attribute("speed").as_float();
cat.r_crouch.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_crouch.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_crouch
node = animations_node.child("l_crouch");
cat.l_crouch.speed = node.attribute("speed").as_float();
cat.l_crouch.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_crouch.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_rise
node = animations_node.child("r_rise");
cat.r_rise.speed = node.attribute("speed").as_float();
cat.r_rise.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_rise.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_rise
node = animations_node.child("l_rise");
cat.l_rise.speed = node.attribute("speed").as_float();
cat.l_rise.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_rise.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_jump
node = animations_node.child("r_jump");
cat.r_jump.speed = node.attribute("speed").as_float();
cat.r_jump.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_jump.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_jump
node = animations_node.child("l_jump");
cat.l_jump.speed = node.attribute("speed").as_float();
cat.l_jump.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_jump.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_fall
node = animations_node.child("r_fall");
cat.r_fall.speed = node.attribute("speed").as_float();
cat.r_fall.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_fall.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_fall
node = animations_node.child("l_fall");
cat.l_fall.speed = node.attribute("speed").as_float();
cat.l_fall.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_fall.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_land_soft
node = animations_node.child("r_land_soft");
cat.r_land_soft.speed = node.attribute("speed").as_float();
cat.r_land_soft.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_land_soft.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_land_soft
node = animations_node.child("l_land_soft");
cat.l_land_soft.speed = node.attribute("speed").as_float();
cat.l_land_soft.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_land_soft.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_roll
node = animations_node.child("r_roll");
cat.r_roll.speed = node.attribute("speed").as_float();
cat.r_roll.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_roll.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_roll
node = animations_node.child("l_roll");
cat.l_roll.speed = node.attribute("speed").as_float();
cat.l_roll.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_roll.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_to_run
node = animations_node.child("r_to_run");
cat.r_to_run.speed = node.attribute("speed").as_float();
cat.r_to_run.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_to_run.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_to_run
node = animations_node.child("l_to_run");
cat.l_to_run.speed = node.attribute("speed").as_float();
cat.l_to_run.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_to_run.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_run
node = animations_node.child("r_run");
cat.r_run.speed = node.attribute("speed").as_float();
cat.r_run.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_run.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_run
node = animations_node.child("l_run");
cat.l_run.speed = node.attribute("speed").as_float();
cat.l_run.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_run.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_turn
node = animations_node.child("r_turn");
cat.r_turn.speed = node.attribute("speed").as_float();
cat.r_turn.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_turn.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_turn
node = animations_node.child("l_turn");
cat.l_turn.speed = node.attribute("speed").as_float();
cat.l_turn.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_turn.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_brake
node = animations_node.child("r_brake");
cat.r_brake.speed = node.attribute("speed").as_float();
cat.r_brake.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_brake.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_brake
node = animations_node.child("l_brake");
cat.l_brake.speed = node.attribute("speed").as_float();
cat.l_brake.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_brake.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//r_dead
node = animations_node.child("r_dead");
cat.r_dead.speed = node.attribute("speed").as_float();
cat.r_dead.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.r_dead.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//l_dead
node = animations_node.child("l_dead");
cat.l_dead.speed = node.attribute("speed").as_float();
cat.l_dead.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.l_dead.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//attack
node = animations_node.child("attack");
cat.attack.speed = node.attribute("speed").as_float();
cat.attack.loop = node.attribute("loop").as_bool();
for (node = node.child("frame"); node; node = node.next_sibling("frame")) {
cat.attack.PushBack({ node.attribute("x").as_int(), node.attribute("y").as_int(), node.attribute("w").as_int(), node.attribute("h").as_int() });
}
//_load_animations
//_CAT
return ret;
}
bool j1EntityFactory::Start()
{
// Load player textures
LOG("Loading entities textures");
CatPeasantTex = App->tex->Load(CatPeasant_spritesheet.GetString());
MonkeyTex = App->tex->Load(Monkey_spritesheet.GetString());
ImpTex = App->tex->Load(Imp_spritesheet.GetString());
PlayerTex = App->tex->Load(Player_spritesheet.GetString());
CatTex = App->tex->Load(Cat_spritesheet.GetString());
return true;
}
bool j1EntityFactory::PreUpdate()
{
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (queue[i].type != ENTITY_TYPES::NO_TYPE)
{
SpawnEntity(queue[i]);
queue[i].type = ENTITY_TYPES::NO_TYPE;
LOG("Spawning entity at %d", queue[i].position.y * App->scene->scale);
}
}
return true;
}
// Called before render is available
bool j1EntityFactory::Update(float dt)
{
for (uint i = 0; i < MAX_ENTITIES; ++i) {
if (entities[i] != nullptr) {
entities[i]->Move(dt);
}
}
if (App->scene->active)
App->scene->MoveCamera();
// Draw Map
App->map->Draw();
for (uint i = 0; i < MAX_ENTITIES; ++i)
if (entities[i] != nullptr) {
if (entities[i]->type == ENTITY_TYPES::CAT_PEASANT_)
entities[i]->Draw(CatPeasantTex);
else if (entities[i]->type == ENTITY_TYPES::IMP_)
entities[i]->Draw(ImpTex);
else if (entities[i]->type == ENTITY_TYPES::MONKEY_)
entities[i]->Draw(MonkeyTex);
else if (entities[i]->type == ENTITY_TYPES::PLAYER_)
entities[i]->Draw(PlayerTex);
else if (entities[i]->type == ENTITY_TYPES::CAT_)
entities[i]->Draw(CatTex);
}
// Draw Above layer
App->map->DrawAboveLayer();
App->gui->Blit(dt);
return true;
}
bool j1EntityFactory::PostUpdate()
{
// check camera position to decide what to spawn
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (entities[i] != nullptr)
{
if (entities[i]->dead) {
delete entities[i];
entities[i] = nullptr;
}
}
}
return true;
}
// Called before quitting
bool j1EntityFactory::CleanUp()
{
LOG("Freeing all entities");
// Remove all paths
p2List_item<PathInfo*>* item;
item = paths.start;
while (item != NULL)
{
RELEASE(item->data);
item = item->next;
}
paths.clear();
App->tex->UnLoad(CatPeasantTex);
App->tex->UnLoad(MonkeyTex);
App->tex->UnLoad(ImpTex);
App->tex->UnLoad(PlayerTex);
App->tex->UnLoad(CatTex);
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (queue[i].type != ENTITY_TYPES::NO_TYPE)
{
queue[i].type = ENTITY_TYPES::NO_TYPE;
queue[i].position = { 0,0 };
}
if (entities[i] != nullptr)
{
delete entities[i];
entities[i] = nullptr;
}
}
playerData = nullptr;
return true;
}
bool j1EntityFactory::AddEntity(EntityInfo& info)
{
bool ret = false;
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (queue[i].type == ENTITY_TYPES::NO_TYPE)
{
queue[i].type = info.type;
queue[i].path = GetPathByIndex(info.path_num);
queue[i].states = info.states;
queue[i].right_death = info.right_death;
if (queue[i].path != nullptr) {
queue[i].position.x = queue[i].path->start_pos.x;
queue[i].position.y = queue[i].path->start_pos.y;
}
else {
queue[i].position.x = info.position.x;
queue[i].position.y = info.position.y;
}
ret = true;
break;
}
}
return ret;
}
Entity* j1EntityFactory::SpawnEntity(const EntityInfo& info)
{
// find room for the new entity
uint i = 0;
for (; entities[i] != nullptr && i < MAX_ENTITIES; ++i);
if (i != MAX_ENTITIES)
{
switch (info.type)
{
case ENTITY_TYPES::CAT_PEASANT_:
entities[i] = new CatPeasant(info.position.x, info.position.y, info.path);
entities[i]->type = ENTITY_TYPES::CAT_PEASANT_;
return (Entity*)entities[i];
break;
case ENTITY_TYPES::IMP_:
entities[i] = new Imp(info.position.x, info.position.y, info.path);
entities[i]->type = ENTITY_TYPES::IMP_;
return (Entity*)entities[i];
break;
case ENTITY_TYPES::MONKEY_:
entities[i] = new Monkey(info.position.x, info.position.y, info.path);
entities[i]->type = ENTITY_TYPES::MONKEY_;
return (Entity*)entities[i];
break;
case ENTITY_TYPES::PLAYER_:
playerData = new Player(info.position.x, info.position.y);
entities[i] = playerData;
entities[i]->type = ENTITY_TYPES::PLAYER_;
return (Entity*)entities[i];
break;
case ENTITY_TYPES::CAT_:
entities[i] = new Cat(info.position.x, info.position.y, info.states, info.right_death);
entities[i]->type = ENTITY_TYPES::CAT_;
return (Entity*)entities[i];
break;
}
}
}
void j1EntityFactory::OnCollision(Collider* c1, Collider* c2)
{
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (entities[i] != nullptr && (entities[i]->GetCollider() == c1)) {
entities[i]->OnCollision(c1, c2);
break;
}
}
}
bool j1EntityFactory::KillAllEntities()
{
bool ret = true;
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (entities[i] != nullptr)
{
entities[i]->dead = true;
}
}
return ret;
}
bool j1EntityFactory::KillAllEntitiesExceptPlayer()
{
bool ret = true;
// Remove all paths
p2List_item<PathInfo*>* item;
item = paths.start;
while (item != NULL)
{
RELEASE(item->data);
item = item->next;
}
paths.clear();
App->tex->UnLoad(CatPeasantTex);
App->tex->UnLoad(MonkeyTex);
App->tex->UnLoad(ImpTex);
App->tex->UnLoad(PlayerTex);
App->tex->UnLoad(CatTex);
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (queue[i].type != ENTITY_TYPES::NO_TYPE && queue[i].type != PLAYER_)
{
queue[i].type = ENTITY_TYPES::NO_TYPE;
queue[i].position = { 0,0 };
}
if (entities[i] != nullptr)
{
if (entities[i] != playerData) {
delete entities[i];
entities[i] = nullptr;
}
}
}
return ret;
}
bool j1EntityFactory::LoadPathsInfo()
{
bool ret = true;
uint index = 1;
// Repetitive paths
SaveRepetitivePaths(index);
// Start-end paths
SaveStartEndPaths(index);
return ret;
}
bool j1EntityFactory::SaveRepetitivePaths(uint& index)
{
bool ret = false;
p2SString tmp("%s%d", "Enemy", index);
Object* obj = App->map->data.GetObjectByName("Enemies", tmp);
while (obj != nullptr) {
// Save actual path
PathInfo* path = new PathInfo();
path->start_pos = { (int)obj->x, (int)obj->y };
path->path = new iPoint[MAX_POLYLINE_POINTS];
memset(path->path, 0, sizeof(iPoint) * MAX_POLYLINE_POINTS);
// Create path
if (obj->polyline != nullptr) {
path->path[0].x = obj->polyline[0] + path->start_pos.x;
path->path[0].y = obj->polyline[1] + path->start_pos.y;
path->path_size = 1;
int i = 1;
while (obj->polyline[i * 2 + 0] != 0 && obj->polyline[i * 2 + 1] != 0 && i < MAX_POLYLINE_POINTS) {
path->path[i].x = obj->polyline[i * 2 + 0] + path->start_pos.x;
path->path[i].y = obj->polyline[i * 2 + 1] + path->start_pos.y;
path->path_size++;
++i;
}
}
paths.add(path);
ret = true;
// Search next path
index++;
p2SString tmp("%s%d", "Enemy", index);
obj = App->map->data.GetObjectByName("Enemies", tmp);
}
if (obj != nullptr)
RELEASE(obj);
return ret;
}
bool j1EntityFactory::SaveStartEndPaths(uint& index)
{
bool ret = false;
p2SString tmp("%s%d%s", "Enemy", index, "S");
Object* obj = App->map->data.GetObjectByName("Enemies", tmp);
while (obj != nullptr) {
// Save actual path
PathInfo* path = new PathInfo();
path->start_pos = { (int)obj->x, (int)obj->y };
p2SString tmp("%s%d%s", "Enemy", index, "E");
obj = App->map->data.GetObjectByName("Enemies", tmp);
if (obj != nullptr) {
path->end_pos = { (int)obj->x, (int)obj->y };
paths.add(path);
ret = true;
}
// Search next path
index++;
p2SString tmp1("%s%d%s", "Enemy", index, "S");
obj = App->map->data.GetObjectByName("Enemies", tmp1);
}
if (obj != nullptr)
RELEASE(obj);
return ret;
}
bool j1EntityFactory::AddEntities()
{
bool ret = false;
EntityInfo info;
// Player
if (!App->scene->loading_state && !App->menu->active) {
info.type = PLAYER_;
AddEntity(info);
}
// Enemies
int index = 1;
p2SString tmp("%s%d", "Enemy", index);
Object* obj = App->map->data.GetObjectByName("Enemies", tmp);
while (obj != nullptr) {
// Add entity
info.type = (ENTITY_TYPES)obj->type;
info.path_num = index;
AddEntity(info);
ret = true;
// Search next entity
index++;
p2SString tmp("%s%d", "Enemy", index);
obj = App->map->data.GetObjectByName("Enemies", tmp);
}
p2SString tmp1("%s%d%s", "Enemy", index, "S");
obj = App->map->data.GetObjectByName("Enemies", tmp1);
while (obj != nullptr) {
// Add entity
info.type = (ENTITY_TYPES)obj->type;
info.path_num = index;
AddEntity(info);
ret = true;
// Search next entity
index++;
p2SString tmp1("%s%d%s", "Enemy", index, "S");
obj = App->map->data.GetObjectByName("Enemies", tmp1);
}
// Cats
index = 1;
p2SString tmp2("%s%d", "Cat", index);
obj = App->map->data.GetObjectByName("Cats", tmp2);
while (obj != nullptr) {
// Add entity
info.type = (ENTITY_TYPES)obj->type;
info.path_num = 0;
info.position.x = (int)obj->x;
info.position.y = (int)obj->y;
info.states = obj->states;
info.right_death = obj->right_death;
AddEntity(info);
ret = true;
// Search next entity
index++;
p2SString tmp2("%s%d", "Cat", index);
obj = App->map->data.GetObjectByName("Cats", tmp2);
}
if (obj != nullptr)
RELEASE(obj);
return ret;
}
PathInfo* j1EntityFactory::GetPathByIndex(uint index) const {
PathInfo* path = nullptr;
p2List_item<PathInfo*>* iterator = paths.start;
int i = 0;
while (iterator != nullptr && i <= index - 1) {
if (i == index - 1)
path = iterator->data;
iterator = iterator->next;
++i;
}
return path;
}
// -------------------------------------------------------------
// -------------------------------------------------------------
bool j1EntityFactory::Load(pugi::xml_node& save)
{
bool ret = false;
pugi::xml_node node;
if (App->scene->last_index != App->scene->index) {
LoadEntities();
}
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (playerData != nullptr) {
if (entities[i] == playerData) {
if (save.child("player") != NULL) {
node = save.child("player");
}
else {
return true;
}
if (node.child("position") != NULL) {
playerData->position.x = node.child("position").attribute("position.x").as_float();
playerData->position.y = node.child("position").attribute("position.y").as_float();
}
if (node.child("state") != NULL) {
playerData->player.SetState((playerstates)(node.child("state").attribute("state").as_int()));
}
if (node.child("speed") != NULL) {
playerData->speed.x = node.child("speed").attribute("speed.x").as_float();
playerData->speed.y = node.child("speed").attribute("speed.y").as_float();
}
}
}
}
ret = true;
return ret;
}
bool j1EntityFactory::LoadEntities()
{
bool ret = false;
// Remove all paths
p2List_item<PathInfo*>* item;
item = paths.start;
while (item != NULL)
{
RELEASE(item->data);
item = item->next;
}
paths.clear();
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (entities[i] != nullptr)
{
delete entities[i];
entities[i] = nullptr;
}
}
EntityInfo info;
info.type = PLAYER_;
AddEntity(info);
if (PreUpdate())
ret = true;
return ret;
}
bool j1EntityFactory::Save(pugi::xml_node& save) const
{
bool ret = false;
pugi::xml_node node;
for (uint i = 0; i < MAX_ENTITIES; ++i)
{
if (playerData != nullptr) {
if (entities[i] == playerData) {
if (save.child("player") == NULL) {
node = save.append_child("player");
}
else {
node = save.child("player");
}
if (node.child("position") == NULL) {
node.append_child("position").append_attribute("position.x") = playerData->position.x;
node.child("position").append_attribute("position.y") = playerData->position.y;
}
else {
node.child("position").attribute("position.x") = playerData->position.x;
node.child("position").attribute("position.y") = playerData->position.y;
}
if (node.child("state") == NULL) {
node.append_child("state").append_attribute("state") = playerData->player.GetState();
}
else {
node.child("state").attribute("state") = playerData->player.GetState();
}
if (node.child("speed") == NULL) {
node.append_child("speed").append_attribute("speed.x") = playerData->speed.x;
node.child("speed").append_attribute("speed.y") = playerData->speed.y;
}
else {
node.child("speed").attribute("speed.x") = playerData->speed.x;
node.child("speed").attribute("speed.y") = playerData->speed.y;
}
}
}
}
ret = true;
return ret;
}
// -------------------------------------------------------------
// -------------------------------------------------------------
PathInfo::PathInfo() {}
PathInfo::PathInfo(const PathInfo& i) :
start_pos(i.start_pos), path(i.path), path_size(i.path_size)
{} | 38.810285 | 254 | 0.676801 | [
"render",
"object"
] |
806eacc6dab2ceee24000e6493848615f2f4b637 | 1,665 | cpp | C++ | src/actions/describe_action.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | 9 | 2021-11-09T13:55:41.000Z | 2022-03-04T05:22:15.000Z | src/actions/describe_action.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | null | null | null | src/actions/describe_action.cpp | abhijat/matchboxdb | 77c055690054deb96dffc29499ad99928370ae99 | [
"BSD-2-Clause"
] | null | null | null | #include <iomanip>
#include <iterator>
#include "describe_action.h"
#include "../sql_parser/describe_statement.h"
#include "../page/page_cache.h"
actions::DescribeAction::DescribeAction(page_cache::PageCache &page_cache,
const ast::DescribeStatement &describe_statement) : _describe_statement(
describe_statement), _page_cache(page_cache) {}
std::string actions::DescribeAction::describe() {
if (_describe_statement.table()) {
return describe_table(_describe_statement.table()->table_name());
} else {
return describe_all_tables();
}
}
std::string actions::DescribeAction::describe_table(const std::string &table_name) {
auto metadata = _page_cache.metadata_for_table(table_name);
std::stringstream ss{};
ss << table_name << " (\n";
// TODO calculate max width first
for (auto i = 0; i < metadata.names.size(); ++i) {
ss << ' ' << std::left << std::setw(24) << metadata.names[i] << std::setw(16) << metadata.types[i] << "\n";
}
ss << ")\n";
return ss.str();
}
std::string actions::DescribeAction::describe_all_tables() {
std::vector<std::string> sorted_tables{_page_cache.table_names()};
std::sort(sorted_tables.begin(), sorted_tables.end());
std::vector<std::string> descriptions{sorted_tables.size()};
std::transform(sorted_tables.cbegin(), sorted_tables.cend(), descriptions.begin(), [&](const auto &table_name) {
return describe_table(table_name);
});
std::stringstream ss{};
std::copy(descriptions.cbegin(), descriptions.cend(), std::ostream_iterator<std::string>(ss, "\n"));
return ss.str();
}
| 33.3 | 116 | 0.66006 | [
"vector",
"transform"
] |
8075d33ea9d34f331790566d6d0ff7f91e27dfee | 577 | hpp | C++ | src/color/YPbPr/YPbPr.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 120 | 2015-12-31T22:30:14.000Z | 2022-03-29T15:08:01.000Z | src/color/YPbPr/YPbPr.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 6 | 2016-08-22T02:14:56.000Z | 2021-11-06T22:39:52.000Z | src/color/YPbPr/YPbPr.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 23 | 2016-02-03T01:56:26.000Z | 2021-09-28T16:36:27.000Z | #ifndef color_YPbPr_YPbPr_
#define color_YPbPr_YPbPr_
#include "./category.hpp"
#include "./akin/akin.hpp"
#include "./trait/trait.hpp"
#include "../generic/model.hpp"
#include "./constant.hpp"
namespace color
{
template< typename type_name, ::color::constant::YPbPr::reference_enum reference_number = ::color::constant::YPbPr::BT_709_entity >
using YPbPr = ::color::model< ::color::category::YPbPr< type_name, reference_number > >;
}
#include "./place/place.hpp"
#include "./get/get.hpp"
#include "./set/set.hpp"
#include "./convert/convert.hpp"
#endif
| 18.03125 | 133 | 0.70364 | [
"model"
] |
8078cc38c3c0498145b148a55214d06032603fa9 | 73,942 | cpp | C++ | models/processor/zesto/ZPIPE-exec/exec-atom.cpp | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 8 | 2016-01-22T18:28:48.000Z | 2021-05-07T02:27:21.000Z | models/processor/zesto/ZPIPE-exec/exec-atom.cpp | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 3 | 2016-04-15T02:58:58.000Z | 2017-01-19T17:07:34.000Z | models/processor/zesto/ZPIPE-exec/exec-atom.cpp | Basseuph/manifold | 99779998911ed7e8b8ff6adacc7f93080409a5fe | [
"BSD-3-Clause"
] | 10 | 2015-12-11T04:16:55.000Z | 2019-05-25T20:58:13.000Z | /* exec-atom.cpp - In order Atom Model */
/*
* __COPYRIGHT__ GT
*/
#include "../zesto-core.h"
#ifdef ZESTO_PARSE_ARGS
if(!strcasecmp(exec_opt_string,"ATOM"))
return new core_exec_atom_t(core);
#else
class core_exec_atom_t : public core_exec_t
{
/* readyQ for scheduling */
struct readyQ_node_t {
struct uop_t * uop;
seq_t uop_seq; /* seq id of uop when inserted - for proper sorting even after uop recycled */
seq_t action_id;
tick_t when_assigned;
struct readyQ_node_t * next;
};
/* struct for a squashable in-flight uop (for example, a uop making its way
down an ALU pipeline). Changing the original uop's tag will make the tags
no longer match, thereby invalidating the in-flight action. */
struct uop_action_t {
struct uop_t * uop;
seq_t action_id;
bool completed;
bool load_enqueued;
bool load_received;
};
/* struct for a generic pipelined ALU */
struct ALU_t {
struct uop_action_t * pipe;
int occupancy;
int latency; /* number of cycles from start of execution to end */
int issue_rate; /* number of cycles between issuing independent instructions on this ALU */
tick_t when_scheduleable; /* cycle when next instruction can be scheduled for this ALU */
tick_t when_executable; /* cycle when next instruction can actually start executing on this ALU */
};
public:
core_exec_atom_t(struct core_t * const core);
virtual void reg_stats(struct stat_sdb_t * const sdb);
virtual void freeze_stats(void);
virtual void update_occupancy(void);
virtual void ALU_exec(void);
virtual void LDST_exec(void);
virtual void RS_schedule(void);
virtual void LDQ_schedule(void);
virtual void recover(const struct Mop_t * const Mop);
virtual void recover(void);
virtual void insert_ready_uop(struct uop_t * const uop);
virtual bool RS_available(int port);
virtual void RS_insert(struct uop_t * const uop);
virtual void RS_fuse_insert(struct uop_t * const uop);
virtual void RS_deallocate(struct uop_t * const uop);
virtual bool LDQ_available(void);
virtual void LDQ_insert(struct uop_t * const uop);
virtual void LDQ_deallocate(struct uop_t * const uop);
virtual void LDQ_squash(struct uop_t * const dead_uop);
virtual bool STQ_available(void);
virtual void STQ_insert_sta(struct uop_t * const uop);
virtual void STQ_insert_std(struct uop_t * const uop);
virtual void STQ_deallocate_sta(void);
virtual bool STQ_deallocate_std(struct uop_t * const uop);
virtual void STQ_deallocate_senior(void);
virtual void STQ_squash_sta(struct uop_t * const dead_uop);
virtual void STQ_squash_std(struct uop_t * const dead_uop);
virtual void STQ_squash_senior(void);
virtual void recover_check_assertions(void);
virtual bool has_load_arrived(int LDQ_index); /*This function checks if a particular load has arrived fully from a cache*/
virtual unsigned long long int get_load_latency(int LDQ_index);
protected:
struct readyQ_node_t * readyQ_free_pool; /* for scheduling readyQ's */
#ifdef DEBUG
int readyQ_free_pool_debt; /* for debugging memory leaks */
#endif
struct uop_t ** RS;
int RS_num;
int RS_eff_num;
struct LDQ_t {
struct uop_t * uop;
md_addr_t virt_addr;
md_paddr_t phys_addr;
bool first_byte_requested;
bool last_byte_requested;
bool first_byte_arrived;
bool last_byte_arrived;
int mem_size;
bool addr_valid;
int store_color; /* STQ index of most recent store before this load */
bool hit_in_STQ; /* received value from STQ */
tick_t when_issued; /* when load actually issued */
tick_t when_completed; /* when load is actually completely finished*/
bool speculative_broadcast; /* made a speculative tag broadcast */
bool partial_forward; /* true if blocked on an earlier partially matching store */
}*LDQ;
int LDQ_head;
int LDQ_tail;
int LDQ_num;
struct STQ_t {
struct uop_t * sta;
struct uop_t * std;
struct uop_t * dl1_uop; //Placeholders for store uops which get returned when the Mop commits
struct uop_t * dtlb_uop;
seq_t uop_seq;
md_addr_t virt_addr;
md_paddr_t phys_addr;
bool first_byte_requested;
bool last_byte_requested;
bool first_byte_written;
bool last_byte_written;
int mem_size;
union val_t value;
bool addr_valid;
bool value_valid;
int next_load; /* LDQ index of next load in program order */
/* for commit */
bool translation_complete; /* dtlb access finished */
bool write_complete; /* write access finished */
seq_t action_id; /* need to squash commits when a core resets (multi-core mode only) */
} * STQ;
int STQ_head;
int STQ_tail;
int STQ_num;
int STQ_senior_num;
int STQ_senior_head;
bool partial_forward_throttle; /* used to control load-issuing in the presence of partial-matching stores */
struct exec_port_t {
struct uop_action_t * payload_pipe;
int occupancy;
struct ALU_t * FU[NUM_FU_CLASSES];
struct readyQ_node_t * readyQ;
struct ALU_t * STQ; /* store-queue lookup/search pipeline for load execution */
tick_t when_bypass_used; /* to make sure only one inst writes back per cycle, which
could happen due to insts with different latencies */
int num_FU_types; /* the number of FU's bound to this port */
enum md_fu_class * FU_types; /* the corresponding types of those FUs */
} * port;
bool check_for_work; /* used to skip ALU exec when there's no uops */
struct memdep_t * memdep;
/* various exec utility functions */
struct readyQ_node_t * get_readyQ_node(void);
void return_readyQ_node(struct readyQ_node_t * const p);
bool check_load_issue_conditions(const struct uop_t * const uop);
void snatch_back(struct uop_t * const replayed_uop);
void load_writeback(unsigned long long int);
/* callbacks need to be static */
static void DL1_callback(void * const op);
static void DL1_split_callback(void * const op);
static void DTLB_callback(void * const op);
static bool translated_callback(void * const op,const seq_t);
static seq_t get_uop_action_id(void * const op);
static void load_miss_reschedule(void * const op, const int new_pred_latency);
/* callbacks used by commit for stores */
static void store_dl1_callback(void * const op);
static void store_dl1_split_callback(void * const op);
static void store_dtlb_callback(void * const op);
static bool store_translated_callback(void * const op,const seq_t);
virtual void memory_callbacks(void);
};
/*******************/
/* SETUP FUNCTIONS */
/*******************/
core_exec_atom_t::core_exec_atom_t(struct core_t * const arg_core):
readyQ_free_pool(NULL),
#ifdef DEBUG
readyQ_free_pool_debt(0),
#endif
RS_num(0), RS_eff_num(0)
{
struct core_knobs_t * knobs = arg_core->knobs;
core = arg_core;
RS = (struct uop_t**) calloc(knobs->exec.RS_size,sizeof(*RS));
if(!RS)
fatal("couldn't calloc RS");
LDQ = (core_exec_atom_t::LDQ_t*) calloc(knobs->exec.LDQ_size,sizeof(*LDQ));
if(!LDQ)
fatal("couldn't calloc LDQ");
STQ = (core_exec_atom_t::STQ_t*) calloc(knobs->exec.STQ_size,sizeof(*STQ));
if(!STQ)
fatal("couldn't calloc STQ");
int i;
/* This shouldn't be necessary, but I threw it in because valgrind (memcheck)
was reporting that STQ[i].sta was being used uninitialized. -GL */
for(i=0;i<knobs->exec.STQ_size;i++)
STQ[i].sta = NULL;
/************************************/
/* execution port payload pipelines */
/************************************/
port = (core_exec_atom_t::exec_port_t*) calloc(knobs->exec.num_exec_ports,sizeof(*port));
if(!port)
fatal("couldn't calloc exec ports");
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
port[i].payload_pipe = (struct uop_action_t*) calloc(knobs->exec.payload_depth,sizeof(*port->payload_pipe));
if(!port[i].payload_pipe)
fatal("couldn't calloc payload pipe");
}
/***************************/
/* execution port bindings */
/***************************/
for(i=0;i<NUM_FU_CLASSES;i++)
{
int j;
knobs->exec.port_binding[i].ports = (int*) calloc(knobs->exec.port_binding[i].num_FUs,sizeof(int));
if(!knobs->exec.port_binding[i].ports) fatal("couldn't calloc %s ports",MD_FU_NAME(i));
for(j=0;j<knobs->exec.port_binding[i].num_FUs;j++)
{
if((knobs->exec.fu_bindings[i][j] < 0) || (knobs->exec.fu_bindings[i][j] >= knobs->exec.num_exec_ports))
fatal("port binding for %s is negative or exceeds the execution width (should be > 0 and < %d)",MD_FU_NAME(i),knobs->exec.num_exec_ports);
knobs->exec.port_binding[i].ports[j] = knobs->exec.fu_bindings[i][j];
}
}
/***************************************/
/* functional unit execution pipelines */
/***************************************/
for(i=0;i<NUM_FU_CLASSES;i++)
{
int j;
for(j=0;j<knobs->exec.port_binding[i].num_FUs;j++)
{
int port_num = knobs->exec.port_binding[i].ports[j];
int latency = knobs->exec.latency[i];
int issue_rate = knobs->exec.issue_rate[i];
port[port_num].FU[i] = (struct ALU_t*) calloc(1,sizeof(struct ALU_t));
if(!port[port_num].FU[i])
fatal("couldn't calloc IEU");
port[port_num].FU[i]->latency = latency;
port[port_num].FU[i]->issue_rate = issue_rate;
port[port_num].FU[i]->pipe = (struct uop_action_t*) calloc(latency,sizeof(struct uop_action_t));
if(!port[port_num].FU[i]->pipe)
fatal("couldn't calloc %s function unit execution pipeline",MD_FU_NAME(i));
if(i==FU_LD) /* load has AGEN and STQ access pipelines */
{
port[port_num].STQ = (struct ALU_t*) calloc(1,sizeof(struct ALU_t));
latency = 3;//CAFFEINE: core->memory.DL1->latency; /* assume STQ latency matched to DL1's */
port[port_num].STQ->latency = latency;
port[port_num].STQ->issue_rate = issue_rate;
port[port_num].STQ->pipe = (struct uop_action_t*) calloc(latency,sizeof(struct uop_action_t));
if(!port[port_num].STQ->pipe)
fatal("couldn't calloc load's STQ exec pipe on port %d",j);
}
}
}
/* shortened list of the FU's available on each port (to speed up FU loop in ALU_exec) */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
port[i].num_FU_types = 0;
int j;
for(j=0;j<NUM_FU_CLASSES;j++)
if(port[i].FU[j])
port[i].num_FU_types++;
port[i].FU_types = (enum md_fu_class *)calloc(port[i].num_FU_types,sizeof(enum md_fu_class));
if(!port[i].FU_types)
fatal("couldn't calloc FU_types array on port %d",i);
int k=0;
for(j=0;j<NUM_FU_CLASSES;j++)
{
if(port[i].FU[j])
{
port[i].FU_types[k] = (enum md_fu_class)j;
k++;
}
}
}
last_Mop_seq = 0 ; // core->global_seq starts from zero
memdep = memdep_create(knobs->exec.memdep_opt_str,core);
check_for_work = true;
}
void
core_exec_atom_t::reg_stats(struct stat_sdb_t * const sdb)
{
char buf[1024];
char buf2[1024];
sprintf(buf,"\n#### Zesto Core#%d Exec Stats ####",core->id);
stat_reg_note(sdb,buf);
sprintf(buf,"c%d.exec_uops_issued",core->id);
stat_reg_counter(sdb, true, buf, "number of uops issued", &core->stat.exec_uops_issued, core->stat.exec_uops_issued, NULL);
sprintf(buf,"c%d.exec_uPC",core->id);
sprintf(buf2,"c%d.exec_uops_issued/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average number of uops executed per cycle", buf2, NULL);
sprintf(buf,"c%d.exec_uops_replayed",core->id);
stat_reg_counter(sdb, true, buf, "number of uops replayed", &core->stat.exec_uops_replayed, core->stat.exec_uops_replayed, NULL);
sprintf(buf,"c%d.exec_avg_replays",core->id);
sprintf(buf2,"c%d.exec_uops_replayed/c%d.exec_uops_issued",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average replays per uop", buf2, NULL);
sprintf(buf,"c%d.exec_uops_snatched",core->id);
stat_reg_counter(sdb, true, buf, "number of uops snatched-back", &core->stat.exec_uops_snatched_back, core->stat.exec_uops_snatched_back, NULL);
sprintf(buf,"c%d.exec_avg_snatched",core->id);
sprintf(buf2,"c%d.exec_uops_snatched/c%d.exec_uops_issued",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average snatch-backs per uop", buf2, NULL);
sprintf(buf,"c%d.num_jeclear",core->id);
stat_reg_counter(sdb, true, buf, "number of branch mispredictions", &core->stat.num_jeclear, core->stat.num_jeclear, NULL);
sprintf(buf,"c%d.num_wp_jeclear",core->id);
stat_reg_counter(sdb, true, buf, "number of branch mispredictions in the shadow of an earlier mispred", &core->stat.num_wp_jeclear, core->stat.num_wp_jeclear, NULL);
sprintf(buf,"c%d.load_nukes",core->id);
stat_reg_counter(sdb, true, buf, "num pipeflushes due to load-store order violation", &core->stat.load_nukes, core->stat.load_nukes, NULL);
sprintf(buf,"c%d.wp_load_nukes",core->id);
stat_reg_counter(sdb, true, buf, "num pipeflushes due to load-store order violation on wrong-path", &core->stat.wp_load_nukes, core->stat.wp_load_nukes, NULL);
sprintf(buf,"c%d.DL1_load_split_accesses",core->id);
stat_reg_counter(sdb, true, buf, "number of loads requiring split accesses", &core->stat.DL1_load_split_accesses, core->stat.DL1_load_split_accesses, NULL);
sprintf(buf,"c%d.DL1_load_split_frac",core->id);
sprintf(buf2,"c%d.DL1_load_split_accesses/(c%d.DL1.load_lookups-c%d.DL1_load_split_accesses)",core->id,core->id,core->id); /* need to subtract since each split access generated two load accesses */
stat_reg_formula(sdb, true, buf, "fraction of loads requiring split accesses", buf2, NULL);
sprintf(buf,"c%d.RS_occupancy",core->id);
stat_reg_counter(sdb, false, buf, "total RS occupancy", &core->stat.RS_occupancy, core->stat.RS_occupancy, NULL);
sprintf(buf,"c%d.RS_eff_occupancy",core->id);
stat_reg_counter(sdb, false, buf, "total RS effective occupancy", &core->stat.RS_eff_occupancy, core->stat.RS_eff_occupancy, NULL);
sprintf(buf,"c%d.RS_empty",core->id);
stat_reg_counter(sdb, false, buf, "total cycles RS was empty", &core->stat.RS_empty_cycles, core->stat.RS_empty_cycles, NULL);
sprintf(buf,"c%d.RS_full",core->id);
stat_reg_counter(sdb, false, buf, "total cycles RS was full", &core->stat.RS_full_cycles, core->stat.RS_full_cycles, NULL);
sprintf(buf,"c%d.RS_avg",core->id);
sprintf(buf2,"c%d.RS_occupancy/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average RS occupancy", buf2, NULL);
sprintf(buf,"c%d.RS_eff_avg",core->id);
sprintf(buf2,"c%d.RS_eff_occupancy/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "effective average RS occupancy", buf2, NULL);
sprintf(buf,"c%d.RS_frac_empty",core->id);
sprintf(buf2,"c%d.RS_empty/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles RS was empty", buf2, NULL);
sprintf(buf,"c%d.RS_frac_full",core->id);
sprintf(buf2,"c%d.RS_full/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles RS was full", buf2, NULL);
sprintf(buf,"c%d.LDQ_occupancy",core->id);
stat_reg_counter(sdb, true, buf, "total LDQ occupancy", &core->stat.LDQ_occupancy, core->stat.LDQ_occupancy, NULL);
sprintf(buf,"c%d.LDQ_empty",core->id);
stat_reg_counter(sdb, true, buf, "total cycles LDQ was empty", &core->stat.LDQ_empty_cycles, core->stat.LDQ_empty_cycles, NULL);
sprintf(buf,"c%d.LDQ_full",core->id);
stat_reg_counter(sdb, true, buf, "total cycles LDQ was full", &core->stat.LDQ_full_cycles, core->stat.LDQ_full_cycles, NULL);
sprintf(buf,"c%d.LDQ_avg",core->id);
sprintf(buf2,"c%d.LDQ_occupancy/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average LDQ occupancy", buf2, NULL);
sprintf(buf,"c%d.LDQ_frac_empty",core->id);
sprintf(buf2,"c%d.LDQ_empty/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles LDQ was empty", buf2, NULL);
sprintf(buf,"c%d.LDQ_frac_full",core->id);
sprintf(buf2,"c%d.LDQ_full/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles LDQ was full", buf2, NULL);
sprintf(buf,"c%d.STQ_occupancy",core->id);
stat_reg_counter(sdb, true, buf, "total STQ occupancy", &core->stat.STQ_occupancy, core->stat.STQ_occupancy, NULL);
sprintf(buf,"c%d.STQ_empty",core->id);
stat_reg_counter(sdb, true, buf, "total cycles STQ was empty", &core->stat.STQ_empty_cycles, core->stat.STQ_empty_cycles, NULL);
sprintf(buf,"c%d.STQ_full",core->id);
stat_reg_counter(sdb, true, buf, "total cycles STQ was full", &core->stat.STQ_full_cycles, core->stat.STQ_full_cycles, NULL);
sprintf(buf,"c%d.STQ_avg",core->id);
sprintf(buf2,"c%d.STQ_occupancy/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "average STQ occupancy", buf2, NULL);
sprintf(buf,"c%d.STQ_frac_empty",core->id);
sprintf(buf2,"c%d.STQ_empty/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles STQ was empty", buf2, NULL);
sprintf(buf,"c%d.STQ_frac_full",core->id);
sprintf(buf2,"c%d.STQ_full/c%d.sim_cycle",core->id,core->id);
stat_reg_formula(sdb, true, buf, "fraction of cycles STQ was full", buf2, NULL);
memdep->reg_stats(sdb, core);
}
void core_exec_atom_t::freeze_stats(void)
{
memdep->freeze_stats();
}
void core_exec_atom_t::update_occupancy(void)
{
/* RS */
core->stat.RS_occupancy += RS_num;
core->stat.RS_eff_occupancy += RS_eff_num;
if(RS_num >= core->knobs->exec.RS_size)
core->stat.RS_full_cycles++;
if(RS_num <= 0)
core->stat.RS_empty_cycles++;
/* LDQ */
core->stat.LDQ_occupancy += LDQ_num;
if(LDQ_num >= core->knobs->exec.LDQ_size)
core->stat.LDQ_full_cycles++;
if(LDQ_num <= 0)
core->stat.LDQ_empty_cycles++;
/* STQ */
core->stat.STQ_occupancy += STQ_num;
if(STQ_num >= core->knobs->exec.STQ_size)
core->stat.STQ_full_cycles++;
if(STQ_num <= 0)
core->stat.STQ_empty_cycles++;
}
/* Functions to support dependency tracking
NOTE: "Ready" Queue is somewhat of a misnomer... uops are placed in the
readyQ when all of their data-flow parents have issued (although not
necessarily executed). However, that doesn't necessarily mean that the
corresponding input *values* are "ready" due to non-zero schedule-to-
execute latencies. */
core_exec_atom_t::readyQ_node_t * core_exec_atom_t::get_readyQ_node(void)
{
struct readyQ_node_t * p = NULL;
if(readyQ_free_pool)
{
p = readyQ_free_pool;
readyQ_free_pool = p->next;
}
else
{
p = (struct readyQ_node_t*) calloc(1,sizeof(*p));
if(!p)
fatal("couldn't calloc a readyQ node");
}
assert(p);
p->next = NULL;
p->when_assigned = core->sim_cycle;
#ifdef DEBUG
readyQ_free_pool_debt++;
#endif
return p;
}
void core_exec_atom_t::return_readyQ_node(struct readyQ_node_t * const p)
{
assert(p);
assert(p->uop);
p->next = readyQ_free_pool;
readyQ_free_pool = p;
p->uop = NULL;
p->when_assigned = -1;
#ifdef DEBUG
readyQ_free_pool_debt--;
#endif
}
/* Add the uop to the corresponding readyQ (based on port binding - we maintain
one readyQ per execution port) */
void core_exec_atom_t::insert_ready_uop(struct uop_t * const uop)
{
struct core_knobs_t * knobs = core->knobs;
zesto_assert((uop->alloc.port_assignment >= 0) && (uop->alloc.port_assignment < knobs->exec.num_exec_ports),(void)0);
zesto_assert(uop->timing.when_completed == TICK_T_MAX,(void)0);
zesto_assert(uop->timing.when_exec == TICK_T_MAX,(void)0);
zesto_assert(uop->timing.when_issued == TICK_T_MAX,(void)0);
zesto_assert(!uop->exec.in_readyQ,(void)0);
struct readyQ_node_t ** RQ = &port[uop->alloc.port_assignment].readyQ;
struct readyQ_node_t * new_node = get_readyQ_node();
new_node->uop = uop;
new_node->uop_seq = uop->decode.uop_seq;
uop->exec.in_readyQ = true;
uop->exec.action_id = core->new_action_id();
new_node->action_id = uop->exec.action_id;
if(!*RQ) /* empty ready queue */
{
*RQ = new_node;
return;
}
struct readyQ_node_t * current = *RQ, * prev = NULL;
/* insert in age order: first find insertion point */
while(current && (current->uop_seq < uop->decode.uop_seq))
{
prev = current;
current = current->next;
}
if(!prev) /* uop is oldest */
{
new_node->next = *RQ;
*RQ = new_node;
}
else
{
new_node->next = current;
prev->next = new_node;
}
}
/*****************************/
/* MAIN SCHED/EXEC FUNCTIONS */
/*****************************/
void core_exec_atom_t::RS_schedule(void) /* for uops in the RS */
{
struct core_knobs_t * knobs = core->knobs;
int i;
/* All instructions leave the reservation stations as long as the next entry in the payload pipe is free,
Even if some operands are not ready it still goes to the payload pipe which is equivalent to the Register fetch stage */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
if(RS[i]) /* There is a uop in the Reservation stations. */
{
/*Every Port is connected to a single RS because this is an inorder pipeline*/
int port_num = RS[i]->alloc.port_assignment;
zesto_assert(i == port_num,(void)0);
if(port[port_num].payload_pipe[0].uop == NULL) /* port is free */
{
struct uop_t * uop = RS[i];
if( (port[port_num].FU[uop->decode.FU_class]->when_scheduleable <= core->sim_cycle) && ((!uop->decode.in_fusion) || uop->decode.fusion_head->alloc.full_fusion_allocated))
{
zesto_assert(uop->alloc.port_assignment == port_num,(void)0);
/*Getting a new action id from for th uop. For fued uops only the fusion head is given a action ID*/
uop->exec.action_id = core->new_action_id();
port[port_num].payload_pipe[0].uop = uop;
port[port_num].payload_pipe[0].action_id = uop->exec.action_id;
port[port_num].occupancy++;
zesto_assert(port[port_num].occupancy <= knobs->exec.payload_depth,(void)0);
uop->timing.when_issued = core->sim_cycle;
check_for_work = true;
#ifdef ZESTO_COUNTERS
core->counters->payload.write++;
core->counters->RS.read++;
core->counters->issue_select.read++;
core->counters->latch.RS2PR.read++;
#endif
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d in RS_schedule %d in_fusion %d spec_mode %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,uop->alloc.port_assignment,uop->decode.in_fusion,uop->Mop->oracle.spec_mode);
#endif
#ifdef ZTRACE
ztrace_print(uop,"e|RS-issue|uop issued to payload RAM");
#endif
if(uop->decode.is_load)
{
int fp_penalty = REG_IS_FPR(uop->decode.odep_name)?knobs->exec.fp_penalty:0;
//TODO caffein-sim add memlatency uop->timing.when_otag_ready = core->sim_cycle + port[i].FU[uop->decode.FU_class]->latency + core->memory.DL1->latency + fp_penalty;
// uop->timing.when_otag_ready = core->sim_cycle + port[i].FU[uop->decode.FU_class]->latency + 3 + fp_penalty;
uop->timing.when_otag_ready = TICK_T_MAX;
}
else
{
int fp_penalty = ((REG_IS_FPR(uop->decode.odep_name) && !(uop->decode.opflags & F_FCOMP)) ||
(!REG_IS_FPR(uop->decode.odep_name) && (uop->decode.opflags & F_FCOMP)))?knobs->exec.fp_penalty:0;
uop->timing.when_otag_ready = core->sim_cycle + port[port_num].FU[uop->decode.FU_class]->latency + fp_penalty;
}
port[port_num].FU[uop->decode.FU_class]->when_scheduleable = core->sim_cycle + port[port_num].FU[uop->decode.FU_class]->issue_rate;
/*All fusion uops pass through the pipeline as a single uop and so odeps of all of them need to be set correctly*/
if(uop->decode.in_fusion)
{
struct uop_t * fusion_uop = uop->decode.fusion_head;
zesto_assert(fusion_uop == uop, (void)0);
while(fusion_uop)
{
struct odep_t * odep = fusion_uop->exec.odep_uop;
while(odep)
{
int j;
tick_t when_ready = 0;
odep->uop->timing.when_itag_ready[odep->op_num] = fusion_uop->timing.when_otag_ready;
for(j=0;j<MAX_IDEPS;j++)
{
if(when_ready < odep->uop->timing.when_itag_ready[j])
when_ready = odep->uop->timing.when_itag_ready[j];
}
odep->uop->timing.when_ready = when_ready;
odep = odep->next;
}
fusion_uop = fusion_uop->decode.fusion_next;
ZESTO_STAT(core->stat.exec_uops_issued++;)
}
}
else /* All uops that are not fused go independently and hence need to be set correctly. */
{
/* tag broadcast to dependents */
struct odep_t * odep = uop->exec.odep_uop;
while(odep)
{
int j;
tick_t when_ready = 0;
odep->uop->timing.when_itag_ready[odep->op_num] = uop->timing.when_otag_ready;
for(j=0;j<MAX_IDEPS;j++)
{
if(when_ready < odep->uop->timing.when_itag_ready[j])
when_ready = odep->uop->timing.when_itag_ready[j];
}
odep->uop->timing.when_ready = when_ready;
odep = odep->next;
}
ZESTO_STAT(core->stat.exec_uops_issued++;)
}
#ifdef ZESTO_COUNTERS
core->counters->RS.write_tag++;
#endif
RS[i] = NULL;
RS_num--;
if(uop->decode.in_fusion)
{
struct uop_t * fusion_uop = uop->decode.fusion_head;
zesto_assert(fusion_uop == uop, (void)0);
while(fusion_uop)
{
fusion_uop->alloc.RS_index = -1;
core->alloc->RS_deallocate(fusion_uop);
RS_eff_num--;
fusion_uop = fusion_uop->decode.fusion_next;
}
}
else /* update port loading table */
{
uop->alloc.RS_index = -1;
core->alloc->RS_deallocate(uop);
}
}
}
}
}
}
/* returns true if load is allowed to issue (or is predicted to be ok) */
bool core_exec_atom_t::check_load_issue_conditions(const struct uop_t * const uop)
{
return true;
}
/* helper function to remove issued uops after a latency misprediction */
void core_exec_atom_t::snatch_back(struct uop_t * const replayed_uop)
{
}
/* The callback functions below (after load_writeback) mark flags
in the uop to specify the completion of each task, and only when
all are done do we call the load-writeback function to finish
off execution of the load. */
void core_exec_atom_t::load_writeback(unsigned long long int addr)
{
struct core_knobs_t * knobs = core->knobs;
//for(i=0;i<knobs->exec.port_binding[FU_LD].num_FUs;i++)
for(int i=0;i<knobs->exec.num_exec_ports;i++)
{
int j;
for(j=0;j<port[i].num_FU_types;j++)
{
enum md_fu_class FU_type = port[i].FU_types[j];
struct ALU_t * FU = port[i].FU[FU_type];
int stage;
if(FU)
stage = FU->latency-1;
/* For inorder cores, all stages of all pipes can handle loads and so we need to scan
all of thme to see which loadis returned. This is done in reverse order so that
the earliest load is reversed. */
if(FU && (FU->occupancy > 0) )
for(;stage>0;stage--)
{
/* load_enqueued field of uop_action should be set and the uop or one of its fused ops
should be a load and the fused uop should not have been killed. */
if(FU->pipe[stage].uop)
if(FU->pipe[stage].load_enqueued && (FU->pipe[stage].uop->decode.is_load || FU->pipe[stage].uop->decode.in_fusion ) && (FU->pipe[stage].action_id == FU->pipe[stage].uop->exec.action_id) )
{
zesto_assert(FU->pipe[stage].load_received == false, (void)0);
struct uop_t * uop = FU->pipe[stage].uop;
if(uop->decode.in_fusion) /*It is possible that the load is not the head uop in a fused set and so we have to scan the whole set*/
{
struct uop_t * fusion_uop = uop->decode.fusion_head;
zesto_assert(fusion_uop == uop, (void)0);
while(uop)
{
if(uop->decode.is_load)
break;
uop = uop->decode.fusion_next;
}
/*if none of the uops in the fused set is a load load_enqueued cannot be set BUG!*/
zesto_assert(uop != NULL, (void)0);
}
/*STQs are used as store buffers for the inorder core*/
if(uop && uop->decode.is_load)//Check if uop exists..it may have finished execution due to a store to load forward
{
if( (uop->oracle.phys_addr & 0xffffffc0) == addr)
{
#ifdef ZESTO_COUNTERS
core->counters->latch.L12LQ.read++;
#endif
int fp_penalty = REG_IS_FPR(uop->decode.odep_name)?knobs->exec.fp_penalty:0;
port[uop->alloc.port_assignment].when_bypass_used = core->sim_cycle+fp_penalty;
uop->exec.ovalue = uop->oracle.ovalue; /* XXX: just using oracle value for now */
uop->exec.ovalue_valid = true;
zesto_assert(uop->timing.when_completed == TICK_T_MAX,(void)0);
uop->timing.when_completed = core->sim_cycle+fp_penalty;
uop->exec.when_data_loaded = core->sim_cycle;
uop->exec.exec_complete=true;
FU->pipe[stage].load_received=true;
FU->pipe[stage].load_enqueued = false;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d in load_writeback ADDR %llx in_fusion %d port %d FU_type %d stage %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,addr,uop->decode.in_fusion,i,j,stage);
#endif
if(uop->decode.is_ctrl && (uop->Mop->oracle.NextPC != uop->Mop->fetch.pred_NPC) && (uop->Mop->decode.is_intr != true) ) /* XXX: for RETN */
{
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]load/RETN mispred detected (no STQ hit)",core->sim_cycle,core->id);
if(core->sim_cycle > PRINT_CYCLE )
md_print_insn(uop->Mop,stdout);
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout," %d \n",core->sim_cycle);
#endif
uop->Mop->fetch.branch_mispred = true;
core->oracle->pipe_recover(uop->Mop,uop->Mop->oracle.NextPC);
ZESTO_STAT(core->stat.num_jeclear++;)
if(uop->Mop->oracle.spec_mode)
ZESTO_STAT(core->stat.num_wp_jeclear++;)
#ifdef ZTRACE
ztrace_print(uop,"e|jeclear|load/RETN mispred detected (no STQ hit)");
#endif
}
#ifdef ZESTO_COUNTERS
if(uop->exec.when_data_loaded != TICK_T_MAX)
{
if((!uop->decode.in_fusion)||(uop->decode.in_fusion&&(uop->decode.fusion_next == NULL))) // this uop is done
{
core->counters->ROB.write++;
}
}
core->counters->load_bypass.read++;
#endif
/* we thought this output would be ready later in the future, but it's ready now! */
if(uop->timing.when_otag_ready > (core->sim_cycle+fp_penalty))
uop->timing.when_otag_ready = core->sim_cycle+fp_penalty;
/* bypass output value to dependents, but also check to see if
dependents were already speculatively scheduled; if not,
wake them up. */
struct odep_t * odep = uop->exec.odep_uop;
while(odep)
{
/* check scheduling info (tags) */
if(odep->uop->timing.when_itag_ready[odep->op_num] > (core->sim_cycle+fp_penalty))
{
int j;
tick_t when_ready = 0;
odep->uop->timing.when_itag_ready[odep->op_num] = core->sim_cycle+fp_penalty;
for(j=0;j<MAX_IDEPS;j++)
if(when_ready < odep->uop->timing.when_itag_ready[j])
when_ready = odep->uop->timing.when_itag_ready[j];
if(when_ready < TICK_T_MAX)
{
odep->uop->timing.when_ready = when_ready;
}
}
#ifdef ZESTO_COUNTERS
if(uop->exec.when_data_loaded != TICK_T_MAX)
{
if((odep->uop->timing.when_allocated != TICK_T_MAX)&&(!odep->uop->exec.ivalue_valid[odep->op_num]))
{
core->counters->RS.write++;
}
}
#endif
/* bypass value if the odep is outside of the fused uop */
if(uop->decode.fusion_head != odep->uop->decode.fusion_head)
zesto_assert(!odep->uop->exec.ivalue_valid[odep->op_num],(void)0);
odep->uop->exec.ivalue_valid[odep->op_num] = true;
if(odep->aflags) /* shouldn't happen for loads? */
{
warn("load modified flags?\n");
odep->uop->exec.ivalue[odep->op_num].dw = uop->exec.oflags;
}
else
odep->uop->exec.ivalue[odep->op_num] = uop->exec.ovalue;
odep->uop->timing.when_ival_ready[odep->op_num] = core->sim_cycle+fp_penalty;
odep = odep->next;
}
}
}
}
}
}
}
}
/* used for accesses that can be serviced entirely by one cacheline,
or by the first access of a split-access */
void core_exec_atom_t::DL1_callback(void * const op)
{
}
/* used only for the second access of a split access */
void core_exec_atom_t::DL1_split_callback(void * const op)
{
}
void core_exec_atom_t::DTLB_callback(void * const op)
{
}
/* returns true if TLB translation has completed */
bool core_exec_atom_t::translated_callback(void * const op, const seq_t action_id)
{
return true;
}
/* Used by the cache processing functions to recover the id of the
uop without needing to know about the uop struct. */
seq_t core_exec_atom_t::get_uop_action_id(void * const op)
{
struct uop_t const * uop = (struct uop_t*) op;
return uop->exec.action_id;
}
/* This function takes care of uops that have been misscheduled due
to a latency misprediction (e.g., they got scheduled assuming
the parent uop would hit in the DL1, but it turns out that the
load latency will be longer due to a cache miss). Uops may be
speculatively rescheduled based on the next anticipated latency
(e.g., L2 hit latency). */
void core_exec_atom_t::load_miss_reschedule(void * const op, const int new_pred_latency)
{
}
/* process loads exiting the STQ search pipeline, update caches */
void core_exec_atom_t::LDST_exec(void)
{
struct core_knobs_t * knobs = core->knobs;
int i;
/* Enqueue Loads to the cache - Loads are enqueued in the load pipeline up to the pipeline latency */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
int j;
for(j=0;j<port[i].num_FU_types;j++)
{
enum md_fu_class FU_type = port[i].FU_types[j];
struct ALU_t * FU = port[i].FU[FU_type];
int stage;
if(FU)
stage = FU->latency-1;
if(FU && (FU->occupancy > 0) )
for(;stage>0;stage--)
{
if(!FU->pipe[stage].load_enqueued && !FU->pipe[stage].load_received && FU->pipe[stage].uop)
{
struct uop_t * uop = FU->pipe[stage].uop;
if(uop->decode.in_fusion)
{
struct uop_t * fusion_uop = uop->decode.fusion_head;
zesto_assert(fusion_uop == uop, (void)0);
while(uop)
{
if(uop->decode.is_load)
break;
uop = uop->decode.fusion_next;
}
/* If none of them is a load, continue to the previous stage */
if(uop==NULL)
continue;
}
if(uop && uop->decode.is_load)
{
//cache_req* request = new cache_req(core->request_id, core->id, uop->oracle.phys_addr, OpMemLd, INITIAL);
ZestoCacheReq* request = new ZestoCacheReq(core->request_id, core->id, uop->oracle.phys_addr, ZestoCacheReq::LOAD);
uop->exec.when_data_loaded = TICK_T_MAX;
uop->exec.when_addr_translated = TICK_T_MAX;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d in load_enqueue ADDR %llx in_fusion %d port %d FU_type %d stage %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,uop->oracle.phys_addr,uop->decode.in_fusion,i,j,stage);
#endif
/* Issue a new Preq and corresponding Mreq */
core_t::Preq preq;
//preq.index = index;
preq.index = 0;
preq.thread_id = core->current_thread->id;
preq.action_id = uop->exec.action_id;
core->my_map.insert(std::pair<int, core_t::Preq>(core->request_id, preq));
core->request_id++;
/* Marking the load is already enqueued into the memory system */
FU->pipe[stage].load_enqueued =true;
FU->pipe[stage].load_received =false;
/* Actually enqueueing the request to cache*/
core->Send<ZestoCacheReq*>(core_t::PORT0, request);
}
}
}
}
}
}
/* Schedule load uops to execute from the LDQ. Load execution occurs in a two-step
process: first the address gets computed (issuing from the RS), and then the
cache/STQ search occur (issuing from the LDQ). */
void core_exec_atom_t::LDQ_schedule(void)
{
}
/* Process actual execution (in ALUs) of uops, as well as shuffling of
uops through the payload latch. */
void core_exec_atom_t::ALU_exec(void)
{
struct core_knobs_t * knobs = core->knobs;
int i;
if(check_for_work == false)
return;
bool work_found = false;
/* Process Functional Units */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
int j;
for(j=0;j<port[i].num_FU_types;j++)
{
enum md_fu_class FU_type = port[i].FU_types[j];
struct ALU_t * FU = port[i].FU[FU_type];
if(FU && (FU->occupancy > 0))
{
work_found = true;
/* process last stage of FU pipeline (those uops completing execution) */
int stage = FU->latency-1;
struct uop_t * uop = FU->pipe[stage].uop;
/* For fused uops we need to know if all of them have completed to mark the FU->stage.uop as exec_complete */
int all_complete=true;
/* We need to iterate thru multiple uops if they are fused together, all_complete tracks
if all have completed and the uop is ready to commit */
while(uop)
{
int squashed;
if(uop->decode.in_fusion)
squashed = (FU->pipe[stage].action_id != uop->decode.fusion_head->exec.action_id);
else
squashed = (FU->pipe[stage].action_id != uop->exec.action_id);
if(uop->Mop->core->id != core->id)
{
squashed=true;
}
if(uop->timing.when_completed != TICK_T_MAX)
{
if(uop->decode.in_fusion)
{
uop = uop->decode.fusion_next;
continue;
}
else
{
if(uop->Mop->oracle.spec_mode == false)
break;
}
}
if(uop->Mop->oracle.spec_mode==true) //&& uop->Mop->decode.op == NOP)
squashed=true;
/* there's a uop completing execution (that hasn't been squashed) */
if(!squashed)// && (!needs_bypass || bypass_available))
{
#ifdef ZESTO_COUNTERS
core->counters->latch.FU2ROB.read++;
if((!uop->decode.in_fusion||(uop->decode.in_fusion&&(uop->decode.fusion_next == NULL)))\
&&uop->exec.ovalue_valid)
{
core->counters->ROB.write++; // this uop is done
}
#endif
if(!(uop->decode.is_sta||uop->decode.is_std||uop->decode.is_load||uop->decode.is_ctrl))
{
port[i].when_bypass_used = core->sim_cycle;
#ifdef ZESTO_COUNTERS
core->counters->exec_bypass.read++;
#endif
}
if(uop->decode.is_load) /* loads need to be processed differently */
{
/*Check the store buffer for a matching store. If found the uop completes else it waits for load_writeback() function to get completed*/
int j=STQ_head;
while(j!=STQ_tail && STQ[j].sta!=NULL )
{
int st_mem_size = STQ[j].mem_size;
int ld_mem_size = uop->decode.mem_size;
md_addr_t st_addr1 = STQ[j].virt_addr; /* addr of first byte */
md_addr_t st_addr2 = STQ[j].virt_addr + st_mem_size - 1; /* addr of last byte */
md_addr_t ld_addr1 = uop->oracle.virt_addr;
md_addr_t ld_addr2 = uop->oracle.virt_addr + ld_mem_size - 1;
if((st_addr1 <= ld_addr1) && (st_addr2 >= ld_addr2)) /* match */
{
if(uop->timing.when_completed != TICK_T_MAX)
{
uop->Mop->fetch.branch_mispred = false;
core->oracle->pipe_flush(uop->Mop);
ZESTO_STAT(core->stat.load_nukes++;)
if(uop->Mop->oracle.spec_mode)
ZESTO_STAT(core->stat.wp_load_nukes++;)
#ifdef ZTRACE
ztrace_print(uop,"e|order-violation|matching store found but load already executed");
#endif
}
else
{
#ifdef ZESTO_COUNTERS
core->counters->storeQ.read++;
core->counters->latch.SQ2LQ.read++; // STQ2ROB (no LDQ)
if((!uop->decode.in_fusion)||(uop->decode.in_fusion&&(uop->decode.fusion_next == NULL))) // this uop is done
{
core->counters->ROB.write++;
}
core->counters->load_bypass.read++;
#endif
int fp_penalty = REG_IS_FPR(uop->decode.odep_name)?knobs->exec.fp_penalty:0;
uop->exec.ovalue = STQ[j].value;
uop->exec.ovalue_valid = true;
zesto_assert(uop->timing.when_completed == TICK_T_MAX,(void)0);
uop->timing.when_completed = core->sim_cycle+fp_penalty;
uop->timing.when_exec = core->sim_cycle+fp_penalty;
if(uop->decode.is_ctrl && (uop->Mop->oracle.NextPC != uop->Mop->fetch.pred_NPC)) /* for RETN */
{
uop->Mop->fetch.branch_mispred = true;
core->oracle->pipe_recover(uop->Mop,uop->Mop->oracle.NextPC);
ZESTO_STAT(core->stat.num_jeclear++;)
if(uop->Mop->oracle.spec_mode)
ZESTO_STAT(core->stat.num_wp_jeclear++;)
#ifdef ZTRACE
ztrace_print(uop,"e|jeclear|load/RETN mispred detected in STQ hit");
#endif
}
/* we thought this output would be ready later in the future, but it's ready now! */
if(uop->timing.when_otag_ready > (core->sim_cycle+fp_penalty))
uop->timing.when_otag_ready = core->sim_cycle+fp_penalty;
struct odep_t * odep = uop->exec.odep_uop;
while(odep)
{
/* check scheduling info (tags) */
if(odep->uop->timing.when_itag_ready[odep->op_num] > core->sim_cycle)
{
int j;
tick_t when_ready = 0;
odep->uop->timing.when_itag_ready[odep->op_num] = core->sim_cycle+fp_penalty;
for(j=0;j<MAX_IDEPS;j++)
if(when_ready < odep->uop->timing.when_itag_ready[j])
when_ready = odep->uop->timing.when_itag_ready[j];
if(when_ready < TICK_T_MAX)
{
odep->uop->timing.when_ready = when_ready;
}
}
#ifdef ZESTO_COUNTERS
if((odep->uop->timing.when_allocated != TICK_T_MAX)&&(!odep->uop->exec.ivalue_valid[odep->op_num]))
{
core->counters->RS.write++;
}
#endif
/* bypass output value to dependents */
odep->uop->exec.ivalue_valid[odep->op_num] = true;
if(odep->aflags) /* shouldn't happen for loads? */
{
warn("load modified flags?");
odep->uop->exec.ivalue[odep->op_num].dw = uop->exec.oflags;
}
else
odep->uop->exec.ivalue[odep->op_num] = uop->exec.ovalue;
odep->uop->timing.when_ival_ready[odep->op_num] = core->sim_cycle+fp_penalty;
odep = odep->next;
}
}
FU->pipe[stage].load_enqueued = false;
FU->pipe[stage].load_received = true;
uop->exec.exec_complete = true;
break;
}/* End of code for matching store buffer entry */
else
{
/* If it does not match the store buffer but is marked as load_received, it means the uop has completed execution. */
if(FU->pipe[stage].load_received==true)
{
FU->pipe[stage].completed=true;
uop->exec.exec_complete =true;
}
}
j=modinc(j,knobs->exec.STQ_size);
}/* End of the loop that searches the Store buffer for possible hits */
/* update load queue entry */
if(FU->pipe[stage].load_received==true)
{
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d Load Received and marked completed PORT %d in_fusion %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,i,uop->decode.in_fusion);
#endif
FU->pipe[stage].completed=true;
uop->exec.exec_complete =true;
}
}/*End of Handling of load uop*/
else
{
int fp_penalty = ((REG_IS_FPR(uop->decode.odep_name) && !(uop->decode.opflags & F_FCOMP)) ||
(!REG_IS_FPR(uop->decode.odep_name) && (uop->decode.opflags & F_FCOMP)))?knobs->exec.fp_penalty:0;
/* TODO: real execute-at-execute of instruction */
/* XXX for now just copy oracle value */
uop->exec.ovalue_valid = true;
uop->exec.ovalue = uop->oracle.ovalue;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d Reached last stage of execution PORT %d in_fusion %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,i,uop->decode.in_fusion);
#endif
/* alloc, uopQ, and decode all have to search for the
recovery point (Mop) because a long flow may have
uops that span multiple sections of the latch. */
if(uop->decode.is_ctrl && (uop->Mop->oracle.NextPC != uop->Mop->fetch.pred_NPC) && (uop->Mop->decode.is_intr != true) )
{
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]Branch mispredicted ",core->sim_cycle,core->id);
#endif
/* in case this instruction gets flushed more than once (jeclear followed by load-nuke) */
uop->Mop->fetch.pred_NPC = uop->Mop->oracle.NextPC;
uop->Mop->fetch.branch_mispred = true;
core->oracle->pipe_recover(uop->Mop,uop->Mop->oracle.NextPC);
ZESTO_STAT(core->stat.num_jeclear++;)
if(uop->Mop->oracle.spec_mode)
ZESTO_STAT(core->stat.num_wp_jeclear++;)
#ifdef ZTRACE
ztrace_print(uop,"e|jeclear|branch mispred detected at execute");
#endif
uop->exec.exec_complete =true;
}
else if(uop->decode.is_sta) /* STQ to be treated as a store buffer */
{
if(STQ_available())
{
STQ_insert_sta(uop);
zesto_assert((uop->alloc.STQ_index >= 0) && (uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
zesto_assert(!STQ[uop->alloc.STQ_index].addr_valid,(void)0);
STQ[uop->alloc.STQ_index].virt_addr = uop->oracle.virt_addr;
STQ[uop->alloc.STQ_index].addr_valid = true;
uop->exec.exec_complete =true;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write_tag++; // addr tag
#endif
}
}
else if(uop->decode.is_std) /* STQ to be treated as a store buffer */
{
STQ_insert_std(uop);
STQ[uop->alloc.STQ_index].value = uop->exec.ovalue;
STQ[uop->alloc.STQ_index].value_valid = true;
uop->exec.exec_complete =true;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write++; // data
#endif
}
else /* Everything that is not a load or a store or a mispredicted branch */
{
uop->exec.exec_complete =true;
}
fflush(stdout);
zesto_assert(uop->timing.when_completed == TICK_T_MAX,(void)0);
uop->timing.when_completed = core->sim_cycle+fp_penalty;
/* bypass output value to dependents */
struct odep_t * odep = uop->exec.odep_uop;
while(odep)
{
#ifdef ZESTO_COUNTERS
if((odep->uop->timing.when_allocated != TICK_T_MAX)&&(!odep->uop->exec.ivalue_valid[odep->op_num]))
core->counters->RS.write++;
#endif
if(uop->decode.fusion_head != odep->uop->decode.fusion_head)
zesto_assert(!odep->uop->exec.ivalue_valid[odep->op_num],(void)0);
odep->uop->exec.ivalue_valid[odep->op_num] = true;
if(odep->aflags)
odep->uop->exec.ivalue[odep->op_num].dw = uop->exec.oflags;
else
odep->uop->exec.ivalue[odep->op_num] = uop->exec.ovalue;
odep->uop->timing.when_ival_ready[odep->op_num] = core->sim_cycle+fp_penalty;
odep = odep->next;
}
} /* End of handling all uops that were not loads */
}
else /* uop and FU->pipe[stage] action id do not match */
{
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d Squashed in_fusion %d ",core->sim_cycle,core->id,FU->pipe[stage].uop->decode.Mop_seq,FU->pipe[stage].uop->decode.uop_seq,FU->pipe[stage].uop->decode.in_fusion);
#endif
FU->pipe[stage].uop =NULL;
FU->pipe[stage].completed = false;
FU->pipe[stage].load_enqueued = false;
FU->pipe[stage].load_received = false;
FU->occupancy--;
}
/* all_complete is a variable that captures if the load has been completed by store to load transfer
or after being returned from the cache(set in load_writeback)*/
all_complete &=uop->exec.exec_complete;
if(uop->decode.in_fusion)
{
uop = uop->decode.fusion_next;
}
else /* Single uop occupying the stage and thus it has only one iteration of the while loop */
uop = NULL;
} /* End of while loop which iterates through all the fused uops that occupy the stage */
/* If all the uops have been completed all_complete should be true */
if(all_complete)
FU->pipe[stage].completed=true;
}
}
} /* End of the loop that goes through the last stages of all the ports and all the FUs marking completed uops in that port */
/* Loops through all the last stages again and retire the uops from the Mop that is at the head of the commit queue */
seq_t commit_seq =last_Mop_seq;
bool all_done=false;
for(int width=2;width>0;width--)
{
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
int j;
for(j=0;j<port[i].num_FU_types;j++)
{
enum md_fu_class FU_type = port[i].FU_types[j];
struct ALU_t * FU = port[i].FU[FU_type];
if(FU && (FU->occupancy > 0))
{
int stage = FU->latency-1;
if(FU->pipe[stage].uop)
{
if( FU->pipe[stage].uop->decode.Mop_seq <= commit_seq)
{
if(FU->pipe[stage].completed==false)
{
all_done &=false;
}
else
{
if(FU->pipe[stage].uop->decode.in_fusion)
{
struct uop_t * fusion_uop = FU->pipe[stage].uop->decode.fusion_head;
while(fusion_uop)
{
fusion_uop->exec.commit_done=true;
fusion_uop = fusion_uop->decode.fusion_next;
}
}
else
{
FU->pipe[stage].uop->exec.commit_done=true;
}
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d in exiting exec stage in_fusion %d ",core->sim_cycle,core->id,FU->pipe[stage].uop->decode.Mop_seq,FU->pipe[stage].uop->decode.uop_seq,FU->pipe[stage].uop->decode.in_fusion);
#endif
FU->pipe[stage].uop =NULL;
FU->pipe[stage].completed = false;
FU->pipe[stage].load_enqueued = false;
FU->pipe[stage].load_received = false;
FU->occupancy--;
last_completed=core->sim_cycle;
}
}
}
}
}
}
if(!all_done)
break;
commit_seq++; /*2-way superscalar so we try to commit two Mops per cycle whereever possible*/
}
/* shuffle the rest of the stages forward */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
int j;
for(j=0;j<port[i].num_FU_types;j++)
{
enum md_fu_class FU_type = port[i].FU_types[j];
struct ALU_t * FU = port[i].FU[FU_type];
if(FU && (FU->occupancy > 0))
{
int stage = FU->latency-1;
if(FU->occupancy > 0)
{
for( /*nada*/; stage > 0; stage--)
{
if(FU->pipe[stage-1].uop && ( FU->pipe[stage].uop == NULL ) )
{
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC shuffling stages Port %d FU_class %d MOP=%d UOP=%d stage%d to stage%d in_fusion %d MopCore %d ",core->sim_cycle,core->id,i,FU_type,FU->pipe[stage-1].uop->decode.Mop_seq,FU->pipe[stage-1].uop->decode.uop_seq,stage-1,stage,FU->pipe[stage-1].uop->decode.in_fusion,FU->pipe[stage-1].uop->Mop->core->id);
if(core->sim_cycle > PRINT_CYCLE )
md_print_insn(FU->pipe[stage-1].uop->Mop,stdout);
#endif
if(FU->pipe[stage-1].uop->Mop->core->id ==core->id)
{
FU->pipe[stage] = FU->pipe[stage-1];
FU->pipe[stage-1].uop = NULL;
zesto_assert(FU->pipe[stage-1].completed == false,(void)0);
}
else
{
FU->pipe[stage-1].uop = NULL;
}
}
}
}
}
}
}
/* Process Payload RAM pipestages */
for(i=0;i<knobs->exec.num_exec_ports;i++)
{
if(port[i].occupancy > 0)
{
int stage = knobs->exec.payload_depth-1;
struct uop_t * uop = port[i].payload_pipe[stage].uop;
work_found = true;
/* uops leaving payload section go to their respective FU's */
if(uop && (port[i].payload_pipe[stage].action_id == uop->exec.action_id)) /* uop is valid, hasn't been squashed */
{
int j;
int all_ready = true;
enum md_fu_class FU_class = uop->decode.FU_class;
for(j=0;j<MAX_IDEPS;j++)
all_ready &= uop->exec.ivalue_valid[j];
if(uop->decode.in_fusion) /*Only move forward if all the fused uops are ready to move*/
{
struct uop_t * fusion_uop = uop->decode.fusion_head;
zesto_assert(fusion_uop == uop, (void)0);
while(fusion_uop)
{
for(int k=0;k<MAX_IDEPS;k++)
{
if(fusion_uop->exec.idep_uop[k])
if(fusion_uop->oracle.idep_uop[k]->decode.in_fusion)
if(fusion_uop->oracle.idep_uop[k]->decode.fusion_head == fusion_uop->decode.fusion_head )
fusion_uop->exec.ivalue_valid[k] = true;
all_ready &= fusion_uop->exec.ivalue_valid[k];
}
fusion_uop = fusion_uop->decode.fusion_next;
}
}
/* have all input values arrived and FU available? */
if((!all_ready) || (port[i].FU[FU_class]->pipe[0].uop != NULL) || (port[i].FU[FU_class]->when_executable > core->sim_cycle))
{
for(j=0;j<MAX_IDEPS;j++)
{
if((!uop->exec.ivalue_valid[j]) && uop->oracle.idep_uop[j] && (uop->oracle.idep_uop[j]->timing.when_otag_ready < core->sim_cycle))
{
uop->timing.when_ready = core->sim_cycle+BIG_LATENCY;
}
}
continue;
}
else /*We have a uop or a fused uop that is ready and can be dispatched to the excution units*/
{
if(uop->decode.in_fusion)
uop->decode.fusion_head->exec.uops_in_RS--;
#ifdef ZTRACE
ztrace_print_start(uop,"e|payload|uop goes to ALU");
#endif
#ifdef ZTRACE
ztrace_print_cont(", deallocates from RS");
#endif
uop->timing.when_exec = core->sim_cycle;
/* this port has the proper FU and the first stage is free. */
zesto_assert(port[i].FU[FU_class] && (port[i].FU[FU_class]->pipe[0].uop == NULL),(void)0);
port[i].FU[FU_class]->pipe[0].uop = uop;
port[i].FU[FU_class]->pipe[0].action_id = uop->exec.action_id;
port[i].FU[FU_class]->occupancy++; /*occupancy is not incremented for each uop in a fused set*/
port[i].FU[FU_class]->when_executable = core->sim_cycle + port[i].FU[FU_class]->issue_rate;
port[i].FU[FU_class]->pipe[0].load_enqueued = false;
port[i].FU[FU_class]->pipe[0].load_received = false;
port[i].FU[FU_class]->pipe[0].completed = false;
check_for_work = true;
port[i].occupancy--;
zesto_assert(port[i].occupancy >= 0,(void)0);
#ifdef ZESTO_COUNTERS
core->counters->FU[i].read++;
#endif
#ifdef ZESTO_COUNTERS
core->counters->payload.read++;
core->counters->latch.PR2FU.read++;
#endif
}
}
else if(uop && (port[i].payload_pipe[stage].action_id != uop->exec.action_id)) /* uop has been squashed */
{
#ifdef ZTRACE
ztrace_print(uop,"e|payload|on exit from payload, uop discovered to have been squashed");
#endif
port[i].payload_pipe[stage].uop = NULL;
port[i].occupancy--;
zesto_assert(port[i].occupancy >= 0,(void)0);
#ifdef ZESTO_COUNTERS
core->counters->payload.write++;
#endif
}
/* shuffle the other uops through the payload pipeline */
for(/*nada*/; stage > 0; stage--)
{
port[i].payload_pipe[stage] = port[i].payload_pipe[stage-1];
port[i].payload_pipe[stage-1].uop = NULL;
}
port[i].payload_pipe[0].uop = NULL;
} /* End of if loop that is executed if occupancy is more than zero on the port */
} /* End of the big loop that goes through all the ports */
check_for_work = work_found;
}
void core_exec_atom_t::recover(const struct Mop_t * const Mop)
{
/* most flushing/squashing is accomplished through assignments of new action_id's */
}
void core_exec_atom_t::recover(void)
{
/* most flushing/squashing is accomplished through assignments of new action_id's */
}
bool core_exec_atom_t::RS_available(int port)
{
struct core_knobs_t * knobs = core->knobs;
//return RS_num < knobs->exec.RS_size;
return(RS[port]==NULL);
}
/* assumes you already called RS_available to check that
an entry is available */
void core_exec_atom_t::RS_insert(struct uop_t * const uop)
{
struct core_knobs_t * knobs = core->knobs;
zesto_assert(RS[uop->alloc.port_assignment] == NULL ,(void)0);
RS[uop->alloc.port_assignment] = uop;
RS_num++;
RS_eff_num++;
uop->alloc.RS_index = uop->alloc.port_assignment;
#ifdef ZESTO_COUNTERS
core->counters->RS.write++;
#endif
if(uop->decode.in_fusion)
uop->exec.uops_in_RS ++; /* used to track when RS can be deallocated */
uop->alloc.full_fusion_allocated = false;
}
/* add uops to an existing entry (where all uops in the same
entry are assumed to be fused) */
void core_exec_atom_t::RS_fuse_insert(struct uop_t * const uop)
{
/* fusion body shares same RS entry as fusion head */
uop->alloc.RS_index = uop->decode.fusion_head->alloc.RS_index;
RS_eff_num++;
uop->decode.fusion_head->exec.uops_in_RS ++;
if(uop->decode.fusion_next == NULL)
uop->decode.fusion_head->alloc.full_fusion_allocated = true;
#ifdef ZESTO_COUNTERS
core->counters->RS.write++;
#endif
}
void core_exec_atom_t::RS_deallocate(struct uop_t * const dead_uop)
{
struct core_knobs_t * knobs = core->knobs;
zesto_assert(dead_uop->alloc.RS_index < knobs->exec.RS_size,(void)0);
if(dead_uop->decode.in_fusion && (dead_uop->timing.when_exec == TICK_T_MAX))
{
dead_uop->decode.fusion_head->exec.uops_in_RS --;
RS_eff_num--;
}
if(!dead_uop->decode.in_fusion)
{
RS_eff_num--;
zesto_assert(RS_eff_num >= 0,(void)0);
}
if(dead_uop->decode.is_fusion_head)
zesto_assert(dead_uop->exec.uops_in_RS == 0,(void)0);
if((!dead_uop->decode.in_fusion) || dead_uop->decode.is_fusion_head) /* make head uop responsible for deallocating RS during recovery */
{
RS[dead_uop->alloc.RS_index] = NULL;
RS_num --;
zesto_assert(RS_num >= 0,(void)0);
#ifdef ZESTO_COUNTERS
core->counters->RS.write_tag++;
#endif
}
dead_uop->alloc.RS_index = -1;
}
bool core_exec_atom_t::LDQ_available(void)
{
return true;
}
void core_exec_atom_t::LDQ_insert(struct uop_t * const uop)
{
}
/* called by commit */
void core_exec_atom_t::LDQ_deallocate(struct uop_t * const uop)
{
}
void core_exec_atom_t::LDQ_squash(struct uop_t * const dead_uop)
{
}
bool core_exec_atom_t::STQ_available(void)
{
struct core_knobs_t * knobs = core->knobs;
return STQ_num < knobs->exec.STQ_size;
}
void core_exec_atom_t::STQ_insert_sta(struct uop_t * const uop)
{
struct core_knobs_t * knobs = core->knobs;
memzero(&STQ[STQ_tail],sizeof(*STQ));
STQ[STQ_tail].sta = uop;
if(STQ[STQ_tail].sta != NULL)
uop->decode.is_sta = true;
STQ[STQ_tail].mem_size = uop->decode.mem_size;
STQ[STQ_tail].uop_seq = uop->decode.uop_seq;
STQ[STQ_tail].value_valid= true;
uop->alloc.STQ_index = STQ_tail;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d put store in SB STA %llx in_fusion %d STQ entry %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,uop->oracle.phys_addr,uop->decode.in_fusion,STQ_tail);
#endif
STQ_num++;
STQ_tail = modinc(STQ_tail,knobs->exec.STQ_size); //(STQ_tail+1) % knobs->exec.STQ_size;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write++;
#endif
}
void core_exec_atom_t::STQ_insert_std(struct uop_t * const uop)
{
struct core_knobs_t * knobs = core->knobs;
/* STQ_tail already incremented from the STA. Just add this uop to STQ->std */
int index = moddec(STQ_tail,knobs->exec.STQ_size); //(STQ_tail - 1 + knobs->exec.STQ_size) % knobs->exec.STQ_size;
uop->alloc.STQ_index = index;
STQ[index].std = uop;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d put store in SB STD %llx in_fusion %d STQ entry %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,uop->oracle.phys_addr,uop->decode.in_fusion,index);
#endif
}
void core_exec_atom_t::STQ_deallocate_sta(void)
{
}
/* returns true if successful */
bool core_exec_atom_t::STQ_deallocate_std(struct uop_t * const uop)
{
struct core_knobs_t * knobs = core->knobs;
return true;
}
void core_exec_atom_t::STQ_deallocate_senior(void)
{
struct core_knobs_t * knobs = core->knobs;
struct uop_t * uop = STQ[STQ_head].sta;
if(uop && STQ[STQ_head].addr_valid && STQ[STQ_head].value_valid)
{
STQ[STQ_head].translation_complete = true; //TODO No support fot TLBs yet so we assume translation complete, otherwise this would be false
STQ[STQ_head].write_complete = false;
///*The mem request to send the load to the cache*/
//cache_req* request = new cache_req(core->request_id, core->id, uop->oracle.phys_addr, OpMemSt, INITIAL);
ZestoCacheReq* request = new ZestoCacheReq(core->request_id, core->id, uop->oracle.phys_addr, ZestoCacheReq::STORE);
#ifdef ZESTO_COUNTERS
core->counters->latch.SQ2L1.read++;
core->counters->storeQ.read++;
#endif
/** Issue a new Preq and corresponding Mreq. */
core_t::Preq preq;
preq.index = uop->alloc.STQ_index;
preq.thread_id = core->current_thread->id;
preq.action_id = STQ[STQ_head].action_id;
core->my_map.insert(std::pair<int, core_t::Preq>(core->request_id, preq));
core->request_id++;
#ifdef ZDEBUG
if(core->sim_cycle > PRINT_CYCLE )
fprintf(stdout,"\n[%lld][Core%d]EXEC MOP=%d UOP=%d store_enqueue %llx in_fusion %d ",core->sim_cycle,core->id,uop->decode.Mop_seq,uop->decode.uop_seq,uop->oracle.phys_addr,uop->decode.in_fusion);
#endif
/*Actually enqueueing the request to cache*/
core->Send<ZestoCacheReq*>(core_t::PORT0, request); // sendtick?
#ifdef ZTRACE
ztrace_print(uop,"c|store|store enqueued to DL1/DTLB");
#endif
STQ[STQ_head].sta=NULL;
STQ[STQ_head].std=NULL;
STQ[STQ_head].value_valid = false;
STQ_num --;
STQ_head = modinc(STQ_head,knobs->exec.STQ_size); //(STQ_head+1) % knobs->exec.STQ_size;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write_tag++;
#endif
}
}
void core_exec_atom_t::STQ_squash_sta(struct uop_t * const dead_uop)
{
struct core_knobs_t * knobs = core->knobs;
zesto_assert((dead_uop->alloc.STQ_index >= 0) && (dead_uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
zesto_assert(STQ[dead_uop->alloc.STQ_index].std == NULL,(void)0);
zesto_assert(STQ[dead_uop->alloc.STQ_index].sta == dead_uop,(void)0);
memzero(&STQ[dead_uop->alloc.STQ_index],sizeof(STQ[0]));
STQ_num --;
STQ_senior_num --;
STQ_tail = moddec(STQ_tail,knobs->exec.STQ_size); //(STQ_tail - 1 + knobs->exec.STQ_size) % knobs->exec.STQ_size;
zesto_assert(STQ_num >= 0,(void)0);
zesto_assert(STQ_senior_num >= 0,(void)0);
dead_uop->alloc.STQ_index = -1;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write_tag++;
#endif
}
void core_exec_atom_t::STQ_squash_std(struct uop_t * const dead_uop)
{
struct core_knobs_t * knobs = core->knobs;
zesto_assert((dead_uop->alloc.STQ_index >= 0) && (dead_uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
zesto_assert(STQ[dead_uop->alloc.STQ_index].std == dead_uop,(void)0);
STQ[dead_uop->alloc.STQ_index].std = NULL;
dead_uop->alloc.STQ_index = -1;
}
void core_exec_atom_t::STQ_squash_senior(void)
{
struct core_knobs_t * knobs = core->knobs;
while(STQ_senior_num > 0)
{
memzero(&STQ[STQ_senior_head],sizeof(*STQ));
STQ[STQ_senior_head].action_id = core->new_action_id();
if((STQ_senior_head == STQ_head) && (STQ_num>0))
{
STQ_head = modinc(STQ_head,knobs->exec.STQ_size); //(STQ_head + 1) % knobs->exec.STQ_size;
STQ_num--;
#ifdef ZESTO_COUNTERS
core->counters->storeQ.write_tag++;
#endif
}
STQ_senior_head = modinc(STQ_senior_head,knobs->exec.STQ_size); //(STQ_senior_head + 1) % knobs->exec.STQ_size;
STQ_senior_num--;
}
}
void core_exec_atom_t::recover_check_assertions(void)
{
zesto_assert(STQ_senior_num == 0,(void)0);
zesto_assert(STQ_num == 0,(void)0);
zesto_assert(LDQ_num == 0,(void)0);
zesto_assert(RS_num == 0,(void)0);
}
bool core_exec_atom_t::has_load_arrived(int LDQ_index)
{
return(LDQ[LDQ_index].last_byte_arrived & LDQ[LDQ_index].first_byte_arrived);
}
unsigned long long int core_exec_atom_t::get_load_latency(int LDQ_index)
{
return (LDQ[LDQ_index].when_issued );
}
/* Stores don't write back to cache/memory until commit. When D$
and DTLB accesses complete, these functions get called which
update the status of the corresponding STQ entries. The STQ
entry cannot be deallocated until the store has completed. */
void core_exec_atom_t::store_dl1_callback(void * const op)
{
struct uop_t * uop = (struct uop_t *)op;
struct core_t * core = uop->core;
struct core_exec_atom_t * E = (core_exec_atom_t*)core->exec;
struct core_knobs_t * knobs = core->knobs;
#ifdef ZTRACE
ztrace_print(uop,"c|store|written to cache/memory");
#endif
zesto_assert((uop->alloc.STQ_index >= 0) && (uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
if(uop->exec.action_id == E->STQ[uop->alloc.STQ_index].action_id)
{
E->STQ[uop->alloc.STQ_index].first_byte_written = true;
if(E->STQ[uop->alloc.STQ_index].last_byte_written)
E->STQ[uop->alloc.STQ_index].write_complete = true;
}
core->return_uop_array(uop);
}
/* only used for the 2nd part of a split write */
void core_exec_atom_t::store_dl1_split_callback(void * const op)
{
struct uop_t * uop = (struct uop_t *)op;
struct core_t * core = uop->core;
struct core_exec_atom_t * E = (core_exec_atom_t*)core->exec;
struct core_knobs_t * knobs = core->knobs;
#ifdef ZTRACE
ztrace_print(uop,"c|store|written to cache/memory");
#endif
zesto_assert((uop->alloc.STQ_index >= 0) && (uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
if(uop->exec.action_id == E->STQ[uop->alloc.STQ_index].action_id)
{
E->STQ[uop->alloc.STQ_index].last_byte_written = true;
if(E->STQ[uop->alloc.STQ_index].first_byte_written)
E->STQ[uop->alloc.STQ_index].write_complete = true;
}
core->return_uop_array(uop);
}
void core_exec_atom_t::store_dtlb_callback(void * const op)
{
struct uop_t * uop = (struct uop_t *)op;
struct core_t * core = uop->core;
struct core_exec_atom_t * E = (core_exec_atom_t*)core->exec;
struct core_knobs_t * knobs = core->knobs;
#ifdef ZTRACE
ztrace_print(uop,"c|store|translated");
#endif
zesto_assert((uop->alloc.STQ_index >= 0) && (uop->alloc.STQ_index < knobs->exec.STQ_size),(void)0);
if(uop->exec.action_id == E->STQ[uop->alloc.STQ_index].action_id)
E->STQ[uop->alloc.STQ_index].translation_complete = true;
core->return_uop_array(uop);
}
bool core_exec_atom_t::store_translated_callback(void * const op, const seq_t action_id /* ignored */)
{
struct uop_t * uop = (struct uop_t *)op;
struct core_t * core = uop->core;
struct core_knobs_t * knobs = core->knobs;
struct core_exec_atom_t * E = (core_exec_atom_t*)core->exec;
if((uop->alloc.STQ_index == -1) || (uop->exec.action_id != E->STQ[uop->alloc.STQ_index].action_id))
return true;
zesto_assert((uop->alloc.STQ_index >= 0) && (uop->alloc.STQ_index < knobs->exec.STQ_size),true);
return E->STQ[uop->alloc.STQ_index].translation_complete;
}
void core_exec_atom_t::memory_callbacks(void)
{
while (core->m_input_from_cache.size() != 0)
{
ZestoCacheReq* request = core->m_input_from_cache.front();
zesto_assert(core->my_map.find(request->req_id) != core->my_map.end(), (void)0);
core_t::Preq preq = (core->my_map.find(request->req_id))->second;
core->my_map.erase(core->my_map.find(request->req_id));
/* Retire in that context */
zesto_assert(preq.thread_id == core->current_thread->id && "Requests thread_id does not match the running thread", (void)0);
if(request->type == ZestoCacheReq::LOAD) //Handling Loads
{
struct uop_t * uop = LDQ[preq.index].uop;
if(uop != NULL)
{
if(preq.action_id == uop->exec.action_id) // a valid load
{
DL1_callback(uop);
DL1_split_callback(uop);
DTLB_callback(uop);
}
}
}
delete(request);
core->m_input_from_cache.pop_front();
}
}
#endif
| 38.753669 | 352 | 0.613116 | [
"model"
] |
807a7878f2b86d810c89eef11e4ae7d434794919 | 19,925 | cpp | C++ | dev/floyd_speak/floyd_benchmark_main.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | dev/floyd_speak/floyd_benchmark_main.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | dev/floyd_speak/floyd_benchmark_main.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | //
// main.cpp
// megastruct
//
// Created by Marcus Zetterquist on 2019-01-28.
// Copyright © 2019 Marcus Zetterquist. All rights reserved.
//
#include "gtest/gtest.h"
#include "benchmark/benchmark.h"
#include <iostream>
#include <vector>
#if 0
/////////////////////////// CSoundEngine
#define CAtomicFIFO std::vector
typedef long TSpeakerID;
struct CSoundEngine;
struct TRealTimeSpeaker {
float fFractionPos;
float fRadius;
float fPitch;
float fX;
float fY;
float fLevel;
float fFilteredMic1Gain;
float fFilteredMic2Gain;
float fGainChangeK;
bool fPlayFlag;
bool fLoopFlag;
const std::int16_t* fSampleData;
long fChannels;
std::uint32_t fFrameCount;
};
class CSpeakerRef {
CSoundEngine* fSoundEngine;
TSpeakerID fID;
};
class CSoundEngine {
float fVolume;
CAtomicFIFO<TSpeakerID> fFreeSpeakerIDs;
std::list<TSpeakerID> fReferencedSpeakersIDs;
CAtomicFIFO<TRealTimeSpeaker> fRealTimeSpeakers;
int32_t fFlushCount;
int32_t fRenderCount;
float fMic1X;
float fMic1Y;
float fMic2X;
float fMic2Y;
long fMagic;
};
/*
GOAL: Manage memory accesses. Move things together, pack data (use CPU instructions to save memory accesses)
- Tag hot members = put them at top, in the same cache-line
Store data in unused bits of floats
We want to know exact ranges of integers so e can store only those bits.
- Vector of pixels, compress non-lossy! Key frames.
- Audio as vector<int16> -- compress with key frames. Skip silent sections,
- ZIP.
*/
/*
FloydNative__TRealTimeSpeaker
Stores 1.33 speakers per CL.
Checking playflag of 1024 speakers accessess 768 CLs. Worst case = 246 cycles * 768 = 188928 cycles for memory accesses
Checking distance to 1024 speakers accesses 768 CLs
CACHE LINE
BYTE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC DDD00000 00000000 00000000 00000000
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
EEEEEEEE EEEEEEEE EEEEEEEE EEEEEEEE FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF GGGGGGGG GGGGGGGG GGGGGGGG GGGGGGGG HHHHHHHH HHHHHHHH HHHHHHHH HHHHHHHH
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
IIIIIIII IIIIIIII IIIIIIII IIIIIIII JJJJJJJJ JJJJJJJJ JJJJJJJJ JJJJJJJJ KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK LLLLLLLL LLLLLLLL LLLLLLLL LLLLLLLL
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
*/
struct FloydNative__TRealTimeSpeaker {
float fX; // HOT A
float fRadius; // HOT B
float fY; // HOT C
// D (3bits) HOT
bool fPlayFlag; // HOT
bool fLoopFlag;
bool fChannels;
float fFractionPos; // E
float fPitch; // F
float fLevel; // G
float fFilteredMic1Gain; // H
float fFilteredMic2Gain; // I
float fGainChangeK; // J
// [int16_t] fSampleData; // K
int16_t* fSampleData__ptr; // K
int64_t fSampleData__count; // L
// long fChannels; // 1 or 2
};
// Faster to have struct of arrays of structs!
// NOTE: Reference & RC or deepcopy. No need for RC if copied.
struct FloydNative__CSoundEngine {
float fVolume;
CAtomicFIFO<TSpeakerID> fFreeSpeakerIDs;
std::list<TSpeakerID> fReferencedSpeakersIDs;
CAtomicFIFO<TRealTimeSpeaker> fRealTimeSpeakers;
int32_t fFlushCount;
int32_t fRenderCount;
float fMic1X;
float fMic1Y;
float fMic2X;
float fMic2Y;
long fMagic;
};
// ??? There can be several memory layouts for [TRealTimeSpeaker] -- need to convert between them, generate function-instanced for them etc.
/*
FloydNativeGenerated__TRealTimeSpeaker2__hot
Stores ONE bit per speaker = 512 speakers per cache line
Checking fPlayFlag of 1024 speakers accesses 2 CLs. Worst case = 246 cycles * 2 = 492 cycles for memory accesses.
CACHE LINE
BYTE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
*/
struct FloydNativeGenerated__TRealTimeSpeaker2__hot {
bool fPlayFlag; // HOT D1
};
/*
FloydNativeGenerated__TRealTimeSpeaker2__roomtemp
Stores 12 bytes per speaker = 5.333 speakers per cache line
Checking distance to 1024 speakers accesses 192 CLs. IMPORTANT: Number will be smaller since we only check distance of ENABLED speakers.
CACHE LINE
BYTE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC -------- -------- -------- --------
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
*/
struct FloydNativeGenerated__TRealTimeSpeaker2__roomtemp {
float fX; // HOT A
float fRadius; // HOT B
float fY; // HOT C
};
struct FloydNativeGenerated__TRealTimeSpeaker2__cold {
bool fLoopFlag; // D2
bool fChannels; // D3
float fFractionPos; // E
float fPitch; // F
float fLevel; // G
float fFilteredMic1Gain; // H
float fFilteredMic2Gain; // I
float fGainChangeK; // J
// [int16_t] fSampleData; // K
int16_t* fSampleData__ptr; // K
int64_t fSampleData__count; // L
};
// Faster to have struct of arrays of structs!
// NOTE: Reference & RC or deepcopy. No need for RC if copied.
struct FloydNative__CSoundEngine2 {
float fVolume;
CAtomicFIFO<TSpeakerID> fFreeSpeakerIDs;
std::list<TSpeakerID> fReferencedSpeakersIDs;
CAtomicFIFO<TRealTimeSpeaker> fRealTimeSpeakers;
int32_t fFlushCount;
int32_t fRenderCount;
float fMic1X;
float fMic1Y;
float fMic2X;
float fMic2Y;
long fMagic;
};
#endif
/*
Generate special create/delete/copy for each struct. It deeply bumps reference counters - no nesting. Flat number of RC bumps.
*/
/*
Cache line latency:
https://stackoverflow.com/questions/3928995/how-do-cache-lines-work
What every programmer should know about memory, Part 1
https://lwn.net/Articles/250967/
*/
/*
CACHE LINE
BYTE 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB CCCCCCCC CCCCCCCC CCCCCCCC CCCCCCCC DDD00000 00000000 00000000 00000000
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
EEEEEEEE EEEEEEEE EEEEEEEE EEEEEEEE FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF GGGGGGGG GGGGGGGG GGGGGGGG GGGGGGGG HHHHHHHH HHHHHHHH HHHHHHHH HHHHHHHH
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
IIIIIIII IIIIIIII IIIIIIII IIIIIIII JJJJJJJJ JJJJJJJJ JJJJJJJJ JJJJJJJJ KKKKKKKK KKKKKKKK KKKKKKKK KKKKKKKK LLLLLLLL LLLLLLLL LLLLLLLL LLLLLLLL
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|<------------------------------------------------------------------->| |<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
*/
/*
CACHE LINE
BYTE 0 1 2 3 4 5 6 7
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
8 9 10 11 12 13 14 15
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
16 17 18 19 20 21 22 23
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
24 25 26 27 28 29 30 31
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
32 33 34 35 36 37 38 39
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
40 41 42 43 44 45 46 47
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
48 49 50 51 52 53 54 55
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
56 57 58 59 60 61 62 63
|<------------------------------------------------------------------->|
-------- -------- -------- -------- -------- -------- -------- --------
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
*/
//////////////////////////////// BENCHMARK -- GOOGLE EXAMPLES
#if 0
int Factorial(int n)
{
if (n < 0 ) {
return 0;
}
return !n ? 1 : n * Factorial(n - 1);
}
// IDEA: Only have load/store of entire cache lines.
// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
EXPECT_EQ(Factorial(0), 1);
}
// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
EXPECT_EQ(Factorial(1), 1);
EXPECT_EQ(Factorial(2), 2);
EXPECT_EQ(Factorial(3), 6);
EXPECT_EQ(Factorial(8), 40320);
}
namespace {
double CalculatePi(int depth) {
double pi = 0.0;
for (int i = 0; i < depth; ++i) {
double numerator = static_cast<double>(((i % 2) * 2) - 1);
double denominator = static_cast<double>((2 * i) - 1);
pi += numerator / denominator;
}
return (pi - 1.0) * 4;
}
std::set<int64_t> ConstructRandomSet(int64_t size) {
std::set<int64_t> s;
for (int i = 0; i < size; ++i) s.insert(s.end(), i);
return s;
}
} // end namespace
static void BM_Factorial(benchmark::State& state) {
int fac_42 = 0;
for (auto _ : state) fac_42 = Factorial(8);
// Prevent compiler optimizations
std::stringstream ss;
ss << fac_42;
state.SetLabel(ss.str());
}
BENCHMARK(BM_Factorial);
BENCHMARK(BM_Factorial)->UseRealTime();
static void BM_CalculatePiRange(benchmark::State& state) {
double pi = 0.0;
for (auto _ : state) pi = CalculatePi(static_cast<int>(state.range(0)));
std::stringstream ss;
ss << pi;
state.SetLabel(ss.str());
}
BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);
static void BM_CalculatePi(benchmark::State& state) {
static const int depth = 1024;
for (auto _ : state) {
benchmark::DoNotOptimize(CalculatePi(static_cast<int>(depth)));
}
}
BENCHMARK(BM_CalculatePi)->Threads(8);
BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);
BENCHMARK(BM_CalculatePi)->ThreadPerCpu();
static void BM_SetInsert(benchmark::State& state) {
std::set<int64_t> data;
for (auto _ : state) {
state.PauseTiming();
data = ConstructRandomSet(state.range(0));
state.ResumeTiming();
for (int j = 0; j < state.range(1); ++j) data.insert(rand());
}
state.SetItemsProcessed(state.iterations() * state.range(1));
state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int));
}
// Test many inserts at once to reduce the total iterations needed. Otherwise, the slower,
// non-timed part of each iteration will make the benchmark take forever.
BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}});
#endif
#if 0
template <typename Container,
typename ValueType = typename Container::value_type>
static void BM_Sequential(benchmark::State& state) {
ValueType v = 42;
for (auto _ : state) {
Container c;
for (int64_t i = state.range(0); --i;) c.push_back(v);
}
const int64_t items_processed = state.iterations() * state.range(0);
state.SetItemsProcessed(items_processed);
state.SetBytesProcessed(items_processed * sizeof(v));
}
BENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int)
->Range(1 << 0, 1 << 10);
BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10);
// Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond.
#ifdef BENCHMARK_HAS_CXX11
BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512);
#endif
static void BM_StringCompare(benchmark::State& state) {
size_t len = static_cast<size_t>(state.range(0));
std::string s1(len, '-');
std::string s2(len, '-');
for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2));
}
BENCHMARK(BM_StringCompare)->Range(1, 1 << 20);
template <class... Args>
void BM_with_args(benchmark::State& state, Args&&...) {
for (auto _ : state) {
}
}
BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44);
BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"),
std::pair<int, double>(42, 3.8));
void BM_non_template_args(benchmark::State& state, int, double) {
while(state.KeepRunning()) {}
}
BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0);
static void BM_DenseThreadRanges(benchmark::State& st) {
switch (st.range(0)) {
case 1:
assert(st.threads == 1 || st.threads == 2 || st.threads == 3);
break;
case 2:
assert(st.threads == 1 || st.threads == 3 || st.threads == 4);
break;
case 3:
assert(st.threads == 5 || st.threads == 8 || st.threads == 11 ||
st.threads == 14);
break;
default:
assert(false && "Invalid test case number");
}
while (st.KeepRunning()) {
}
}
BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3);
BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2);
BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3);
#endif
| 38.391137 | 144 | 0.446023 | [
"vector"
] |
8080082cf4d1fd4bda7fe4eceab80927e9603288 | 30,620 | cpp | C++ | simplemd/MolecularDynamicsSimulation.cpp | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 6 | 2021-02-06T17:21:10.000Z | 2022-01-27T21:36:55.000Z | simplemd/MolecularDynamicsSimulation.cpp | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 1 | 2021-06-24T15:17:46.000Z | 2021-06-25T11:54:52.000Z | simplemd/MolecularDynamicsSimulation.cpp | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 6 | 2021-12-16T11:39:24.000Z | 2022-03-28T07:00:30.000Z | // Copyright (C) 2015 Technische Universitaet Muenchen
// This file is part of the Mamico project. For conditions of distribution
// and use, please see the copyright notice in Mamico's main folder, or at
// www5.in.tum.de/mamico
#include "simplemd/MolecularDynamicsSimulation.h"
simplemd::MolecularDynamicsSimulation::
MolecularDynamicsSimulation(const simplemd::configurations::MolecularDynamicsConfiguration& configuration):
_configuration(configuration),
_timeIntegrator(NULL), _updateLinkedCellListsMapping(NULL), _vtkMoleculeWriter(NULL),
_lennardJonesForce(NULL), _emptyLinkedListsMapping(NULL), _rdfMapping(NULL),
_boundaryTreatment(NULL),
_localMDSimulation(0),
_profilePlotter(NULL),
_parallelTopologyService(NULL),
_moleculeService(NULL),
_linkedCellService(NULL),
_molecularPropertiesService(NULL),
// initialise external forces
_externalForceService(configuration.getExternalForceConfigurations())
{
}
double simplemd::MolecularDynamicsSimulation::getNumberDensity(
unsigned int numberMolecules,
const tarch::la::Vector<MD_DIM,double> &domainSize
) const {
double density = 1.0;
for (unsigned int d = 0; d < MD_DIM; d++){
density = density/domainSize[d];
}
return (density*numberMolecules);
}
// TODO: fix duplicate copy-paste code in both versions of initServices
void simplemd::MolecularDynamicsSimulation::initServices(){
// set vtk file stem and checkpoint filestem -> only one MD simulation runs
_localMDSimulation = 0;
_vtkFilestem = _configuration.getVTKConfiguration().getFilename();
_checkpointFilestem = _configuration.getCheckpointConfiguration().getFilename();
// initialise local variable with global information first (they are adapted later on)
tarch::la::Vector<MD_DIM,double> localDomainSize(_configuration.getDomainConfiguration().getGlobalDomainSize());
tarch::la::Vector<MD_DIM,double> localDomainOffset(_configuration.getDomainConfiguration().getGlobalDomainOffset());
tarch::la::Vector<MD_DIM,unsigned int> moleculesPerDirection(_configuration.getDomainConfiguration().getMoleculesPerDirection());
tarch::la::Vector<MD_DIM,double> realMeshWidth(0.0);
tarch::la::Vector<MD_DIM,unsigned int> processCoordinates(0);
double linkedCellVolume = 1.0;
simplemd::moleculemappings::InitialPositionAndForceUpdate initialPositionAndForceUpdate(
_configuration.getSimulationConfiguration().getDt(),
_configuration.getMoleculeConfiguration().getMass()
);
// initialise services -> initialise ParallelTopologyService first (also for serial case!) and then,
// initialise other services, if this process contributes to the simulation in some way
// Note: initBuffers must also be called on non-idle processors, but only after MoleculeService has been initialised.
_parallelTopologyService = new simplemd::services::ParallelTopologyService(
_configuration.getDomainConfiguration().getGlobalDomainSize(),
_configuration.getDomainConfiguration().getGlobalDomainOffset(),
_configuration.getDomainConfiguration().getMeshWidth(),
_configuration.getMPIConfiguration().getNumberOfProcesses(),
_configuration.getDomainConfiguration().getBoundary()
);
if (_parallelTopologyService==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _parallelTopologyService==NULL!" << std::endl; exit(EXIT_FAILURE);}
if (!_parallelTopologyService->isIdle()){
// set local periodic boundary information in periodicBoundary from here on
_localBoundary = _parallelTopologyService->getLocalBoundaryInformation();
// get process coordinates for the local process
processCoordinates = _parallelTopologyService->getProcessCoordinates();
// get local meshwidth defined by ParallelTopologyService
realMeshWidth = _parallelTopologyService->getMeshWidth();
// determine local domain size and local domain offset and local number of molecules
for (unsigned int d = 0; d < MD_DIM; d++){
localDomainSize[d] = localDomainSize[d]/(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
localDomainOffset[d] = localDomainOffset[d]
+ ( processCoordinates[d]*_parallelTopologyService->getLocalNumberOfCells()[d]*
realMeshWidth[d] );
int missingMolecules = moleculesPerDirection[d]%(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
moleculesPerDirection[d] = moleculesPerDirection[d]/(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
for(int i=0;i<missingMolecules;i++){
if ( processCoordinates[d] ==
(unsigned int) ( i*(1.0 * _configuration.getMPIConfiguration().getNumberOfProcesses()[d]) / missingMolecules) )
moleculesPerDirection[d]++;
}
}
#if (MD_DEBUG==MD_YES)
if (_parallelTopologyService->getProcessCoordinates()==tarch::la::Vector<MD_DIM,unsigned int>(0)){
std::cout << "Local number of cells: " << _parallelTopologyService->getLocalNumberOfCells() << std::endl;
}
std::cout << "Rank: " << _parallelTopologyService->getRank() << " Boundary: " << _localBoundary << ", process coordinates: " << processCoordinates << std::endl;
std::cout << " Local Domain size: " << localDomainSize << ", local domain offset: " << localDomainOffset << std::endl;
#endif
tarch::utils::RandomNumberService::getInstance().init(_configuration.getSimulationConfiguration().fixSeed());
_molecularPropertiesService = new simplemd::services::MolecularPropertiesService(
_configuration.getMoleculeConfiguration().getMass(),
_configuration.getMoleculeConfiguration().getEpsilon(),
_configuration.getMoleculeConfiguration().getSigma(),
_configuration.getDomainConfiguration().getCutoffRadius(),
_configuration.getDomainConfiguration().getKB()
);
if (_molecularPropertiesService==NULL){std::cout << "ERROR MolecularDynamicsSimulation::initServices(): _molecularPropertiesService==NULL!" << std::endl;exit(EXIT_FAILURE);}
// either initialise from checkpoint data or via a certain number of molecules per direction
if (_configuration.getDomainConfiguration().initFromCheckpoint()){
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
_configuration.getDomainConfiguration().getCheckpointFilestem(),
_configuration.getDomainConfiguration().getBlockSize(),
*_parallelTopologyService
);
} else if (_configuration.getDomainConfiguration().initFromSequentialCheckpoint()){
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
_configuration.getDomainConfiguration().getCheckpointFilestem(),
_configuration.getDomainConfiguration().getBlockSize()
);
} else {
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
moleculesPerDirection,
_configuration.getMoleculeConfiguration().getMeanVelocity(),
_configuration.getDomainConfiguration().getKB(),
_configuration.getMoleculeConfiguration().getTemperature(),
_configuration.getDomainConfiguration().getBlockSize(),
*_molecularPropertiesService
);
}
if (_moleculeService==NULL){std::cout << "ERROR MolecularDynamicsSimulation::initServices(): _moleculeService==NULL!" << std::endl; exit(EXIT_FAILURE);}
// initialise buffers. After this call, the ParallelTopologyService initialisation is complete
_parallelTopologyService->initBuffers( _moleculeService->getNumberMolecules() );
_linkedCellService = new simplemd::services::LinkedCellService(
localDomainSize, localDomainOffset,
*_parallelTopologyService, *_moleculeService
);
if (_linkedCellService==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _linkedCellService==NULL!" << std::endl;exit(EXIT_FAILURE);}
// init boundary treatment
_boundaryTreatment= new simplemd::BoundaryTreatment(*_parallelTopologyService,*_moleculeService,*_linkedCellService);
if (_boundaryTreatment==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _boundaryTreatment==NULL!" << std::endl; exit(EXIT_FAILURE);}
// init all mappings here
_timeIntegrator = new simplemd::moleculemappings::VelocityStoermerVerletMapping(_configuration.getDomainConfiguration().getKB(),
_configuration.getSimulationConfiguration().getDt(), _configuration.getMoleculeConfiguration().getMass(),
_configuration.getDomainConfiguration().getBoundary(),_configuration.getDomainConfiguration().getGlobalDomainOffset(),
_configuration.getDomainConfiguration().getGlobalDomainSize());
if (_timeIntegrator==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _timeIntegrator==NULL!" << std::endl; exit(EXIT_FAILURE);}
_updateLinkedCellListsMapping = new simplemd::moleculemappings::UpdateLinkedCellListsMapping(*_parallelTopologyService,*_linkedCellService);
if (_updateLinkedCellListsMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _updateLinkedCellListsMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
_vtkMoleculeWriter = new simplemd::moleculemappings::VTKMoleculeWriter(*_parallelTopologyService,*_moleculeService,_vtkFilestem);
if (_vtkMoleculeWriter==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _vtkMoleculeWriter==NULL!" << std::endl; exit(EXIT_FAILURE);}
// cell mappings
_lennardJonesForce = new simplemd::cellmappings::LennardJonesForceMapping(_externalForceService,*_molecularPropertiesService);
if (_lennardJonesForce==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _lennardJonesForce==NULL!" << std::endl; exit(EXIT_FAILURE);}
_emptyLinkedListsMapping=new simplemd::cellmappings::EmptyLinkedListsMapping();
if (_emptyLinkedListsMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _emptyLinkedListsMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
_rdfMapping = new simplemd::cellmappings::RDFMapping(*_parallelTopologyService,*_linkedCellService,_configuration.getDomainConfiguration().getCutoffRadius(),
_configuration.getRDFConfiguration().getNumberOfPoints());
if (_rdfMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _rdfMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
// initialise profile plotter
if (_profilePlotter != NULL){delete _profilePlotter; _profilePlotter = NULL;}
linkedCellVolume = 1.0;
for (unsigned int d = 0; d < MD_DIM; d++){ linkedCellVolume = linkedCellVolume *_linkedCellService->getMeshWidth()[d];}
_profilePlotter = new simplemd::ProfilePlotter(_configuration.getProfilePlotterConfigurations(),*_parallelTopologyService,*_linkedCellService,linkedCellVolume,_localMDSimulation);
if (_profilePlotter == NULL){ std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initService(): _profilePlotter==NULL!" << std::endl; exit(EXIT_FAILURE);}
// -------------- do initial force computations and position update ----------
_boundaryTreatment->fillBoundaryCells(_localBoundary,*_parallelTopologyService);
// compute forces between molecules.
// After this step, each molecule has received all force contributions from its neighbors.
_linkedCellService->iterateCellPairs(*_lennardJonesForce,false);
_boundaryTreatment->emptyGhostBoundaryCells();
_linkedCellService->iterateCells(*_emptyLinkedListsMapping,false);
_moleculeService->iterateMolecules(initialPositionAndForceUpdate,false);
// sort molecules into linked cells
_moleculeService->iterateMolecules(*_updateLinkedCellListsMapping,false);
// -------------- do initial force computations and position update (end) ----------
} // end is process not idle
}
void simplemd::MolecularDynamicsSimulation::initServices(const tarch::utils::MultiMDService<MD_DIM> &multiMDService,unsigned int localMDSimulation){
// set vtk file stem and checkpoint filestem;
_localMDSimulation = localMDSimulation;
std::stringstream filestems;
filestems << _configuration.getVTKConfiguration().getFilename() << "_" << localMDSimulation << "_";
_vtkFilestem = filestems.str();
filestems.str("");
filestems << _configuration.getCheckpointConfiguration().getFilename() << "_" << localMDSimulation << "_";
_checkpointFilestem = filestems.str();
filestems.str("");
// initialise local variable with global information first (they are adapted later on)
tarch::la::Vector<MD_DIM,double> localDomainSize(_configuration.getDomainConfiguration().getGlobalDomainSize());
tarch::la::Vector<MD_DIM,double> localDomainOffset(_configuration.getDomainConfiguration().getGlobalDomainOffset());
tarch::la::Vector<MD_DIM,unsigned int> moleculesPerDirection(_configuration.getDomainConfiguration().getMoleculesPerDirection());
tarch::la::Vector<MD_DIM,double> realMeshWidth(0.0);
tarch::la::Vector<MD_DIM,unsigned int> processCoordinates(0);
double linkedCellVolume = 1.0;
simplemd::moleculemappings::InitialPositionAndForceUpdate initialPositionAndForceUpdate(
_configuration.getSimulationConfiguration().getDt(),
_configuration.getMoleculeConfiguration().getMass()
);
// initialise services -> initialise ParallelTopologyService first (also for serial case!) and then,
// initialise other services, if this process contributes to the simulation in some way
// Note: initBuffers must also be called on non-idle processors, but only after MoleculeService has been initialised.
_parallelTopologyService = new simplemd::services::ParallelTopologyService(
_configuration.getDomainConfiguration().getGlobalDomainSize(),
_configuration.getDomainConfiguration().getGlobalDomainOffset(),
_configuration.getDomainConfiguration().getMeshWidth(),
_configuration.getMPIConfiguration().getNumberOfProcesses(),
_configuration.getDomainConfiguration().getBoundary()
// DIFFERENCE TO initServices(): use communicator of MultiMDService
#if (MD_PARALLEL==MD_YES)
,multiMDService.getLocalCommunicator()
#endif
);
if (_parallelTopologyService==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _parallelTopologyService==NULL!" << std::endl; exit(EXIT_FAILURE);}
if (!_parallelTopologyService->isIdle()){
// set local periodic boundary information in periodicBoundary from here on
_localBoundary = _parallelTopologyService->getLocalBoundaryInformation();
// get process coordinates for the local process
processCoordinates = _parallelTopologyService->getProcessCoordinates();
// get local meshwidth defined by ParallelTopologyService
realMeshWidth = _parallelTopologyService->getMeshWidth();
// determine local domain size and local domain offset and local number of molecules
for (unsigned int d = 0; d < MD_DIM; d++){
localDomainSize[d] = localDomainSize[d]/(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
localDomainOffset[d] = localDomainOffset[d]
+ ( processCoordinates[d]*_parallelTopologyService->getLocalNumberOfCells()[d]*
realMeshWidth[d] );
int missingMolecules = moleculesPerDirection[d]%(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
moleculesPerDirection[d] = moleculesPerDirection[d]/(_configuration.getMPIConfiguration().getNumberOfProcesses()[d]);
for(int i=0;i<missingMolecules;i++){
if ( processCoordinates[d] ==
(unsigned int) ( i*(1.0 * _configuration.getMPIConfiguration().getNumberOfProcesses()[d]) / missingMolecules) )
moleculesPerDirection[d]++;
}
}
#if (MD_DEBUG==MD_YES)
if (_parallelTopologyService->getProcessCoordinates()==tarch::la::Vector<MD_DIM,unsigned int>(0)){
std::cout << "Local number of cells: " << _parallelTopologyService->getLocalNumberOfCells() << std::endl;
}
std::cout << "Rank: " << _parallelTopologyService->getRank() << " Boundary: " << _localBoundary << ", process coordinates: " << processCoordinates << std::endl;
std::cout << " Local Domain size: " << localDomainSize << ", local domain offset: " << localDomainOffset << std::endl;
#endif
tarch::utils::RandomNumberService::getInstance().init(_configuration.getSimulationConfiguration().fixSeed());
_molecularPropertiesService = new simplemd::services::MolecularPropertiesService(
_configuration.getMoleculeConfiguration().getMass(),
_configuration.getMoleculeConfiguration().getEpsilon(),
_configuration.getMoleculeConfiguration().getSigma(),
_configuration.getDomainConfiguration().getCutoffRadius(),
_configuration.getDomainConfiguration().getKB()
);
if (_molecularPropertiesService==NULL){std::cout << "ERROR MolecularDynamicsSimulation::initServices(): _molecularPropertiesService==NULL!" << std::endl;exit(EXIT_FAILURE);}
// either initialise from checkpoint data or via a certain number of molecules per direction
if (_configuration.getDomainConfiguration().initFromCheckpoint()){
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
_configuration.getDomainConfiguration().getCheckpointFilestem(),
_configuration.getDomainConfiguration().getBlockSize(),
*_parallelTopologyService
);
} else if (_configuration.getDomainConfiguration().initFromSequentialCheckpoint()){
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
_configuration.getDomainConfiguration().getCheckpointFilestem(),
_configuration.getDomainConfiguration().getBlockSize()
);
} else {
_moleculeService = new simplemd::services::MoleculeService(
localDomainSize,
localDomainOffset,
moleculesPerDirection,
_configuration.getMoleculeConfiguration().getMeanVelocity(),
_configuration.getDomainConfiguration().getKB(),
_configuration.getMoleculeConfiguration().getTemperature(),
_configuration.getDomainConfiguration().getBlockSize(),
*_molecularPropertiesService
);
}
if (_moleculeService==NULL){std::cout << "ERROR MolecularDynamicsSimulation::initServices(): _moleculeService==NULL!" << std::endl; exit(EXIT_FAILURE);}
// initialise buffers. After this call, the ParallelTopologyService initialisation is complete
_parallelTopologyService->initBuffers( _moleculeService->getNumberMolecules() );
_linkedCellService = new simplemd::services::LinkedCellService(
localDomainSize, localDomainOffset,
*_parallelTopologyService, *_moleculeService
);
if (_linkedCellService==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _linkedCellService==NULL!" << std::endl;exit(EXIT_FAILURE);}
// init boundary treatment
_boundaryTreatment= new simplemd::BoundaryTreatment(*_parallelTopologyService,*_moleculeService,*_linkedCellService);
if (_boundaryTreatment==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _boundaryTreatment==NULL!" << std::endl; exit(EXIT_FAILURE);}
// init all mappings here
_timeIntegrator = new simplemd::moleculemappings::VelocityStoermerVerletMapping(_configuration.getDomainConfiguration().getKB(),
_configuration.getSimulationConfiguration().getDt(), _configuration.getMoleculeConfiguration().getMass(),
_configuration.getDomainConfiguration().getBoundary(),_configuration.getDomainConfiguration().getGlobalDomainOffset(),
_configuration.getDomainConfiguration().getGlobalDomainSize());
if (_timeIntegrator==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _timeIntegrator==NULL!" << std::endl; exit(EXIT_FAILURE);}
_updateLinkedCellListsMapping = new simplemd::moleculemappings::UpdateLinkedCellListsMapping(*_parallelTopologyService,*_linkedCellService);
if (_updateLinkedCellListsMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _updateLinkedCellListsMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
_vtkMoleculeWriter = new simplemd::moleculemappings::VTKMoleculeWriter(*_parallelTopologyService,*_moleculeService,_vtkFilestem);
if (_vtkMoleculeWriter==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _vtkMoleculeWriter==NULL!" << std::endl; exit(EXIT_FAILURE);}
// cell mappings
_lennardJonesForce = new simplemd::cellmappings::LennardJonesForceMapping(_externalForceService,*_molecularPropertiesService);
if (_lennardJonesForce==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _lennardJonesForce==NULL!" << std::endl; exit(EXIT_FAILURE);}
_emptyLinkedListsMapping=new simplemd::cellmappings::EmptyLinkedListsMapping();
if (_emptyLinkedListsMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _emptyLinkedListsMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
_rdfMapping = new simplemd::cellmappings::RDFMapping(*_parallelTopologyService,*_linkedCellService,_configuration.getDomainConfiguration().getCutoffRadius(),
_configuration.getRDFConfiguration().getNumberOfPoints());
if (_rdfMapping==NULL){std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initServices(): _rdfMapping==NULL!" << std::endl; exit(EXIT_FAILURE);}
// initialise profile plotter
if (_profilePlotter != NULL){delete _profilePlotter; _profilePlotter = NULL;}
linkedCellVolume = 1.0;
for (unsigned int d = 0; d < MD_DIM; d++){ linkedCellVolume = linkedCellVolume *_linkedCellService->getMeshWidth()[d];}
_profilePlotter = new simplemd::ProfilePlotter(_configuration.getProfilePlotterConfigurations(),*_parallelTopologyService,*_linkedCellService,linkedCellVolume,_localMDSimulation);
if (_profilePlotter == NULL){ std::cout << "ERROR simplemd::MolecularDynamicsSimulation::initService(): _profilePlotter==NULL!" << std::endl; exit(EXIT_FAILURE);}
// -------------- do initial force computations and position update ----------
_boundaryTreatment->fillBoundaryCells(_localBoundary,*_parallelTopologyService);
// compute forces between molecules.
// After this step, each molecule has received all force contributions from its neighbors.
_linkedCellService->iterateCellPairs(*_lennardJonesForce,false);
_boundaryTreatment->emptyGhostBoundaryCells();
_linkedCellService->iterateCells(*_emptyLinkedListsMapping,false);
_moleculeService->iterateMolecules(initialPositionAndForceUpdate,false);
// sort molecules into linked cells
_moleculeService->iterateMolecules(*_updateLinkedCellListsMapping,false);
// -------------- do initial force computations and position update (end) ----------
} // end is process not idle
}
void simplemd::MolecularDynamicsSimulation::shutdownServices(){
// shutdown services
if (!_parallelTopologyService->isIdle()){
_linkedCellService->shutdown();
_moleculeService->shutdown();
_molecularPropertiesService->shutdown();
tarch::utils::RandomNumberService::getInstance().shutdown();
}
_parallelTopologyService->shutdown();
// delete mappings
if (_timeIntegrator!=NULL){ delete _timeIntegrator; _timeIntegrator=NULL;}
if (_updateLinkedCellListsMapping!=NULL){ delete _updateLinkedCellListsMapping; _updateLinkedCellListsMapping=NULL;}
if (_vtkMoleculeWriter!=NULL){delete _vtkMoleculeWriter; _vtkMoleculeWriter=NULL;}
if (_lennardJonesForce!=NULL){delete _lennardJonesForce; _lennardJonesForce=NULL;}
if (_emptyLinkedListsMapping!=NULL){delete _emptyLinkedListsMapping; _emptyLinkedListsMapping=NULL;}
if (_rdfMapping!=NULL){delete _rdfMapping; _rdfMapping=NULL;}
// delete profile plotter and parallel topology service, and boundary treatment, and molecule service
if (_boundaryTreatment!=NULL){delete _boundaryTreatment; _boundaryTreatment=NULL;}
if (_profilePlotter != NULL){delete _profilePlotter; _profilePlotter = NULL;}
if (_linkedCellService!=NULL){delete _linkedCellService; _linkedCellService=NULL;}
if (_moleculeService !=NULL){delete _moleculeService; _moleculeService = NULL;}
if (_molecularPropertiesService!=NULL){delete _molecularPropertiesService; _molecularPropertiesService=NULL;}
if (_parallelTopologyService != NULL){delete _parallelTopologyService; _parallelTopologyService=NULL;}
}
void simplemd::MolecularDynamicsSimulation::
simulateOneTimestep(const unsigned int &t){
// nop for idle processes
if (_parallelTopologyService->isIdle()){
return;
}
// Before this step, the ghost layer contains exactly those particles, which have left the local part of the domain during the previous timestep.
// The algorithm proceeds as follows:
//
// 1. put particles from ghost cells into the correct cells again:
// + If the ghost cell is part of a parallel boundary, molecules in the cell are sent to the respective neighboring process
// and sorted into the corresponding inner cell upon unpacking of receive buffer.
// + If the ghost cell is part of a local periodic boundary, molecules in ghost cells are replicated with adapted position with
// respect to periodic boundary conditions, and stored in the local buffer.
// Upon unpacking the local buffer, molecules are resorted into the correct cells.
//
// 2. fill ghost cells (for periodic boundaries or parallel boundaries).
// After this step, all periodic/ parallel ghost layer cells are
// populated with molecules from the respective periodic/ parallel neighbour cell.
// In the parallel case, all inner, but near boundary, cells are broadcasted to each respective ghost layer cell.
//
// Depending on whether overlapping is switched on, we enter the respective methods:
// + If overlapping is off, perform described steps 1. and 2. via putBoundaryParticlesToInnerCellsAndFillBoundaryCells and then
// compute forces.
// + If overlapping is on, perform described steps 1. and 2., compute forces on inner part of domain, wait for communication
// buffers to arrive, then compute forces near boundaries, all within putBoundaryParticlesToInnerCellsFillBoundaryCellsAndOverlapWithForceComputations.
if(!_configuration.getSimulationConfiguration().useOverlappingCommunicationWithForceComputation()) {
_boundaryTreatment->putBoundaryParticlesToInnerCellsAndFillBoundaryCells(_localBoundary,*_parallelTopologyService);
// compute forces between molecules.
_linkedCellService->iterateCellPairs(*_lennardJonesForce,false);
} else {
_boundaryTreatment->putBoundaryParticlesToInnerCellsFillBoundaryCellsAndOverlapWithForceComputations(
_localBoundary, *_parallelTopologyService,*_lennardJonesForce, false);
}
evaluateStatistics(t);
_boundaryTreatment->emptyGhostBoundaryCells();
// plot VTK output
if ( (_configuration.getVTKConfiguration().getWriteEveryTimestep() != 0)
&& (t % _configuration.getVTKConfiguration().getWriteEveryTimestep() == 0) ){
_vtkMoleculeWriter->setTimestep(t);
_moleculeService->iterateMolecules(*_vtkMoleculeWriter,false);
}
// write checkpoint
if ( (_configuration.getCheckpointConfiguration().getWriteEveryTimestep() != 0)
&& (t % _configuration.getCheckpointConfiguration().getWriteEveryTimestep() == 0) ){
_moleculeService->writeCheckPoint(*_parallelTopologyService,_checkpointFilestem,t);
}
// reorganise memory if needed
if ( (_configuration.getSimulationConfiguration().getReorganiseMemoryEveryTimestep() != 0)
&& (t % _configuration.getSimulationConfiguration().getReorganiseMemoryEveryTimestep() == 0) ){
_moleculeService->reorganiseMemory(*_parallelTopologyService,*_linkedCellService);
}
// empty linked lists
_linkedCellService->iterateCells(*_emptyLinkedListsMapping,false);
// time integration. After this step, the velocities and the positions of the molecules have been updated.
_moleculeService->iterateMolecules(*_timeIntegrator,false);
// sort molecules into linked cells
_moleculeService->iterateMolecules(*_updateLinkedCellListsMapping,false);
if (_parallelTopologyService->getProcessCoordinates()==tarch::la::Vector<MD_DIM,unsigned int>(0)){
if(t%50==0) std::cout << "Finish MD timestep " << t << "..." << std::endl;
}
}
void simplemd::MolecularDynamicsSimulation::runSimulation(){
// time loop
for (unsigned int t = 0; t < _configuration.getSimulationConfiguration().getNumberOfTimesteps(); t++){
// simulate one timestep
simulateOneTimestep(t);
}
if (_parallelTopologyService->getProcessCoordinates()==tarch::la::Vector<MD_DIM,unsigned int>(0)){
std::cout << "Finish MD simulation." << std::endl;
}
}
void simplemd::MolecularDynamicsSimulation::evaluateStatistics(const unsigned int& t){
const unsigned int timeInterval = _configuration.getSimulationConfiguration().computeMacroscopicQuantitiesEveryTimestep();
if (_configuration.getRDFConfiguration().isDefined()){
if (t>=_configuration.getRDFConfiguration().getStartAtTimestep()){
if ( (t-_configuration.getRDFConfiguration().getStartAtTimestep())%_configuration.getRDFConfiguration().getEvaluateEveryTimestep()==0){
_linkedCellService->iterateCellPairs(*_rdfMapping,false);
if ( (t-_configuration.getRDFConfiguration().getStartAtTimestep())%_configuration.getRDFConfiguration().getWriteEveryTimestep()==0){
_rdfMapping->evaluateRDF(_localMDSimulation);
}
}
}
}
if ( (timeInterval!=0) && (t%timeInterval==0) ){
// compute average velocity
simplemd::cellmappings::ComputeMeanVelocityMapping computeMeanVelocityMapping(*_parallelTopologyService,_localMDSimulation);
_linkedCellService->iterateCells(computeMeanVelocityMapping,false);
// compute average temperature
simplemd::cellmappings::ComputeTemperatureMapping computeTemperatureMapping(*_parallelTopologyService,*_molecularPropertiesService,
computeMeanVelocityMapping.getMeanVelocity(),_localMDSimulation);
_linkedCellService->iterateCells(computeTemperatureMapping,false);
}
// trigger profile plotting
_profilePlotter->accumulateAndPlotInformation(t);
}
| 61.609658 | 192 | 0.757609 | [
"vector"
] |
80890310baa8ae2cd8b267f4b46e0bec01df5c3e | 106,621 | cpp | C++ | src/libawkward/util.cpp | nikoladze/awkward-1.0 | 7e1001b6ee59f1cba96cf57d144e7f2719f07e69 | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/util.cpp | nikoladze/awkward-1.0 | 7e1001b6ee59f1cba96cf57d144e7f2719f07e69 | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/util.cpp | nikoladze/awkward-1.0 | 7e1001b6ee59f1cba96cf57d144e7f2719f07e69 | [
"BSD-3-Clause"
] | null | null | null | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
#include <sstream>
#include <set>
#include "rapidjson/document.h"
#include "awkward/cpu-kernels/identities.h"
#include "awkward/cpu-kernels/getitem.h"
#include "awkward/cpu-kernels/operations.h"
#include "awkward/cpu-kernels/reducers.h"
#include "awkward/util.h"
#include "awkward/Identities.h"
namespace rj = rapidjson;
namespace awkward {
namespace util {
void
handle_error(const struct Error& err,
const std::string& classname,
const Identities* identities) {
if (err.str != nullptr) {
std::stringstream out;
out << "in " << classname;
if (err.identity != kSliceNone && identities != nullptr) {
if (0 <= err.identity && err.identity < identities->length()) {
out << " with identity ["
<< identities->identity_at(err.identity) << "]";
}
else {
out << " with invalid identity";
}
}
if (err.attempt != kSliceNone) {
out << " attempting to get " << err.attempt;
}
out << ", " << err.str;
throw std::invalid_argument(out.str());
}
}
template <typename T>
IndexOf<T> make_starts(const IndexOf<T>& offsets) {
return IndexOf<T>(offsets.ptr(),
offsets.offset(),
offsets.length() - 1);
}
template <typename T>
IndexOf<T> make_stops(const IndexOf<T>& offsets) {
return IndexOf<T>(offsets.ptr(),
offsets.offset() + 1,
offsets.length() - 1);
}
template IndexOf<int32_t> make_starts(const IndexOf<int32_t>& offsets);
template IndexOf<uint32_t> make_starts(const IndexOf<uint32_t>& offsets);
template IndexOf<int64_t> make_starts(const IndexOf<int64_t>& offsets);
template IndexOf<int32_t> make_stops(const IndexOf<int32_t>& offsets);
template IndexOf<uint32_t> make_stops(const IndexOf<uint32_t>& offsets);
template IndexOf<int64_t> make_stops(const IndexOf<int64_t>& offsets);
std::string
quote(const std::string& x, bool doublequote) {
// TODO: escape characters, possibly using RapidJSON.
if (doublequote) {
return std::string("\"") + x + std::string("\"");
}
else {
return std::string("'") + x + std::string("'");
}
}
RecordLookupPtr
init_recordlookup(int64_t numfields) {
RecordLookupPtr out = std::make_shared<RecordLookup>();
for (int64_t i = 0; i < numfields; i++) {
out.get()->push_back(std::to_string(i));
}
return out;
}
int64_t
fieldindex(const RecordLookupPtr& recordlookup,
const std::string& key,
int64_t numfields) {
int64_t out = -1;
if (recordlookup.get() != nullptr) {
for (size_t i = 0; i < recordlookup.get()->size(); i++) {
if (recordlookup.get()->at(i) == key) {
out = (int64_t)i;
break;
}
}
}
if (out == -1) {
try {
out = (int64_t)std::stoi(key);
}
catch (std::invalid_argument err) {
throw std::invalid_argument(
std::string("key ") + quote(key, true)
+ std::string(" does not exist (not in record)"));
}
if (!(0 <= out && out < numfields)) {
throw std::invalid_argument(
std::string("key interpreted as fieldindex ") + key
+ std::string(" for records with only " + std::to_string(numfields)
+ std::string(" fields")));
}
}
return out;
}
const std::string
key(const RecordLookupPtr& recordlookup,
int64_t fieldindex,
int64_t numfields) {
if (fieldindex >= numfields) {
throw std::invalid_argument(
std::string("fieldindex ") + std::to_string(fieldindex)
+ std::string(" for records with only " + std::to_string(numfields)
+ std::string(" fields")));
}
if (recordlookup.get() != nullptr) {
return recordlookup.get()->at((size_t)fieldindex);
}
else {
return std::to_string(fieldindex);
}
}
bool
haskey(const RecordLookupPtr& recordlookup,
const std::string& key,
int64_t numfields) {
try {
fieldindex(recordlookup, key, numfields);
}
catch (std::invalid_argument err) {
return false;
}
return true;
}
const std::vector<std::string>
keys(const RecordLookupPtr& recordlookup, int64_t numfields) {
std::vector<std::string> out;
if (recordlookup.get() != nullptr) {
out.insert(out.end(),
recordlookup.get()->begin(),
recordlookup.get()->end());
}
else {
int64_t cols = numfields;
for (int64_t j = 0; j < cols; j++) {
out.push_back(std::to_string(j));
}
}
return out;
}
bool
parameter_equals(const Parameters& parameters,
const std::string& key,
const std::string& value) {
auto item = parameters.find(key);
std::string myvalue;
if (item == parameters.end()) {
myvalue = "null";
}
else {
myvalue = item->second;
}
rj::Document mine;
rj::Document yours;
mine.Parse<rj::kParseNanAndInfFlag>(myvalue.c_str());
yours.Parse<rj::kParseNanAndInfFlag>(value.c_str());
return mine == yours;
}
bool
parameters_equal(const Parameters& self, const Parameters& other) {
std::set<std::string> checked;
for (auto pair : self) {
if (!parameter_equals(other, pair.first, pair.second)) {
return false;
}
checked.insert(pair.first);
}
for (auto pair : other) {
if (checked.find(pair.first) == checked.end()) {
if (!parameter_equals(self, pair.first, pair.second)) {
return false;
}
}
}
return true;
}
bool
parameter_isstring(const Parameters& parameters, const std::string& key) {
auto item = parameters.find(key);
if (item == parameters.end()) {
return false;
}
rj::Document mine;
mine.Parse<rj::kParseNanAndInfFlag>(item->second.c_str());
return mine.IsString();
}
bool
parameter_isname(const Parameters& parameters, const std::string& key) {
auto item = parameters.find(key);
if (item == parameters.end()) {
return false;
}
rj::Document mine;
mine.Parse<rj::kParseNanAndInfFlag>(item->second.c_str());
if (!mine.IsString()) {
return false;
}
std::string value = mine.GetString();
if (value.empty()) {
return false;
}
if (!((value[0] >= 'a' && value[0] <= 'z') ||
(value[0] >= 'A' && value[0] <= 'Z') ||
(value[0] == '_'))) {
return false;
}
for (size_t i = 1; i < value.length(); i++) {
if (!((value[i] >= 'a' && value[i] <= 'z') ||
(value[i] >= 'A' && value[i] <= 'Z') ||
(value[i] >= '0' && value[i] <= '9') ||
(value[i] == '_'))) {
return false;
}
}
return true;
}
const std::string
parameter_asstring(const Parameters& parameters, const std::string& key) {
auto item = parameters.find(key);
if (item == parameters.end()) {
throw std::runtime_error("parameter is null");
}
rj::Document mine;
mine.Parse<rj::kParseNanAndInfFlag>(item->second.c_str());
if (!mine.IsString()) {
throw std::runtime_error("parameter is not a string");
}
return mine.GetString();
}
std::string
gettypestr(const Parameters& parameters, const TypeStrs& typestrs) {
auto item = parameters.find("__record__");
if (item != parameters.end()) {
std::string source = item->second;
rj::Document recname;
recname.Parse<rj::kParseNanAndInfFlag>(source.c_str());
if (recname.IsString()) {
std::string name = recname.GetString();
for (auto pair : typestrs) {
if (pair.first == name) {
return pair.second;
}
}
}
}
item = parameters.find("__array__");
if (item != parameters.end()) {
std::string source = item->second;
rj::Document recname;
recname.Parse<rj::kParseNanAndInfFlag>(source.c_str());
if (recname.IsString()) {
std::string name = recname.GetString();
for (auto pair : typestrs) {
if (pair.first == name) {
return pair.second;
}
}
}
}
return std::string();
}
template <>
Error awkward_identities32_from_listoffsetarray<int32_t>(
int32_t* toptr,
const int32_t* fromptr,
const int32_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listoffsetarray32(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_listoffsetarray<uint32_t>(
int32_t* toptr,
const int32_t* fromptr,
const uint32_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listoffsetarrayU32(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_listoffsetarray<int64_t>(
int32_t* toptr,
const int32_t* fromptr,
const int64_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listoffsetarray64(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listoffsetarray<int32_t>(
int64_t* toptr,
const int64_t* fromptr,
const int32_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listoffsetarray32(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listoffsetarray<uint32_t>(
int64_t* toptr,
const int64_t* fromptr,
const uint32_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listoffsetarrayU32(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listoffsetarray<int64_t>(
int64_t* toptr,
const int64_t* fromptr,
const int64_t* fromoffsets,
int64_t fromptroffset,
int64_t offsetsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listoffsetarray64(
toptr,
fromptr,
fromoffsets,
fromptroffset,
offsetsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_listarray<int32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listarray32(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_listarray<uint32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listarrayU32(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_listarray<int64_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_listarray64(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listarray<int32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listarray32(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listarray<uint32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listarrayU32(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_listarray<int64_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t fromptroffset,
int64_t startsoffset,
int64_t stopsoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_listarray64(
uniquecontents,
toptr,
fromptr,
fromstarts,
fromstops,
fromptroffset,
startsoffset,
stopsoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_indexedarray<int32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int32_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_indexedarray32(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_indexedarray<uint32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const uint32_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_indexedarrayU32(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_indexedarray<int64_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int64_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities32_from_indexedarray64(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_indexedarray<int32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int32_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_indexedarray32(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_indexedarray<uint32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const uint32_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_indexedarrayU32(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities64_from_indexedarray<int64_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int64_t* fromindex,
int64_t fromptroffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth) {
return awkward_identities64_from_indexedarray64(
uniquecontents,
toptr,
fromptr,
fromindex,
fromptroffset,
indexoffset,
tolength,
fromlength,
fromwidth);
}
template <>
Error awkward_identities32_from_unionarray<int8_t,
int32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int8_t* fromtags,
const int32_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities32_from_unionarray8_32(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_identities32_from_unionarray<int8_t,
uint32_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int8_t* fromtags,
const uint32_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities32_from_unionarray8_U32(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_identities32_from_unionarray<int8_t,
int64_t>(
bool* uniquecontents,
int32_t* toptr,
const int32_t* fromptr,
const int8_t* fromtags,
const int64_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities32_from_unionarray8_64(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_identities64_from_unionarray<int8_t,
int32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int8_t* fromtags,
const int32_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities64_from_unionarray8_32(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_identities64_from_unionarray<int8_t,
uint32_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int8_t* fromtags,
const uint32_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities64_from_unionarray8_U32(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_identities64_from_unionarray<int8_t,
int64_t>(
bool* uniquecontents,
int64_t* toptr,
const int64_t* fromptr,
const int8_t* fromtags,
const int64_t* fromindex,
int64_t fromptroffset,
int64_t tagsoffset,
int64_t indexoffset,
int64_t tolength,
int64_t fromlength,
int64_t fromwidth,
int64_t which) {
return awkward_identities64_from_unionarray8_64(
uniquecontents,
toptr,
fromptr,
fromtags,
fromindex,
fromptroffset,
tagsoffset,
indexoffset,
tolength,
fromlength,
fromwidth,
which);
}
template <>
Error awkward_index_carry_64<int8_t>(
int8_t* toindex,
const int8_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t lenfromindex,
int64_t length) {
return awkward_index8_carry_64(
toindex,
fromindex,
carry,
fromindexoffset,
lenfromindex,
length);
}
template <>
Error awkward_index_carry_64<uint8_t>(
uint8_t* toindex,
const uint8_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t lenfromindex,
int64_t length) {
return awkward_indexU8_carry_64(
toindex,
fromindex,
carry,
fromindexoffset,
lenfromindex,
length);
}
template <>
Error awkward_index_carry_64<int32_t>(
int32_t* toindex,
const int32_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t lenfromindex,
int64_t length) {
return awkward_index32_carry_64(
toindex,
fromindex,
carry,
fromindexoffset,
lenfromindex,
length);
}
template <>
Error awkward_index_carry_64<uint32_t>(
uint32_t* toindex,
const uint32_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t lenfromindex,
int64_t length) {
return awkward_indexU32_carry_64(
toindex,
fromindex,
carry,
fromindexoffset,
lenfromindex,
length);
}
template <>
Error awkward_index_carry_64<int64_t>(
int64_t* toindex,
const int64_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t lenfromindex,
int64_t length) {
return awkward_index64_carry_64(
toindex,
fromindex,
carry,
fromindexoffset,
lenfromindex,
length);
}
template <>
Error awkward_index_carry_nocheck_64<int8_t>(
int8_t* toindex,
const int8_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t length) {
return awkward_index8_carry_nocheck_64(
toindex,
fromindex,
carry,
fromindexoffset,
length);
}
template <>
Error awkward_index_carry_nocheck_64<uint8_t>(
uint8_t* toindex,
const uint8_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t length) {
return awkward_indexU8_carry_nocheck_64(
toindex,
fromindex,
carry,
fromindexoffset,
length);
}
template <>
Error awkward_index_carry_nocheck_64<int32_t>(
int32_t* toindex,
const int32_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t length) {
return awkward_index32_carry_nocheck_64(
toindex,
fromindex,
carry,
fromindexoffset,
length);
}
template <>
Error awkward_index_carry_nocheck_64<uint32_t>(
uint32_t* toindex,
const uint32_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t length) {
return awkward_indexU32_carry_nocheck_64(
toindex,
fromindex,
carry,
fromindexoffset,
length);
}
template <>
Error awkward_index_carry_nocheck_64<int64_t>(
int64_t* toindex,
const int64_t* fromindex,
const int64_t* carry,
int64_t fromindexoffset,
int64_t length) {
return awkward_index64_carry_nocheck_64(
toindex,
fromindex,
carry,
fromindexoffset,
length);
}
template <>
Error awkward_listarray_getitem_next_at_64<int32_t>(
int64_t* tocarry,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t at) {
return awkward_listarray32_getitem_next_at_64(
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
at);
}
template <>
Error awkward_listarray_getitem_next_at_64<uint32_t>(
int64_t* tocarry,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t at) {
return awkward_listarrayU32_getitem_next_at_64(
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
at);
}
template <>
Error awkward_listarray_getitem_next_at_64<int64_t>(
int64_t* tocarry,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t at) {
return awkward_listarray64_getitem_next_at_64(
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
at);
}
template <>
Error awkward_listarray_getitem_next_range_carrylength<int32_t>(
int64_t* carrylength,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarray32_getitem_next_range_carrylength(
carrylength,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_carrylength<uint32_t>(
int64_t* carrylength,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarrayU32_getitem_next_range_carrylength(
carrylength,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_carrylength<int64_t>(
int64_t* carrylength,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarray64_getitem_next_range_carrylength(
carrylength,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_64<int32_t>(
int32_t* tooffsets,
int64_t* tocarry,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarray32_getitem_next_range_64(
tooffsets,
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_64<uint32_t>(
uint32_t* tooffsets,
int64_t* tocarry,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarrayU32_getitem_next_range_64(
tooffsets,
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_64<int64_t>(
int64_t* tooffsets,
int64_t* tocarry,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset,
int64_t start,
int64_t stop,
int64_t step) {
return awkward_listarray64_getitem_next_range_64(
tooffsets,
tocarry,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset,
start,
stop,
step);
}
template <>
Error awkward_listarray_getitem_next_range_counts_64<int32_t>(
int64_t* total,
const int32_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarray32_getitem_next_range_counts_64(
total,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_range_counts_64<uint32_t>(
int64_t* total,
const uint32_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarrayU32_getitem_next_range_counts_64(
total,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_range_counts_64<int64_t>(
int64_t* total,
const int64_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarray64_getitem_next_range_counts_64(
total,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_range_spreadadvanced_64<int32_t>(
int64_t* toadvanced,
const int64_t* fromadvanced,
const int32_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarray32_getitem_next_range_spreadadvanced_64(
toadvanced,
fromadvanced,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_range_spreadadvanced_64<uint32_t>(
int64_t* toadvanced,
const int64_t* fromadvanced,
const uint32_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarrayU32_getitem_next_range_spreadadvanced_64(
toadvanced,
fromadvanced,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_range_spreadadvanced_64<int64_t>(
int64_t* toadvanced,
const int64_t* fromadvanced,
const int64_t* fromoffsets,
int64_t lenstarts) {
return awkward_listarray64_getitem_next_range_spreadadvanced_64(
toadvanced,
fromadvanced,
fromoffsets,
lenstarts);
}
template <>
Error awkward_listarray_getitem_next_array_64<int32_t>(
int64_t* tocarry,
int64_t* toadvanced,
const int32_t* fromstarts,
const int32_t* fromstops,
const int64_t* fromarray,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarray32_getitem_next_array_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_next_array_64<uint32_t>(
int64_t* tocarry,
int64_t* toadvanced,
const uint32_t* fromstarts,
const uint32_t* fromstops,
const int64_t* fromarray,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarrayU32_getitem_next_array_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_next_array_64<int64_t>(
int64_t* tocarry,
int64_t* toadvanced,
const int64_t* fromstarts,
const int64_t* fromstops,
const int64_t* fromarray,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarray64_getitem_next_array_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_next_array_advanced_64<int32_t>(
int64_t* tocarry,
int64_t* toadvanced,
const int32_t* fromstarts,
const int32_t* fromstops,
const int64_t* fromarray,
const int64_t* fromadvanced,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarray32_getitem_next_array_advanced_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
fromadvanced,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_next_array_advanced_64<uint32_t>(
int64_t* tocarry,
int64_t* toadvanced,
const uint32_t* fromstarts,
const uint32_t* fromstops,
const int64_t* fromarray,
const int64_t* fromadvanced,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarrayU32_getitem_next_array_advanced_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
fromadvanced,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_next_array_advanced_64<int64_t>(
int64_t* tocarry,
int64_t* toadvanced,
const int64_t* fromstarts,
const int64_t* fromstops,
const int64_t* fromarray,
const int64_t* fromadvanced,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lenarray,
int64_t lencontent) {
return awkward_listarray64_getitem_next_array_advanced_64(
tocarry,
toadvanced,
fromstarts,
fromstops,
fromarray,
fromadvanced,
startsoffset,
stopsoffset,
lenstarts,
lenarray,
lencontent);
}
template <>
Error awkward_listarray_getitem_carry_64<int32_t>(
int32_t* tostarts,
int32_t* tostops,
const int32_t* fromstarts,
const int32_t* fromstops,
const int64_t* fromcarry,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lencarry) {
return awkward_listarray32_getitem_carry_64(
tostarts,
tostops,
fromstarts,
fromstops,
fromcarry,
startsoffset,
stopsoffset,
lenstarts,
lencarry);
}
template <>
Error awkward_listarray_getitem_carry_64<uint32_t>(
uint32_t* tostarts,
uint32_t* tostops,
const uint32_t* fromstarts,
const uint32_t* fromstops,
const int64_t* fromcarry,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lencarry) {
return awkward_listarrayU32_getitem_carry_64(
tostarts,
tostops,
fromstarts,
fromstops,
fromcarry,
startsoffset,
stopsoffset,
lenstarts,
lencarry);
}
template <>
Error awkward_listarray_getitem_carry_64<int64_t>(
int64_t* tostarts,
int64_t* tostops,
const int64_t* fromstarts,
const int64_t* fromstops,
const int64_t* fromcarry,
int64_t startsoffset,
int64_t stopsoffset,
int64_t lenstarts,
int64_t lencarry) {
return awkward_listarray64_getitem_carry_64(
tostarts,
tostops,
fromstarts,
fromstops,
fromcarry,
startsoffset,
stopsoffset,
lenstarts,
lencarry);
}
template <>
Error awkward_listarray_num_64<int32_t>(
int64_t* tonum,
const int32_t* fromstarts,
int64_t startsoffset,
const int32_t* fromstops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray32_num_64(
tonum,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_num_64<uint32_t>(
int64_t* tonum,
const uint32_t* fromstarts,
int64_t startsoffset,
const uint32_t* fromstops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarrayU32_num_64(
tonum,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_num_64<int64_t>(
int64_t* tonum,
const int64_t* fromstarts,
int64_t startsoffset,
const int64_t* fromstops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray64_num_64(
tonum,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
length);
}
template <>
Error awkward_listoffsetarray_flatten_offsets_64<int32_t>(
int64_t* tooffsets,
const int32_t* outeroffsets,
int64_t outeroffsetsoffset,
int64_t outeroffsetslen,
const int64_t* inneroffsets,
int64_t inneroffsetsoffset,
int64_t inneroffsetslen) {
return awkward_listoffsetarray32_flatten_offsets_64(
tooffsets,
outeroffsets,
outeroffsetsoffset,
outeroffsetslen,
inneroffsets,
inneroffsetsoffset,
inneroffsetslen);
}
template <>
Error awkward_listoffsetarray_flatten_offsets_64<uint32_t>(
int64_t* tooffsets,
const uint32_t* outeroffsets,
int64_t outeroffsetsoffset,
int64_t outeroffsetslen,
const int64_t* inneroffsets,
int64_t inneroffsetsoffset,
int64_t inneroffsetslen) {
return awkward_listoffsetarrayU32_flatten_offsets_64(
tooffsets,
outeroffsets,
outeroffsetsoffset,
outeroffsetslen,
inneroffsets,
inneroffsetsoffset,
inneroffsetslen);
}
template <>
Error awkward_listoffsetarray_flatten_offsets_64<int64_t>(
int64_t* tooffsets,
const int64_t* outeroffsets,
int64_t outeroffsetsoffset,
int64_t outeroffsetslen,
const int64_t* inneroffsets,
int64_t inneroffsetsoffset,
int64_t inneroffsetslen) {
return awkward_listoffsetarray64_flatten_offsets_64(
tooffsets,
outeroffsets,
outeroffsetsoffset,
outeroffsetslen,
inneroffsets,
inneroffsetsoffset,
inneroffsetslen);
}
template <>
Error awkward_indexedarray_flatten_none2empty_64<int32_t>(
int64_t* outoffsets,
const int32_t* outindex,
int64_t outindexoffset,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_indexedarray32_flatten_none2empty_64(
outoffsets,
outindex,
outindexoffset,
outindexlength,
offsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_indexedarray_flatten_none2empty_64<uint32_t>(
int64_t* outoffsets,
const uint32_t* outindex,
int64_t outindexoffset,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_indexedarrayU32_flatten_none2empty_64(
outoffsets,
outindex,
outindexoffset,
outindexlength,
offsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_indexedarray_flatten_none2empty_64<int64_t>(
int64_t* outoffsets,
const int64_t* outindex,
int64_t outindexoffset,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_indexedarray64_flatten_none2empty_64(
outoffsets,
outindex,
outindexoffset,
outindexlength,
offsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_unionarray_flatten_length_64<int8_t,
int32_t>(
int64_t* total_length,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int32_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarray32_flatten_length_64(
total_length,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_unionarray_flatten_length_64<int8_t,
uint32_t>(
int64_t* total_length,
const int8_t* fromtags,
int64_t fromtagsoffset,
const uint32_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarrayU32_flatten_length_64(
total_length,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_unionarray_flatten_length_64<int8_t,
int64_t>(
int64_t* total_length,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int64_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarray64_flatten_length_64(
total_length,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_unionarray_flatten_combine_64<int8_t,
int32_t>(
int8_t* totags,
int64_t* toindex,
int64_t* tooffsets,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int32_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarray32_flatten_combine_64(
totags,
toindex,
tooffsets,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_unionarray_flatten_combine_64<int8_t,
uint32_t>(
int8_t* totags,
int64_t* toindex,
int64_t* tooffsets,
const int8_t* fromtags,
int64_t fromtagsoffset,
const uint32_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarrayU32_flatten_combine_64(
totags,
toindex,
tooffsets,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_unionarray_flatten_combine_64<int8_t,
int64_t>(
int8_t* totags,
int64_t* toindex,
int64_t* tooffsets,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int64_t* fromindex,
int64_t fromindexoffset,
int64_t length,
int64_t** offsetsraws,
int64_t* offsetsoffsets) {
return awkward_unionarray64_flatten_combine_64(
totags,
toindex,
tooffsets,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
length,
offsetsraws,
offsetsoffsets);
}
template <>
Error awkward_indexedarray_flatten_nextcarry_64<int32_t>(
int64_t* tocarry,
const int32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray32_flatten_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_flatten_nextcarry_64<uint32_t>(
int64_t* tocarry,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarrayU32_flatten_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_flatten_nextcarry_64<int64_t>(
int64_t* tocarry,
const int64_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray64_flatten_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_numnull<int32_t>(
int64_t* numnull,
const int32_t* fromindex,
int64_t indexoffset,
int64_t lenindex) {
return awkward_indexedarray32_numnull(
numnull,
fromindex,
indexoffset,
lenindex);
}
template <>
Error awkward_indexedarray_numnull<uint32_t>(
int64_t* numnull,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t lenindex) {
return awkward_indexedarrayU32_numnull(
numnull,
fromindex,
indexoffset,
lenindex);
}
template <>
Error awkward_indexedarray_numnull<int64_t>(
int64_t* numnull,
const int64_t* fromindex,
int64_t indexoffset,
int64_t lenindex) {
return awkward_indexedarray64_numnull(
numnull,
fromindex,
indexoffset,
lenindex);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_64<int32_t>(
int64_t* tocarry,
int32_t* toindex,
const int32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray32_getitem_nextcarry_outindex_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_64<uint32_t>(
int64_t* tocarry,
uint32_t* toindex,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarrayU32_getitem_nextcarry_outindex_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_64<int64_t>(
int64_t* tocarry,
int64_t* toindex,
const int64_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray64_getitem_nextcarry_outindex_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_mask_64<int32_t>(
int64_t* tocarry,
int64_t* toindex,
const int32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray32_getitem_nextcarry_outindex_mask_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_mask_64<uint32_t>(
int64_t* tocarry,
int64_t* toindex,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarrayU32_getitem_nextcarry_outindex_mask_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_outindex_mask_64<int64_t>(
int64_t* tocarry,
int64_t* toindex,
const int64_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray64_getitem_nextcarry_outindex_mask_64(
tocarry,
toindex,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_64<int32_t>(
int64_t* tocarry,
const int32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray32_getitem_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_64<uint32_t>(
int64_t* tocarry,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarrayU32_getitem_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_nextcarry_64<int64_t>(
int64_t* tocarry,
const int64_t* fromindex,
int64_t indexoffset,
int64_t lenindex,
int64_t lencontent) {
return awkward_indexedarray64_getitem_nextcarry_64(
tocarry,
fromindex,
indexoffset,
lenindex,
lencontent);
}
template <>
Error awkward_indexedarray_getitem_carry_64<int32_t>(
int32_t* toindex,
const int32_t* fromindex,
const int64_t* fromcarry,
int64_t indexoffset,
int64_t lenindex,
int64_t lencarry) {
return awkward_indexedarray32_getitem_carry_64(
toindex,
fromindex,
fromcarry,
indexoffset,
lenindex,
lencarry);
}
template <>
Error awkward_indexedarray_getitem_carry_64<uint32_t>(
uint32_t* toindex,
const uint32_t* fromindex,
const int64_t* fromcarry,
int64_t indexoffset,
int64_t lenindex,
int64_t lencarry) {
return awkward_indexedarrayU32_getitem_carry_64(
toindex,
fromindex,
fromcarry,
indexoffset,
lenindex,
lencarry);
}
template <>
Error awkward_indexedarray_getitem_carry_64<int64_t>(
int64_t* toindex,
const int64_t* fromindex,
const int64_t* fromcarry,
int64_t indexoffset,
int64_t lenindex,
int64_t lencarry) {
return awkward_indexedarray64_getitem_carry_64(
toindex,
fromindex,
fromcarry,
indexoffset,
lenindex,
lencarry);
}
template <>
Error awkward_indexedarray_overlay_mask8_to64<int32_t>(
int64_t* toindex,
const int8_t* mask,
int64_t maskoffset,
const int32_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarray32_overlay_mask8_to64(
toindex,
mask,
maskoffset,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_overlay_mask8_to64<uint32_t>(
int64_t* toindex,
const int8_t* mask,
int64_t maskoffset,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarrayU32_overlay_mask8_to64(
toindex,
mask,
maskoffset,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_overlay_mask8_to64<int64_t>(
int64_t* toindex,
const int8_t* mask,
int64_t maskoffset,
const int64_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarray64_overlay_mask8_to64(
toindex,
mask,
maskoffset,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_mask8<int32_t>(
int8_t* tomask,
const int32_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarray32_mask8(
tomask,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_mask8<uint32_t>(
int8_t* tomask,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarrayU32_mask8(
tomask,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_mask8<int64_t>(
int8_t* tomask,
const int64_t* fromindex,
int64_t indexoffset,
int64_t length) {
return awkward_indexedarray64_mask8(
tomask,
fromindex,
indexoffset,
length);
}
template <>
Error awkward_indexedarray_simplify32_to64<int32_t>(
int64_t* toindex,
const int32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray32_simplify32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplify32_to64<uint32_t>(
int64_t* toindex,
const uint32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarrayU32_simplify32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplify32_to64<int64_t>(
int64_t* toindex,
const int64_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray64_simplify32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplifyU32_to64<int32_t>(
int64_t* toindex,
const int32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const uint32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray32_simplifyU32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplifyU32_to64<uint32_t>(
int64_t* toindex,
const uint32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const uint32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarrayU32_simplifyU32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplifyU32_to64<int64_t>(
int64_t* toindex,
const int64_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const uint32_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray64_simplifyU32_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplify64_to64<int32_t>(
int64_t* toindex,
const int32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int64_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray32_simplify64_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplify64_to64<uint32_t>(
int64_t* toindex,
const uint32_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int64_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarrayU32_simplify64_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_indexedarray_simplify64_to64<int64_t>(
int64_t* toindex,
const int64_t* outerindex,
int64_t outeroffset,
int64_t outerlength,
const int64_t* innerindex,
int64_t inneroffset,
int64_t innerlength) {
return awkward_indexedarray64_simplify64_to64(
toindex,
outerindex,
outeroffset,
outerlength,
innerindex,
inneroffset,
innerlength);
}
template <>
Error awkward_unionarray_regular_index_getsize<int8_t>(
int64_t* size,
const int8_t* fromtags,
int64_t tagsoffset,
int64_t length) {
return awkward_unionarray8_regular_index_getsize(
size,
fromtags,
tagsoffset,
length);
}
template <>
Error awkward_unionarray_regular_index<int8_t,
int32_t>(
int32_t* toindex,
int32_t* current,
int64_t size,
const int8_t* fromtags,
int64_t tagsoffset,
int64_t length) {
return awkward_unionarray8_32_regular_index(
toindex,
current,
size,
fromtags,
tagsoffset,
length);
}
template <>
Error awkward_unionarray_regular_index<int8_t,
uint32_t>(
uint32_t* toindex,
uint32_t* current,
int64_t size,
const int8_t* fromtags,
int64_t tagsoffset,
int64_t length) {
return awkward_unionarray8_U32_regular_index(
toindex,
current,
size,
fromtags,
tagsoffset,
length);
}
template <>
Error awkward_unionarray_regular_index<int8_t,
int64_t>(
int64_t* toindex,
int64_t* current,
int64_t size,
const int8_t* fromtags,
int64_t tagsoffset,
int64_t length) {
return awkward_unionarray8_64_regular_index(
toindex,
current,
size,
fromtags,
tagsoffset,
length);
}
template <>
Error awkward_unionarray_project_64<int8_t,
int32_t>(
int64_t* lenout,
int64_t* tocarry,
const int8_t* fromtags,
int64_t tagsoffset,
const int32_t* fromindex,
int64_t indexoffset,
int64_t length,
int64_t which) {
return awkward_unionarray8_32_project_64(
lenout,
tocarry,
fromtags,
tagsoffset,
fromindex,
indexoffset,
length,
which);
}
template <>
Error awkward_unionarray_project_64<int8_t,
uint32_t>(
int64_t* lenout,
int64_t* tocarry,
const int8_t* fromtags,
int64_t tagsoffset,
const uint32_t* fromindex,
int64_t indexoffset,
int64_t length,
int64_t which) {
return awkward_unionarray8_U32_project_64(
lenout,
tocarry,
fromtags,
tagsoffset,
fromindex,
indexoffset,
length,
which);
}
template <>
Error awkward_unionarray_project_64<int8_t,
int64_t>(
int64_t* lenout,
int64_t* tocarry,
const int8_t* fromtags,
int64_t tagsoffset,
const int64_t* fromindex,
int64_t indexoffset,
int64_t length,
int64_t which) {
return awkward_unionarray8_64_project_64(
lenout,
tocarry,
fromtags,
tagsoffset,
fromindex,
indexoffset,
length,
which);
}
template <>
Error awkward_listarray_compact_offsets64(
int64_t* tooffsets,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t startsoffset,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray32_compact_offsets64(
tooffsets,
fromstarts,
fromstops,
startsoffset,
stopsoffset,
length);
}
template <>
Error awkward_listarray_compact_offsets64(
int64_t* tooffsets,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t startsoffset,
int64_t stopsoffset,
int64_t length) {
return awkward_listarrayU32_compact_offsets64(
tooffsets,
fromstarts,
fromstops,
startsoffset,
stopsoffset,
length);
}
template <>
Error awkward_listarray_compact_offsets64(
int64_t* tooffsets,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t startsoffset,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray64_compact_offsets64(
tooffsets,
fromstarts,
fromstops,
startsoffset,
stopsoffset,
length);
}
template <>
Error awkward_listoffsetarray_compact_offsets64(
int64_t* tooffsets,
const int32_t* fromoffsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listoffsetarray32_compact_offsets64(
tooffsets,
fromoffsets,
offsetsoffset,
length);
}
template <>
Error awkward_listoffsetarray_compact_offsets64(
int64_t* tooffsets,
const uint32_t* fromoffsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listoffsetarrayU32_compact_offsets64(
tooffsets,
fromoffsets,
offsetsoffset,
length);
}
template <>
Error awkward_listoffsetarray_compact_offsets64(
int64_t* tooffsets,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listoffsetarray64_compact_offsets64(
tooffsets,
fromoffsets,
offsetsoffset,
length);
}
template <>
Error awkward_listarray_broadcast_tooffsets64<int32_t>(
int64_t* tocarry,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength,
const int32_t* fromstarts,
int64_t startsoffset,
const int32_t* fromstops,
int64_t stopsoffset,
int64_t lencontent) {
return awkward_listarray32_broadcast_tooffsets64(
tocarry,
fromoffsets,
offsetsoffset,
offsetslength,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
lencontent);
}
template <>
Error awkward_listarray_broadcast_tooffsets64<uint32_t>(
int64_t* tocarry,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength,
const uint32_t* fromstarts,
int64_t startsoffset,
const uint32_t* fromstops,
int64_t stopsoffset,
int64_t lencontent) {
return awkward_listarrayU32_broadcast_tooffsets64(
tocarry,
fromoffsets,
offsetsoffset,
offsetslength,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
lencontent);
}
template <>
Error awkward_listarray_broadcast_tooffsets64<int64_t>(
int64_t* tocarry,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength,
const int64_t* fromstarts,
int64_t startsoffset,
const int64_t* fromstops,
int64_t stopsoffset,
int64_t lencontent) {
return awkward_listarray64_broadcast_tooffsets64(
tocarry,
fromoffsets,
offsetsoffset,
offsetslength,
fromstarts,
startsoffset,
fromstops,
stopsoffset,
lencontent);
}
template <>
Error awkward_listoffsetarray_toRegularArray<int32_t>(
int64_t* size,
const int32_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_listoffsetarray32_toRegularArray(
size,
fromoffsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_listoffsetarray_toRegularArray<uint32_t>(
int64_t* size,
const uint32_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_listoffsetarrayU32_toRegularArray(
size,
fromoffsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_listoffsetarray_toRegularArray(
int64_t* size,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t offsetslength) {
return awkward_listoffsetarray64_toRegularArray(
size,
fromoffsets,
offsetsoffset,
offsetslength);
}
template <>
Error awkward_unionarray_simplify8_32_to8_64<int8_t,
int32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_32_simplify8_32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_32_to8_64<int8_t,
uint32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const uint32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_U32_simplify8_32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_32_to8_64<int8_t,
int64_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int64_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_64_simplify8_32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_U32_to8_64<int8_t,
int32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const uint32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_32_simplify8_U32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_U32_to8_64<int8_t,
uint32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const uint32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const uint32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_U32_simplify8_U32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_U32_to8_64<int8_t,
int64_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int64_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const uint32_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_64_simplify8_U32_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_64_to8_64<int8_t,
int32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int64_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_32_simplify8_64_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_64_to8_64<int8_t,
uint32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const uint32_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int64_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_U32_simplify8_64_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify8_64_to8_64<int8_t,
int64_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* outertags,
int64_t outertagsoffset,
const int64_t* outerindex,
int64_t outerindexoffset,
const int8_t* innertags,
int64_t innertagsoffset,
const int64_t* innerindex,
int64_t innerindexoffset,
int64_t towhich,
int64_t innerwhich,
int64_t outerwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_64_simplify8_64_to8_64(
totags,
toindex,
outertags,
outertagsoffset,
outerindex,
outerindexoffset,
innertags,
innertagsoffset,
innerindex,
innerindexoffset,
towhich,
innerwhich,
outerwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify_one_to8_64<int8_t,
int32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int32_t* fromindex,
int64_t fromindexoffset,
int64_t towhich,
int64_t fromwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_32_simplify_one_to8_64(
totags,
toindex,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
towhich,
fromwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify_one_to8_64<int8_t,
uint32_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* fromtags,
int64_t fromtagsoffset,
const uint32_t* fromindex,
int64_t fromindexoffset,
int64_t towhich,
int64_t fromwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_U32_simplify_one_to8_64(
totags,
toindex,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
towhich,
fromwhich,
length,
base);
}
template <>
Error awkward_unionarray_simplify_one_to8_64<int8_t,
int64_t>(
int8_t* totags,
int64_t* toindex,
const int8_t* fromtags,
int64_t fromtagsoffset,
const int64_t* fromindex,
int64_t fromindexoffset,
int64_t towhich,
int64_t fromwhich,
int64_t length,
int64_t base) {
return awkward_unionarray8_64_simplify_one_to8_64(
totags,
toindex,
fromtags,
fromtagsoffset,
fromindex,
fromindexoffset,
towhich,
fromwhich,
length,
base);
}
template <>
Error awkward_listarray_getitem_jagged_expand_64<int32_t>(
int64_t* multistarts,
int64_t* multistops,
const int64_t* singleoffsets,
int64_t* tocarry,
const int32_t* fromstarts,
int64_t fromstartsoffset,
const int32_t* fromstops,
int64_t fromstopsoffset,
int64_t jaggedsize,
int64_t length) {
return awkward_listarray32_getitem_jagged_expand_64(
multistarts,
multistops,
singleoffsets,
tocarry,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
jaggedsize,
length);
}
template <>
Error awkward_listarray_getitem_jagged_expand_64(
int64_t* multistarts,
int64_t* multistops,
const int64_t* singleoffsets,
int64_t* tocarry,
const uint32_t* fromstarts,
int64_t fromstartsoffset,
const uint32_t* fromstops,
int64_t fromstopsoffset,
int64_t jaggedsize,
int64_t length) {
return awkward_listarrayU32_getitem_jagged_expand_64(
multistarts,
multistops,
singleoffsets,
tocarry,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
jaggedsize,
length);
}
template <>
Error awkward_listarray_getitem_jagged_expand_64(
int64_t* multistarts,
int64_t* multistops,
const int64_t* singleoffsets,
int64_t* tocarry,
const int64_t* fromstarts,
int64_t fromstartsoffset,
const int64_t* fromstops,
int64_t fromstopsoffset,
int64_t jaggedsize,
int64_t length) {
return awkward_listarray64_getitem_jagged_expand_64(
multistarts,
multistops,
singleoffsets,
tocarry,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
jaggedsize,
length);
}
template <>
Error awkward_listarray_getitem_jagged_apply_64<int32_t>(
int64_t* tooffsets,
int64_t* tocarry,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const int64_t* sliceindex,
int64_t sliceindexoffset,
int64_t sliceinnerlen,
const int32_t* fromstarts,
int64_t fromstartsoffset,
const int32_t* fromstops,
int64_t fromstopsoffset,
int64_t contentlen) {
return awkward_listarray32_getitem_jagged_apply_64(
tooffsets,
tocarry,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
sliceindex,
sliceindexoffset,
sliceinnerlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
contentlen);
}
template <>
Error awkward_listarray_getitem_jagged_apply_64<uint32_t>(
int64_t* tooffsets,
int64_t* tocarry,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const int64_t* sliceindex,
int64_t sliceindexoffset,
int64_t sliceinnerlen,
const uint32_t* fromstarts,
int64_t fromstartsoffset,
const uint32_t* fromstops,
int64_t fromstopsoffset,
int64_t contentlen) {
return awkward_listarrayU32_getitem_jagged_apply_64(
tooffsets,
tocarry,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
sliceindex,
sliceindexoffset,
sliceinnerlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
contentlen);
}
template <>
Error awkward_listarray_getitem_jagged_apply_64<int64_t>(
int64_t* tooffsets,
int64_t* tocarry,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const int64_t* sliceindex,
int64_t sliceindexoffset,
int64_t sliceinnerlen,
const int64_t* fromstarts,
int64_t fromstartsoffset,
const int64_t* fromstops,
int64_t fromstopsoffset,
int64_t contentlen) {
return awkward_listarray64_getitem_jagged_apply_64(
tooffsets,
tocarry,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
sliceindex,
sliceindexoffset,
sliceinnerlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset,
contentlen);
}
template <>
Error awkward_listarray_getitem_jagged_descend_64<int32_t>(
int64_t* tooffsets,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const int32_t* fromstarts,
int64_t fromstartsoffset,
const int32_t* fromstops,
int64_t fromstopsoffset) {
return awkward_listarray32_getitem_jagged_descend_64(
tooffsets,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset);
}
template <>
Error awkward_listarray_getitem_jagged_descend_64<uint32_t>(
int64_t* tooffsets,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const uint32_t* fromstarts,
int64_t fromstartsoffset,
const uint32_t* fromstops,
int64_t fromstopsoffset) {
return awkward_listarrayU32_getitem_jagged_descend_64(
tooffsets,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset);
}
template <>
Error awkward_listarray_getitem_jagged_descend_64<int64_t>(
int64_t* tooffsets,
const int64_t* slicestarts,
int64_t slicestartsoffset,
const int64_t* slicestops,
int64_t slicestopsoffset,
int64_t sliceouterlen,
const int64_t* fromstarts,
int64_t fromstartsoffset,
const int64_t* fromstops,
int64_t fromstopsoffset) {
return awkward_listarray64_getitem_jagged_descend_64(
tooffsets,
slicestarts,
slicestartsoffset,
slicestops,
slicestopsoffset,
sliceouterlen,
fromstarts,
fromstartsoffset,
fromstops,
fromstopsoffset);
}
template <>
Error awkward_indexedarray_reduce_next_64<int32_t>(
int64_t* nextcarry,
int64_t* nextparents,
int64_t* outindex,
const int32_t* index,
int64_t indexoffset,
int64_t* parents,
int64_t parentsoffset,
int64_t length) {
return awkward_indexedarray32_reduce_next_64(
nextcarry,
nextparents,
outindex,
index,
indexoffset,
parents,
parentsoffset,
length);
}
template <>
Error awkward_indexedarray_reduce_next_64<uint32_t>(
int64_t* nextcarry,
int64_t* nextparents,
int64_t* outindex,
const uint32_t* index,
int64_t indexoffset,
int64_t* parents,
int64_t parentsoffset,
int64_t length) {
return awkward_indexedarrayU32_reduce_next_64(
nextcarry,
nextparents,
outindex,
index,
indexoffset,
parents,
parentsoffset,
length);
}
template <>
Error awkward_indexedarray_reduce_next_64<int64_t>(
int64_t* nextcarry,
int64_t* nextparents,
int64_t* outindex,
const int64_t* index,
int64_t indexoffset,
int64_t* parents,
int64_t parentsoffset,
int64_t length) {
return awkward_indexedarray64_reduce_next_64(
nextcarry,
nextparents,
outindex,
index,
indexoffset,
parents,
parentsoffset,
length);
}
template <>
Error awkward_UnionArray_fillna_64<int32_t>(
int64_t* toindex,
const int32_t* fromindex,
int64_t offset,
int64_t length) {
return awkward_UnionArray_fillna_from32_to64(
toindex,
fromindex,
offset,
length);
}
template <>
Error awkward_UnionArray_fillna_64<uint32_t>(
int64_t* toindex,
const uint32_t* fromindex,
int64_t offset,
int64_t length) {
return awkward_UnionArray_fillna_fromU32_to64(
toindex,
fromindex,
offset,
length);
}
template <>
Error awkward_UnionArray_fillna_64<int64_t>(
int64_t* toindex,
const int64_t* fromindex,
int64_t offset,
int64_t length) {
return awkward_UnionArray_fillna_from64_to64(
toindex,
fromindex,
offset,
length);
}
template <>
Error awkward_ListArray_min_range<int32_t>(
int64_t* tomin,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray32_min_range(
tomin,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_min_range<uint32_t>(
int64_t* tomin,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArrayU32_min_range(
tomin,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_min_range<int64_t>(
int64_t* tomin,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray64_min_range(
tomin,
fromstarts,
fromstops,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListOffsetArray_rpad_length_axis1<int32_t>(
int32_t* tooffsets,
const int32_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t length,
int64_t* tocount) {
return awkward_ListOffsetArray32_rpad_length_axis1(
tooffsets,
fromoffsets,
offsetsoffset,
fromlength,
length,
tocount);
}
template <>
Error awkward_ListOffsetArray_rpad_length_axis1<uint32_t>(
uint32_t* tooffsets,
const uint32_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t length,
int64_t* tocount) {
return awkward_ListOffsetArrayU32_rpad_length_axis1(
tooffsets,
fromoffsets,
offsetsoffset,
fromlength,
length,
tocount);
}
template <>
Error awkward_ListOffsetArray_rpad_length_axis1<int64_t>(
int64_t* tooffsets,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t length,
int64_t* tocount) {
return awkward_ListOffsetArray64_rpad_length_axis1(
tooffsets,
fromoffsets,
offsetsoffset,
fromlength,
length,
tocount);
}
template <>
Error awkward_ListOffsetArray_rpad_axis1_64<int32_t>(
int64_t* toindex,
const int32_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t target) {
return awkward_ListOffsetArray32_rpad_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
fromlength,
target);
}
template <>
Error awkward_ListOffsetArray_rpad_axis1_64<uint32_t>(
int64_t* toindex,
const uint32_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t target) {
return awkward_ListOffsetArrayU32_rpad_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
fromlength,
target);
}
template <>
Error awkward_ListOffsetArray_rpad_axis1_64<int64_t>(
int64_t* toindex,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t fromlength,
int64_t target) {
return awkward_ListOffsetArray64_rpad_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
fromlength,
target);
}
template <>
Error awkward_ListArray_rpad_axis1_64<int32_t>(
int64_t* toindex,
const int32_t* fromstarts,
const int32_t* fromstops,
int32_t* tostarts,
int32_t* tostops,
int64_t target,
int64_t length,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray32_rpad_axis1_64(
toindex,
fromstarts,
fromstops,
tostarts,
tostops,
target,
length,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_rpad_axis1_64<uint32_t>(
int64_t* toindex,
const uint32_t* fromstarts,
const uint32_t* fromstops,
uint32_t* tostarts,
uint32_t* tostops,
int64_t target,
int64_t length,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArrayU32_rpad_axis1_64(
toindex,
fromstarts,
fromstops,
tostarts,
tostops,
target,
length,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_rpad_axis1_64<int64_t>(
int64_t* toindex,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t* tostarts,
int64_t* tostops,
int64_t target,
int64_t length,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray64_rpad_axis1_64(
toindex,
fromstarts,
fromstops,
tostarts,
tostops,
target,
length,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_rpad_and_clip_length_axis1<int32_t>(
int64_t* tolength,
const int32_t* fromstarts,
const int32_t* fromstops,
int64_t target,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray32_rpad_and_clip_length_axis1(
tolength,
fromstarts,
fromstops,
target,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_rpad_and_clip_length_axis1<uint32_t>(
int64_t* tolength,
const uint32_t* fromstarts,
const uint32_t* fromstops,
int64_t target,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArrayU32_rpad_and_clip_length_axis1(
tolength,
fromstarts,
fromstops,
target,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListArray_rpad_and_clip_length_axis1<int64_t>(
int64_t* tolength,
const int64_t* fromstarts,
const int64_t* fromstops,
int64_t target,
int64_t lenstarts,
int64_t startsoffset,
int64_t stopsoffset) {
return awkward_ListArray64_rpad_and_clip_length_axis1(
tolength,
fromstarts,
fromstops,
target,
lenstarts,
startsoffset,
stopsoffset);
}
template <>
Error awkward_ListOffsetArray_rpad_and_clip_axis1_64<int32_t>(
int64_t* toindex,
const int32_t* fromoffsets,
int64_t offsetsoffset,
int64_t length,
int64_t target) {
return awkward_ListOffsetArray32_rpad_and_clip_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
length,
target);
}
template <>
Error awkward_ListOffsetArray_rpad_and_clip_axis1_64<uint32_t>(
int64_t* toindex,
const uint32_t* fromoffsets,
int64_t offsetsoffset,
int64_t length,
int64_t target) {
return awkward_ListOffsetArrayU32_rpad_and_clip_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
length,
target);
}
template <>
Error awkward_ListOffsetArray_rpad_and_clip_axis1_64<int64_t>(
int64_t* toindex,
const int64_t* fromoffsets,
int64_t offsetsoffset,
int64_t length,
int64_t target) {
return awkward_ListOffsetArray64_rpad_and_clip_axis1_64(
toindex,
fromoffsets,
offsetsoffset,
length,
target);
}
template <>
Error awkward_listarray_validity<int32_t>(
const int32_t* starts,
int64_t startsoffset,
const int32_t* stops,
int64_t stopsoffset,
int64_t length,
int64_t lencontent) {
return awkward_listarray32_validity(
starts,
startsoffset,
stops,
stopsoffset,
length,
lencontent);
}
template <>
Error awkward_listarray_validity<uint32_t>(
const uint32_t* starts,
int64_t startsoffset,
const uint32_t* stops,
int64_t stopsoffset,
int64_t length,
int64_t lencontent) {
return awkward_listarrayU32_validity(
starts,
startsoffset,
stops,
stopsoffset,
length,
lencontent);
}
template <>
Error awkward_listarray_validity<int64_t>(
const int64_t* starts,
int64_t startsoffset,
const int64_t* stops,
int64_t stopsoffset,
int64_t length,
int64_t lencontent) {
return awkward_listarray64_validity(
starts,
startsoffset,
stops,
stopsoffset,
length,
lencontent);
}
template <>
Error awkward_indexedarray_validity<int32_t>(
const int32_t* index,
int64_t indexoffset,
int64_t length,
int64_t lencontent,
bool isoption) {
return awkward_indexedarray32_validity(
index,
indexoffset,
length,
lencontent,
isoption);
}
template <>
Error awkward_indexedarray_validity<uint32_t>(
const uint32_t* index,
int64_t indexoffset,
int64_t length,
int64_t lencontent,
bool isoption) {
return awkward_indexedarrayU32_validity(
index,
indexoffset,
length,
lencontent,
isoption);
}
template <>
Error awkward_indexedarray_validity<int64_t>(
const int64_t* index,
int64_t indexoffset,
int64_t length,
int64_t lencontent,
bool isoption) {
return awkward_indexedarray64_validity(
index,
indexoffset,
length,
lencontent,
isoption);
}
template <>
Error awkward_unionarray_validity<int8_t,
int32_t>(
const int8_t* tags,
int64_t tagsoffset,
const int32_t* index,
int64_t indexoffset,
int64_t length,
int64_t numcontents,
const int64_t* lencontents) {
return awkward_unionarray8_32_validity(
tags,
tagsoffset,
index,
indexoffset,
length,
numcontents,
lencontents);
}
template <>
Error awkward_unionarray_validity<int8_t,
uint32_t>(
const int8_t* tags,
int64_t tagsoffset,
const uint32_t* index,
int64_t indexoffset,
int64_t length,
int64_t numcontents,
const int64_t* lencontents) {
return awkward_unionarray8_U32_validity(
tags,
tagsoffset,
index,
indexoffset,
length,
numcontents,
lencontents);
}
template <>
Error awkward_unionarray_validity<int8_t,
int64_t>(
const int8_t* tags,
int64_t tagsoffset,
const int64_t* index,
int64_t indexoffset,
int64_t length,
int64_t numcontents,
const int64_t* lencontents) {
return awkward_unionarray8_64_validity(
tags,
tagsoffset,
index,
indexoffset,
length,
numcontents,
lencontents);
}
template <>
Error awkward_listarray_localindex_64<int32_t>(
int64_t* toindex,
const int32_t* offsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listarray32_localindex_64(
toindex,
offsets,
offsetsoffset,
length);
}
template <>
Error awkward_listarray_localindex_64<uint32_t>(
int64_t* toindex,
const uint32_t* offsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listarrayU32_localindex_64(
toindex,
offsets,
offsetsoffset,
length);
}
template <>
Error awkward_listarray_localindex_64<int64_t>(
int64_t* toindex,
const int64_t* offsets,
int64_t offsetsoffset,
int64_t length) {
return awkward_listarray64_localindex_64(
toindex,
offsets,
offsetsoffset,
length);
}
template <>
Error awkward_listarray_combinations_length_64<int32_t>(
int64_t* totallen,
int64_t* tooffsets,
int64_t n,
bool replacement,
const int32_t* starts,
int64_t startsoffset,
const int32_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray32_combinations_length_64(
totallen,
tooffsets,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_combinations_length_64<uint32_t>(
int64_t* totallen,
int64_t* tooffsets,
int64_t n,
bool replacement,
const uint32_t* starts,
int64_t startsoffset,
const uint32_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarrayU32_combinations_length_64(
totallen,
tooffsets,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_combinations_length_64<int64_t>(
int64_t* totallen,
int64_t* tooffsets,
int64_t n,
bool replacement,
const int64_t* starts,
int64_t startsoffset,
const int64_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray64_combinations_length_64(
totallen,
tooffsets,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_combinations_64<int32_t>(
int64_t** tocarry,
int64_t n,
bool replacement,
const int32_t* starts,
int64_t startsoffset,
const int32_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray32_combinations_64(
tocarry,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_combinations_64<uint32_t>(
int64_t** tocarry,
int64_t n,
bool replacement,
const uint32_t* starts,
int64_t startsoffset,
const uint32_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarrayU32_combinations_64(
tocarry,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
Error awkward_listarray_combinations_64<int64_t>(
int64_t** tocarry,
int64_t n,
bool replacement,
const int64_t* starts,
int64_t startsoffset,
const int64_t* stops,
int64_t stopsoffset,
int64_t length) {
return awkward_listarray64_combinations_64(
tocarry,
n,
replacement,
starts,
startsoffset,
stops,
stopsoffset,
length);
}
template <>
int8_t awkward_index_getitem_at_nowrap<int8_t>(
const int8_t* ptr,
int64_t offset,
int64_t at) {
return awkward_index8_getitem_at_nowrap(
ptr,
offset,
at);
}
template <>
uint8_t awkward_index_getitem_at_nowrap<uint8_t>(
const uint8_t* ptr,
int64_t offset,
int64_t at) {
return awkward_indexU8_getitem_at_nowrap(
ptr,
offset,
at);
}
template <>
int32_t awkward_index_getitem_at_nowrap<int32_t>(
const int32_t* ptr,
int64_t offset,
int64_t at) {
return awkward_index32_getitem_at_nowrap(
ptr,
offset,
at);
}
template <>
uint32_t awkward_index_getitem_at_nowrap<uint32_t>(
const uint32_t* ptr,
int64_t offset,
int64_t at) {
return awkward_indexU32_getitem_at_nowrap(
ptr,
offset,
at);
}
template <>
int64_t awkward_index_getitem_at_nowrap<int64_t>(
const int64_t* ptr,
int64_t offset,
int64_t at) {
return awkward_index64_getitem_at_nowrap(
ptr,
offset,
at);
}
template <>
void awkward_index_setitem_at_nowrap<int8_t>(
int8_t* ptr,
int64_t offset,
int64_t at,
int8_t value) {
awkward_index8_setitem_at_nowrap(
ptr,
offset,
at,
value);
}
template <>
void awkward_index_setitem_at_nowrap<uint8_t>(
uint8_t* ptr,
int64_t offset,
int64_t at,
uint8_t value) {
awkward_indexU8_setitem_at_nowrap(
ptr,
offset,
at,
value);
}
template <>
void awkward_index_setitem_at_nowrap<int32_t>(
int32_t* ptr,
int64_t offset,
int64_t at,
int32_t value) {
awkward_index32_setitem_at_nowrap(
ptr,
offset,
at,
value);
}
template <>
void awkward_index_setitem_at_nowrap<uint32_t>(
uint32_t* ptr,
int64_t offset,
int64_t at,
uint32_t value) {
awkward_indexU32_setitem_at_nowrap(
ptr,
offset,
at,
value);
}
template <>
void awkward_index_setitem_at_nowrap<int64_t>(
int64_t* ptr,
int64_t offset,
int64_t at,
int64_t value) {
awkward_index64_setitem_at_nowrap(
ptr,
offset,
at,
value);
}
}
}
| 25.822475 | 90 | 0.60807 | [
"vector"
] |
8092b639a64e110d0b37d37e8eba8640d6cc92b2 | 1,394 | cpp | C++ | codeforces/1468/d/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codeforces/1468/d/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codeforces/1468/d/d.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/debug.h"
#else
#define db(...)
#endif
#define all(v) v.begin(), v.end()
#define pb push_back
using ll = long long;
const int NAX = 2e5 + 5, MOD = 1000000007;
#define int ll
void solveCase()
{
int n, m, a, b;
cin >> n >> m >> a >> b;
if (a > b)
{
a = n - a + 1;
b = n - b + 1;
}
vector<int> bombs(m);
for (auto &x : bombs)
cin >> x;
sort(all(bombs));
auto check = [&](int cnt) -> bool {
int maxt = 0;
db(cnt);
int b1 = b;
for (int i = cnt - 1; i >= 0; i--)
{
if (a == b1)
return false;
db(cnt - 1 - i + bombs[i]);
maxt = max(maxt, cnt - 1 - i + bombs[i]);
b1--;
}
if (a == b1)
return false;
db(b - 1, b1, maxt);
return (b - 1) > maxt;
};
int low = 0, high = m, ans = 0;
while (low <= high)
{
int mid = (low + high) / 2;
if (check(mid))
{
ans = max(ans, mid);
low = mid + 1;
}
else
high = mid - 1;
}
cout << ans << '\n';
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; ++i)
solveCase();
return 0;
} | 18.103896 | 53 | 0.412482 | [
"vector"
] |
8095edc3c6b39174cedcd9608b354bb31065052d | 26,633 | cc | C++ | arcane/src/arcane/ios/XmfMeshReader.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/ios/XmfMeshReader.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | arcane/src/arcane/ios/XmfMeshReader.cc | JeromeDuboisPro/framework | d88925495e3787fdaf640c29728dcac385160188 | [
"Apache-2.0"
] | null | null | null | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* XmfMeshReader.cc (C) 2000-2010 */
/* */
/* Lecture/Ecriture d'un fichier au format XMF. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/ArcaneTypes.h"
#include "arcane/utils/ArcanePrecomp.h"
#include "arcane/utils/Iostream.h"
#include "arcane/utils/StdHeader.h"
#include "arcane/utils/HashTableMap.h"
#include "arcane/utils/ValueConvert.h"
#include "arcane/utils/ScopedPtr.h"
#include "arcane/utils/ITraceMng.h"
#include "arcane/utils/String.h"
#include "arcane/utils/IOException.h"
#include "arcane/utils/Collection.h"
#include "arcane/utils/Enumerator.h"
#include "arcane/utils/NotImplementedException.h"
#include "arcane/utils/Real3.h"
#include "arcane/AbstractService.h"
#include "arcane/FactoryService.h"
#include "arcane/IMainFactory.h"
#include "arcane/IMeshReader.h"
#include "arcane/ISubDomain.h"
#include "arcane/IPrimaryMesh.h"
#include "arcane/IItemFamily.h"
#include "arcane/Item.h"
#include "arcane/ItemEnumerator.h"
#include "arcane/VariableTypes.h"
#include "arcane/IVariableAccessor.h"
#include "arcane/IParallelMng.h"
#include "arcane/IIOMng.h"
#include "arcane/IXmlDocumentHolder.h"
#include "arcane/XmlNodeList.h"
#include "arcane/XmlNode.h"
#include "arcane/IMeshUtilities.h"
#include "arcane/IMeshWriter.h"
#include "arcane/BasicService.h"
#define XDMF_USE_ANSI_STDLIB
#include "vtkxdmf2/XdmfArray.h"
#include "vtkxdmf2/XdmfAttribute.h"
#include "vtkxdmf2/XdmfDOM.h"
#include "vtkxdmf2/XdmfDataDesc.h"
#include "vtkxdmf2/XdmfDataItem.h"
#include "vtkxdmf2/XdmfGrid.h"
#include "vtkxdmf2/XdmfTopology.h"
#include "vtkxdmf2/XdmfGeometry.h"
#include "vtkxdmf2/XdmfTime.h"
/*#define H5_USE_16_API
#include <hdf5.h>*/
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
using namespace xdmf2;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Lecteur des fichiers de maillage aux format msh.
*/
class XmfMeshReader: public AbstractService, public IMeshReader{
public:
XmfMeshReader(const ServiceBuildInfo& sbi);
public:
virtual void build() {}
bool allowExtension(const String& str){return (str=="xmf");}
virtual eReturnType readMeshFromFile(IPrimaryMesh* mesh,const XmlNode& mesh_node,
const String& file_name, const String& dir_name,bool use_internal_partition);
ISubDomain* subDomain() { return m_sub_domain; }
private:
ISubDomain* m_sub_domain;
eReturnType _readTopology(XdmfTopology*, XdmfInt64&, Int32Array&, Int32Array&, Int32Array&, SharedArray<Int32>);
eReturnType _readMixedTopology(XdmfTopology*, XdmfInt64, Int32Array&, Int32Array&, Int32Array&, SharedArray<Int32>);
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_REGISTER_SUB_DOMAIN_FACTORY(XmfMeshReader, IMeshReader, XmfNewMeshReader);
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
XmfMeshReader::XmfMeshReader(const ServiceBuildInfo& sbi):AbstractService(sbi), m_sub_domain(sbi.subDomain()){}
/*****************************************************************************\
* [_addThisConnectivity] *
\*****************************************************************************/
#define _addThisConnectivity(nNodes, arcType)\
cells_type.add(arcType);\
cells_nb_node.add(nNodes);\
for (XdmfInt32 z=0; z<nNodes; ++z)\
cells_connectivity.add(nodesUidArray[xdmfConnectivity->GetValueAsInt32(i++)]);
/*****************************************************************************\
* [_readMixedTopology] *
\*****************************************************************************/
IMeshReader::eReturnType XmfMeshReader::
_readMixedTopology(XdmfTopology *Topology,
XdmfInt64 nb_elements,
Int32Array& cells_nb_node,
Int32Array& cells_connectivity,
Int32Array& cells_type,
SharedArray<Int32> nodesUidArray)
{
info() << "[_readMixedTopology] Entering";
XdmfArray *xdmfConnectivity=Topology->GetConnectivity(NULL, XDMF_TRUE);
XdmfInt32 numType=xdmfConnectivity->GetNumberType();
info() << "xdmfConnectivity.CoreLength=" << xdmfConnectivity->GetCoreLength()<< " numType=" << numType;
if (numType != XDMF_INT32_TYPE)
throw NotSupportedException(A_FUNCINFO, "Not supported connectivity num type");
XdmfInt32 nNodesForThisElement;
XdmfInt64 iElementsScaned=0;
for(XdmfInt64 i=0; iElementsScaned < nb_elements; iElementsScaned++){
// info() << "[_readMixedTopology] scan=" << iElementsScaned << "/" << nb_elements;
switch (xdmfConnectivity->GetValueAsInt32(i++)){
case (XDMF_POLYVERTEX): // 0x1
nNodesForThisElement=xdmfConnectivity->GetValueAsInt32(i++);
// info() << "[_readMixedTopology] XDMF_POLYVERTEX(" << nNodesForThisElement << ")";
switch (nNodesForThisElement){
case (1): _addThisConnectivity(1, IT_Vertex); break;
case (12): _addThisConnectivity(12, IT_Octaedron12); break;
case (14): _addThisConnectivity(14, IT_Enneedron14); break;
case (16): _addThisConnectivity(16, IT_Decaedron16); break;
case (7): _addThisConnectivity(7, IT_HemiHexa7); break;
case (6): _addThisConnectivity(6, IT_HemiHexa6); break;
// GG: je commente ces deux cas car dans la version de Oct2015 cela ne compile
// pas car IT_AntiWedgetLeft6 vaut 16 et donc la même valeur dans le switch
// que pour le IT_Decaedron16. De toute facon, je pense que le case avant ne fonctionnait
// pas car la valeur pour 6 noeuds est déjà prise par IT_HemiHexa6.
//case (IT_AntiWedgeLeft6): _addThisConnectivity(6, IT_AntiWedgeLeft6); break;
//case (IT_AntiWedgeRight6): _addThisConnectivity(6, IT_AntiWedgeRight6); break;
case (5): _addThisConnectivity(5, IT_HemiHexa5); break;
case (55): _addThisConnectivity(5, IT_DiTetra5); break;
default:
throw FatalErrorException(A_FUNCINFO, "XDMF_POLYVERTEX with unknown number of nodes");
}
break;
case (XDMF_POLYLINE): // 0x2
nNodesForThisElement=xdmfConnectivity->GetValueAsInt32(i++);
// info() << "[_readMixedTopology] XDMF_POLYLINE("<<nNodesForThisElement<<")";
switch (nNodesForThisElement){
case (2): _addThisConnectivity(2, IT_Line2); break;
default: throw FatalErrorException(A_FUNCINFO, "XDMF_POLYLINE with unknown number of nodes");
}
break;
case (XDMF_POLYGON): // 0x3
nNodesForThisElement=xdmfConnectivity->GetValueAsInt32(i++);
// info() << "[_readMixedTopology] XDMF_POLYGON("<<nNodesForThisElement<<")";
switch (nNodesForThisElement){
case (5): _addThisConnectivity(5, IT_Pentagon5); break;
case (6): _addThisConnectivity(6, IT_Hexagon6); break;
default: throw FatalErrorException(A_FUNCINFO, "XDMF_POLYGON with unknown number of nodes");
}
break;
case (XDMF_TRI):_addThisConnectivity(3, IT_Triangle3); break;// 0x4
case (XDMF_QUAD):_addThisConnectivity(4, IT_Quad4); break;// 0x5
case (XDMF_TET):_addThisConnectivity(4, IT_Tetraedron4); break;// 0x6
case (XDMF_PYRAMID):_addThisConnectivity(5, IT_Pyramid5); break;// 0x7
case (XDMF_WEDGE ):_addThisConnectivity(6, IT_Pentaedron6); break;// 0x8
case (XDMF_HEX):_addThisConnectivity(8, IT_Hexaedron8); break;// 0x9
case (XDMF_TET_10):_addThisConnectivity(10, IT_Heptaedron10); break;// 0x0026
case (XDMF_EDGE_3):
case (XDMF_TRI_6):
case (XDMF_QUAD_8):
case (XDMF_PYRAMID_13):
case (XDMF_WEDGE_15):
case (XDMF_HEX_20):
default: throw NotSupportedException(A_FUNCINFO, "Not supported topology type in a mixed one");
}
}
// delete xdmfConnectivity;
info() << "[_readMixedTopology] Done";
return RTOk;
}
/*****************************************************************************\
* [_readTopology] *
XML Element : Topology
XML Attribute : Name = Any String
XML Attribute : TopologyType = Polyvertex | Polyline | Polygon |
Triangle | Quadrilateral | Tetrahedron | Pyramid| Wedge | Hexahedron |
Edge_3 | Triagle_6 | Quadrilateral_8 | Tetrahedron_10 | Pyramid_13 |
Wedge_15 | Hexahedron_20 |
Mixed |
2DSMesh | 2DRectMesh | 2DCoRectMesh |
3DSMesh | 3DRectMesh | 3DCoRectMesh
XML Attribute : NumberOfElements = Number of Cells
XML Attribute : NodesPerElement = # (Only Important for Polyvertex, Polygon and Polyline)
XML Attribute : Order = Order of Nodes if not Default
XML BaseOffset: Offset if not 0
\*****************************************************************************/
IMeshReader::eReturnType XmfMeshReader::
_readTopology(XdmfTopology *Topology,
XdmfInt64& nb_elements,
Int32Array& cells_nb_node,
Int32Array& cells_connectivity,
Int32Array& cells_type,
SharedArray<Int32> nodesUidArray)
{
info() << "[_readTopology] Entering";
if (!Topology) throw FatalErrorException(A_FUNCINFO, "Null topology");
if (Topology->UpdateInformation() != XDMF_SUCCESS) throw FatalErrorException(A_FUNCINFO, "Error in UpdateInformation");
if (Topology->Update() != XDMF_SUCCESS) throw FatalErrorException(A_FUNCINFO, "Error in Update");
nb_elements = Topology->GetNumberOfElements();
info() << "\tHave found a " << Topology->GetClassAsString() << " "
<< Topology->GetTopologyTypeAsString() << " topology with " << nb_elements << " elements";
switch (Topology->GetTopologyType()){
case (XDMF_2DSMESH): // 0x0100
case (XDMF_2DRECTMESH): // 0x0101
case (XDMF_2DCORECTMESH): // 0x0102
case (XDMF_3DRECTMESH): // 0x1101
case (XDMF_3DCORECTMESH): // 0x1102
case (XDMF_3DSMESH):{ // 0x1100
// Try to do something with these kind of structured topologies
if ((nb_elements%3)==0){
for(XdmfInt64 i=0; i<nb_elements/3; i+=3){
cells_type.add(IT_Triangle3);
cells_nb_node.add(3);
for (Integer z=0; z<3; ++z)
cells_connectivity.add(i+z);
}
}else if ((nb_elements%4)==0){
for(XdmfInt64 i=0; i<nb_elements/4; i+=4){
cells_type.add(IT_Quad4);
cells_nb_node.add(4);
for (Integer z=0; z<4; ++z)
cells_connectivity.add(i+z);
}
}else throw FatalErrorException(A_FUNCINFO, "Could not match XDMF_3DSMESH with a known mesh");
return RTOk;
}
// Otherwise, read a mixed topology should do the trick
case (XDMF_POLYVERTEX): // 0x1
case (XDMF_POLYLINE): // 0x2
case (XDMF_POLYGON): // 0x3
case (XDMF_TRI): // 0x4
case (XDMF_QUAD): // 0x5
case (XDMF_TET): // 0x6
case (XDMF_PYRAMID): // 0x7
case (XDMF_WEDGE ): // 0x8
case (XDMF_HEX): // 0x9
case (XDMF_EDGE_3): // 0x0022
case (XDMF_TRI_6): // 0x0024
case (XDMF_QUAD_8): // 0x0025
case (XDMF_TET_10): // 0x0026
case (XDMF_PYRAMID_13): // 0x0027
case (XDMF_WEDGE_15): // 0x0028
case (XDMF_HEX_20): // 0x0029
case (XDMF_MIXED): // 0x0070
if (_readMixedTopology(Topology, nb_elements, cells_nb_node, cells_connectivity, cells_type, nodesUidArray) != RTOk)
throw FatalErrorException(A_FUNCINFO, "Error in _readMixedTopology");
break;
case (XDMF_NOTOPOLOGY): // 0x0
default: throw NotSupportedException(A_FUNCINFO, "Not supported topology type");
}
// Topology->Release();
// delete Topology;
info() << "[_readTopology] Release & Done";
return RTOk;
}
/*****************************************************************************
[readMeshFromFile]
The organization of XDMF begins with the Xdmf element. So that parsers can
distinguish from previous versions of XDMF, there exists a Version attribute
(currently at 2.0).
Xdmf elements contain one or more Domain elements (computational
domain). There is seldom motivation to have more than one Domain.
A Domain can have one or more Grid elements.
Each Grid contains a Topology, Geometry, and zero or more Attribute elements.
Topology specifies the connectivity of the grid while
Geometry specifies the location of the grid nodes.
*****************************************************************************/
IMeshReader::eReturnType XmfMeshReader::
readMeshFromFile(IPrimaryMesh* mesh,const XmlNode& mesh_node,
const String& file_name, const String& dir_name,bool use_internal_partition)
{
IParallelMng* pm = mesh->parallelMng();
bool is_parallel = pm->isParallel();
Integer sid = pm->commRank();
bool itWasAnArcanProduction=true;
info() << "[readMeshFromFile] Entering";
XdmfDOM *DOM = new XdmfDOM();
// Parse the XML File
if (DOM->SetInputFileName(file_name.localstr()) != XDMF_SUCCESS) throw FatalErrorException(A_FUNCINFO, "SetInputFileName");
if (DOM->Parse() != XDMF_SUCCESS) throw FatalErrorException(A_FUNCINFO, "Parse");
XdmfXmlNode XdmfRoot = DOM->GetTree();
// Version verification
if (strcmp(DOM->Get(XdmfRoot, "Version"), "2.0")<0) throw NotSupportedException(A_FUNCINFO, "Not supported Xdmf-file version");
// Now scan all of its children
XdmfInt64 nRootChildren=DOM->GetNumberOfChildren(XdmfRoot);
info() << "GetNumberOfChildren=" << nRootChildren;
//Xdmf elements contain one or more Domain elements
XdmfInt32 nDomains= DOM->FindNumberOfElements("Domain");
info() << "nDomains=" << nDomains;
for(XdmfInt64 iDomain=0; iDomain < nDomains; ++iDomain){
XdmfXmlNode foundDomain=DOM->FindElement("Domain", iDomain, XdmfRoot, 0);
if (foundDomain != NULL) info() << "Have found domain" << iDomain;
// A Domain can have one or more Grid elements.
XdmfInt32 nGrids= DOM->FindNumberOfElements("Grid", foundDomain);
info() << "nGrids=" << nGrids;
for(XdmfInt32 iGrid=0; iGrid < nGrids; ++iGrid){
/*****************************
Looking for the domain's Grid
******************************/
XdmfXmlNode foundGrid=DOM->FindElement("Grid", iGrid, foundDomain, 0);
if (foundGrid == NULL) throw FatalErrorException(A_FUNCINFO, "Grid not found for domain");
XdmfGrid *Grid = new XdmfGrid();
Grid->SetDOM(DOM);
Grid->SetElement(foundGrid);
Grid->UpdateInformation();
info() << "Have found a " << Grid->GetGridTypeAsString() << " grid";
if (Grid->GetGridType() != XDMF_GRID_UNIFORM) throw NotSupportedException(A_FUNCINFO, "Not supported GRID type");
/*****************************************************
Looking for XML attribute which Name="CellsUniqueIDs"
******************************************************/
XdmfXmlNode cellsUniqueIDsXmlNode = DOM->FindElementByAttribute ("Name", "CellsUniqueIDs", 0, foundGrid);
Int32UniqueArray cellsUidArray;
if (cellsUniqueIDsXmlNode) {
info() << "[XmfMeshReader] cellsUidArray were found";
XdmfAttribute *attribute = new XdmfAttribute();
attribute->SetDOM(DOM);
attribute->SetElement(cellsUniqueIDsXmlNode);
attribute->UpdateInformation();
attribute->Update();
XdmfArray *xmfGroup = attribute->GetValues();
info() << attribute->GetName() << "(" << attribute->GetAttributeTypeAsString() << ", "
<< attribute->GetAttributeCenterAsString() << ", " << xmfGroup->GetNumberOfElements() <<")";
XdmfInt64 nb_item = xmfGroup->GetNumberOfElements();
for(XdmfInt64 uid=0; uid<nb_item; ++uid)
cellsUidArray.add(xmfGroup->GetValueAsInt32(uid));
}else itWasAnArcanProduction=false;
/*****************************************************
Looking for XML attribute which Name="NodesUniqueIDs"
******************************************************/
XdmfXmlNode nodesUniqueIDsXmlNode = DOM->FindElementByAttribute ("Name", "NodesUniqueIDs", 0, foundGrid);
SharedArray<Int32> nodesUidArray;
if (nodesUniqueIDsXmlNode) {
info() << "[XmfMeshReader] nodesUidArray were found";
XdmfAttribute *attribute = new XdmfAttribute();
attribute->SetDOM(DOM);
attribute->SetElement(nodesUniqueIDsXmlNode);
attribute->UpdateInformation();
attribute->Update();
XdmfArray *xmfGroup = attribute->GetValues();
info() << attribute->GetName() << "(" << attribute->GetAttributeTypeAsString() << ", "
<< attribute->GetAttributeCenterAsString() << ", " << xmfGroup->GetNumberOfElements() <<")";
XdmfInt64 nb_item = xmfGroup->GetNumberOfElements();
for(XdmfInt64 uid=0; uid<nb_item; ++uid)
nodesUidArray.add(xmfGroup->GetValueAsInt32(uid));
}
else itWasAnArcanProduction=false;
/*****************************************************
Looking for XML attribute which Name="NodesOwner"
******************************************************/
XdmfXmlNode nodesOwnerXmlNode = DOM->FindElementByAttribute ("Name", "NodesOwner", 0, foundGrid);
Int32UniqueArray nodesOwnerArray;
if (nodesOwnerXmlNode) {
info() << "[XmfMeshReader] nodesOwnerArray were found";
XdmfAttribute *attribute = new XdmfAttribute();
attribute->SetDOM(DOM);
attribute->SetElement(nodesOwnerXmlNode);
attribute->UpdateInformation();
attribute->Update();
XdmfArray *xmfGroup = attribute->GetValues();
info() << attribute->GetName() << "(" << attribute->GetAttributeTypeAsString() << ", "
<< attribute->GetAttributeCenterAsString() << ", " << xmfGroup->GetNumberOfElements() <<")";
XdmfInt64 nb_item = xmfGroup->GetNumberOfElements();
for(XdmfInt64 uid=0; uid<nb_item; ++uid)
nodesOwnerArray.add(xmfGroup->GetValueAsInt32(uid));
}
else
itWasAnArcanProduction=false;
/******************************
Each Grid contains a Geometry,
*******************************/
XdmfGeometry* xmfGometry = Grid->GetGeometry();
if (!xmfGometry)
ARCANE_FATAL("No xmfGeometry");
info() << "\tHave found a " << xmfGometry->GetGeometryTypeAsString() << " geometry";
if (xmfGometry->GetGeometryType() != XDMF_GEOMETRY_XYZ)
throw NotSupportedException(A_FUNCINFO, "Not supported geometry type");
xmfGometry->UpdateInformation();
xmfGometry->Update();
HashTableMapT<Int64,Real3> nodes_coords(xmfGometry->GetNumberOfPoints(),true);
XdmfInt64 nbOfNodes = xmfGometry->GetNumberOfPoints();
/****************************************************
If it is not ours, just fake the indirection process
*****************************************************/
if (!itWasAnArcanProduction){
info() << "If it is not ours, just fake the indirection process";
for(Integer uid=0; uid<nbOfNodes; ++uid){
nodesUidArray.add(uid);
cellsUidArray.add(uid);
nodesOwnerArray.add(uid);
}
}
XdmfArray *xdmfPoints = xmfGometry->GetPoints(XDMF_TRUE);// true to create the array
XdmfInt32 numType=xdmfPoints->GetNumberType();
if (numType!=XDMF_FLOAT32_TYPE) throw NotSupportedException(A_FUNCINFO, "Not supported geometry number type");
XdmfInt64 iNode=0;
for(XdmfInt64 i=0; iNode<nbOfNodes; iNode++, i+=3){
Real3 coords=Real3(xdmfPoints->GetValueAsFloat32(i),
xdmfPoints->GetValueAsFloat32(i+1),
xdmfPoints->GetValueAsFloat32(i+2));
nodes_coords.nocheckAdd(nodesUidArray[iNode], coords);
}
/******************************
Each Grid contains a Topology,
*******************************/
XdmfInt64 nb_elements;
Int32UniqueArray cells_nb_node;
Int32UniqueArray cells_connectivity;
Int32UniqueArray cells_type;
XdmfTopology *topology=Grid->GetTopology();
if (_readTopology(topology, nb_elements, cells_nb_node, cells_connectivity, cells_type, nodesUidArray) != RTOk)
throw IOException("XmfMeshReader", "_readTopology error");
// Create hash table for nodes owner.
HashTableMapT<Int64,Int32> nodes_owner_map(nbOfNodes,true);
if (nodesOwnerXmlNode && itWasAnArcanProduction){
info() << "[_XmfMeshReader] Create hash table for nodes owner";
for(Integer i=0; i<nbOfNodes; ++i ){
//info() << nodesUidArray[i] <<":"<<nodesOwnerArray[i];
nodes_owner_map.nocheckAdd(nodesUidArray[i], nodesOwnerArray[i]);
}
}
/****************************
* Now building cells_infos *
****************************/
Int64UniqueArray cells_infos;
info() << "[_XmfMeshReader] Création des mailles, nb_cell=" << nb_elements << " cells_type.size=" << cells_type.size();
Integer connectivity_index = 0;
for(Integer i=0; i<cells_type.size(); ++i ){
cells_infos.add(cells_type[i]);
cells_infos.add(cellsUidArray[i]);
for (Integer z=0; z<cells_nb_node[i]; ++z )
cells_infos.add(cells_connectivity[connectivity_index+z]);
connectivity_index += cells_nb_node[i];
}
/********************************
* Setting Dimension & Allocating *
********************************/
info() << "[XmfMeshReader] ## Mesh 3D ##";
mesh->setDimension(3);
info() << "[XmfMeshReader] ## Allocating ##";
mesh->allocateCells(cells_type.size(), cells_infos, false);
/**********************************************************************
Positionne les propriétaires des noeuds à partir des groupes de noeuds
***********************************************************************/
ItemInternalList internalNodes(mesh->itemsInternal(IK_Node));
info() << "[XmfMeshReader] internalNodes.size()="<<internalNodes.size();
if (nodesOwnerXmlNode && itWasAnArcanProduction){
info() << "[XmfMeshReader] Setting nodes owners from xmf file";
for(Integer i=0, is=internalNodes.size(); i<is; ++i){
ItemInternal* internal_node = internalNodes[i];
//info() << "[XmfMeshReader] "<<internal_node->uniqueId()<<":"<<nodes_owner_map[internal_node->uniqueId()];
Int32 true_owner = nodes_owner_map[internal_node->uniqueId()];
internal_node->setOwner(true_owner,sid);
}
}
else{
for(Integer i=0, is=internalNodes.size(); i<is; ++i)
internalNodes[i]->setOwner(sid,sid);
}
ItemInternalList internalCells(mesh->itemsInternal(IK_Cell));
info() << "[XmfMeshReader] internalCells.size()="<<internalCells.size();
for(Integer i=0, is=internalCells.size(); i<is; ++i)
internalCells[i]->setOwner(sid,sid);
/********************************************
* Now finishing & preparing for ghost layout *
********************************************/
info() << "[XmfMeshReader] ## Ending with endAllocate ##";
mesh->endAllocate();
if (is_parallel){
info() << "[XmfMeshReader] ## setOwnersFromCells ##";
mesh->setOwnersFromCells();
}
info() << "\n\n[XmfMeshReader] ## Now dealing with ghost's layer ##";
info() << "[XmfMeshReader] mesh.nbNode=" <<mesh->nbNode() << " mesh.nbCell="<< mesh->nbCell();
/***********************************************************
and zero or more Attribute elements (fetching Other Groups)
************************************************************/
XdmfInt32 nAttributes=Grid->GetNumberOfAttributes();
info() << "nAttributes=" << nAttributes;
for(XdmfInt64 iAttribute=0; iAttribute < nAttributes; ++iAttribute){
XdmfAttribute *attribute = Grid->GetAttribute(iAttribute);
if ((attribute == NULL || (!itWasAnArcanProduction))) continue;
if ((strcasecmp(attribute->GetName(), "NodesUniqueIDs")==0)||
(strcasecmp(attribute->GetName(), "CellsUniqueIDs")==0)||
(strcasecmp(attribute->GetName(), "NodesOwner")==0)){
info() << "Skipping " << attribute->GetName();
continue;
}
attribute->Update();
XdmfArray *xmfGroup = attribute->GetValues();
info() << attribute->GetName() << "(" << attribute->GetAttributeTypeAsString() << ", "
<< attribute->GetAttributeCenterAsString() << ", " << xmfGroup->GetNumberOfElements() <<")";
eItemKind itemKind=(eItemKind)xmfGroup->GetValueAsInt32(0);
IItemFamily* family = mesh->itemFamily(itemKind);
Integer nb_item = xmfGroup->GetNumberOfElements() - 1;
Int64UniqueArray unique_ids(nb_item);
// Les éléments suivant contiennent les uniqueId() des entités du groupe.
for(XdmfInt64 z=0; z<nb_item; ++z )
unique_ids[z] = xmfGroup->GetValueAsInt32(z+1);
// Récupère le localId() correspondant.
Int32UniqueArray local_ids(unique_ids.size());
family->itemsUniqueIdToLocalId(local_ids,unique_ids,false);
// Tous les entités ne sont pas forcément dans le maillage actuel et
// il faut donc les filtrer.
Int32UniqueArray ids;
for(Integer i=0; i<nb_item; ++i )
if (local_ids[i]!=NULL_ITEM_LOCAL_ID)
ids.add(local_ids[i]);
info() << "Create group family=" << family->name() << " name=" << attribute->GetName() << " ids=" << ids.size();
family->createGroup(attribute->GetName(),ids,true);
}
/*********************
* Now insert coords *
*********************/
info() << "[XmfMeshReader] ## Now insert coords ##";
VariableNodeReal3& nodes_coord_var(mesh->nodesCoordinates());
ENUMERATE_NODE(iNode,mesh->ownNodes()){
nodes_coord_var[iNode] = nodes_coords[iNode->uniqueId()];
}
/****************************************
* Synchronizing groups/variables & nodes *
****************************************/
mesh->synchronizeGroupsAndVariables();
}
}
info() << "[readMeshFromFile] RTOk";
// delete DOM;
// delete geometry;
// delete topology;
return RTOk;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 43.876442 | 128 | 0.606128 | [
"mesh",
"geometry",
"3d"
] |
8096f727b129fbf8b31448e1dcc8c52696043706 | 63,200 | hpp | C++ | aslib/AsKey.hpp | Kasugaccho/RPG-MapMaker | bef857b9de4d7e26e4050ecf603f167552412f0a | [
"CC0-1.0"
] | 92 | 2018-07-02T03:23:08.000Z | 2020-12-29T12:56:21.000Z | aslib/AsKey.hpp | Kasugaccho/RPG-MapMaker | bef857b9de4d7e26e4050ecf603f167552412f0a | [
"CC0-1.0"
] | null | null | null | aslib/AsKey.hpp | Kasugaccho/RPG-MapMaker | bef857b9de4d7e26e4050ecf603f167552412f0a | [
"CC0-1.0"
] | 5 | 2021-02-18T14:17:19.000Z | 2021-12-31T16:11:03.000Z | /*#######################################################################################
Made by Kasugaccho
Made by As Project
https://github.com/Kasugaccho/AsLib
wanotaitei@gmail.com
This code is licensed under CC0.
#######################################################################################*/
#ifndef INCLUDED_AS_PROJECT_LIBRARY_KEY
#define INCLUDED_AS_PROJECT_LIBRARY_KEY
namespace AsLib
{
//dir
enum :std::size_t
{
MOB_DOWN,
MOB_UP,
MOB_LEFT,
MOB_RIGHT,
MOB_LEFT_UP,
MOB_RIGHT_UP,
MOB_LEFT_DOWN,
MOB_RIGHT_DOWN,
MOB_CENTER,
};
//キーボード配列ID
enum :std::size_t {
aslib_key_unknown,
aslib_key_grave_accentilde,
aslib_key_1,
aslib_key_2,
aslib_key_3,
aslib_key_4,
aslib_key_5,
aslib_key_6,
aslib_key_7,
aslib_key_8,
aslib_key_9,
aslib_key_0,
aslib_key_hyphennderscore,
aslib_key_equallus,
aslib_key_international3,
aslib_key_dELETE_Backspace,
aslib_key_tab,
aslib_key_q,
aslib_key_w,
aslib_key_e,
aslib_key_r,
aslib_key_t,
aslib_key_y,
aslib_key_u,
aslib_key_i,
aslib_key_o,
aslib_key_p,
aslib_key_left_square_bracketeft_curly_bracket,
aslib_key_right_square_bracketight_curly_bracket,
aslib_key_ertical_line,
aslib_key_caps_Lock,
aslib_key_a,
aslib_key_s,
aslib_key_d,
aslib_key_f,
aslib_key_g,
aslib_key_h,
aslib_key_j,
aslib_key_k,
aslib_key_l,
aslib_key_semicolon,
aslib_key_colon,
aslib_key_non_US_numberilde,
aslib_key_enter,
aslib_key_left_shift,
aslib_key_unknown1,
aslib_key_z,
aslib_key_x,
aslib_key_c,
aslib_key_v,
aslib_key_b,
aslib_key_n,
aslib_key_m,
aslib_key_commaess_than_sign,
aslib_key_full_stopreater_than_sign,
aslib_key_solidusuestion,
aslib_key_international1,
aslib_key_right_shift,
aslib_key_left_control,
aslib_key_unknown2,
aslib_key_left_alt,
aslib_key_space,
aslib_key_right_alt,
aslib_key_unknown3,
aslib_key_right_control,
aslib_key_unknown4,
aslib_key_unknown5,
aslib_key_unknown6,
aslib_key_unknown7,
aslib_key_unknown8,
aslib_key_unknown9,
aslib_key_unknown10,
aslib_key_unknown11,
aslib_key_unknown12,
aslib_key_unknown13,
aslib_key_insert,
aslib_key_delete_Forward,
aslib_key_unknown14,
aslib_key_unknown15,
aslib_key_left,
aslib_key_home,
aslib_key_end,
aslib_key_unknown16,
aslib_key_up,
aslib_key_down,
aslib_key_pageUp,
aslib_key_pageDown,
aslib_key_unknown17,
aslib_key_unknown18,
aslib_key_right,
Keypad_Num_Locklear,
Keypad_7,
Keypad_4,
Keypad_1,
aslib_key_unknown19,
Keypad_solidus,
Keypad_8,
Keypad_5,
Keypad_2,
Keypad_0,
Keypad_asterisk,
Keypad_9,
Keypad_6,
Keypad_3,
Keypad_full_stopelete,
Keypad_hyphen,
Keypad_plus,
aslib_key_unknown20,
Keypad_ENTER,
aslib_key_unknown21,
aslib_key_eSCAPE,
aslib_key_unknown22,
aslib_key_f1,
aslib_key_f2,
aslib_key_f3,
aslib_key_f4,
aslib_key_f5,
aslib_key_f6,
aslib_key_f7,
aslib_key_f8,
aslib_key_f9,
aslib_key_f10,
aslib_key_f11,
aslib_key_f12,
aslib_key_printScreen,
aslib_key_scroll_Lock,
aslib_key_pause,
aslib_key_left_GUI,
aslib_key_right_GUI,
aslib_key_application,
aslib_key_unknown23,
aslib_key_international5,
aslib_key_international4,
aslib_key_international2,
aslib_key_keyLast,
aslib_key_135,
aslib_key_136,
aslib_key_137,
aslib_key_138,
aslib_key_139,
aslib_key_140,
aslib_key_141,
aslib_key_142,
aslib_key_143,
aslib_key_144,
aslib_key_145,
aslib_key_146,
aslib_key_147,
aslib_key_148,
aslib_key_149,
aslib_key_150,
aslib_key_151,
aslib_key_152,
aslib_key_153,
aslib_key_154,
aslib_key_155,
aslib_key_156,
aslib_key_157,
aslib_key_158,
aslib_key_159,
aslib_key_160,
aslib_key_161,
aslib_key_162,
aslib_key_163,
aslib_key_164,
aslib_key_165,
aslib_key_166,
aslib_key_167,
aslib_key_168,
aslib_key_169,
aslib_key_170,
aslib_key_171,
aslib_key_172,
aslib_key_173,
aslib_key_174,
aslib_key_175,
aslib_key_176,
aslib_key_177,
aslib_key_178,
aslib_key_179,
aslib_key_180,
aslib_key_181,
aslib_key_182,
aslib_key_183,
aslib_key_184,
aslib_key_185,
aslib_key_186,
aslib_key_187,
aslib_key_188,
aslib_key_189,
aslib_key_190,
aslib_key_191,
aslib_key_192,
aslib_key_193,
aslib_key_194,
aslib_key_195,
aslib_key_196,
aslib_key_197,
aslib_key_198,
aslib_key_199,
aslib_key_200,
aslib_key_201,
aslib_key_202,
aslib_key_203,
aslib_key_204,
aslib_key_205,
aslib_key_206,
aslib_key_207,
aslib_key_208,
aslib_key_209,
aslib_key_210,
aslib_key_211,
aslib_key_212,
aslib_key_213,
aslib_key_214,
aslib_key_215,
aslib_key_216,
aslib_key_217,
aslib_key_218,
aslib_key_219,
aslib_key_220,
aslib_key_221,
aslib_key_222,
aslib_key_223,
aslib_key_224,
aslib_key_225,
aslib_key_226,
aslib_key_227,
aslib_key_228,
aslib_key_229,
aslib_key_230,
aslib_key_231,
aslib_key_232,
aslib_key_233,
aslib_key_234,
aslib_key_235,
aslib_key_236,
aslib_key_237,
aslib_key_238,
aslib_key_239,
aslib_key_240,
aslib_key_241,
aslib_key_242,
aslib_key_243,
aslib_key_244,
aslib_key_245,
aslib_key_246,
aslib_key_247,
aslib_key_248,
aslib_key_249,
aslib_key_250,
aslib_key_251,
aslib_key_252,
aslib_key_253,
aslib_key_254,
aslib_key_255,
aslib_key_left_up,
aslib_key_right_up,
aslib_key_left_down,
aslib_key_right_down,
aslib_key_w_a,
aslib_key_w_d,
aslib_key_s_a,
aslib_key_s_d,
};
//class KeyControl
//{
//public:
//private:
// std::array<std::int32_t, 256>aslib_update_key = {};
// //std::array<std::int32_t, 256>config = {};
// //std::array<Counter, 256> counter = {};
//};
enum :std::size_t {
bba0
,KEY_INPUT_ESCAPE0x01//EscキーD_DIK_ESCAPE
,KEY_INPUT_10x02//1キーD_DIK_1
,KEY_INPUT_20x03//2キーD_DIK_2
,KEY_INPUT_30x04//3キーD_DIK_3
,KEY_INPUT_40x05//4キーD_DIK_4
,KEY_INPUT_50x06//5キーD_DIK_5
,KEY_INPUT_60x07//6キーD_DIK_6
,KEY_INPUT_70x08//7キーD_DIK_7
,KEY_INPUT_80x09//8キーD_DIK_8
,KEY_INPUT_90x0A//9キーD_DIK_9
,KEY_INPUT_00x0B//0キーD_DIK_0
,KEY_INPUT_MINUS0x0C//-キーD_DIK_MINUS
,bba13
,KEY_INPUT_BACK0x0E//BackSpaceキーD_DIK_BACK
,KEY_INPUT_TAB0x0F//TabキーD_DIK_TAB
,KEY_INPUT_Q0x10//QキーD_DIK_Q
,KEY_INPUT_W0x11//WキーD_DIK_W
,KEY_INPUT_E0x12//EキーD_DIK_E
,KEY_INPUT_R0x13//RキーD_DIK_R
,KEY_INPUT_T0x14//TキーD_DIK_T
,KEY_INPUT_Y0x15//YキーD_DIK_Y
,KEY_INPUT_U0x16//UキーD_DIK_U
,KEY_INPUT_I0x17//IキーD_DIK_I
,KEY_INPUT_O0x18//OキーD_DIK_O
,KEY_INPUT_P0x19//PキーD_DIK_P
,KEY_INPUT_LBRACKET0x1A//[キーD_DIK_LBRACKET
,KEY_INPUT_RBRACKET0x1B//]キーD_DIK_RBRACKET
,KEY_INPUT_RETURN0x1C//EnterキーD_DIK_RETURN
,KEY_INPUT_LCONTROL0x1D//左CtrlキーD_DIK_LCONTROL
,KEY_INPUT_A0x1E//AキーD_DIK_A
,KEY_INPUT_S0x1F//SキーD_DIK_S
,KEY_INPUT_D0x20//DキーD_DIK_D
,KEY_INPUT_F0x21//FキーD_DIK_F
,KEY_INPUT_G0x22//GキーD_DIK_G
,KEY_INPUT_H0x23//HキーD_DIK_H
,KEY_INPUT_J0x24//JキーD_DIK_J
,KEY_INPUT_K0x25//KキーD_DIK_K
,KEY_INPUT_L0x26//LキーD_DIK_L
,KEY_INPUT_SEMICOLON0x27//;キーD_DIK_SEMICOLON
,bba40
,bba41
,KEY_INPUT_LSHIFT0x2A//左ShiftキーD_DIK_LSHIFT
,KEY_INPUT_BACKSLASH0x2B//\キーD_DIK_BACKSLASH
,KEY_INPUT_Z0x2C//ZキーD_DIK_Z
,KEY_INPUT_X0x2D//XキーD_DIK_X
,KEY_INPUT_C0x2E//CキーD_DIK_C
,KEY_INPUT_V0x2F//VキーD_DIK_V
,KEY_INPUT_B0x30//BキーD_DIK_B
,KEY_INPUT_N0x31//NキーD_DIK_N
,KEY_INPUT_M0x32//MキーD_DIK_M
,KEY_INPUT_COMMA0x33//,キーD_DIK_COMMA
,KEY_INPUT_PERIOD0x34//.キーD_DIK_PERIOD
,KEY_INPUT_SLASH0x35///キーD_DIK_SLASH
,KEY_INPUT_RSHIFT0x36//右ShiftキーD_DIK_RSHIFT
,KEY_INPUT_MULTIPLY0x37//テンキー*キーD_DIK_MULTIPLY
,KEY_INPUT_LALT0x38//左AltキーD_DIK_LALT
,KEY_INPUT_SPACE0x39//スペースキーD_DIK_SPACE
,KEY_INPUT_CAPSLOCK0x3A//CaspLockキーD_DIK_CAPSLOCK
,KEY_INPUT_F10x3B//F1キーD_DIK_F1
,KEY_INPUT_F20x3C//F2キーD_DIK_F2
,KEY_INPUT_F30x3D//F3キーD_DIK_F3
,KEY_INPUT_F40x3E//F4キーD_DIK_F4
,KEY_INPUT_F50x3F//F5キーD_DIK_F5
,KEY_INPUT_F60x40//F6キーD_DIK_F6
,KEY_INPUT_F70x41//F7キーD_DIK_F7
,KEY_INPUT_F80x42//F8キーD_DIK_F8
,KEY_INPUT_F90x43//F9キーD_DIK_F9
,KEY_INPUT_F100x44//F10キーD_DIK_F10
,KEY_INPUT_NUMLOCK0x45//テンキーNumLockキーD_DIK_NUMLOCK
,KEY_INPUT_SCROLL0x46//ScrollLockキーD_DIK_SCROLL
,KEY_INPUT_NUMPAD70x47//テンキー7D_DIK_NUMPAD7
,KEY_INPUT_NUMPAD80x48//テンキー8D_DIK_NUMPAD8
,KEY_INPUT_NUMPAD90x49//テンキー9D_DIK_NUMPAD9
,KEY_INPUT_SUBTRACT0x4A//テンキー-キーD_DIK_SUBTRACT
,KEY_INPUT_NUMPAD40x4B//テンキー4D_DIK_NUMPAD4
,KEY_INPUT_NUMPAD50x4C//テンキー5D_DIK_NUMPAD5
,KEY_INPUT_NUMPAD60x4D//テンキー6D_DIK_NUMPAD6
,KEY_INPUT_ADD0x4E//テンキー+キーD_DIK_ADD
,KEY_INPUT_NUMPAD10x4F//テンキー1D_DIK_NUMPAD1
,KEY_INPUT_NUMPAD20x50//テンキー2D_DIK_NUMPAD2
,KEY_INPUT_NUMPAD30x51//テンキー3D_DIK_NUMPAD3
,KEY_INPUT_NUMPAD00x52//テンキー0D_DIK_NUMPAD0
,KEY_INPUT_DECIMAL0x53//テンキー.キーD_DIK_DECIMAL
,bba84
,bba85
,bba86
,KEY_INPUT_F110x57//F11キーD_DIK_F11
,KEY_INPUT_F120x58//F12キーD_DIK_F12
,bba89
,bba90
,bba91
,bba92
,bba93
,bba94
,bba95
,bba96
,bba97
,bba98
,bba99
,bba100
,bba101
,bba102
,bba103
,bba104
,bba105
,bba106
,bba107
,bba108
,bba109
,bba110
,bba111
,bba112
,KEY_INPUT_KANA0x70//カナキーD_DIK_KANA
,bba113
,bba114
,bba115
,bba116
,bba117
,bba118
,bba119
,bba120
,KEY_INPUT_CONVERT0x79//変換キーD_DIK_CONVERT
,bba122
,KEY_INPUT_NOCONVERT0x7B//無変換キーD_DIK_NOCONVERT
,bba124
,KEY_INPUT_YEN0x7D//¥キーD_DIK_YEN
,bba126
,bba127
,bba128
,bba129
,bba130
,bba131
,bba132
,bba133
,bba134
,bba135
,bba136
,bba137
,bba138
,bba139
,bba140
,bba141
,bba142
,bba143
,KEY_INPUT_PREVTRACK0x90//^キーD_DIK_PREVTRACK
,KEY_INPUT_AT0x91//@キーD_DIK_AT
,KEY_INPUT_COLON0x92//:キーD_DIK_COLON
,bba147
,KEY_INPUT_KANJI0x94//漢字キーD_DIK_KANJI
,bba149
,bba150
,bba151
,bba152
,bba153
,bba154
,bba155
,KEY_INPUT_NUMPADENTER0x9C//テンキーのエンターキーD_DIK_NUMPADENTER
,KEY_INPUT_RCONTROL0x9D//右CtrlキーD_DIK_RCONTROL
,bba158
,bba159
,bba160
,bba161
,bba162
,bba163
,bba164
,bba165
,bba166
,bba167
,bba168
,bba169
,bba170
,bba171
,bba172
,bba173
,bba174
,bba175
,bba176
,bba177
,bba178
,bba179
,bba180
,KEY_INPUT_DIVIDE0xB5//テンキー/キーD_DIK_DIVIDE
,bba182
,KEY_INPUT_SYSRQ0xB7//PrintScreenキーD_DIK_SYSRQ
,KEY_INPUT_RALT0xB8//右AltキーD_DIK_RALT
,bba185
,bba186
,bba187
,bba188
,bba189
,bba190
,bba191
,bba192
,bba193
,bba194
,bba195
,bba196
,KEY_INPUT_PAUSE0xC5//PauseBreakキーD_DIK_PAUSE
,bba198
,KEY_INPUT_HOME0xC7//HomeキーD_DIK_HOME
,KEY_INPUT_UP0xC8//上キーD_DIK_UP
,KEY_INPUT_PGUP0xC9//PageUpキーD_DIK_PGUP
,bba202
,KEY_INPUT_LEFT0xCB//左キーD_DIK_LEFT
,bba204
,KEY_INPUT_RIGHT0xCD//右キーD_DIK_RIGHT
,bba206
,KEY_INPUT_END0xCF//EndキーD_DIK_END
,KEY_INPUT_DOWN0xD0//下キーD_DIK_DOWN
,KEY_INPUT_PGDN0xD1//PageDownキーD_DIK_PGDN
,KEY_INPUT_INSERT0xD2//InsertキーD_DIK_INSERT
,KEY_INPUT_DELETE0xD3//DeleteキーD_DIK_DELETE
,bba212
,bba213
,bba214
,bba215
,bba216
,bba217
,bba218
,KEY_INPUT_LWIN0xDB//左WinキーD_DIK_LWIN
,KEY_INPUT_RWIN0xDC//右WinキーD_DIK_RWIN
,KEY_INPUT_APPS0xDD//アプリケーションメニューキーD_DIK_APPS
,bba222
, bba223
, bba224
, bba225
, bba226
, bba227
, bba228
, bba229
, bba230
, bba231
, bba232
, bba233
, bba234
, bba235
, bba236
, bba237
, bba238
, bba239
, bba240
, bba241
, bba242
, bba243
, bba244
, bba245
, bba246
, bba247
, bba248
, bba249
, bba250
, bba251
, bba252
, bba253
, bba254
, bba255
, bba256
};
#if defined(ASLIB_INCLUDE_DL) //DxLib
void checkKey(bool* const AS_key,Counter* const AS_count) noexcept
{
constexpr std::array<std::size_t, aslib_key_keyLast> DL_AS_key{
0,
KEY_INPUT_KANJI,
KEY_INPUT_1,
KEY_INPUT_2,
KEY_INPUT_3,
KEY_INPUT_4,
KEY_INPUT_5,
KEY_INPUT_6,
KEY_INPUT_7,
KEY_INPUT_8,
KEY_INPUT_9,
KEY_INPUT_0,
KEY_INPUT_MINUS,
KEY_INPUT_PREVTRACK,
KEY_INPUT_YEN,
KEY_INPUT_BACK,
KEY_INPUT_TAB,
KEY_INPUT_Q,
KEY_INPUT_W,
KEY_INPUT_E,
KEY_INPUT_R,
KEY_INPUT_T,
KEY_INPUT_Y,
KEY_INPUT_U,
KEY_INPUT_I,
KEY_INPUT_O,
KEY_INPUT_P,
KEY_INPUT_AT,
KEY_INPUT_LBRACKET,
KEY_INPUT_BACKSLASH,
KEY_INPUT_CAPSLOCK,
KEY_INPUT_A,
KEY_INPUT_S,
KEY_INPUT_D,
KEY_INPUT_F,
KEY_INPUT_G,
KEY_INPUT_H,
KEY_INPUT_J,
KEY_INPUT_K,
KEY_INPUT_L,
KEY_INPUT_SEMICOLON,
KEY_INPUT_COLON,
KEY_INPUT_RBRACKET,
KEY_INPUT_RETURN,
KEY_INPUT_LSHIFT,
0,
KEY_INPUT_Z,
KEY_INPUT_X,
KEY_INPUT_C,
KEY_INPUT_V,
KEY_INPUT_B,
KEY_INPUT_N,
KEY_INPUT_M,
KEY_INPUT_COMMA,
KEY_INPUT_PERIOD,
KEY_INPUT_SLASH,
KEY_INPUT_BACKSLASH,
KEY_INPUT_RSHIFT,
KEY_INPUT_LCONTROL,
0,
KEY_INPUT_LALT,
KEY_INPUT_SPACE,
KEY_INPUT_RALT,
0,
KEY_INPUT_RCONTROL,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
KEY_INPUT_INSERT,
KEY_INPUT_DELETE,
0,
0,
KEY_INPUT_LEFT,
KEY_INPUT_HOME,
KEY_INPUT_END,
0,
KEY_INPUT_UP,
KEY_INPUT_DOWN,
KEY_INPUT_PGUP,
KEY_INPUT_PGDN,
0,
0,
KEY_INPUT_RIGHT,
0,//KEY_INPUT_NUMPADNUM_LOCKLEAR,
KEY_INPUT_NUMPAD7,
KEY_INPUT_NUMPAD4,
KEY_INPUT_NUMPAD1,
0,
KEY_INPUT_DIVIDE,
KEY_INPUT_NUMPAD8,
KEY_INPUT_NUMPAD5,
KEY_INPUT_NUMPAD2,
KEY_INPUT_NUMPAD0,
KEY_INPUT_MULTIPLY,
KEY_INPUT_NUMPAD9,
KEY_INPUT_NUMPAD6,
KEY_INPUT_NUMPAD3,
KEY_INPUT_DECIMAL,
KEY_INPUT_SUBTRACT,
KEY_INPUT_ADD,
0,
KEY_INPUT_NUMPADENTER,
0,
KEY_INPUT_ESCAPE,
0,
KEY_INPUT_F1,
KEY_INPUT_F2,
KEY_INPUT_F3,
KEY_INPUT_F4,
KEY_INPUT_F5,
KEY_INPUT_F6,
KEY_INPUT_F7,
KEY_INPUT_F8,
KEY_INPUT_F9,
KEY_INPUT_F10,
KEY_INPUT_F11,
KEY_INPUT_F12,
0,//KEY_INPUT_PRINTSCREEN,
0,//KEY_INPUT_SCROLL_LOCK,
KEY_INPUT_PAUSE,
0,//KEY_INPUT_LEFT_GUI,
0,//KEY_INPUT_RIGHT_GUI,
0,//KEY_INPUT_APPLICATION,
0,
0,//KEY_INPUT_INTERNATIONAL5,
0,//KEY_INPUT_INTERNATIONAL4,
0//KEY_INPUT_INTERNATIONAL2,
};
std::array<char, 256> DL_key;
DxLib::GetHitKeyStateAll(DL_key.data());
for (std::size_t i{}; i < aslib_key_keyLast; ++i) {
if (DL_key[DL_AS_key[i]] != 0) AS_key[i] = true;
else AS_key[i] = false;
AS_count[i].update(bool(AS_key[i]));
}
return;
}
#elif defined(ASLIB_INCLUDE_S3) //Siv3D
void checkKey(bool* const AS_key, Counter* const AS_count) noexcept
{
for (std::size_t i{}; i < aslib_key_keyLast; ++i) {
AS_key[i] = false;
}
AS_key[aslib_key_1] = bool(s3d::Key1.pressed());
AS_key[aslib_key_2] = bool(s3d::Key2.pressed());
AS_key[aslib_key_3] = bool(s3d::Key3.pressed());
AS_key[aslib_key_4] = bool(s3d::Key4.pressed());
AS_key[aslib_key_5] = bool(s3d::Key5.pressed());
AS_key[aslib_key_6] = bool(s3d::Key6.pressed());
AS_key[aslib_key_7] = bool(s3d::Key7.pressed());
AS_key[aslib_key_8] = bool(s3d::Key8.pressed());
AS_key[aslib_key_9] = bool(s3d::Key9.pressed());
AS_key[aslib_key_0] = bool(s3d::Key0.pressed());
AS_key[aslib_key_a] = bool(s3d::KeyA.pressed());
AS_key[aslib_key_b] = bool(s3d::KeyB.pressed());
AS_key[aslib_key_c] = bool(s3d::KeyC.pressed());
AS_key[aslib_key_d] = bool(s3d::KeyD.pressed());
AS_key[aslib_key_e] = bool(s3d::KeyE.pressed());
AS_key[aslib_key_f] = bool(s3d::KeyF.pressed());
AS_key[aslib_key_g] = bool(s3d::KeyG.pressed());
AS_key[aslib_key_h] = bool(s3d::KeyH.pressed());
AS_key[aslib_key_i] = bool(s3d::KeyI.pressed());
AS_key[aslib_key_j] = bool(s3d::KeyJ.pressed());
AS_key[aslib_key_k] = bool(s3d::KeyK.pressed());
AS_key[aslib_key_l] = bool(s3d::KeyL.pressed());
AS_key[aslib_key_m] = bool(s3d::KeyM.pressed());
AS_key[aslib_key_n] = bool(s3d::KeyN.pressed());
AS_key[aslib_key_o] = bool(s3d::KeyO.pressed());
AS_key[aslib_key_p] = bool(s3d::KeyP.pressed());
AS_key[aslib_key_q] = bool(s3d::KeyQ.pressed());
AS_key[aslib_key_r] = bool(s3d::KeyR.pressed());
AS_key[aslib_key_s] = bool(s3d::KeyS.pressed());
AS_key[aslib_key_t] = bool(s3d::KeyT.pressed());
AS_key[aslib_key_u] = bool(s3d::KeyU.pressed());
AS_key[aslib_key_v] = bool(s3d::KeyV.pressed());
AS_key[aslib_key_w] = bool(s3d::KeyW.pressed());
AS_key[aslib_key_x] = bool(s3d::KeyX.pressed());
AS_key[aslib_key_y] = bool(s3d::KeyY.pressed());
AS_key[aslib_key_z] = bool(s3d::KeyZ.pressed());
AS_key[aslib_key_f1] = bool(s3d::KeyF1.pressed());
AS_key[aslib_key_f2] = bool(s3d::KeyF2.pressed());
AS_key[aslib_key_f3] = bool(s3d::KeyF3.pressed());
AS_key[aslib_key_f4] = bool(s3d::KeyF4.pressed());
AS_key[aslib_key_f5] = bool(s3d::KeyF5.pressed());
AS_key[aslib_key_f6] = bool(s3d::KeyF6.pressed());
AS_key[aslib_key_f7] = bool(s3d::KeyF7.pressed());
AS_key[aslib_key_f8] = bool(s3d::KeyF8.pressed());
AS_key[aslib_key_f9] = bool(s3d::KeyF9.pressed());
AS_key[aslib_key_f10] = bool(s3d::KeyF10.pressed());
AS_key[aslib_key_f11] = bool(s3d::KeyF11.pressed());
AS_key[aslib_key_f12] = bool(s3d::KeyF12.pressed());
AS_key[aslib_key_left] = bool(s3d::KeyLeft.pressed());
AS_key[aslib_key_right] = bool(s3d::KeyRight.pressed());
AS_key[aslib_key_up] = bool(s3d::KeyUp.pressed());
AS_key[aslib_key_down] = bool(s3d::KeyDown.pressed());
AS_key[aslib_key_left_shift] = bool(s3d::KeyLShift.pressed());
AS_key[aslib_key_right_shift] = bool(s3d::KeyRShift.pressed());
AS_key[aslib_key_left_control] = bool(s3d::KeyLControl.pressed());
AS_key[aslib_key_right_control] = bool(s3d::KeyRControl.pressed());
AS_key[aslib_key_left_alt] = bool(s3d::KeyLAlt.pressed());
AS_key[aslib_key_right_alt] = bool(s3d::KeyRAlt.pressed());
AS_key[aslib_key_enter] = bool(s3d::KeyEnter.pressed());
for (std::size_t i{}; i < aslib_key_keyLast; ++i) {
AS_count[i].update(bool(AS_key[i]));
}
return;
}
#elif defined(ASLIB_INCLUDE_OF)
void checkKey(bool* const AS_key, Counter* const AS_count) noexcept
{
return;
}
#elif defined(ASLIB_INCLUDE_C2)
void checkKey(bool* const AS_key, Counter* const AS_count) noexcept
{
return;
}
#elif defined(ASLIB_INCLUDE_SF)
return 0;
#elif defined(ASLIB_INCLUDE_TP)
void checkKey(bool* const AS_key, Counter* const AS_count) noexcept
{
return;
}
#else //Console
void checkKey(bool* const AS_key, Counter* const AS_count) noexcept
{
return;
}
#endif
enum :std::size_t {
aslib_counter_empty,
aslib_counter_touch,
aslib_counter_up,
aslib_counter_down,
aslib_counter_touch0,
aslib_counter_up0,
aslib_counter_down0,
};
const bool updateKey_(const std::size_t id_ = 0, const bool is_update = false, const std::size_t count_id = aslib_counter_empty,const bool is_set=false) noexcept
{
static bool aslib_update_key[aslib_key_keyLast];
static Counter aslib_update_count[aslib_key_keyLast];
if (is_update) checkKey(aslib_update_key, aslib_update_count);
switch (count_id)
{
case aslib_counter_touch: return aslib_update_count[id_].count();
case aslib_counter_up: return aslib_update_count[id_].up();
case aslib_counter_down: return aslib_update_count[id_].down();
case aslib_counter_touch0: return aslib_update_count[id_].count0();
case aslib_counter_up0: return aslib_update_count[id_].up0();
case aslib_counter_down0: return aslib_update_count[id_].down0();
default: break;
}
if (is_set) {
aslib_update_key[id_] = true;
aslib_update_count[id_].update(true);
}
return aslib_update_key[id_];
}
inline bool asKeySet(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_empty, true); }
inline bool asKey(const std::size_t& id_) noexcept { return updateKey_(id_, false); }
inline bool asKeyTouch(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_touch); }
inline bool asKeyTouch0(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_touch0); }
inline bool asKeyUp(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_up); }
inline bool asKeyUp0(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_up0); }
inline bool asKeyDown(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_down); }
inline bool asKeyDown0(const std::size_t& id_) noexcept { return updateKey_(id_, false, aslib_counter_down0); }
inline bool asKeyA() noexcept { return updateKey_(aslib_key_a, false); }
inline bool asKeyA_Touch() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_touch); }
inline bool asKeyA_Touch0() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_touch0); }
inline bool asKeyA_Up() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_up); }
inline bool asKeyA_Up0() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_up0); }
inline bool asKeyA_Down() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_down); }
inline bool asKeyA_Down0() noexcept { return updateKey_(aslib_key_a, false, aslib_counter_down0); }
inline bool asKeyB() noexcept { return updateKey_(aslib_key_b, false); }
inline bool asKeyB_Touch() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_touch); }
inline bool asKeyB_Touch0() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_touch0); }
inline bool asKeyB_Up() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_up); }
inline bool asKeyB_Up0() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_up0); }
inline bool asKeyB_Down() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_down); }
inline bool asKeyB_Down0() noexcept { return updateKey_(aslib_key_b, false, aslib_counter_down0); }
inline bool asKeyC() noexcept { return updateKey_(aslib_key_c, false); }
inline bool asKeyC_Touch() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_touch); }
inline bool asKeyC_Touch0() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_touch0); }
inline bool asKeyC_Up() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_up); }
inline bool asKeyC_Up0() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_up0); }
inline bool asKeyC_Down() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_down); }
inline bool asKeyC_Down0() noexcept { return updateKey_(aslib_key_c, false, aslib_counter_down0); }
inline bool asKeyD() noexcept { return updateKey_(aslib_key_d, false); }
inline bool asKeyD_Touch() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_touch); }
inline bool asKeyD_Touch0() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_touch0); }
inline bool asKeyD_Up() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_up); }
inline bool asKeyD_Up0() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_up0); }
inline bool asKeyD_Down() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_down); }
inline bool asKeyD_Down0() noexcept { return updateKey_(aslib_key_d, false, aslib_counter_down0); }
inline bool asKeyE() noexcept { return updateKey_(aslib_key_e, false); }
inline bool asKeyE_Touch() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_touch); }
inline bool asKeyE_Touch0() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_touch0); }
inline bool asKeyE_Up() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_up); }
inline bool asKeyE_Up0() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_up0); }
inline bool asKeyE_Down() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_down); }
inline bool asKeyE_Down0() noexcept { return updateKey_(aslib_key_e, false, aslib_counter_down0); }
inline bool asKeyF() noexcept { return updateKey_(aslib_key_f, false); }
inline bool asKeyF_Touch() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_touch); }
inline bool asKeyF_Touch0() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_touch0); }
inline bool asKeyF_Up() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_up); }
inline bool asKeyF_Up0() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_up0); }
inline bool asKeyF_Down() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_down); }
inline bool asKeyF_Down0() noexcept { return updateKey_(aslib_key_f, false, aslib_counter_down0); }
inline bool asKeyG() noexcept { return updateKey_(aslib_key_g, false); }
inline bool asKeyG_Touch() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_touch); }
inline bool asKeyG_Touch0() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_touch0); }
inline bool asKeyG_Up() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_up); }
inline bool asKeyG_Up0() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_up0); }
inline bool asKeyG_Down() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_down); }
inline bool asKeyG_Down0() noexcept { return updateKey_(aslib_key_g, false, aslib_counter_down0); }
inline bool asKeyH() noexcept { return updateKey_(aslib_key_h, false); }
inline bool asKeyH_Touch() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_touch); }
inline bool asKeyH_Touch0() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_touch0); }
inline bool asKeyH_Up() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_up); }
inline bool asKeyH_Up0() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_up0); }
inline bool asKeyH_Down() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_down); }
inline bool asKeyH_Down0() noexcept { return updateKey_(aslib_key_h, false, aslib_counter_down0); }
inline bool asKeyI() noexcept { return updateKey_(aslib_key_i, false); }
inline bool asKeyI_Touch() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_touch); }
inline bool asKeyI_Touch0() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_touch0); }
inline bool asKeyI_Up() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_up); }
inline bool asKeyI_Up0() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_up0); }
inline bool asKeyI_Down() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_down); }
inline bool asKeyI_Down0() noexcept { return updateKey_(aslib_key_i, false, aslib_counter_down0); }
inline bool asKeyJ() noexcept { return updateKey_(aslib_key_j, false); }
inline bool asKeyJ_Touch() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_touch); }
inline bool asKeyJ_Touch0() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_touch0); }
inline bool asKeyJ_Up() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_up); }
inline bool asKeyJ_Up0() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_up0); }
inline bool asKeyJ_Down() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_down); }
inline bool asKeyJ_Down0() noexcept { return updateKey_(aslib_key_j, false, aslib_counter_down0); }
inline bool asKeyK() noexcept { return updateKey_(aslib_key_k, false); }
inline bool asKeyK_Touch() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_touch); }
inline bool asKeyK_Touch0() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_touch0); }
inline bool asKeyK_Up() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_up); }
inline bool asKeyK_Up0() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_up0); }
inline bool asKeyK_Down() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_down); }
inline bool asKeyK_Down0() noexcept { return updateKey_(aslib_key_k, false, aslib_counter_down0); }
inline bool asKeyL() noexcept { return updateKey_(aslib_key_l, false); }
inline bool asKeyL_Touch() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_touch); }
inline bool asKeyL_Touch0() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_touch0); }
inline bool asKeyL_Up() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_up); }
inline bool asKeyL_Up0() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_up0); }
inline bool asKeyL_Down() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_down); }
inline bool asKeyL_Down0() noexcept { return updateKey_(aslib_key_l, false, aslib_counter_down0); }
inline bool asKeyM() noexcept { return updateKey_(aslib_key_m, false); }
inline bool asKeyM_Touch() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_touch); }
inline bool asKeyM_Touch0() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_touch0); }
inline bool asKeyM_Up() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_up); }
inline bool asKeyM_Up0() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_up0); }
inline bool asKeyM_Down() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_down); }
inline bool asKeyM_Down0() noexcept { return updateKey_(aslib_key_m, false, aslib_counter_down0); }
inline bool asKeyN() noexcept { return updateKey_(aslib_key_n, false); }
inline bool asKeyN_Touch() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_touch); }
inline bool asKeyN_Touch0() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_touch0); }
inline bool asKeyN_Up() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_up); }
inline bool asKeyN_Up0() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_up0); }
inline bool asKeyN_Down() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_down); }
inline bool asKeyN_Down0() noexcept { return updateKey_(aslib_key_n, false, aslib_counter_down0); }
inline bool asKeyO() noexcept { return updateKey_(aslib_key_o, false); }
inline bool asKeyO_Touch() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_touch); }
inline bool asKeyO_Touch0() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_touch0); }
inline bool asKeyO_Up() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_up); }
inline bool asKeyO_Up0() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_up0); }
inline bool asKeyO_Down() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_down); }
inline bool asKeyO_Down0() noexcept { return updateKey_(aslib_key_o, false, aslib_counter_down0); }
inline bool asKeyP() noexcept { return updateKey_(aslib_key_p, false); }
inline bool asKeyP_Touch() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_touch); }
inline bool asKeyP_Touch0() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_touch0); }
inline bool asKeyP_Up() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_up); }
inline bool asKeyP_Up0() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_up0); }
inline bool asKeyP_Down() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_down); }
inline bool asKeyP_Down0() noexcept { return updateKey_(aslib_key_p, false, aslib_counter_down0); }
inline bool asKeyQ() noexcept { return updateKey_(aslib_key_q, false); }
inline bool asKeyQ_Touch() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_touch); }
inline bool asKeyQ_Touch0() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_touch0); }
inline bool asKeyQ_Up() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_up); }
inline bool asKeyQ_Up0() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_up0); }
inline bool asKeyQ_Down() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_down); }
inline bool asKeyQ_Down0() noexcept { return updateKey_(aslib_key_q, false, aslib_counter_down0); }
inline bool asKeyR() noexcept { return updateKey_(aslib_key_r, false); }
inline bool asKeyR_Touch() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_touch); }
inline bool asKeyR_Touch0() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_touch0); }
inline bool asKeyR_Up() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_up); }
inline bool asKeyR_Up0() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_up0); }
inline bool asKeyR_Down() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_down); }
inline bool asKeyR_Down0() noexcept { return updateKey_(aslib_key_r, false, aslib_counter_down0); }
inline bool asKeyS() noexcept { return updateKey_(aslib_key_s, false); }
inline bool asKeyS_Touch() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_touch); }
inline bool asKeyS_Touch0() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_touch0); }
inline bool asKeyS_Up() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_up); }
inline bool asKeyS_Up0() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_up0); }
inline bool asKeyS_Down() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_down); }
inline bool asKeyS_Down0() noexcept { return updateKey_(aslib_key_s, false, aslib_counter_down0); }
inline bool asKeyT() noexcept { return updateKey_(aslib_key_t, false); }
inline bool asKeyT_Touch() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_touch); }
inline bool asKeyT_Touch0() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_touch0); }
inline bool asKeyT_Up() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_up); }
inline bool asKeyT_Up0() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_up0); }
inline bool asKeyT_Down() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_down); }
inline bool asKeyT_Down0() noexcept { return updateKey_(aslib_key_t, false, aslib_counter_down0); }
inline bool asKeyU() noexcept { return updateKey_(aslib_key_u, false); }
inline bool asKeyU_Touch() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_touch); }
inline bool asKeyU_Touch0() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_touch0); }
inline bool asKeyU_Up() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_up); }
inline bool asKeyU_Up0() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_up0); }
inline bool asKeyU_Down() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_down); }
inline bool asKeyU_Down0() noexcept { return updateKey_(aslib_key_u, false, aslib_counter_down0); }
inline bool asKeyV() noexcept { return updateKey_(aslib_key_v, false); }
inline bool asKeyV_Touch() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_touch); }
inline bool asKeyV_Touch0() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_touch0); }
inline bool asKeyV_Up() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_up); }
inline bool asKeyV_Up0() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_up0); }
inline bool asKeyV_Down() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_down); }
inline bool asKeyV_Down0() noexcept { return updateKey_(aslib_key_v, false, aslib_counter_down0); }
inline bool asKeyW() noexcept { return updateKey_(aslib_key_w, false); }
inline bool asKeyW_Touch() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_touch); }
inline bool asKeyW_Touch0() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_touch0); }
inline bool asKeyW_Up() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_up); }
inline bool asKeyW_Up0() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_up0); }
inline bool asKeyW_Down() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_down); }
inline bool asKeyW_Down0() noexcept { return updateKey_(aslib_key_w, false, aslib_counter_down0); }
inline bool asKeyX() noexcept { return updateKey_(aslib_key_x, false); }
inline bool asKeyX_Touch() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_touch); }
inline bool asKeyX_Touch0() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_touch0); }
inline bool asKeyX_Up() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_up); }
inline bool asKeyX_Up0() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_up0); }
inline bool asKeyX_Down() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_down); }
inline bool asKeyX_Down0() noexcept { return updateKey_(aslib_key_x, false, aslib_counter_down0); }
inline bool asKeyY() noexcept { return updateKey_(aslib_key_y, false); }
inline bool asKeyY_Touch() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_touch); }
inline bool asKeyY_Touch0() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_touch0); }
inline bool asKeyY_Up() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_up); }
inline bool asKeyY_Up0() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_up0); }
inline bool asKeyY_Down() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_down); }
inline bool asKeyY_Down0() noexcept { return updateKey_(aslib_key_y, false, aslib_counter_down0); }
inline bool asKeyZ() noexcept { return updateKey_(aslib_key_z, false); }
inline bool asKeyZ_Touch() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_touch); }
inline bool asKeyZ_Touch0() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_touch0); }
inline bool asKeyZ_Up() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_up); }
inline bool asKeyZ_Up0() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_up0); }
inline bool asKeyZ_Down() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_down); }
inline bool asKeyZ_Down0() noexcept { return updateKey_(aslib_key_z, false, aslib_counter_down0); }
inline bool asKey0() noexcept { return updateKey_(aslib_key_0, false); }
inline bool asKey0_Touch() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_touch); }
inline bool asKey0_Touch0() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_touch0); }
inline bool asKey0_Up() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_up); }
inline bool asKey0_Up0() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_up0); }
inline bool asKey0_Down() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_down); }
inline bool asKey0_Down0() noexcept { return updateKey_(aslib_key_0, false, aslib_counter_down0); }
inline bool asKey1() noexcept { return updateKey_(aslib_key_1, false); }
inline bool asKey1_Touch() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_touch); }
inline bool asKey1_Touch0() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_touch0); }
inline bool asKey1_Up() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_up); }
inline bool asKey1_Up0() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_up0); }
inline bool asKey1_Down() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_down); }
inline bool asKey1_Down0() noexcept { return updateKey_(aslib_key_1, false, aslib_counter_down0); }
inline bool asKey2() noexcept { return updateKey_(aslib_key_2, false); }
inline bool asKey2_Touch() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_touch); }
inline bool asKey2_Touch0() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_touch0); }
inline bool asKey2_Up() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_up); }
inline bool asKey2_Up0() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_up0); }
inline bool asKey2_Down() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_down); }
inline bool asKey2_Down0() noexcept { return updateKey_(aslib_key_2, false, aslib_counter_down0); }
inline bool asKey3() noexcept { return updateKey_(aslib_key_3, false); }
inline bool asKey3_Touch() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_touch); }
inline bool asKey3_Touch0() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_touch0); }
inline bool asKey3_Up() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_up); }
inline bool asKey3_Up0() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_up0); }
inline bool asKey3_Down() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_down); }
inline bool asKey3_Down0() noexcept { return updateKey_(aslib_key_3, false, aslib_counter_down0); }
inline bool asKey4() noexcept { return updateKey_(aslib_key_4, false); }
inline bool asKey4_Touch() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_touch); }
inline bool asKey4_Touch0() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_touch0); }
inline bool asKey4_Up() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_up); }
inline bool asKey4_Up0() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_up0); }
inline bool asKey4_Down() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_down); }
inline bool asKey4_Down0() noexcept { return updateKey_(aslib_key_4, false, aslib_counter_down0); }
inline bool asKey5() noexcept { return updateKey_(aslib_key_5, false); }
inline bool asKey5_Touch() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_touch); }
inline bool asKey5_Touch0() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_touch0); }
inline bool asKey5_Up() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_up); }
inline bool asKey5_Up0() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_up0); }
inline bool asKey5_Down() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_down); }
inline bool asKey5_Down0() noexcept { return updateKey_(aslib_key_5, false, aslib_counter_down0); }
inline bool asKey6() noexcept { return updateKey_(aslib_key_6, false); }
inline bool asKey6_Touch() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_touch); }
inline bool asKey6_Touch0() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_touch0); }
inline bool asKey6_Up() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_up); }
inline bool asKey6_Up0() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_up0); }
inline bool asKey6_Down() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_down); }
inline bool asKey6_Down0() noexcept { return updateKey_(aslib_key_6, false, aslib_counter_down0); }
inline bool asKey7() noexcept { return updateKey_(aslib_key_7, false); }
inline bool asKey7_Touch() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_touch); }
inline bool asKey7_Touch0() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_touch0); }
inline bool asKey7_Up() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_up); }
inline bool asKey7_Up0() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_up0); }
inline bool asKey7_Down() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_down); }
inline bool asKey7_Down0() noexcept { return updateKey_(aslib_key_7, false, aslib_counter_down0); }
inline bool asKey8() noexcept { return updateKey_(aslib_key_8, false); }
inline bool asKey8_Touch() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_touch); }
inline bool asKey8_Touch0() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_touch0); }
inline bool asKey8_Up() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_up); }
inline bool asKey8_Up0() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_up0); }
inline bool asKey8_Down() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_down); }
inline bool asKey8_Down0() noexcept { return updateKey_(aslib_key_8, false, aslib_counter_down0); }
inline bool asKey9() noexcept { return updateKey_(aslib_key_9, false); }
inline bool asKey9_Touch() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_touch); }
inline bool asKey9_Touch0() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_touch0); }
inline bool asKey9_Up() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_up); }
inline bool asKey9_Up0() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_up0); }
inline bool asKey9_Down() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_down); }
inline bool asKey9_Down0() noexcept { return updateKey_(aslib_key_9, false, aslib_counter_down0); }
inline bool asKeyEnter() noexcept { return updateKey_(aslib_key_enter, false); }
inline bool asKeyEnterTouch() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_touch); }
inline bool asKeyEnterTouch0() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_touch0); }
inline bool asKeyEnterUp() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_up); }
inline bool asKeyEnterUp0() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_up0); }
inline bool asKeyEnterDown() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_down); }
inline bool asKeyEnterDown0() noexcept { return updateKey_(aslib_key_enter, false, aslib_counter_down0); }
inline bool asKeyUp() noexcept { return updateKey_(aslib_key_up, false); }
inline bool asKeyUpTouch() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_touch); }
inline bool asKeyUpTouch0() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_touch0); }
inline bool asKeyUpUp() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_up); }
inline bool asKeyUpUp0() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_up0); }
inline bool asKeyUpDown() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_down); }
inline bool asKeyUpDown0() noexcept { return updateKey_(aslib_key_up, false, aslib_counter_down0); }
inline bool asKeyDown() noexcept { return updateKey_(aslib_key_down, false); }
inline bool asKeyDownTouch() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_touch); }
inline bool asKeyDownTouch0() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_touch0); }
inline bool asKeyDownUp() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_up); }
inline bool asKeyDownUp0() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_up0); }
inline bool asKeyDownDown() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_down); }
inline bool asKeyDownDown0() noexcept { return updateKey_(aslib_key_down, false, aslib_counter_down0); }
inline bool asKeyLeft() noexcept { return updateKey_(aslib_key_left, false); }
inline bool asKeyLeftTouch() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_touch); }
inline bool asKeyLeftTouch0() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_touch0); }
inline bool asKeyLeftUp() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_up); }
inline bool asKeyLeftUp0() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_up0); }
inline bool asKeyLeftDown() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_down); }
inline bool asKeyLeftDown0() noexcept { return updateKey_(aslib_key_left, false, aslib_counter_down0); }
inline bool asKeyRight() noexcept { return updateKey_(aslib_key_right, false); }
inline bool asKeyRightTouch() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_touch); }
inline bool asKeyRightTouch0() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_touch0); }
inline bool asKeyRightUp() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_up); }
inline bool asKeyRightUp0() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_up0); }
inline bool asKeyRightDown() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_down); }
inline bool asKeyRightDown0() noexcept { return updateKey_(aslib_key_right, false, aslib_counter_down0); }
//inline bool asKeyA() { return updateKey_(aslib_key_a, false); }
//inline bool asKeyA_Touch() { return updateKey_(aslib_key_a, false, aslib_counter_touch); }
//inline bool asKeyA_Touch0() { return updateKey_(aslib_key_a, false, aslib_counter_touch0); }
//inline bool asKeyA_Up() { return updateKey_(aslib_key_a, false, aslib_counter_up); }
//inline bool asKeyA_Up0() { return updateKey_(aslib_key_a, false, aslib_counter_up0); }
//inline bool asKeyA_Down() { return updateKey_(aslib_key_a, false, aslib_counter_down); }
//inline bool asKeyA_Down0() { return updateKey_(aslib_key_a, false, aslib_counter_down0); }
inline void updateKey() noexcept { updateKey_(0, true); }
//switch (player_move_left_up[i])
//{
//case aslib_key_w_a:
// if (asKeyW_Touch() && asKeyA_Touch()) return MOB_LEFT_UP;
// break;
//case aslib_key_w_d:
// if (asKeyW_Touch() && asKeyD_Touch()) return MOB_RIGHT_UP;
// return MOB_CENTER;
//case aslib_key_s_a:
// if (asKeyS_Touch() && asKeyA_Touch()) return MOB_LEFT_DOWN;
// return MOB_CENTER;
//case aslib_key_s_d:
// if (asKeyS_Touch() && asKeyD_Touch()) return MOB_RIGHT_DOWN;
// return MOB_CENTER;
//case aslib_key_left_up:
// if (asKeyLeftTouch() && asKeyUpTouch()) return MOB_LEFT_UP;
// return MOB_CENTER;
//case aslib_key_right_up:
// if (asKeyRightTouch() && asKeyUpTouch()) return MOB_RIGHT_UP;
// return MOB_CENTER;
//case aslib_key_left_down:
// if (asKeyLeftTouch() && asKeyDownTouch()) return MOB_LEFT_DOWN;
// return MOB_CENTER;
//case aslib_key_right_down:
// if (asKeyRightTouch() && asKeyDownTouch()) return MOB_RIGHT_DOWN;
// return MOB_CENTER;
//}
struct AsKeyList {
AsKeyList() = default;
//プレイヤー系
std::vector<std::size_t> player_move_down;
std::vector<std::size_t> player_move_up;
std::vector<std::size_t> player_move_left;
std::vector<std::size_t> player_move_right;
std::vector<std::size_t> player_move_left_up;
std::vector<std::size_t> player_move_right_up;
std::vector<std::size_t> player_move_left_down;
std::vector<std::size_t> player_move_right_down;
//通常系
std::vector<std::size_t> ok;
std::vector<std::size_t> back;
std::vector<std::size_t> menu;
const bool is_ok() const noexcept {
for (std::size_t i{}; i < ok.size(); ++i) {
if (ok[i] < 256 && asKeyUp(ok[i])) return true;
}
return false;
}
AsKeyList& addKeyOK() noexcept {
ok.emplace_back(aslib_key_enter);
ok.emplace_back(aslib_key_space);
ok.emplace_back(aslib_key_z);
return *this;
}
AsKeyList& addKeyBack() noexcept {
back.emplace_back(aslib_key_x);
return *this;
}
AsKeyList& addKeyUpDown() noexcept {
player_move_down.emplace_back(aslib_key_down);
player_move_up.emplace_back(aslib_key_up);
return *this;
}
AsKeyList& addKeyCross() noexcept {
player_move_down.emplace_back(aslib_key_down);
player_move_up.emplace_back(aslib_key_up);
player_move_left.emplace_back(aslib_key_left);
player_move_right.emplace_back(aslib_key_right);
player_move_left_up.emplace_back(aslib_key_left_up);
player_move_right_up.emplace_back(aslib_key_right_up);
player_move_left_down.emplace_back(aslib_key_left_down);
player_move_right_down.emplace_back(aslib_key_right_down);
return *this;
}
AsKeyList& addKeyCrossW() noexcept {
player_move_down.emplace_back(aslib_key_s);
player_move_up.emplace_back(aslib_key_w);
player_move_left.emplace_back(aslib_key_a);
player_move_right.emplace_back(aslib_key_d);
player_move_left_up.emplace_back(aslib_key_w_a);
player_move_right_up.emplace_back(aslib_key_w_d);
player_move_left_down.emplace_back(aslib_key_s_a);
player_move_right_down.emplace_back(aslib_key_s_d);
return *this;
}
const bool isTouch(const std::size_t is_) const noexcept {
switch (is_)
{
case aslib_key_w_a:
if (asKeyW_Touch() && asKeyA_Touch()) return true;
return false;
case aslib_key_w_d:
if (asKeyW_Touch() && asKeyD_Touch()) return true;
return false;
case aslib_key_s_a:
if (asKeyS_Touch() && asKeyA_Touch()) return true;
return false;
case aslib_key_s_d:
if (asKeyS_Touch() && asKeyD_Touch()) return true;
return false;
case aslib_key_left_up:
if (asKeyLeftTouch() && asKeyUpTouch()) return true;
return false;
case aslib_key_right_up:
if (asKeyRightTouch() && asKeyUpTouch()) return true;
return false;
case aslib_key_left_down:
if (asKeyLeftTouch() && asKeyDownTouch()) return true;
return false;
case aslib_key_right_down:
if (asKeyRightTouch() && asKeyDownTouch()) return true;
return false;
}
return false;
}
const std::size_t playerMove4() const noexcept {
for (std::size_t i{}; i < player_move_down.size(); ++i) {
if (player_move_down[i] > 255) {
if (isTouch(player_move_down[i])) return MOB_DOWN;
else continue;
}
if (asKeyTouch(player_move_down[i])) return MOB_DOWN;
}
for (std::size_t i{}; i < player_move_up.size(); ++i) {
if (player_move_up[i] > 255) {
if (isTouch(player_move_up[i])) return MOB_UP;
else continue;
}
if (asKeyTouch(player_move_up[i])) return MOB_UP;
}
for (std::size_t i{}; i < player_move_left.size(); ++i) {
if (player_move_left[i] > 255) {
if (isTouch(player_move_left[i])) return MOB_LEFT;
else continue;
}
if (asKeyTouch(player_move_left[i])) return MOB_LEFT;
}
for (std::size_t i{}; i < player_move_right.size(); ++i) {
if (player_move_right[i] > 255) {
if (isTouch(player_move_right[i])) return MOB_RIGHT;
else continue;
}
if (asKeyTouch(player_move_right[i])) return MOB_RIGHT;
}
return MOB_CENTER;
}
const std::size_t playerMove8() const noexcept {
for (std::size_t i{}; i < player_move_left_up.size(); ++i) {
if (player_move_left_up[i] > 255) {
if (isTouch(player_move_left_up[i])) return MOB_LEFT_UP;
else continue;
}
if (asKeyTouch(player_move_left_up[i])) return MOB_LEFT_UP;
}
for (std::size_t i{}; i < player_move_right_up.size(); ++i) {
if (player_move_right_up[i] > 255) {
if (isTouch(player_move_right_up[i])) return MOB_RIGHT_UP;
else continue;
}
if (asKeyTouch(player_move_right_up[i])) return MOB_RIGHT_UP;
}
for (std::size_t i{}; i < player_move_left_down.size(); ++i) {
if (player_move_left_down[i] > 255) {
if (isTouch(player_move_left_down[i])) return MOB_LEFT_DOWN;
else continue;
}
if (asKeyTouch(player_move_left_down[i])) return MOB_LEFT_DOWN;
}
for (std::size_t i{}; i < player_move_right_down.size(); ++i) {
if (player_move_right_down[i] > 255) {
if (isTouch(player_move_right_down[i])) return MOB_RIGHT_DOWN;
else continue;
}
if (asKeyTouch(player_move_right_down[i])) return MOB_RIGHT_DOWN;
}
return playerMove4();
}
};
}
// bool* checkKey9() {
// constexpr std::array<std::size_t, 256> AS_DL_key{
// aslib_key_unknown,//Ka0
// aslib_key_eSCAPE,//KESCAPE0x01//EscキーD_DIK_ESCAPE
// aslib_key_1,//K10x02//1キーD_DIK_1
// aslib_key_2,//K20x03//2キーD_DIK_2
// aslib_key_3,//K30x04//3キーD_DIK_3
// aslib_key_4,//K40x05//4キーD_DIK_4
// aslib_key_5,//K50x06//5キーD_DIK_5
// aslib_key_6,//K60x07//6キーD_DIK_6
// aslib_key_7,//K70x08//7キーD_DIK_7
// aslib_key_8,//K80x09//8キーD_DIK_8
// aslib_key_9,//K90x0A//9キーD_DIK_9
// aslib_key_0,//K00x0B//0キーD_DIK_0
// 0,//KMINUS0x0C//-キーD_DIK_MINUS
// aslib_key_unknown,//Ka13
// 0,//KBACK0x0E//BackSpaceキーD_DIK_BACK
// 0,//KTAB0x0F//TabキーD_DIK_TAB
// aslib_key_q,//KQ0x10//QキーD_DIK_Q
// aslib_key_w,//KW0x11//WキーD_DIK_W
// aslib_key_e,//KE0x12//EキーD_DIK_E
// aslib_key_r,//KR0x13//RキーD_DIK_R
// aslib_key_t,//KT0x14//TキーD_DIK_T
// aslib_key_y,//KY0x15//YキーD_DIK_Y
// aslib_key_u,//KU0x16//UキーD_DIK_U
// aslib_key_i,//KI0x17//IキーD_DIK_I
// aslib_key_o,//KO0x18//OキーD_DIK_O
// aslib_key_p,//KP0x19//PキーD_DIK_P
// 0,//KLBRACKET0x1A//[キーD_DIK_LBRACKET
// 0,//KRBRACKET0x1B//]キーD_DIK_RBRACKET
// 0,//KRETURN0x1C//EnterキーD_DIK_RETURN
// 0,//KLCONTROL0x1D//左CtrlキーD_DIK_LCONTROL
// aslib_key_a,//KA0x1E//AキーD_DIK_A
// aslib_key_s,//KS0x1F//SキーD_DIK_S
// aslib_key_d,//KD0x20//DキーD_DIK_D
// aslib_key_f,//KF0x21//FキーD_DIK_F
// aslib_key_g,//KG0x22//GキーD_DIK_G
// aslib_key_h,//KH0x23//HキーD_DIK_H
// aslib_key_j,//KJ0x24//JキーD_DIK_J
// aslib_key_k,//KK0x25//KキーD_DIK_K
// aslib_key_l,//KL0x26//LキーD_DIK_L
// aslib_key_semicolon,//KSEMICOLON0x27//;キーD_DIK_SEMICOLON
// aslib_key_unknown,//Ka40
// aslib_key_unknown,//Ka41
// 0,//KLSHIFT0x2A//左ShiftキーD_DIK_LSHIFT
// 0,//KBACKSLASH0x2B//\キーD_DIK_BACKSLASH
// aslib_key_z,//KZ0x2C//ZキーD_DIK_Z
// aslib_key_x,//KX0x2D//XキーD_DIK_X
// aslib_key_c,//KC0x2E//CキーD_DIK_C
// aslib_key_v,//KV0x2F//VキーD_DIK_V
// aslib_key_b,//KB0x30//BキーD_DIK_B
// aslib_key_n,//KN0x31//NキーD_DIK_N
// aslib_key_m,//KM0x32//MキーD_DIK_M
// 0,//KCOMMA0x33//,キーD_DIK_COMMA
// 0,//KPERIOD0x34//.キーD_DIK_PERIOD
// 0,//KSLASH0x35///キーD_DIK_SLASH
// 0,//KRSHIFT0x36//右ShiftキーD_DIK_RSHIFT
// 0,//KMULTIPLY0x37//テンキー*キーD_DIK_MULTIPLY
// 0,//KLALT0x38//左AltキーD_DIK_LALT
// 0,//KSPACE0x39//スペースキーD_DIK_SPACE
// 0,//KCAPSLOCK0x3A//CaspLockキーD_DIK_CAPSLOCK
// aslib_key_f1,//KF10x3B//F1キーD_DIK_F1
// aslib_key_f2,//KF20x3C//F2キーD_DIK_F2
// aslib_key_f3,//KF30x3D//F3キーD_DIK_F3
// aslib_key_f4,//KF40x3E//F4キーD_DIK_F4
// aslib_key_f5,//KF50x3F//F5キーD_DIK_F5
// aslib_key_f6,//KF60x40//F6キーD_DIK_F6
// aslib_key_f7,//KF70x41//F7キーD_DIK_F7
// aslib_key_f8,//KF80x42//F8キーD_DIK_F8
// aslib_key_f9,//KF90x43//F9キーD_DIK_F9
// aslib_key_f10,//KF100x44//F10キーD_DIK_F10
// 0,//KNUMLOCK0x45//テンキーNumLockキーD_DIK_NUMLOCK
// 0,//KSCROLL0x46//ScrollLockキーD_DIK_SCROLL
// Keypad_7,//KNUMPAD70x47//テンキー7D_DIK_NUMPAD7
// Keypad_8,//KNUMPAD80x48//テンキー8D_DIK_NUMPAD8
// Keypad_9,//KNUMPAD90x49//テンキー9D_DIK_NUMPAD9
// 0,//KSUBTRACT0x4A//テンキー-キーD_DIK_SUBTRACT
// Keypad_4,//KNUMPAD40x4B//テンキー4D_DIK_NUMPAD4
// Keypad_5,//KNUMPAD50x4C//テンキー5D_DIK_NUMPAD5
// Keypad_6,//KNUMPAD60x4D//テンキー6D_DIK_NUMPAD6
// aslib_key_unknown,//KaDD0x4E//テンキー+キーD_DIK_ADD
// Keypad_1,//KNUMPAD10x4F//テンキー1D_DIK_NUMPAD1
// Keypad_2,//KNUMPAD20x50//テンキー2D_DIK_NUMPAD2
// Keypad_3,//KNUMPAD30x51//テンキー3D_DIK_NUMPAD3
// Keypad_0,//KNUMPAD00x52//テンキー0D_DIK_NUMPAD0
// 0,//KDECIMAL0x53//テンキー.キーD_DIK_DECIMAL
// aslib_key_unknown,//Ka84
// aslib_key_unknown,//Ka85
// aslib_key_unknown,//Ka86
// aslib_key_f11,//KF110x57//F11キーD_DIK_F11
// aslib_key_f12,//KF120x58//F12キーD_DIK_F12
// aslib_key_unknown,//Ka89
// aslib_key_unknown,//Ka90
// aslib_key_unknown,//Ka91
// aslib_key_unknown,//Ka92
// aslib_key_unknown,//Ka93
// aslib_key_unknown,//Ka94
// aslib_key_unknown,//Ka95
// aslib_key_unknown,//Ka96
// aslib_key_unknown,//Ka97
// aslib_key_unknown,//Ka98
// aslib_key_unknown,//Ka99
// aslib_key_unknown,//Ka100
// aslib_key_unknown,//Ka101
// aslib_key_unknown,//Ka102
// aslib_key_unknown,//Ka103
// aslib_key_unknown,//Ka104
// aslib_key_unknown,//Ka105
// aslib_key_unknown,//Ka106
// aslib_key_unknown,//Ka107
// aslib_key_unknown,//Ka108
// aslib_key_unknown,//Ka109
// aslib_key_unknown,//Ka110
// aslib_key_unknown,//Ka111
// 0,//KKANA0x70//カナキーD_DIK_KANA
// aslib_key_unknown,//Ka113
// aslib_key_unknown,//Ka114
// aslib_key_unknown,//Ka115
// aslib_key_unknown,//Ka116
// aslib_key_unknown,//Ka117
// aslib_key_unknown,//Ka118
// aslib_key_unknown,//Ka119
// aslib_key_unknown,//Ka120
// 0,//KCONVERT0x79//変換キーD_DIK_CONVERT
// aslib_key_unknown,//Ka122
// 0,//KNOCONVERT0x7B//無変換キーD_DIK_NOCONVERT
// aslib_key_unknown,//Ka124
// 0,//KYEN0x7D//¥キーD_DIK_YEN
// aslib_key_unknown,//Ka126
// aslib_key_unknown,//Ka127
// aslib_key_unknown,//Ka128
// aslib_key_unknown,//Ka129
// aslib_key_unknown,//Ka130
// aslib_key_unknown,//Ka131
// aslib_key_unknown,//Ka132
// aslib_key_unknown,//Ka133
// aslib_key_unknown,//Ka134
// aslib_key_unknown,//Ka135
// aslib_key_unknown,//Ka136
// aslib_key_unknown,//Ka137
// aslib_key_unknown,//Ka138
// aslib_key_unknown,//Ka139
// aslib_key_unknown,//Ka140
// aslib_key_unknown,//Ka141
// aslib_key_unknown,//Ka142
// aslib_key_unknown,//Ka143
// 0,//KPREVTRACK0x90//^キーD_DIK_PREVTRACK
// aslib_key_unknown,//KaT0x91//@キーD_DIK_AT
// 0,//KCOLON0x92//:キーD_DIK_COLON
// aslib_key_unknown,//Ka147
// aslib_key_grave_accentilde,//KKANJI0x94//漢字キーD_DIK_KANJI
// aslib_key_unknown,//Ka149
// aslib_key_unknown,//Ka150
// aslib_key_unknown,//Ka151
// aslib_key_unknown,//Ka152
// aslib_key_unknown,//Ka153
// aslib_key_unknown,//Ka154
// aslib_key_unknown,//Ka155
// Keypad_ENTER,//KNUMPADENTER0x9C//テンキーのエンターキーD_DIK_NUMPADENTER
// 0,//KRCONTROL0x9D//右CtrlキーD_DIK_RCONTROL
// aslib_key_unknown,//Ka158
// aslib_key_unknown,//Ka159
// aslib_key_unknown,//Ka160
// aslib_key_unknown,//Ka161
// aslib_key_unknown,//Ka162
// aslib_key_unknown,//Ka163
// aslib_key_unknown,//Ka164
// aslib_key_unknown,//Ka165
// aslib_key_unknown,//Ka166
// aslib_key_unknown,//Ka167
// aslib_key_unknown,//Ka168
// aslib_key_unknown,//Ka169
// aslib_key_unknown,//Ka170
// aslib_key_unknown,//Ka171
// aslib_key_unknown,//Ka172
// aslib_key_unknown,//Ka173
// aslib_key_unknown,//Ka174
// aslib_key_unknown,//Ka175
// aslib_key_unknown,//Ka176
// aslib_key_unknown,//Ka177
// aslib_key_unknown,//Ka178
// aslib_key_unknown,//Ka179
// aslib_key_unknown,//Ka180
// 0,//KDIVIDE0xB5//テンキー/キーD_DIK_DIVIDE
// aslib_key_unknown,//Ka182
// 0,//KSYSRQ0xB7//PrintScreenキーD_DIK_SYSRQ
// 0,//KRALT0xB8//右AltキーD_DIK_RALT
// aslib_key_unknown,//Ka185
// aslib_key_unknown,//Ka186
// aslib_key_unknown,//Ka187
// aslib_key_unknown,//Ka188
// aslib_key_unknown,//Ka189
// aslib_key_unknown,//Ka190
// aslib_key_unknown,//Ka191
// aslib_key_unknown,//Ka192
// aslib_key_unknown,//Ka193
// aslib_key_unknown,//Ka194
// aslib_key_unknown,//Ka195
// aslib_key_unknown,//Ka196
// 0,//KPAUSE0xC5//PauseBreakキーD_DIK_PAUSE
// aslib_key_unknown,//Ka198
// 0,//KHOME0xC7//HomeキーD_DIK_HOME
// aslib_key_up,//KUP0xC8//上キーD_DIK_UP
// 0,//KPGUP0xC9//PageUpキーD_DIK_PGUP
// aslib_key_unknown,//Ka202
// aslib_key_left,//KLEFT0xCB//左キーD_DIK_LEFT
// aslib_key_unknown,//Ka204
// aslib_key_right,//KRIGHT0xCD//右キーD_DIK_RIGHT
// aslib_key_unknown,//Ka206
// 0,//KEND0xCF//EndキーD_DIK_END
// aslib_key_down,//KDOWN0xD0//下キーD_DIK_DOWN
// 0,//KPGDN0xD1//PageDownキーD_DIK_PGDN
// 0,//KINSERT0xD2//InsertキーD_DIK_INSERT
// 0,//KDELETE0xD3//DeleteキーD_DIK_DELETE
// aslib_key_unknown,//Ka212
// aslib_key_unknown,//Ka213
// aslib_key_unknown,//Ka214
// aslib_key_unknown,//Ka215
// aslib_key_unknown,//Ka216
// aslib_key_unknown,//Ka217
// aslib_key_unknown,//Ka218
// 0,//KLWIN0xDB//左WinキーD_DIK_LWIN
// 0,//KRWIN0xDC//右WinキーD_DIK_RWIN
// aslib_key_unknown,//KaPPS0xDD//アプリケーションメニューキーD_DIK_APPS
// aslib_key_unknown,//Ka222
// aslib_key_unknown,//Ka223
// aslib_key_unknown,//Ka224
// aslib_key_unknown,//Ka225
// aslib_key_unknown,//Ka226
// aslib_key_unknown,//Ka227
// aslib_key_unknown,//Ka228
// aslib_key_unknown,//Ka229
// aslib_key_unknown,//Ka230
// aslib_key_unknown,//Ka231
// aslib_key_unknown,//Ka232
// aslib_key_unknown,//Ka233
// aslib_key_unknown,//Ka234
// aslib_key_unknown,//Ka235
// aslib_key_unknown,//Ka236
// aslib_key_unknown,//Ka237
// aslib_key_unknown,//Ka238
// aslib_key_unknown,//Ka239
// aslib_key_unknown,//Ka240
// aslib_key_unknown,//Ka241
// aslib_key_unknown,//Ka242
// aslib_key_unknown,//Ka243
// aslib_key_unknown,//Ka244
// aslib_key_unknown,//Ka245
// aslib_key_unknown,//Ka246
// aslib_key_unknown,//Ka247
// aslib_key_unknown,//Ka248
// aslib_key_unknown,//Ka249
// aslib_key_unknown,//Ka250
// aslib_key_unknown,//Ka251
// aslib_key_unknown,//Ka252
// aslib_key_unknown,//Ka253
// aslib_key_unknown,//Ka254
// aslib_key_unknown//Ka255
// };
// bool AS_key[aslib_key_keyLast] = { false };
//
// std::array<char,256> DL_key;
// DxLib::GetHitKeyStateAll(DL_key.data());
// for (std::size_t i{}; i < 256; ++i) {
// if (DL_key[i] != 0) {
// //AS_key[AS_DL_key[i]] = true;
// }
// }
// return AS_key;
//}
#endif //Included AsProject Library | 38.095238 | 161 | 0.767991 | [
"vector"
] |
809ab34a26bc5678cc986b94b9a0e9701811d0fd | 2,320 | hpp | C++ | Toast-Core/include/toast/http/handler.hpp | JacisNonsense/ToastCPP | e4879902aacfcbadff87f1bdce021befee72882a | [
"MIT"
] | 4 | 2016-07-18T13:21:07.000Z | 2017-01-05T05:47:56.000Z | Toast-Core/include/toast/http/handler.hpp | JacisNonsense/ToastCPP | e4879902aacfcbadff87f1bdce021befee72882a | [
"MIT"
] | null | null | null | Toast-Core/include/toast/http/handler.hpp | JacisNonsense/ToastCPP | e4879902aacfcbadff87f1bdce021befee72882a | [
"MIT"
] | null | null | null | #pragma once
#include "toast/http/request.hpp"
#include "toast/http/response.hpp"
#include "toast/http/websocket.hpp"
#include "toast/library.hpp"
#include <map>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define route(httpMethod, url, handlerType, method) \
register_route(httpMethod, url, new Toast::HTTP::RequestHandler<handlerType, Toast::HTTP::StreamResponse>(this, &handlerType::method ));
#define route_type(httpMethod, url, handlerType, method, responseType) \
register_route(httpMethod, url, new Toast::HTTP::RequestHandler<handlerType, responseType>(this, &handlerType::method ));
namespace Toast {
namespace HTTP {
class Server; // Fwd Declaration for Toast::HTTP::Server
class Handler {
public:
API Handler();
API virtual ~Handler();
API virtual void set_server(Server *server);
API virtual void pre_process(Request *request, Response *response);
API virtual Response *process(Request *request);
API virtual void post_process(Request *request, Response *response);
API virtual Response *handle_request(Request *request);
API void set_prefix(string prefix);
API virtual void webSocketReady(WebSocket *websocket);
API virtual void webSocketData(WebSocket *websocket, string data);
API virtual void webSocketClosed(WebSocket *websocket);
API virtual void register_web_socket(string route, WebSocketHandler *handler);
API virtual void web_socket(string route, WebSocketHandler *handler); // same as registerWebSocket
API virtual void register_route(string httpMethod, string route, RequestHandlerBase *handler);
API virtual void setup();
API virtual Response *serverInternalError(string message);
API virtual bool handles(string method, string url);
API vector<string> get_urls();
protected:
Server *server;
string prefix;
map<string, RequestHandlerBase* > routes;
map<string, WebSocketHandler *> wsRoutes;
vector<string> urls;
};
class HTTPHandler : public Handler {
public:
API HTTPHandler();
API void pre_process(Request *request, Response *response);
};
class DirHandler : public Handler {
public:
API DirHandler(string uri_base, string dir);
API virtual Response *process(Request *request);
private:
string _uri_base;
string _dir;
};
}
} | 31.351351 | 140 | 0.743103 | [
"vector"
] |
80a1d214815116301c23e80c1cfdbd7549729756 | 1,171 | cpp | C++ | src/problems/1-50/19/problem19.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | 1 | 2019-12-25T10:17:15.000Z | 2019-12-25T10:17:15.000Z | src/problems/1-50/19/problem19.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | src/problems/1-50/19/problem19.cpp | abeccaro/project-euler | c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3 | [
"MIT"
] | null | null | null | //
// Created by Alex Beccaro on 17/12/17.
//
#include "problem19.hpp"
using std::vector;
namespace problems {
uint32_t problem19::days_in_month(unsigned int year, unsigned int month) {
switch (month) {
case 2: return year % 4 == 0 ? 29 : 28; // safe for 1901-2000
case 4:
case 6:
case 9:
case 11: return 30;
default: return 31;
}
}
uint32_t problem19::count_sundays(const vector<uint32_t>& days_in_months, uint32_t passed_from_sunday) {
uint32_t sundays = 0;
for (uint32_t days_in_month : days_in_months) {
if (passed_from_sunday == 0)
sundays++;
passed_from_sunday = (days_in_month + passed_from_sunday) % 7;
}
return sundays;
}
uint32_t problem19::solve() {
vector<uint32_t> days_in_months;
days_in_months.reserve(1200);
for (uint32_t y = 1901; y <= 2000; y++)
for (uint32_t m = 1; m <= 12; m++)
days_in_months.push_back(days_in_month(y, m));
return count_sundays(days_in_months, 2); // 1 Jan 1901 was a Tuesday
}
} | 27.232558 | 108 | 0.571307 | [
"vector"
] |
80a1ff32c3f628a0731b792672258240846b987d | 7,741 | cpp | C++ | software/latency/src/latency/latency-app-continuous-walking.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 92 | 2016-01-14T21:03:50.000Z | 2021-12-01T17:57:46.000Z | software/latency/src/latency/latency-app-continuous-walking.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 62 | 2016-01-16T18:08:14.000Z | 2016-03-24T15:16:28.000Z | software/latency/src/latency/latency-app-continuous-walking.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 41 | 2016-01-14T21:26:58.000Z | 2022-03-28T03:10:39.000Z | #include <stdio.h>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <sys/time.h>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/bot_core.hpp"
#include "lcmtypes/drc/atlas_state_t.hpp"
#include "lcmtypes/drc/atlas_command_t.hpp"
#include "lcmtypes/drc/robot_state_t.hpp"
#include "lcmtypes/drc/utime_two_t.hpp"
#include "lcmtypes/drc/atlas_raw_imu_batch_t.hpp"
#include "lcmtypes/drc/double_array_t.hpp"
#include "lcmtypes/drc/map_request_t.hpp"
#include "lcmtypes/drc/map_image_t.hpp"
#include "lcmtypes/drc/foot_contact_estimate_t.hpp"
#include "lcmtypes/bot_core/pose_t.hpp"
#include "lcmtypes/bot_core/images_t.hpp"
#include "lcmtypes/mav_estimator.hpp"
#include <latency/latency.hpp>
#include <ConciseArgs>
using namespace std;
class App
{
public:
App(boost::shared_ptr<lcm::LCM> &_lcm, int period_);
~App() {}
boost::shared_ptr<lcm::LCM> _lcm;
void handleAtlasStateMsg(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::atlas_state_t * msg);
void handleCamera(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t * msg);
void handleCameraFiltered(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t * msg);
void handleCameraFused(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t * msg);
void handleMapRequest(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::map_request_t * msg);
void handleMapDepth(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::map_image_t * msg);
void handleFootcontact(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::foot_contact_estimate_t * msg);
void handleFootstepPlanRequest(const lcm::ReceiveBuffer* rbuf, const std::string& chan);
void handleFootstepPlan(const lcm::ReceiveBuffer* rbuf, const std::string& chan);
int period_;
private:
std::vector<Latency*> lats_;
std::vector <float> lat_time_;
std::vector <float> lat_msgs_;
int counter_;
bool measure_gpf_;
};
App::App(boost::shared_ptr<lcm::LCM> &_lcm, int period_):
_lcm(_lcm),period_(period_){
Latency* a_lat0 = new Latency(period_);
lats_.push_back(a_lat0) ; //
Latency* a_lat1 = new Latency(period_);
lats_.push_back(a_lat1) ;
Latency* a_lat2 = new Latency(period_);
lats_.push_back(a_lat2) ;
Latency* a_lat3 = new Latency(period_);
lats_.push_back(a_lat3) ;
lat_time_ = {0.0, 0.0, 0.0, 0.0};
lat_msgs_ = {0.0, 0.0, 0.0, 0.0};
_lcm->subscribe("ATLAS_STATE", &App::handleAtlasStateMsg, this);
_lcm->subscribe("CAMERA", &App::handleCamera, this);
_lcm->subscribe("CAMERA_FILTERED", &App::handleCameraFiltered, this);
_lcm->subscribe("CAMERA_FUSED", &App::handleCameraFused, this);
_lcm->subscribe("MAP_DEPTH", &App::handleMapDepth, this);
_lcm->subscribe("MAP_REQUEST", &App::handleMapRequest, this);
_lcm->subscribe("FOOT_CONTACT_ESTIMATE_SLOW", &App::handleFootcontact, this);
_lcm->subscribe("FOOTSTEP_PLAN_REQUEST", &App::handleFootstepPlanRequest, this);
_lcm->subscribe("FOOTSTEP_PLAN_RESPONSE", &App::handleFootstepPlan, this);
counter_=0;
}
// same as bot_timestamp_now():
int64_t _timestamp_now(){
struct timeval tv;
gettimeofday (&tv, NULL);
return (int64_t) tv.tv_sec * 1000000 + tv.tv_usec;
}
int64_t atlas_utime_msg;
int temp_counter=0;
void App::handleAtlasStateMsg(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::atlas_state_t * msg){
int64_t utime_now = _timestamp_now();
lats_[0]->add_from(msg->utime, utime_now);
// std::cout << temp_counter << " " << msg->utime << "\n";
temp_counter++;
atlas_utime_msg = msg->utime;
}
void App::handleCamera(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const bot_core::images_t * msg){
// std::cout << (atlas_utime_msg - msg->utime)*1E-3 << " atlas to camera msg latency\n";
// temp_counter=0;
// std::cout << " c "<< msg->utime<< "\n";
lats_[1]->add_from(msg->utime, atlas_utime_msg );
bool new_data = lats_[0]->add_to(msg->utime, atlas_utime_msg, "SYNC", lat_time_[0], lat_msgs_[0] );
if (new_data){
if (counter_% 10==0){
std::cout << "AST-ERS | CAM-FIL | CAM-FUS | REQ-MAP "
<< " || "
<< "AST-ERS | CAM-FIL | CAM-FUS | REQ-MAP \n";// <msec|msg>\n";
}
std::cout.precision(5);
std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout << lat_time_[0] << " | " << lat_time_[1] << " | " << lat_time_[2] << " | " << lat_time_[3]
<< " || "
<< lat_msgs_[0] << " | " << lat_msgs_[1] << " | " << lat_msgs_[2] << " | " << lat_msgs_[3] << "\n";
drc::double_array_t msgout;
msgout.utime = atlas_utime_msg;
msgout.num_values = 2;
msgout.values = { lat_time_[0], lat_time_[1]};
_lcm->publish( ("LATENCY") , &msgout);
counter_++;
}
}
void App::handleCameraFiltered(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t * msg) {
lats_[1]->add_to(msg->utime, atlas_utime_msg, "FILT" , lat_time_[1], lat_msgs_[1]);
lats_[2]->add_from(msg->utime, atlas_utime_msg );
// std::cout << " f "<< msg->utime<< "\n";
}
void App::handleCameraFused(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::images_t * msg) {
lats_[2]->add_to(msg->utime, atlas_utime_msg, "FUSE" , lat_time_[2], lat_msgs_[2]);
std::cout << temp_counter << " k "<< msg->utime<< "\n";
}
int64_t map_request_utime_now;
void App::handleMapRequest(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::map_request_t * msg){
map_request_utime_now = _timestamp_now();
}
void App::handleMapDepth(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::map_image_t * msg){
double dtime = (_timestamp_now() - map_request_utime_now)*1E-3 ;
// std::cout << dtime <<" map server delay\n"; // neglibible delay
}
int64_t contact_change_utime_now;
float last_left_contact = 0;
float last_right_contact = 0;
void App::handleFootcontact(const lcm::ReceiveBuffer* rbuf, const std::string& chan, const drc::foot_contact_estimate_t * msg){
if (last_left_contact != msg->left_contact){
//std::cout << "left change\n";
contact_change_utime_now = _timestamp_now();
}
if (last_right_contact != msg->right_contact){
//std::cout << "right change\n";
contact_change_utime_now = _timestamp_now();
}
last_left_contact = msg->left_contact;
last_right_contact = msg->right_contact;
}
int64_t footstep_request_utime_now;
void App::handleFootstepPlanRequest(const lcm::ReceiveBuffer* rbuf, const std::string& chan){
footstep_request_utime_now = _timestamp_now();
double dtime = (_timestamp_now() - contact_change_utime_now)*1E-3 ;
//std::cout << " " << dtime <<" segmentation planner delay\n";
}
void App::handleFootstepPlan(const lcm::ReceiveBuffer* rbuf, const std::string& chan){
double dtime = (_timestamp_now() - footstep_request_utime_now)*1E-3 ;
//std::cout << dtime <<" footstep planner delay\n";
}
int main (int argc, char ** argv){
std::cout << "0: ATLAS_STATE <-> EST_ROBOT_STATE\n";
std::cout << "1: ATLAS_IMU_BATCH <-> POSE_BODY\n";
ConciseArgs parser(argc, argv, "latency-app");
int period=200;
parser.add(period, "p", "period", "Counting Period in samples");
parser.parse();
cout << "period is: " << period << " samples\n";
boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
if(!lcm->good())
return 1;
App app(lcm, period);
cout << "App ready"<< endl;
while(0 == lcm->handle());
return 0;
}
| 34.404444 | 127 | 0.674202 | [
"vector"
] |
80a41c12755434ba815e75142f67217acf48b1ec | 716 | cpp | C++ | Examples/src/standard_depths_tests.cpp | zzawadz/DepthLib | b7a4e847624f4bff407b8ab3a7acc08445692470 | [
"MIT"
] | 1 | 2015-03-01T20:07:34.000Z | 2015-03-01T20:07:34.000Z | Examples/src/standard_depths_tests.cpp | zzawadz/DepthLib | b7a4e847624f4bff407b8ab3a7acc08445692470 | [
"MIT"
] | null | null | null | Examples/src/standard_depths_tests.cpp | zzawadz/DepthLib | b7a4e847624f4bff407b8ab3a7acc08445692470 | [
"MIT"
] | null | null | null | /*
* standard_depths_test.cpp
*
* Created on: March 2, 2015
* Author: zzawadz
*/
#include <iostream>
#include "DepthLib.hpp"
#include "../Utils/Utils.hpp"
int main()
{
arma::colvec x = arma::linspace(1.0, 10.0,10);
arma::colvec y = arma::linspace(1.0, 10.0,10);
std::cout << Depth::TukeyUtils::tukey_depth1d(x,y) << std::endl;
arma::mat xMat(10,2);
xMat.randn();
Depth::ProjectionDepth projDepth;
projDepth.calculate_depth(xMat, xMat);
//arma::colvec big(10000000);
//big.randn();
//std::cout << "Depth calculation for vector of size 1000000 took "
//<< measure<>::execution( [&]() { Depth::TukeyUtils::tukey_depth1d(big, big); }) << " microseconds. " << std::endl;
return 0;
} | 21.69697 | 118 | 0.638268 | [
"vector"
] |
80a69087286404e12d99aa5211eaaae2130d30c8 | 14,418 | cpp | C++ | src/HumdrumFileStream.cpp | humdrum-tools/minHumdrum | 1f1e6a1281b40a6d6c9fed6666d96221cd619dc0 | [
"BSD-2-Clause"
] | null | null | null | src/HumdrumFileStream.cpp | humdrum-tools/minHumdrum | 1f1e6a1281b40a6d6c9fed6666d96221cd619dc0 | [
"BSD-2-Clause"
] | null | null | null | src/HumdrumFileStream.cpp | humdrum-tools/minHumdrum | 1f1e6a1281b40a6d6c9fed6666d96221cd619dc0 | [
"BSD-2-Clause"
] | null | null | null | //
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Tue Dec 11 16:09:32 PST 2012
// Last Modified: Tue Dec 11 16:09:38 PST 2012
// Last Modified: Fri Mar 11 21:26:18 PST 2016 Changed to STL
// Last Modified: Fri Dec 2 19:25:41 PST 2016 Moved to humlib
// Filename: HumdrumFileStream.cpp
// URL: https://github.com/craigsapp/humlib/blob/master/src/HumdrumFileStream.cpp
// Syntax: C++11; humlib
// vim: syntax=cpp ts=3 noexpandtab nowrap
//
// Description: Higher-level functions for processing Humdrum files.
// Inherits HumdrumFileStreamBasic and adds rhythmic and other
// types of analyses to the HumdrumFileStream class.
//
#include "HumdrumFileStream.h"
#include "HumdrumFileSet.h"
#include "HumRegex.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
namespace hum {
// START_MERGE
//////////////////////////////
//
// HumdrumFileStream::HumdrumFileStream --
//
HumdrumFileStream::HumdrumFileStream(void) {
m_curfile = -1;
}
HumdrumFileStream::HumdrumFileStream(char** list) {
m_curfile = -1;
setFileList(list);
}
HumdrumFileStream::HumdrumFileStream(const vector<string>& list) {
m_curfile = -1;
setFileList(list);
}
HumdrumFileStream::HumdrumFileStream(Options& options) {
m_curfile = -1;
vector<string> list;
options.getArgList(list);
setFileList(list);
}
HumdrumFileStream::HumdrumFileStream(const string& datastring) {
m_curfile = -1;
m_stringbuffer << datastring;
}
//////////////////////////////
//
// HumdrumFileStream::clear -- reset the contents of the class.
//
void HumdrumFileStream::clear(void) {
m_curfile = 0;
m_filelist.resize(0);
m_universals.resize(0);
m_newfilebuffer.resize(0);
// m_stringbuffer.clear(0);
m_stringbuffer.str("");
}
//////////////////////////////
//
// HumdrumFileStream::setFileList --
//
int HumdrumFileStream::setFileList(char** list) {
m_filelist.reserve(1000);
m_filelist.resize(0);
int i = 0;
while (list[i] != NULL) {
m_filelist.push_back(list[i]);
i++;
}
return i;
}
int HumdrumFileStream::setFileList(const vector<string>& list) {
m_filelist = list;
return (int)list.size();
}
//////////////////////////////
//
// HumdrumFileStream::loadString --
//
void HumdrumFileStream::loadString(const string& data) {
m_curfile = -1;
m_stringbuffer << data;
}
//////////////////////////////
//
// HumdrumFileStream::read -- alias for getFile.
//
int HumdrumFileStream::read(HumdrumFile& infile) {
return getFile(infile);
}
int HumdrumFileStream::read(HumdrumFileSet& infiles) {
infiles.clear();
HumdrumFile* infile = new HumdrumFile;
while (getFile(*infile)) {
infiles.appendHumdrumPointer(infile);
infile = new HumdrumFile;
}
delete infile;
return 0;
}
//////////////////////////////
//
// HumdrumFileStream::readSingleSegment -- Get a single file for a set structure.
//
int HumdrumFileStream::readSingleSegment(HumdrumFileSet& infiles) {
infiles.clear();
HumdrumFile* infile = new HumdrumFile;
int status = getFile(*infile);
if (!status) {
delete infile;
} else {
infiles.appendHumdrumPointer(infile);
}
return status;
}
//////////////////////////////
//
// HumdrumFileStream::eof -- returns true if there is no more segements
// to read from the input source(s).
//
int HumdrumFileStream::eof(void) {
istream* newinput = NULL;
// Read HumdrumFile contents from:
// (1) Current ifstream if open
// (2) Next filename if ifstream is done
// (3) cin if no ifstream open and no filenames
// (1) Is an ifstream open?, then yes, there is more data to read.
if (m_instream.is_open() && !m_instream.eof()) {
return 0;
}
// (1b) Is the URL data buffer open?
else if (m_urlbuffer.str() != "") {
return 0;
}
// (2) If ifstream is closed but there is a file to be processed,
// load it into the ifstream and start processing it immediately.
else if ((m_filelist.size() > 0) && (m_curfile < (int)m_filelist.size()-1)) {
return 0;
} else {
// no input fstream open and no list of files to process, so
// start (or continue) reading from standard input.
if (m_curfile < 0) {
// but only read from cin if no files have previously been read
newinput = &cin;
}
if ((newinput != NULL) && newinput->eof()) {
return 1;
}
}
return 1;
}
//////////////////////////////
//
// HumdrumFileStream::getFile -- fills a HumdrumFile class with content
// from the input stream or next input file in the list. Returns
// true if content was extracted, fails if there is no more HumdrumFiles
// in the input stream.
//
int HumdrumFileStream::getFile(HumdrumFile& infile) {
infile.clear();
istream* newinput = NULL;
restarting:
newinput = NULL;
if (m_urlbuffer.eof()) {
// If the URL buffer is at its end, clear the buffer.
m_urlbuffer.str("");
}
// Read HumdrumFile contents from:
// (1) Read from string buffer
// (2) Current ifstream if open
// (3) Next filename if ifstream is done
// (4) cin if no ifstream open and no filenames
// (1) Is there content in the string buffer?
if (!m_stringbuffer.str().empty()) {
newinput = &m_stringbuffer;
}
// (2) Is an ifstream open?
else if (m_instream.is_open() && !m_instream.eof()) {
newinput = &m_instream;
}
// (2b) Is the URL data buffer open?
else if (m_urlbuffer.str() != "") {
m_urlbuffer.clear();
newinput = &m_urlbuffer;
}
// (3) If ifstream is closed but there is a file to be processed,
// load it into the ifstream and start processing it immediately.
else if (((int)m_filelist.size() > 0) &&
(m_curfile < (int)m_filelist.size()-1)) {
m_curfile++;
if (m_instream.is_open()) {
m_instream.close();
}
if (strstr(m_filelist[m_curfile].c_str(), "://") != NULL) {
// The next file to read is a URL/URI, so buffer the
// data from the internet and start reading that instead
// of reading from a file on the hard disk.
fillUrlBuffer(m_urlbuffer, m_filelist[m_curfile].c_str());
infile.setFilename(m_filelist[m_curfile].c_str());
goto restarting;
}
m_instream.open(m_filelist[m_curfile].c_str());
infile.setFilename(m_filelist[m_curfile].c_str());
if (!m_instream.is_open()) {
// file does not exist or cannot be opened close
// the file and try luck with next file in the list
// (perhaps given an error or warning?).
infile.setFilename("");
m_instream.close();
goto restarting;
}
newinput = &m_instream;
} else {
// no input fstream open and no list of files to process, so
// start (or continue) reading from standard input.
if (m_curfile < 0) {
// but only read from cin if no files have previously been read
newinput = &cin;
}
}
// At this point the newinput istream is set to read from the given
// file or from standard input, so start reading Humdrum content.
// If there is "m_newfilebuffer" content, then set the filename of the
// HumdrumFile to that value.
if (m_newfilebuffer.size() > 0) {
// store the filename for the current HumdrumFile being read:
HumRegex hre;
if (hre.search(m_newfilebuffer,
R"(^!!!!SEGMENT\s*([+-]?\d+)?\s*:\s*(.*)\s*$)")) {
if (hre.getMatchLength(1) > 0) {
infile.setSegmentLevel(atoi(hre.getMatch(1).c_str()));
} else {
infile.setSegmentLevel(0);
}
infile.setFilename(hre.getMatch(2));
} else if ((m_curfile >=0) && (m_curfile < (int)m_filelist.size())
&& (m_filelist.size() > 0)) {
infile.setFilename(m_filelist[m_curfile].c_str());
} else {
// reading from standard input, but no name.
}
}
if (newinput == NULL) {
// something strange happened, or no more files to read.
return 0;
}
stringstream buffer;
int foundUniversalQ = 0;
// Start reading the input stream. If !!!!SEGMENT: universal comment
// is found, then store that line in m_newfilebuffer and return the
// newly read HumdrumFile. If other universal comments are found, then
// overwrite the old universal comments here.
int addedFilename = 0;
//int searchName = 0;
int dataFoundQ = 0;
int starstarFoundQ = 0;
int starminusFoundQ = 0;
if (m_newfilebuffer.size() < 4) {
//searchName = 1;
}
char templine[123123] = {0};
if (newinput->eof()) {
if (m_curfile < (int)m_filelist.size()-1) {
m_curfile++;
goto restarting;
}
// input stream is close and there is no more files to process.
return 0;
}
istream& input = *newinput;
// if the previous line from the last read starts with "**"
// then treat it as part of the current file.
if ((m_newfilebuffer.size() > 1) &&
(strncmp(m_newfilebuffer.c_str(), "**", 2)) == 0) {
buffer << m_newfilebuffer << "\n";
m_newfilebuffer = "";
starstarFoundQ = 1;
}
while (!input.eof()) {
input.getline(templine, 123123, '\n');
if ((!dataFoundQ) &&
(strncmp(templine, "!!!!SEGMENT", strlen("!!!!SEGMENT")) == 0)) {
string tempstring;
tempstring = templine;
HumRegex hre;
if (hre.search(tempstring,
"^!!!!SEGMENT\\s*([+-]?\\d+)?\\s*:\\s*(.*)\\s*$")) {
if (hre.getMatchLength(1) > 0) {
infile.setSegmentLevel(atoi(hre.getMatch(1).c_str()));
} else {
infile.setSegmentLevel(0);
}
infile.setFilename(hre.getMatch(2));
}
}
if (strncmp(templine, "**", 2) == 0) {
if (starstarFoundQ == 1) {
m_newfilebuffer = templine;
// already found a **, so this one is defined as a file
// segment. Exit from the loop and process the previous
// content, waiting until the next read for to start with
// this line.
break;
}
starstarFoundQ = 1;
}
if (input.eof() && (strcmp(templine, "") == 0)) {
// No more data coming from current stream, so this is
// the end of the HumdrumFile. Break from the while loop
// and then store the read contents of the stream in the
// HumdrumFile.
break;
}
// (1) Does the line start with "!!!!SEGMENT"? If so, then
// this is either the name of the current or next file to process.
// (1a) this is the name of the current file to process if no
// data has yet been found,
// (1b) or a name is being actively searched for.
if (strncmp(templine, "!!!!SEGMENT", strlen("!!!!SEGMENT")) == 0) {
m_newfilebuffer = templine;
if (dataFoundQ) {
// this new filename is for the next chunk to process in the
// current file stream, not this one, so stop reading the
// HumdrumFile content and send what has already been read back
// out with new contents.
} else {
// !!!!SEGMENT: came before any real data was read, so
// it is most likely the name of the current file
// (i.e., it comes at the start of the file stream and
// is the name of the first HumdrumFile in the stream).
HumRegex hre;
if (hre.search(m_newfilebuffer,
R"(^!!!!SEGMENT\s*([+-]?\d+)?\s:\s*(.*)\s*$)")) {
if (hre.getMatchLength(1) > 0) {
infile.setSegmentLevel(atoi(hre.getMatch(1).c_str()));
} else {
infile.setSegmentLevel(0);
}
infile.setFilename(hre.getMatch(2));
}
}
}
int len = (int)strlen(templine);
if ((len > 4) && (strncmp(templine, "!!!!", 4) == 0) &&
(templine[4] != '!') &&
(dataFoundQ == 0) &&
(strncmp(templine, "!!!!filter:", strlen("!!!!filter:")) != 0) &&
(strncmp(templine, "!!!!SEGMENT:", strlen("!!!!SEGMENT:")) != 0)) {
// This is a universal comment. Should it be appended
// to the list or should the current list be erased and
// this record placed into the first entry?
if (foundUniversalQ) {
// already found a previous universal, so append.
m_universals.push_back(templine);
} else {
// new universal comment, to delete all previous
// universal comments and store this one.
m_universals.reserve(1000);
m_universals.resize(1);
m_universals[0] = templine;
foundUniversalQ = 1;
}
continue;
}
if (strncmp(templine, "*-", 2) == 0) {
starminusFoundQ = 1;
}
// if before first ** in a data file or after *-, and the line
// does not start with '!' or '*', then assume that it is a file
// name which should be added to the file list to read.
if (((starminusFoundQ == 1) || (starstarFoundQ == 0))
&& (templine[0] != '*') && (templine[0] != '!')) {
if ((templine[0] != '\0') && (templine[0] != ' ')) {
// The file can only be added once in this manner
// so that infinite loops are prevented.
int found = 0;
for (int mm=0; mm<(int)m_filelist.size(); mm++) {
if (strcmp(m_filelist[mm].c_str(), templine) == 0) {
found = 1;
}
}
if (!found) {
m_filelist.push_back(templine);
addedFilename = 1;
}
continue;
}
}
dataFoundQ = 1; // found something other than universal comments
// should empty lines be treated somewhat as universal comments?
// store the data line for later parsing into HumdrumFile record:
buffer << templine << "\n";
}
if (dataFoundQ == 0) {
// never found anything for some strange reason.
if (addedFilename) {
goto restarting;
}
return 0;
}
// Arriving here means that reading of the data stream is complete.
// The string stream variable "buffer" contains the HumdrumFile
// content, so send it to the HumdrumFile variable. Also, prepend
// Universal comments (demoted into Global comments) at the start
// of the data stream (maybe allow for postpending Universal comments
// in the future).
stringstream contents;
contents.str(""); // empty any contents in buffer
contents.clear(); // reset error flags in buffer
for (int i=0; i<(int)m_universals.size(); i++) {
// Convert universals reference records to globals, but do not demote !!!!filter:
if (m_universals[i].compare(0, 11, "!!!!filter:") == 0) {
continue;
}
contents << &(m_universals[i][1]) << "\n";
}
contents << buffer.str();
string filename = infile.getFilename();
infile.readNoRhythm(contents);
if (!filename.empty()) {
infile.setFilename(filename);
}
return 1;
}
//////////////////////////////
//
// HumdrumFileStream::fillUrlBuffer --
//
void HumdrumFileStream::fillUrlBuffer(stringstream& uribuffer,
const string& uriname) {
#ifdef USING_URI
uribuffer.str(""); // empty any contents in buffer
uribuffer.clear(); // reset error flags in buffer
string webaddress = HumdrumFileBase::getUriToUrlMapping(uriname);
HumdrumFileBase::readStringFromHttpUri(uribuffer, webaddress);
#endif
}
// END_MERGE
} // end namespace hum
| 27.050657 | 91 | 0.645582 | [
"vector"
] |
80a7f526880a2df1d13c63a71acaaf51f0cbdeb6 | 2,567 | cc | C++ | source/neuropod/backends/tensorflow/tf_utils.cc | vishalbelsare/neuropod | 9dd2ca81e0fbf0b24fc461e426fc4b5b0925aa9f | [
"Apache-2.0"
] | 887 | 2020-06-08T16:10:28.000Z | 2022-03-27T21:55:43.000Z | source/neuropod/backends/tensorflow/tf_utils.cc | vishalbelsare/neuropod | 9dd2ca81e0fbf0b24fc461e426fc4b5b0925aa9f | [
"Apache-2.0"
] | 150 | 2020-06-09T10:43:15.000Z | 2022-03-30T02:48:39.000Z | source/neuropod/backends/tensorflow/tf_utils.cc | vishalbelsare/neuropod | 9dd2ca81e0fbf0b24fc461e426fc4b5b0925aa9f | [
"Apache-2.0"
] | 70 | 2020-06-08T18:43:12.000Z | 2022-03-18T20:37:51.000Z | /* Copyright (c) 2021 UATC, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "neuropod/backends/tensorflow/tf_utils.hh"
#include "neuropod/internal/error_utils.hh"
#include "neuropod/internal/logging.hh"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/public/session.h"
namespace neuropod
{
// Utility to move a TF graph to a specific device
void move_graph_to_device(tensorflow::GraphDef &graph, tensorflow::Session &session, const NeuropodDevice target)
{
// Figure out the correct target device
std::string target_device = "/device:CPU:0";
if (target != Device::CPU)
{
// Get all the available devices
std::vector<tensorflow::DeviceAttributes> devices;
check_tf_status(session.ListDevices(&devices));
// Check if we have any GPUs
bool found_gpu = std::any_of(devices.begin(), devices.end(), [](const tensorflow::DeviceAttributes &device) {
return device.device_type() == "GPU";
});
// If we have a GPU, update the target device
if (found_gpu)
{
target_device = std::string("/device:GPU:") + std::to_string(target);
}
}
// Iterate through all the nodes in the graph and move them to the target device
for (auto &node : *graph.mutable_node())
{
const auto &node_device = node.device();
// If a node is on CPU, leave it there
if (node_device != "/device:CPU:0" && node_device != target_device)
{
SPDLOG_TRACE("TF: Moving node {} from device {} to device {}", node.name(), node_device, target_device);
node.set_device(target_device);
}
else
{
SPDLOG_TRACE("TF: Leaving node {} on device {}", node.name(), node_device);
}
}
}
// Throws an error if `status` is not ok
void check_tf_status(const tensorflow::Status &status)
{
if (!status.ok())
{
NEUROPOD_ERROR("TensorFlow error: {}", status.error_message());
}
}
} // namespace neuropod
| 32.910256 | 117 | 0.667705 | [
"vector"
] |
80adc399f241028c9854ecfbaba09fda7ccd4efa | 1,402 | cc | C++ | chrome/browser/protector/protector_utils.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/browser/protector/protector_utils.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/browser/protector/protector_utils.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/protector/protector_utils.h"
#include <vector>
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/protector/keys.h"
#include "chrome/common/chrome_switches.h"
#include "crypto/hmac.h"
namespace protector {
std::string SignSetting(const std::string& value) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(kProtectorSigningKey)) {
LOG(WARNING) << "Failed to initialize HMAC algorithm for signing";
return std::string();
}
std::vector<unsigned char> digest(hmac.DigestLength());
if (!hmac.Sign(value, &digest[0], digest.size())) {
LOG(WARNING) << "Failed to sign setting";
return std::string();
}
return std::string(&digest[0], &digest[0] + digest.size());
}
bool IsSettingValid(const std::string& value, const std::string& signature) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(kProtectorSigningKey)) {
LOG(WARNING) << "Failed to initialize HMAC algorithm for verification.";
return false;
}
return hmac.Verify(value, signature);
}
bool IsEnabled() {
return CommandLine::ForCurrentProcess()->HasSwitch(switches::kProtector);
}
} // namespace protector
| 29.208333 | 77 | 0.713267 | [
"vector"
] |
80add50746f7c8ad65d735e481a46c33737cc581 | 2,172 | cpp | C++ | ros/src/airsim_car_ros_pkgs/nodes/odometer.cpp | danthony06/AirSim | b8f0ec63536baf83bb4d4bc00671c05fc4a278f4 | [
"MIT"
] | 7 | 2020-05-22T18:00:19.000Z | 2021-01-07T08:31:19.000Z | ros/src/airsim_car_ros_pkgs/nodes/odometer.cpp | danthony06/AirSim | b8f0ec63536baf83bb4d4bc00671c05fc4a278f4 | [
"MIT"
] | null | null | null | ros/src/airsim_car_ros_pkgs/nodes/odometer.cpp | danthony06/AirSim | b8f0ec63536baf83bb4d4bc00671c05fc4a278f4 | [
"MIT"
] | 7 | 2020-05-22T20:08:22.000Z | 2021-01-22T09:39:17.000Z | #include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <tf/tf.h>
#include <geometry_msgs/TransformStamped.h>
#include <sensor_msgs/Imu.h>
#include <nav_msgs/Odometry.h>
int main(int argc, char** argv){
ros::init(argc, argv, "odometry_publisher");
double th = 0.0;
ros::Time last = ros::Time(0);
ros::NodeHandle n;
ros::NodeHandle pnh("~");
std::string vehicle_frame;
pnh.param<std::string>("vehicle_frame", vehicle_frame, "base_link");
ros::Subscriber imu_sub = n.subscribe<sensor_msgs::Imu>("imu_in", 10, [&](const sensor_msgs::ImuConstPtr& msg)
{
if (last == ros::Time(0))
{
last = ros::Time::now();
}
th -= (ros::Time::now()-last).toSec()*msg->angular_velocity.z;
last = ros::Time::now();
});
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom", 50);
double x = 0.0;
double y = 0.0;
ros::Time last_time = ros::Time::now();
tf2_ros::TransformBroadcaster odom_broadcaster;
ros::Subscriber odom_sub = n.subscribe<nav_msgs::Odometry>("odom_in", 10, [&](const nav_msgs::OdometryConstPtr& msg)
{
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = msg->header.stamp;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = vehicle_frame;
double dt = (msg->header.stamp - last_time).toSec();
double vx = msg->twist.twist.linear.x;
double vy = 0.0;
double delta_x = (vx * cos(th) - vy * sin(th)) * dt;
double delta_y = (vx * sin(th) + vy * cos(th)) * dt;
last_time = msg->header.stamp;
x += delta_x;
y += delta_y;
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = msg->pose.pose.position.z;
odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(th);
nav_msgs::Odometry odom = *msg;
odom.header.frame_id = "odom";
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.orientation = odom_trans.transform.rotation;
odom_pub.publish(odom);
//send the transform
odom_broadcaster.sendTransform(odom_trans);
});
while(n.ok()){
ros::spinOnce();
}
}
| 30.591549 | 118 | 0.662523 | [
"transform"
] |
01f51ebebc0e4a7c2dd0e7f2330bb50e7a477332 | 9,501 | cpp | C++ | gunns-ts-models/common/controllers/valveAssemblies/TsOpenCloseValveAssembly.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | gunns-ts-models/common/controllers/valveAssemblies/TsOpenCloseValveAssembly.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | gunns-ts-models/common/controllers/valveAssemblies/TsOpenCloseValveAssembly.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /**
@file
@brief Open/Close Valve Assembly Model implementation.
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
LIBRARY DEPENDENCY:
((common/sensors/SensorBooleanAi.o)
(common/controllers/fluid/TsOpenCloseValveController.o))
*/
#include "TsOpenCloseValveAssembly.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] controller (--) Valve controller config data.
/// @param[in] sensorOpen (--) Open sensor config data.
/// @param[in] sensorClosed (--) Closed sensor config data.
///
/// @details Default constructs this Open/Close Valve Assembly configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyConfigData::TsOpenCloseValveAssemblyConfigData(
const TsPoweredValveControllerConfigData& controller,
const SensorBooleanAiConfigData& sensorOpen,
const SensorBooleanAiConfigData& sensorClosed)
:
mController (controller),
mSensorOpen (sensorOpen),
mSensorClosed(sensorClosed)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Open/Close Valve Assembly configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyConfigData::~TsOpenCloseValveAssemblyConfigData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source to copy.
///
/// @details Copy constructs this Open/Close Valve Assembly configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyConfigData::TsOpenCloseValveAssemblyConfigData(
const TsOpenCloseValveAssemblyConfigData& that)
:
mController (that.mController),
mSensorOpen (that.mSensorOpen),
mSensorClosed(that.mSensorClosed)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object assigned from.
///
/// @return TsOpenCloseValveAssemblyConfigData& (--) Object assigned to.
///
/// @details Assignment operator for this Open/Close Valve Assembly configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyConfigData& TsOpenCloseValveAssemblyConfigData::operator=(
const TsOpenCloseValveAssemblyConfigData& that)
{
if (this != &that) {
mController = that.mController;
mSensorOpen = that.mSensorOpen;
mSensorClosed = that.mSensorClosed;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] controller (--) Valve controller input data.
/// @param[in] sensorOpen (--) Open sensor input data.
/// @param[in] sensorClosed (--) Closed sensor input data.
///
/// @details Default constructs this Open/Close Valve Assembly input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyInputData::TsOpenCloseValveAssemblyInputData(
const TsPoweredValveControllerInputData& controller,
const SensorBooleanAiInputData& sensorOpen,
const SensorBooleanAiInputData& sensorClosed)
:
mController (controller),
mSensorOpen (sensorOpen),
mSensorClosed(sensorClosed)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Open/Close Valve Assembly input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyInputData::~TsOpenCloseValveAssemblyInputData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source to copy.
///
/// @details Copy constructs this Open/Close Valve Assembly input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyInputData::TsOpenCloseValveAssemblyInputData(
const TsOpenCloseValveAssemblyInputData& that)
:
mController (that.mController),
mSensorOpen (that.mSensorOpen),
mSensorClosed(that.mSensorClosed)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object assigned from.
///
/// @return TsPoweredValveControllerInputData& (--) Object assigned to.
///
/// @details Assignment operator for this Open/Close Valve Assembly input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssemblyInputData& TsOpenCloseValveAssemblyInputData::operator=(
const TsOpenCloseValveAssemblyInputData& that)
{
if (this != &that) {
mController = that.mController;
mSensorOpen = that.mSensorOpen;
mSensorClosed = that.mSensorClosed;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default constructs this Open/Close Valve Assembly model.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssembly::TsOpenCloseValveAssembly()
:
mController(),
mSensorOpen(),
mSensorClosed(),
mInitialized(false)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Open/Close Valve Assembly model.
////////////////////////////////////////////////////////////////////////////////////////////////////
TsOpenCloseValveAssembly::~TsOpenCloseValveAssembly()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Configuration data.
/// @param[in] inputData (--) Input data.
/// @param[in] name (--) Object name.
///
/// @return void
///
/// @throws TsInitializationException
///
/// @details Initializes this Open/Close Valve Assembly model with configuration and input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsOpenCloseValveAssembly::initialize(const TsOpenCloseValveAssemblyConfigData& configData,
const TsOpenCloseValveAssemblyInputData& inputData,
const std::string& name)
{
/// - Reset the initialization complete flag.
mInitialized = false;
/// - Initialize controller and sensors with config & input data.
mController .initialize(configData.mController, inputData.mController, name + ".mController");
mSensorOpen .initialize(configData.mSensorOpen, inputData.mSensorOpen, name + ".mSensorOpen");
mSensorClosed.initialize(configData.mSensorClosed, inputData.mSensorClosed, name + ".mSensorClosed");
/// - Initialize remaining state data.
mInitialized = mController .isInitialized() and
mSensorOpen .isInitialized() and
mSensorClosed.isInitialized();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Execution time step
///
/// @return void
///
/// @details Updates the sensors and controller.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsOpenCloseValveAssembly::update(const double dt)
{
/// - Update controller.
mController.update(dt);
/// - Update sensors. Sensors are assumed powered by their telemetry card so are effectively
/// always on.
mController.setOpenSensed (mSensorOpen .sense(dt, true, mController.getPosition()));
mController.setCloseSensed(mSensorClosed.sense(dt, true, mController.getPosition()));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] supplyVoltageFlag (--) Power flag.
/// @param[in] command (--) Valve open/close command.
/// @param[in] dt (s) Time step.
///
/// @return void
///
/// @details Updates the sensors and controller with arguments, so it can be run from a container.
////////////////////////////////////////////////////////////////////////////////////////////////////
void TsOpenCloseValveAssembly::update(const bool supplyVoltageFlag,
const TsOpenCloseValveCmd& command,
const double dt)
{
/// - Set supply voltage flag and command.
mController.setSupplyVoltageFlag(supplyVoltageFlag);
mController.setCommand(command);
/// - Update the sensors and controller.
update(dt);
}
| 42.605381 | 105 | 0.495211 | [
"object",
"model"
] |
01f5f3cdf699b98b71b835b92537ac65aa742d85 | 23,768 | cpp | C++ | admin/snapin/dfsadmin/dfsshlex/dfsshprp.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/snapin/dfsadmin/dfsshlex/dfsshprp.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/snapin/dfsadmin/dfsshlex/dfsshprp.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
DfsShPrp.cpp
Abstract:
This module contains the implementation for CDfsShellExtProp
This is used to implement the property page for Shell Extension.
Author:
Constancio Fernandes (ferns@qspl.stpp.soft.net) 12-Jan-1998
Environment:
Revision History:
--*/
#include "stdafx.h"
#include "resource.h"
#include "DfsShlEx.h"
#include "DfsPath.h"
#include "DfsShPrp.h"
#include "DfsShell.h"
#include <lmcons.h>
#include <lmerr.h>
#include <lmdfs.h>
#include "dfshelp.h"
CDfsShellExtProp::CDfsShellExtProp():CQWizardPageImpl<CDfsShellExtProp>(false)
/*++
Routine Description:
Ctor of CDfsShellExtProp.
Calls the ctor of it's parent
--*/
{
m_pIShProp = NULL;
LoadStringFromResource(IDS_ALTERNATE_LIST_PATH, &m_bstrAlternateListPath);
LoadStringFromResource(IDS_ALTERNATE_LIST_ACTIVE, &m_bstrAlternateListActive);
LoadStringFromResource(IDS_ALTERNATE_LIST_STATUS, &m_bstrAlternateListStatus);
LoadStringFromResource(IDS_ALTERNATE_LIST_YES, &m_bstrAlternateListYes);
LoadStringFromResource(IDS_ALTERNATE_LIST_NO, &m_bstrAlternateListNo);
LoadStringFromResource(IDS_ALTERNATE_LIST_OK, &m_bstrAlternateListOK);
LoadStringFromResource(IDS_ALTERNATE_LIST_UNREACHABLE, &m_bstrAlternateListUnreachable);
}
CDfsShellExtProp::~CDfsShellExtProp(
)
/*++
Routine Description:
dtor of CDfsShellExtProp.
Free the notify handle.
--*/
{
/* ImageList_Destroy already called by the desctructor of list control
if (NULL != m_hImageList)
ImageList_Destroy(m_hImageList);
*/
}
LRESULT
CDfsShellExtProp::OnInitDialog(
IN UINT i_uMsg,
IN WPARAM i_wParam,
LPARAM i_lParam,
IN OUT BOOL& io_bHandled
)
/*++
Routine Description:
Called at the start. Used to set dialog defaults
--*/
{
SetDlgItemText(IDC_DIR_PATH, m_bstrDirPath);
_SetImageList();
_SetAlternateList();
return TRUE;
}
HRESULT
CDfsShellExtProp::put_DfsShellPtr(
IN IShellPropSheetExt* i_pDfsShell
)
/*++
Routine Description:
Called at the start by CDfsShell. Used to set a back pointer to CDfsShell object to call Release().
--*/
{
if (!i_pDfsShell)
return(E_INVALIDARG);
if (m_pIShProp)
m_pIShProp->Release();
m_pIShProp = i_pDfsShell;
m_pIShProp->AddRef();
return(S_OK);
}
HRESULT
CDfsShellExtProp::put_DirPaths(
IN BSTR i_bstrDirPath,
IN BSTR i_bstrEntryPath
)
/*++
Routine Description:
Set the value of Directory Path for this directory. and the largest entrypath.
Arguments:
i_bstrDirPath - Contains the new value for Entry Path
i_bstrEntryPath - The largest Dfs entry path that matches this directory.
--*/
{
if (!i_bstrDirPath)
return(E_INVALIDARG);
m_bstrDirPath = i_bstrDirPath;
m_bstrEntryPath = i_bstrEntryPath;
if (!m_bstrDirPath || !i_bstrEntryPath)
return(E_OUTOFMEMORY);
return S_OK;
}
LRESULT
CDfsShellExtProp::OnApply(
)
{
return TRUE;
}
LRESULT
CDfsShellExtProp::OnParentClosing(
IN UINT i_uMsg,
IN WPARAM i_wParam,
LPARAM i_lParam,
IN OUT BOOL& io_bHandled
)
/*++
Routine Description:
Used by the node to tell the propery page to close.
--*/
{
return TRUE;
}
void
CDfsShellExtProp::Delete()
/*++
Routine Description:
Called when property sheet is release to do clean up.
*/
{
if (m_pIShProp)
m_pIShProp->Release();
}
LRESULT
CDfsShellExtProp::OnFlushPKT(
IN WORD i_wNotifyCode,
IN WORD i_wID,
IN HWND i_hWndCtl,
IN OUT BOOL& io_bHandled
)
/*++
Routine Description:
Called when Flush PKT table is called.
Flushes client PKT table.
*/
{
if (!m_bstrEntryPath)
return(E_FAIL);
NET_API_STATUS nstatRetVal = 0;
DFS_INFO_102 DfsInfoLevel102;
// Set timeout = 0 to flush local PKT.
DfsInfoLevel102.Timeout = 0;
// Display hour glass.
CWaitCursor WaitCursor;
nstatRetVal = NetDfsSetClientInfo(
m_bstrEntryPath,
NULL,
NULL,
102,
(LPBYTE) &DfsInfoLevel102
);
if (nstatRetVal != NERR_Success)
DisplayMessageBoxForHR(HRESULT_FROM_WIN32(nstatRetVal));
return(true);
}
void
CDfsShellExtProp::_UpdateTextForReplicaState(
IN HWND hwndControl,
IN int nIndex,
IN enum SHL_DFS_REPLICA_STATE ReplicaState
)
{
LVITEM lvi = {0};
lvi.iItem = nIndex;
lvi.mask = LVIF_TEXT;
// insert the 2nd column "Active"
lvi.iSubItem = 1;
if (ReplicaState == SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN ||
ReplicaState == SHL_DFS_REPLICA_STATE_ACTIVE_OK ||
ReplicaState == SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE )
lvi.pszText = m_bstrAlternateListYes;
else
lvi.pszText = m_bstrAlternateListNo;
ListView_SetItem(hwndControl, &lvi);
// insert the 3rd column "Status"
lvi.iSubItem = 2;
switch (ReplicaState)
{
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_UNKNOWN:
lvi.pszText = _T("");
break;
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
case SHL_DFS_REPLICA_STATE_OK:
lvi.pszText = m_bstrAlternateListOK;
break;
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
lvi.pszText = m_bstrAlternateListUnreachable;
break;
}
ListView_SetItem(hwndControl, &lvi);
}
void
CDfsShellExtProp::_SetAlternateList()
/*++
Routine Description:
Finds out if the given path is a Dfs Path, and if it is
then finds out the alternates available for this path up to
the last directory. These are then added to the alternate list.
*/
{
HWND hwndControl = ::GetDlgItem(m_hWnd, IDC_ALTERNATE_LIST);
if (NULL == ((CDfsShell *)m_pIShProp)->m_ppDfsAlternates)
return;
//
// calculate the listview column width
//
RECT rect;
ZeroMemory(&rect, sizeof(rect));
::GetWindowRect(hwndControl, &rect);
int nControlWidth = rect.right - rect.left;
int nVScrollbarWidth = GetSystemMetrics(SM_CXVSCROLL);
int nBorderWidth = GetSystemMetrics(SM_CXBORDER);
int nControlNetWidth = nControlWidth - nVScrollbarWidth - 4 * nBorderWidth;
int nWidth1 = nControlNetWidth / 2;
int nWidth2 = nControlNetWidth / 4;
int nWidth3 = nControlNetWidth - nWidth1 - nWidth2;
//
// insert columns
//
LV_COLUMN col;
ZeroMemory(&col, sizeof(col));
col.mask = LVCF_TEXT | LVCF_WIDTH;
col.cx = nWidth1;
col.pszText = m_bstrAlternateListPath;
ListView_InsertColumn(hwndControl, 0, &col);
col.cx = nWidth2;
col.pszText = m_bstrAlternateListActive;
ListView_InsertColumn(hwndControl, 1, &col);
col.cx = nWidth3;
col.pszText = m_bstrAlternateListStatus;
ListView_InsertColumn(hwndControl, 2, &col);
//
// Set full row selection style
//
ListView_SetExtendedListViewStyleEx(hwndControl, LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);
// For each alternate stored in the parent shell object
// add to list.
for (int i = 0; NULL != ((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i] ; i++)
{
int nIndex = 0;
LVITEM lvi = {0};
lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
lvi.pszText = (((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i])->bstrAlternatePath;
lvi.iImage = (((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i])->ReplicaState;
lvi.lParam = (LPARAM)(((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i]);
lvi.iSubItem = 0;
// Select the active replica.
switch ((((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i])->ReplicaState)
{
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
lvi.mask |= LVIF_STATE;
lvi.state = LVIS_SELECTED | LVIS_FOCUSED;
nIndex = ListView_InsertItem(hwndControl, &lvi);
break;
case SHL_DFS_REPLICA_STATE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_OK:
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
nIndex = ListView_InsertItem(hwndControl, &lvi);
break;
default:
_ASSERT(FALSE);
break;
}
_UpdateTextForReplicaState(hwndControl, nIndex, (((CDfsShell *)m_pIShProp)->m_ppDfsAlternates[i])->ReplicaState);
}
}
HRESULT
CDfsShellExtProp::_SetImageList(
)
/*++
Routine Description:
Create and initialize the Imagelist for alternates.
--*/
{
// Load bitmap from resource
HBITMAP hBitmap = (HBITMAP)LoadImage(_Module.GetModuleInstance(), MAKEINTRESOURCE(IDB_Replica),
IMAGE_BITMAP, 0, 0, LR_SHARED | LR_LOADTRANSPARENT);
if(!hBitmap)
return HRESULT_FROM_WIN32(GetLastError());;
// Try and get the exact bitmap size and number of bitmaps for
// image list
int icxBitmap = 16;
int icyBitmap = 16;
int iNoOfBitmaps = 6;
BITMAP bmpRec;
if (GetObject(hBitmap, sizeof(bmpRec), &bmpRec))
{
if (bmpRec.bmHeight > 0)
{
icyBitmap = bmpRec.bmHeight;
// Since the bitmaps are squares
icxBitmap = icyBitmap;
// Since all the bitmaps are in a line in the original bitmap
iNoOfBitmaps = bmpRec.bmWidth / bmpRec.bmHeight;
}
}
// Create the image list
HIMAGELIST hImageList = ImageList_Create(icxBitmap, icyBitmap, ILC_COLOR, iNoOfBitmaps, 0);
if (NULL == hImageList)
{
DeleteObject(hBitmap);
return E_FAIL;
}
ImageList_Add(hImageList, hBitmap, (HBITMAP)NULL);
// The specified image list will be destroyed when the list view control is destroyed.
SendDlgItemMessage( IDC_ALTERNATE_LIST, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM)hImageList);
DeleteObject(hBitmap);
return S_OK;
}
LRESULT
CDfsShellExtProp::OnNotify(
IN UINT i_uMsg,
IN WPARAM i_wParam,
IN LPARAM i_lParam,
IN OUT BOOL& io_bHandled
)
/*++
Routine Description:
Notify message for user actions. We handle only the mouse double click right now
Arguments:
i_lParam - Details about the control sending the notify
io_bHandled - Whether we handled this message or not.
--*/
{
io_bHandled = FALSE; // So that the base class gets this notify too
NMHDR* pNMHDR = (NMHDR*)i_lParam;
if (!pNMHDR)
return FALSE;
if (IDC_ALTERNATE_LIST == pNMHDR->idFrom)
{
if (NM_DBLCLK == pNMHDR->code)
{
SetActive();
} else if (LVN_ITEMCHANGED == pNMHDR->code)
{
int n = ListView_GetSelectedCount(GetDlgItem(IDC_ALTERNATE_LIST));
::EnableWindow(GetDlgItem(IDC_SET_ACTIVE), (n == 1));
}
}
return TRUE;
}
BOOL
CDfsShellExtProp::SetActive()
/*++
Routine Description:
Sets the first selected alternate to be active.
--*/
{
HWND hwndAlternateLV = GetDlgItem(IDC_ALTERNATE_LIST);
int iSelected = ListView_GetNextItem(hwndAlternateLV, -1, LVNI_ALL | LVNI_SELECTED);
if (-1 == iSelected)
return FALSE; // nothing selected
LV_ITEM lvItem = {0};
lvItem.mask = LVIF_PARAM;
lvItem.iItem = iSelected;
ListView_GetItem(hwndAlternateLV, &lvItem);
LPDFS_ALTERNATES pDfsAlternate = (LPDFS_ALTERNATES)lvItem.lParam;
if (!pDfsAlternate )
return(FALSE);
// set the item to be active
DFS_INFO_101 DfsInfo101 = {0};
DfsInfo101.State = DFS_STORAGE_STATE_ACTIVE;
NET_API_STATUS nstatRetVal = NetDfsSetClientInfo(
m_bstrEntryPath,
pDfsAlternate->bstrServer,
pDfsAlternate->bstrShare,
101,
(LPBYTE) &DfsInfo101
);
if (nstatRetVal != NERR_Success)
{
DisplayMessageBoxForHR(HRESULT_FROM_WIN32(nstatRetVal));
return FALSE;
}
// Reset the image of the last Active alternate/s to normal.
int nIndex = -1;
while ((nIndex = ListView_GetNextItem(hwndAlternateLV, nIndex, LVNI_ALL)) != -1)
{
ZeroMemory(&lvItem, sizeof(lvItem));
lvItem.mask = LVIF_PARAM;
lvItem.iItem = nIndex;
ListView_GetItem(hwndAlternateLV, &lvItem);
LPDFS_ALTERNATES pTempDfsAlternate = (LPDFS_ALTERNATES)lvItem.lParam;
BOOL bActive = TRUE;
switch (pTempDfsAlternate->ReplicaState)
{
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
pTempDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_UNKNOWN;
break;
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
pTempDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_OK;
break;
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
pTempDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_UNREACHABLE;
break;
case SHL_DFS_REPLICA_STATE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_OK:
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
default:
bActive = FALSE;
break;
}
if (bActive)
{
lvItem.mask = LVIF_IMAGE | LVIF_STATE;
lvItem.state = LVIS_SELECTED | LVIS_FOCUSED;
lvItem.iImage = pTempDfsAlternate->ReplicaState;
ListView_SetItem(hwndAlternateLV,&lvItem);
_UpdateTextForReplicaState(hwndAlternateLV, nIndex, pTempDfsAlternate->ReplicaState);
break;
}
}
// set the new active alternate
BOOL bActive = FALSE;
switch (pDfsAlternate->ReplicaState)
{
case SHL_DFS_REPLICA_STATE_UNKNOWN:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN;
break;
case SHL_DFS_REPLICA_STATE_OK:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_ACTIVE_OK;
break;
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE;
break;
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
default:
bActive = TRUE;
break;
}
if (!bActive)
{
lvItem.iItem = iSelected;
lvItem.mask = LVIF_IMAGE;
lvItem.iImage = pDfsAlternate->ReplicaState;
ListView_SetItem(hwndAlternateLV,&lvItem);
_UpdateTextForReplicaState(hwndAlternateLV, iSelected, pDfsAlternate->ReplicaState);
}
return TRUE;
}
/*++
This function is called when a user clicks the ? in the top right of a property sheet
and then clciks a control, or when they hit F1 in a control.
--*/
LRESULT CDfsShellExtProp::OnCtxHelp(
IN UINT i_uMsg,
IN WPARAM i_wParam,
IN LPARAM i_lParam,
IN OUT BOOL& io_bHandled
)
{
LPHELPINFO lphi = (LPHELPINFO) i_lParam;
if (!lphi || lphi->iContextType != HELPINFO_WINDOW || lphi->iCtrlId < 0)
return FALSE;
::WinHelp((HWND)(lphi->hItemHandle),
DFS_CTX_HELP_FILE,
HELP_WM_HELP,
(DWORD_PTR)(PVOID)g_aHelpIDs_IDD_DFS_SHELL_PROP);
return TRUE;
}
/*++
This function handles "What's This" help when a user right clicks the control
--*/
LRESULT CDfsShellExtProp::OnCtxMenuHelp(
IN UINT i_uMsg,
IN WPARAM i_wParam,
IN LPARAM i_lParam,
IN OUT BOOL& io_bHandled
)
{
::WinHelp((HWND)i_wParam,
DFS_CTX_HELP_FILE,
HELP_CONTEXTMENU,
(DWORD_PTR)(PVOID)g_aHelpIDs_IDD_DFS_SHELL_PROP);
return TRUE;
}
LRESULT CDfsShellExtProp::OnCheckStatus(
IN WORD i_wNotifyCode,
IN WORD i_wID,
IN HWND i_hWndCtl,
IN OUT BOOL& io_bHandled
)
/*++
Routine Description:
Checks the status of all selected alternates. If it is reachable then the
reachable icon is displayed or the unreachable icon is displayed.
--*/
{
CWaitCursor WaitCursor;
HWND hwndAlternateLV = GetDlgItem(IDC_ALTERNATE_LIST);
int nIndex = -1;
while (-1 != (nIndex = ListView_GetNextItem(hwndAlternateLV, nIndex, LVNI_ALL | LVNI_SELECTED)))
{
LV_ITEM lvItem = {0};
lvItem.mask = LVIF_PARAM;
lvItem.iItem = nIndex;
ListView_GetItem(hwndAlternateLV, &lvItem);
LPDFS_ALTERNATES pDfsAlternate = (LPDFS_ALTERNATES)lvItem.lParam;
if (!pDfsAlternate )
return(FALSE);
// See if the path actaully exists (reachable).
DWORD dwErr = GetFileAttributes(pDfsAlternate->bstrAlternatePath);
if (0xffffffff == dwErr)
{ // We failed to get the file attributes for entry path
switch (pDfsAlternate->ReplicaState)
{
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE;
break;
case SHL_DFS_REPLICA_STATE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_OK:
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_UNREACHABLE;
break;
default:
_ASSERT(FALSE);
break;
}
}
else
{
switch (pDfsAlternate->ReplicaState)
{
case SHL_DFS_REPLICA_STATE_ACTIVE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_ACTIVE_OK:
case SHL_DFS_REPLICA_STATE_ACTIVE_UNREACHABLE:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_ACTIVE_OK;
break;
case SHL_DFS_REPLICA_STATE_UNKNOWN:
case SHL_DFS_REPLICA_STATE_OK:
case SHL_DFS_REPLICA_STATE_UNREACHABLE:
pDfsAlternate->ReplicaState = SHL_DFS_REPLICA_STATE_OK;
break;
default:
_ASSERT(FALSE);
break;
}
}
lvItem.mask = LVIF_IMAGE;
lvItem.iImage = pDfsAlternate->ReplicaState;
ListView_SetItem(hwndAlternateLV,&lvItem);
_UpdateTextForReplicaState(hwndAlternateLV, nIndex, pDfsAlternate->ReplicaState);
}
return TRUE;
}
LRESULT CDfsShellExtProp::OnSetActiveReferral(
IN WORD i_wNotifyCode,
IN WORD i_wID,
IN HWND i_hWndCtl,
IN OUT BOOL& io_bHandled
)
{
SetActive();
return TRUE;
}
HRESULT
LoadStringFromResource(
IN const UINT i_uResourceID,
OUT BSTR* o_pbstrReadValue
)
/*++
Routine Description:
This method returns a resource string.
The method no longer uses a fixed string to read the resource.
Inspiration from MFC's CString::LoadString.
Arguments:
i_uResourceID - The resource id
o_pbstrReadValue - The BSTR* into which the value is copied
--*/
{
if (!o_pbstrReadValue)
return E_INVALIDARG;
TCHAR szResString[1024];
ULONG uCopiedLen = 0;
szResString[0] = NULL;
// Read the string from the resource
uCopiedLen = ::LoadString(_Module.GetModuleInstance(), i_uResourceID, szResString, 1024);
// If nothing was copied it is flagged as an error
if(uCopiedLen <= 0)
{
return HRESULT_FROM_WIN32(::GetLastError());
}
else
{
*o_pbstrReadValue = ::SysAllocString(szResString);
if (!*o_pbstrReadValue)
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT
GetErrorMessage(
IN DWORD i_dwError,
OUT BSTR* o_pbstrErrorMsg
)
{
if (0 == i_dwError || !o_pbstrErrorMsg)
return E_INVALIDARG;
HRESULT hr = S_OK;
LPTSTR lpBuffer = NULL;
DWORD dwRet = ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, i_dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpBuffer, 0, NULL);
if (0 == dwRet)
{
// if no message is found, GetLastError will return ERROR_MR_MID_NOT_FOUND
hr = HRESULT_FROM_WIN32(GetLastError());
if (HRESULT_FROM_WIN32(ERROR_MR_MID_NOT_FOUND) == hr ||
0x80070000 == (i_dwError & 0xffff0000) ||
0 == (i_dwError & 0xffff0000) )
{ // Try locating the message from NetMsg.dll.
hr = S_OK;
DWORD dwNetError = i_dwError & 0x0000ffff;
HINSTANCE hLib = LoadLibrary(_T("netmsg.dll"));
if (!hLib)
hr = HRESULT_FROM_WIN32(GetLastError());
else
{
dwRet = ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
hLib, dwNetError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpBuffer, 0, NULL);
if (0 == dwRet)
hr = HRESULT_FROM_WIN32(GetLastError());
FreeLibrary(hLib);
}
}
}
if (SUCCEEDED(hr))
{
*o_pbstrErrorMsg = SysAllocString(lpBuffer);
LocalFree(lpBuffer);
}
else
{
// we failed to retrieve the error message from system/netmsg.dll,
// report the error code directly to user
hr = S_OK;
TCHAR szString[32];
_stprintf(szString, _T("0x%x"), i_dwError);
*o_pbstrErrorMsg = SysAllocString(szString);
}
if (!*o_pbstrErrorMsg)
hr = E_OUTOFMEMORY;
return hr;
}
int
DisplayMessageBox(
IN HWND hwndParent,
IN UINT uType, // style of message box
IN DWORD dwErr,
IN UINT iStringId, // OPTIONAL: String resource Id
...) // Optional arguments
{
_ASSERT(dwErr != 0 || iStringId != 0); // One of the parameter must be non-zero
HRESULT hr = S_OK;
TCHAR szCaption[1024], szString[1024];
CComBSTR bstrErrorMsg, bstrResourceString, bstrMsg;
::LoadString(_Module.GetModuleInstance(), IDS_APPLICATION_NAME,
szCaption, sizeof(szCaption)/sizeof(TCHAR));
if (dwErr)
hr = GetErrorMessage(dwErr, &bstrErrorMsg);
if (SUCCEEDED(hr))
{
if (iStringId == 0)
{
bstrMsg = bstrErrorMsg;
}
else
{
::LoadString(_Module.GetModuleInstance(), iStringId,
szString, sizeof(szString)/sizeof(TCHAR));
va_list arglist;
va_start(arglist, iStringId);
LPTSTR lpBuffer = NULL;
DWORD dwRet = ::FormatMessage(
FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER,
szString,
0, // dwMessageId
0, // dwLanguageId, ignored
(LPTSTR)&lpBuffer,
0, // nSize
&arglist);
va_end(arglist);
if (dwRet == 0)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
else
{
bstrMsg = lpBuffer;
if (dwErr)
bstrMsg += bstrErrorMsg;
LocalFree(lpBuffer);
}
}
}
if (FAILED(hr))
{
// Failed to retrieve the proper message, report the failure directly to user
_stprintf(szString, _T("0x%x"), hr);
bstrMsg = szString;
}
return ::MessageBox(hwndParent, bstrMsg, szCaption, uType);
}
HRESULT
DisplayMessageBoxForHR(
IN HRESULT i_hr
)
{
DisplayMessageBox(::GetActiveWindow(), MB_OK, i_hr, 0);
return S_OK;
}
| 27.541136 | 118 | 0.634929 | [
"object"
] |
bf0669a5c5fd5b6e171dd687d43f3495d0c75d25 | 1,987 | cpp | C++ | number-of-islands.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | 2 | 2019-01-10T17:50:26.000Z | 2019-05-23T14:31:58.000Z | number-of-islands.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | null | null | null | number-of-islands.cpp | mittalnaman2706/LeetCode | ba7e1602fb70ca0063c3e5573ea0661cc5ae9856 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int n,m;
int a[1000][1000];
void func(int i,int j)
{
int z,x;
/*for(z=0;z<n;z++)
{
for(x=0;x<m;x++)
cout<<a[z][x]<<" ";
cout<<endl;
}
cout<<endl;
*/
//
for(z=i-1;z>=0;z--){
if(a[z][j]!=1)
break;
else if(a[z][j]==1){
a[z][j]=2;
func(z,j);
}
}
//Down
for(z=i+1;z<n;z++){
if(a[z][j]!=1)
break;
else if(a[z][j]==1){
a[z][j]=2;
func(z,j);
}
}
//Left
for(z=j-1;z>=0;z--){
if(a[i][z]!=1)
break;
else if(a[i][z]==1){
a[i][z]=2;
func(i,z);
}
}
//Right
for(z=j+1;z<m;z++){
if(a[i][z]!=1)
break;
else if(a[i][z]==1){
a[i][z]=2;
func(i,z);
}
}
return;
}
int numIslands(vector<vector<char>>& grid) {
int i,j,k;
n=grid.size();
if(!n)
return 0;
m=grid[0].size();
if(!m || !n)
return 0;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
a[i][j]=grid[i][j]-48;
int c=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]==1)
{
// cout<<i<<' '<<j<<endl;
a[i][j]=2;
func(i,j);
// cout<<i<<' '<<j<<endl;
c++;
}
}
}/*
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}*/
return c;
}
}; | 21.138298 | 48 | 0.24006 | [
"vector"
] |
bf0a7f64c9221ddb515f96fdfc4d6a2d2966d642 | 6,911 | hpp | C++ | linear_container.hpp | mikecovlee/toys | 58e5b0b2eb51350cd1817eb79b3a13488f2e576a | [
"Apache-2.0"
] | 10 | 2017-06-15T05:11:02.000Z | 2021-08-18T12:08:26.000Z | linear_container.hpp | mikecovlee/toys | 58e5b0b2eb51350cd1817eb79b3a13488f2e576a | [
"Apache-2.0"
] | null | null | null | linear_container.hpp | mikecovlee/toys | 58e5b0b2eb51350cd1817eb79b3a13488f2e576a | [
"Apache-2.0"
] | 5 | 2019-03-12T15:16:59.000Z | 2021-08-15T03:41:11.000Z | #pragma once
// Linear Container by Michael Lee
#include <stdexcept>
#include <memory>
namespace cov {
template<typename data_t, typename size_t>
void uninitialized_copy_n(data_t *src, data_t *dest, size_t count)
{
if (count > 0) {
using byte_t=unsigned char;
byte_t *_src = reinterpret_cast<byte_t *>(src);
byte_t *_dest = reinterpret_cast<byte_t *>(dest);
size_t _count = count * sizeof(data_t);
for (size_t idx = 0; idx < _count; ++idx)
*(_dest + idx) = *(_src + idx);
}
}
template<typename data_t, typename size_t>
void normal_copy_n(data_t *src, data_t *dest, size_t count)
{
if (count > 0) {
for (size_t idx = 0; idx < count; ++idx)
::new(dest + idx) data_t(*(src + idx));
}
}
template<typename data_t, typename size_t=std::size_t, template<typename> class allocator_t=std::allocator>
class linear_container {
protected:
static allocator_t<data_t> m_allocator;
size_t m_capacity = 0, m_size = 0;
data_t *m_data = nullptr;
virtual void extend()=0;
public:
constexpr linear_container() = default;
linear_container(const linear_container &lc) : m_capacity(lc.m_capacity), m_size(lc.m_size),
m_data(m_allocator.allocate(lc.m_capacity))
{
normal_copy_n(lc.m_data, m_data, m_size);
}
linear_container(linear_container &&lc) noexcept
{
swap(lc);
}
virtual ~linear_container()
{
clear();
}
linear_container &operator=(const linear_container &lc)
{
assign(lc);
return *this;
}
linear_container &operator=(linear_container &&lc) noexcept
{
swap(lc);
return *this;
}
void assign(const linear_container &lc)
{
if (&lc != this) {
clear();
m_capacity = lc.m_capacity;
m_size = lc.m_size;
m_data = m_allocator.allocate(m_capacity);
normal_copy_n(lc.m_data, m_data, m_size);
}
}
data_t &at(size_t idx)
{
if (idx >= m_size)
throw std::out_of_range("linear container");
else
return m_data[idx];
}
const data_t &at(size_t idx) const
{
if (idx >= m_size)
throw std::out_of_range("linear container");
else
return m_data[idx];
}
data_t &operator[](size_t idx)
{
return m_data[idx];
}
const data_t &operator[](size_t idx) const
{
return m_data[idx];
}
data_t &front()
{
return *m_data;
}
const data_t &front() const
{
return *m_data;
}
data_t &back()
{
return *(m_data + m_size - 1);
}
const data_t &back() const
{
return *(m_data + m_size - 1);
}
data_t *data() const
{
return m_data;
}
bool empty() const
{
return m_size == 0;
}
size_t size() const
{
return m_size;
}
virtual void reserve(size_t)=0;
size_t capacity() const
{
return m_capacity;
}
virtual void shrink_to_fit()=0;
void clear()
{
for (size_t idx = 0; idx < m_size; ++idx)
(m_data + idx)->~data_t();
if (m_data != nullptr)
m_allocator.deallocate(m_data, m_capacity);
m_capacity = 0;
m_size = 0;
m_data = nullptr;
}
template<typename...args_t>
void emplace_back(args_t &&...args)
{
if (m_size == m_capacity)
extend();
::new(m_data + (m_size++)) data_t(std::forward<args_t>(args)...);
}
void push_back(const data_t &dat)
{
emplace_back(dat);
}
void pop_back()
{
if (m_size == 0)
throw std::logic_error("Pop back from empty linear container.");
else
(m_data + (m_size--))->~data_t();
}
void resize(size_t count, const data_t &dat)
{
if (count == m_size)
return;
if (count > m_size) {
reserve(count);
while (m_size < count)
::new(m_data + (m_size++)) data_t(dat);
}
else {
while (m_size > count)
(m_data + (m_size--))->~data_t();
}
}
void resize(size_t count)
{
resize(count, data_t());
}
void swap(linear_container &lc)
{
std::swap(lc.m_capacity, m_capacity);
std::swap(lc.m_size, m_size);
std::swap(lc.m_data, m_data);
}
void swap(linear_container &&lc) noexcept
{
std::swap(lc.m_capacity, m_capacity);
std::swap(lc.m_size, m_size);
std::swap(lc.m_data, m_data);
}
};
template<typename data_t, typename size_t=std::size_t, size_t chunk_size = 32, template<typename> class allocator_t=std::allocator>
class array_list final : public linear_container<data_t, size_t, allocator_t> {
using parent_t=linear_container<data_t, size_t, allocator_t>;
size_t compute_capacity(size_t cap)
{
if (cap % chunk_size == 0)
return cap;
else
return ((cap - cap % chunk_size) / chunk_size + 1) * chunk_size;
}
virtual void extend() override
{
this->reserve(chunk_size);
}
public:
using parent_t::parent_t;
virtual void reserve(size_t new_cap) override
{
if (this->m_capacity - this->m_size < chunk_size) {
size_t cap = this->m_capacity + compute_capacity(new_cap);
data_t *dat = parent_t::m_allocator.allocate(cap);
uninitialized_copy_n(this->m_data, dat, this->m_size);
if (this->m_data != nullptr)
parent_t::m_allocator.deallocate(this->m_data, this->m_capacity);
this->m_capacity = cap;
this->m_data = dat;
}
}
virtual void shrink_to_fit() override
{
if (this->m_capacity - this->m_size > chunk_size) {
size_t cap = compute_capacity(this->m_size);
data_t *dat = parent_t::m_allocator.allocate(cap);
uninitialized_copy_n(this->m_data, dat, this->m_size);
if (this->m_data != nullptr)
parent_t::m_allocator.deallocate(this->m_data, this->m_capacity);
this->m_capacity = cap;
this->m_data = dat;
}
}
};
template<typename data_t, typename size_t=std::size_t, template<typename> class allocator_t=std::allocator>
class vector final : public linear_container<data_t, size_t, allocator_t> {
using parent_t=linear_container<data_t, size_t, allocator_t>;
virtual void extend() override
{
this->reserve(this->m_capacity > 0 ? this->m_capacity : 1);
}
public:
using parent_t::parent_t;
virtual void reserve(size_t new_cap) override
{
if (this->m_capacity - this->m_size < new_cap) {
size_t cap = this->m_size + new_cap;
data_t *dat = parent_t::m_allocator.allocate(cap);
uninitialized_copy_n(this->m_data, dat, this->m_size);
if (this->m_data != nullptr)
parent_t::m_allocator.deallocate(this->m_data, this->m_capacity);
this->m_capacity = cap;
this->m_data = dat;
}
}
virtual void shrink_to_fit() override
{
if (this->m_capacity > this->m_size) {
size_t cap = this->m_size;
data_t *dat = parent_t::m_allocator.allocate(cap);
uninitialized_copy_n(this->m_data, dat, this->m_size);
if (this->m_data != nullptr)
parent_t::m_allocator.deallocate(this->m_data, this->m_capacity);
this->m_capacity = cap;
this->m_data = dat;
}
}
};
template<typename data_t, typename size_t, template<typename> class allocator_t> allocator_t<data_t> linear_container<data_t, size_t, allocator_t>::m_allocator;
} | 22.733553 | 161 | 0.654464 | [
"vector"
] |
bf0c44d6472bdf23dddd2b5bcef3a333e3218a2b | 4,008 | cpp | C++ | udp.cpp | urbanze/esp32-udp | 451eb1b730f2d69022c8c5711409df028527b0cd | [
"MIT"
] | null | null | null | udp.cpp | urbanze/esp32-udp | 451eb1b730f2d69022c8c5711409df028527b0cd | [
"MIT"
] | null | null | null | udp.cpp | urbanze/esp32-udp | 451eb1b730f2d69022c8c5711409df028527b0cd | [
"MIT"
] | null | null | null | #include "udp.h"
//===========UDP===========
/**
* @brief Start UDP Server to listen packets in specific port.
*
* Called only one time per port.
* If you want to listen another port, recall this function.
*
* @param [port]: Port.
*/
void UDP::begin(uint16_t port)
{
struct sockaddr_in addr;
memset(&sar, 0, sizeof(sar));
memset(&addr, 0, sizeof(addr));
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (!sr)
{
sr = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sr < 0)
{
ESP_LOGE(tag, "Fail to create socket [%d]", errno);
return;
}
}
if (bind(sr, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
ESP_LOGE(tag, "Fail to bind socket [%d]", errno);
close(sr);
return;
}
}
/**
* @brief Start packet to be sent over UDP.
*
* This can be called only one time per IP/port.
* If you want to send to another IP/port, recall this function.
*
* @param [*ip]: IP String. Eg: "192.168.4.2"
* @param [port]: Port.
*/
void UDP::beginPacket(const char *ip, uint16_t port)
{
memset(&sas, 0, sizeof(sas));
sas.sin_addr.s_addr = inet_addr(ip);
sas.sin_family = AF_INET;
sas.sin_port = htons(port);
if (!ss)
{
ss = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (ss < 0)
{
ESP_LOGE(tag, "Fail to create socket [%d]", errno);
return;
}
}
}
/**
* @brief Close socket if object.
*/
void UDP::stop()
{
close(sr);
close(ss);
}
/**
* @brief Flush (erase) all data available in RX queue.
*/
void UDP::flush()
{
uint8_t bff = 0;
int16_t avl = available();
for (int16_t i = 0; i < avl; i++)
{
recvfrom(sr, &bff, 1, MSG_DONTWAIT, (struct sockaddr*)&sar, &fromlen);
}
}
/**
* @brief Get how many Bytes are available to read.
*
* @return Bytes available to read.
*/
int16_t UDP::available()
{
int16_t avl = 0;
ioctl(sr, FIONREAD, &avl);
return avl;
}
/**
* @brief Get source IP from last received packet.
*/
char *UDP::remoteIP()
{
memset(rmt_ip, 0, sizeof(rmt_ip));
inet_ntop(AF_INET, &sar.sin_addr, rmt_ip, sizeof(rmt_ip));
return rmt_ip;
}
/**
* @brief Get source Port from last received packet.
*/
uint16_t UDP::remotePort()
{
return ntohs(sar.sin_port);
}
/**
* @brief Send data over UDP connection.
*
* @param [*text]: Data do send.
*
* @return Data wrote.
*/
int16_t UDP::write(uint8_t *data, uint16_t size)
{
if (sr)
{
if (sendto(sr, data, size, 0, (struct sockaddr*)&sas, sizeof(sas)) < 0)
{
ESP_LOGE(tag, "Fail to send [%d]", errno);
close(sr);
return -1;
}
}
else
{
if (sendto(ss, data, size, 0, (struct sockaddr*)&sas, sizeof(sas)) < 0)
{
ESP_LOGE(tag, "Fail to send [%d]", errno);
close(ss);
return -1;
}
}
return size;
}
/**
* @brief Send data over UDP connection.
*
* printf() alias.
*
* @return Data wrote.
*/
int16_t UDP::printf(const char *format, ...)
{
va_list vl;
va_start(vl, format);
int16_t size = vsnprintf(NULL, 0, format, vl)+1;
va_end(vl);
char bff[size] = {0};
vsprintf(bff, format, vl);
return write((uint8_t*)bff, size);
}
/**
* @brief Read only one Byte of data available.
*
* @return Data of Byte value readed.
*/
uint8_t UDP::read()
{
uint8_t bff = 0;
recvfrom(sr, &bff, 1, MSG_DONTWAIT, (struct sockaddr*)&sar, &fromlen);
return bff;
}
/**
* @brief Read [size] Bytes of data available.
*/
void UDP::readBytes(uint8_t *bff, uint16_t size)
{
recvfrom(sr, bff, size, MSG_DONTWAIT, (struct sockaddr*)&sar, &fromlen);
}
/**
* @brief Read [size] Bytes of data available.
*/
void UDP::readBytes(char *bff, uint16_t size)
{
recvfrom(sr, bff, size, MSG_DONTWAIT, (struct sockaddr*)&sar, &fromlen);
}
| 19.647059 | 79 | 0.566866 | [
"object"
] |
bf0fb57e1b0241e63e3bbccdd891971785fd4340 | 40,773 | cpp | C++ | roomedit/owl-6.34/source/framewin.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | roomedit/owl-6.34/source/framewin.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | roomedit/owl-6.34/source/framewin.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | //----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1991, 1996 by Borland International, All Rights Reserved
//
/// \file
/// Implementation of class TFrameWindow, a TWindow with additional features
/// for frames, such as client window, menus, icons, etc.
//----------------------------------------------------------------------------
#include <owl/pch.h>
#include <stdio.h>
#include <owl/docking.h>
#include <owl/framewin.h>
#include <owl/applicat.h>
#include <owl/menu.h>
#include <owl/uimetric.h>
#include <owl/bardescr.h>
using namespace std;
namespace owl {
#if !defined(WM_SETICON)
# define WM_SETICON 0x0080
#endif
OWL_DIAGINFO;
DIAG_DECLARE_GROUP(OwlCmd);
DEFINE_RESPONSE_TABLE1(TFrameWindow, TWindow)
EV_WM_PAINT,
EV_WM_ERASEBKGND,
EV_WM_QUERYDRAGICON,
EV_WM_INITMENUPOPUP,
EV_WM_SETFOCUS,
EV_WM_SIZE,
EV_WM_PARENTNOTIFY,
EV_WM_QUERYNEWPALETTE,
EV_WM_PALETTECHANGED,
END_RESPONSE_TABLE;
//
/// Overrides TCommandEnable::Enable. Enables or disables the menu options that
/// control the appearance of the corresponding menu item.
//
void
TMenuItemEnabler::Enable(bool enable)
{
TCommandEnabler::Enable(enable);
::EnableMenuItem(HMenu, Position,
MF_BYPOSITION | (enable ? MF_ENABLED : MF_GRAYED));
}
//
/// Overrides TCommandEnable::SetText. Changes the text of the corresponding menu
//
void
TMenuItemEnabler::SetText(LPCTSTR str)
{
::ModifyMenu(HMenu, Position, MF_BYPOSITION | MF_STRING, Id, str);
}
//
/// Overrides TCommandEnable::SetCheck. Checks or unchecks the corresponding menu
/// item. The state parameter reflects the menu item's state, which can be checked,
/// unchecked, or indeterminate.
//
void
TMenuItemEnabler::SetCheck(int state)
{
::CheckMenuItem(HMenu, Position,
MF_BYPOSITION | (state == Checked ? MF_CHECKED : MF_UNCHECKED));
}
//----------------------------------------------------------------------------
//
/// Constructs a window object with the parent window supplied in parent, which is
/// zero if this is the main window. title, which by default is zero, contains the
/// title displayed in the window's caption bar. clientWnd is the client window for
/// this frame window or zero if none exists. shrinkToClient controls whether the
/// client window will size to fit the frame or the frame window will fit the
/// client. Note that this parameter only affects the size of the main window. When
/// a client window is used in a frame window that doesn't have shrinktoClient set,
/// the client window resizes to fit the frame window. When a client window is used
/// in a frame window that has the shrinktoClient set, the frame window shrinks to
/// fit the size of the client window.
//
TFrameWindow::TFrameWindow(TWindow* parent,
LPCTSTR title,
TWindow* clientWnd,
bool shrinkToClient,
TModule* module)
{
// Initialize virtual base, in case the derived-most used default ctor
//
TWindow::Init(parent, title, module);
IconResId = 0; // remember that we still need to init
Init(clientWnd, shrinkToClient);
}
//
/// String-aware overload
//
TFrameWindow::TFrameWindow(
TWindow* parent,
const tstring& title,
TWindow* client,
bool shrinkToClient,
TModule* module)
{
TWindow::Init(parent, title, module);
IconResId = 0;
Init(client, shrinkToClient);
}
//
/// Constructor for a TFrameWindow that is being used as an alias for a
/// non-ObjectWindows window. hWnd is the handle to the existing window object that
/// TFrameWindow controls; module contains the module passed to the base class's
/// contructor.
///
/// This constructor is generally not used by derived
/// classes, only as generic alias to a framewindow-like HWND
//
TFrameWindow::TFrameWindow(HWND THandle, TModule* module)
:
TWindow(THandle, module)
{
Init(0);
}
//
/// Protected constructor for use by immediate virtually derived classes.
/// Immediate derivitives must call Init() before constructions are done.
//
TFrameWindow::TFrameWindow()
{
IconResId = 0; // Zero this member to remember that we still need to init
}
//
/// Normal initialization of a default constructed TFrameWindow. Is ignored
/// if called more than once.
///
/// This initialize function is for use with virtually derived classes, which must
/// call Init before construction is completed. This procedure provides necessary
/// data to virtually derived classes and takes care of providing the data in the
/// appropriate sequence.
//
void
TFrameWindow::Init(TWindow* clientWnd, bool shrinkToClient)
{
if (!IconResId) {
Attr.Style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
Attr.X = Attr.W = CW_USEDEFAULT;
if (clientWnd)
Attr.Style |= WS_CLIPCHILDREN;
if (shrinkToClient)
SetFlag(wfShrinkToClient);
Init(clientWnd);
}
}
//
// Private initializer does a bulk of the common frame window initialization
//
void
TFrameWindow::Init(TWindow* clientWnd)
{
HWndRestoreFocus = 0;
KeyboardHandling = false;
ClientWnd = clientWnd;
MenuDescr = 0;
BarDescr = 0;
DeleteBar = false;
MergeModule = 0;
CurIcon = 0;
CurIconSm = 0;
IconModule = 0;
IconSmModule = 0;
SetIcon(&GetGlobalModule(), IDI_OWLAPP);
#if !defined( MAINWIN )
SetIconSm(&GetGlobalModule(), IDI_OWLAPPSM);
#endif
MinimizedPos = TPoint(-1,-1); // Windows convention for never minimized
if (ClientWnd) {
ClientWnd->SetParent(this);
ClientWnd->EnableAutoCreate(); // in case client is a dialog
SetBkgndColor(NoErase); // no need to erase client area
}
}
//
/// Destructor for a TFrameWindow
//
/// Deletes any associated menu descriptor.
//
TFrameWindow::~TFrameWindow()
{
if (IsFlagSet(wfMainWindow))
if (GetApplication()->GetMainWindow() == this)
GetApplication()->ClearMainWindow();
delete MenuDescr;
if(DeleteBar)
delete BarDescr;
}
//
// Return a state mask representing the enabled menu items (up to 32)
//
static uint32
GetMenuStateBits(HMENU hmenu, int count)
{
uint32 bit = 1;
uint32 result = 0;
for (int i = 0; i < count; i++) {
uint state = GetMenuState(hmenu, i, MF_BYPOSITION);
if (state != (uint)-1) {
if (!(state & (MF_DISABLED | MF_GRAYED))) {
result |= bit;
}
}
bit <<= 1;
}
return result;
}
//
/// Responds to WM_INITMENUPOPUP by performing a command enable run on each
/// of the menu items in the popup menu
///
/// Sent before a pop-up menu is displayed, EvInitMenuPopup lets an application
/// change the items on the menu before the menu is displayed. EvInitMenuPopup
/// controls whether the items on the pop-up menu are enabled or disabled, checked
/// or unchecked, or strings. HMENU indicates the menu handle. index is the index of
/// the pop-up menu. sysMenu indicates if the pop-up menu is the system menu.
//
void
TFrameWindow::EvInitMenuPopup(HMENU hPopupMenu, uint index, bool sysMenu)
{
if (!sysMenu && hPopupMenu) {
const int count = ::GetMenuItemCount(hPopupMenu);
// Save current state of visible top level menus
//
uint32 preState = 0;
if (hPopupMenu == GetMenu())
preState = GetMenuStateBits(hPopupMenu, count);
TWindow::EvInitMenuPopup(hPopupMenu, index, sysMenu);
// If the top level menu state changes, redraw the menu bar
//
if (hPopupMenu == GetMenu())
if (GetMenuStateBits(hPopupMenu, count) != preState)
DrawMenuBar();
}
}
//
/// Overrides TWindow's virtual function. TApplication calls the main window's
/// IdleAction when no messages are waiting to be processed. TFrameWindow uses this
/// idle time to perform command enabling for the menu bar. It also forwards
/// IdleAction to each of its children. IdleAction can be overridden to do
/// background processing.
//
bool
TFrameWindow::IdleAction(long idleCount)
{
if (idleCount == 0) {
// do command enabling for the menu bar if this is the active task
//
if (GetFocus()) {
long style = ::GetWindowLong(*this, GWL_STYLE);
if (!(style & WS_CHILD)) {
if (IsWindow()) {
HMENU hMenu = ::GetMenu(*this);
if (IsMenu(hMenu))
HandleMessage(WM_INITMENUPOPUP, TParam1(hMenu));
}
}
}
}
// give child windows an opportunity to do any idle processing
//
return TWindow::IdleAction(idleCount);
}
//
/// Locates and returns the child window that is the target of the command and
/// command enable messages. If the current application does not have focus or if
/// the focus is within a toolbar in the application, GetCommandTarget returns the
/// most recently active child window.
///
/// If an alternative form of command processing is desired, a user's main window
/// class can override this function. TFrameWindow's EvCommand and EvCommandEnable
/// functions use GetCommandTarget to find the command target window. This member is
/// not available under Presentation Manager.
//
HWND
TFrameWindow::GetCommandTarget()
{
// Retrieve the focus window and our client
//
HWND hFocus = ::GetFocus();
TWindow* client = GetClientWindow();
// 1. The first candidate is a focus window that's a child of our client
//
if (hFocus && client && client->IsChild(hFocus)) {
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - focus, "\
"child of client: " << hex << uint(hFocus));
return hFocus;
}
// 2. The next option is our client window itself
//
if (client) {
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - client: " << *client);
return *client;
}
// 3. The next option is a focus window that's a child of ours
//
if (hFocus && IsChild(hFocus)) {
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - focus, "\
<< hex << uint(hFocus));
return hFocus;
}
// 4. If all of the above fail, resort to the last focus child of ours
//
if (HWndRestoreFocus) {
#if defined(__TRACE) || defined(__WARN)
TWindow* win = GetWindowPtr(HWndRestoreFocus);
if (!win) {
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - HwndRestoreFocus, "\
<< hex << uint(HWndRestoreFocus));
} else {
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - HwndRestoreFocus, "\
<< *win);
}
#endif
return HWndRestoreFocus;
}
// 5. When all else fails, send ourselves in
//
TRACEX(OwlCmd, 1, "TFrameWindow::GetCommandTarget - self, " << *this);
return *this;
}
//
/// Handle WM_COMMAND to provide extra processing for commands:
/// Extra processing for commands: starts with the command target window
/// (usually the focus window) and gives it and its parent windows an
/// opportunity to handle the command.
//
TResult
TFrameWindow::EvCommand(uint id, HWND hCtl, uint notifyCode)
{
TRACEX(OwlCmd, 1, "TFrameWindow::EvCommand - id(" << id << "), ctl(" <<\
hex << uint(hCtl) << "), code(" << notifyCode << ")");
// Walk the command chain from the command target back up to us or until
// we hit a child that is an owl window. Delegate to owl-child or forward to
// our base if no child is found.
//
if (hCtl == 0) {
HWND hCmdTarget = GetCommandTarget();
// Check owl parentage too in case the HWNDs were reparented
//
while (hCmdTarget && hCmdTarget != GetHandle()) {
TWindow* cmdTarget = GetWindowPtr(hCmdTarget);
if (cmdTarget)
return cmdTarget->EvCommand(id, hCtl, notifyCode);
hCmdTarget = ::GetParent(hCmdTarget);
}
}
return TWindow::EvCommand(id, hCtl, notifyCode);
}
//
/// Handle WM_COMMAND_ENABLE to provide command enable distribution and default
/// support for windows without command enable handlers.
///
/// Handles checking and unchecking of the frame window's menu items.
/// EvCommandEnable uses TWindow's RouteCommandEnable member function to perform the
/// majority of this command enabling work.
//
void
TFrameWindow::EvCommandEnable(TCommandEnabler& commandEnabler)
{
// Don't process for windows out of our window tree (esp. other apps)
//
RouteCommandEnable(GetCommandTarget(), commandEnabler);
}
//
/// Overrides TWindow's virtual function. Performs preprocessing of window messages.
/// If the child window has requested keyboard navigation, PreProcessMsg handles any
/// accelerator key messages and then processes any other keyboard messages.
//
bool
TFrameWindow::PreProcessMsg(MSG& msg)
{
if (TWindow::PreProcessMsg(msg))
return true; // Processed accelerators
if (KeyboardHandling && msg.message >= WM_KEYFIRST &&
msg.message <= WM_KEYLAST)
{
HWND parent = ::GetParent(msg.hwnd);
// Retrieve the COMBO handle if we're in the EDIT ctrl parented to the
// combobox
//
tchar szClassName[0x10];
::GetClassName(parent, szClassName, COUNTOF(szClassName));
if (!_tcsicmp(szClassName, _T("COMBOBOX")))
parent = ::GetParent(parent);
if (parent && ::IsDialogMessage(parent, &msg))
return true;
}
return false;
}
//
/// Overrides TWindow's non-virtual SetMenu function, thus allowing derived classes
/// the opportunity to implement this function differently from TWindow. SetMenu
/// sets the window's menu to the menu indicated by newMenu. If newMenu is 0, the
/// window's current menu is removed. SetMenu returns 0 if the menu remains
/// unchanged; otherwise, it returns a nonzero value.
///
/// It also calls the application's PreProcessMenu() if it is the main window
/// to let it make any changes just before setting.
//
bool
TFrameWindow::SetMenu(HMENU newMenu)
{
if (IsFlagSet(wfMainWindow))
GetApplication()->PreProcessMenu(newMenu);
return TWindow::SetMenu(newMenu);
}
//
/// Perform a high-level menu assignment either before or after the HWND for the
/// window has been created.
///
/// Sets Attr.Menu to the supplied menuResId and frees any previous strings pointed
/// to by Attr.Menu. If HWindow is nonzero, loads and sets the menu of the window,
/// destroying any previously existing menu.
///
/// Returns true if successful; false otherwise
//
bool
TFrameWindow::AssignMenu(TResId menuResId)
{
if (menuResId != Attr.Menu) {
if (Attr.Menu.IsString())
delete[] Attr.Menu.GetString();
Attr.Menu = menuResId.IsString() ? TResId(strnewdup(menuResId)) : menuResId;
}
// If the window has been created then load and set the new menu and destroy
// the old menu
//
if (!GetHandle())
return true;
HMENU curMenu = GetMenu();
HMENU newMenu = LoadMenu(Attr.Menu);
if (!SetMenu(newMenu))
return false;
if (curMenu)
::DestroyMenu(curMenu);
return true;
}
//
/// Sets the icon in the module specified in iconModule to the resource ID specified
/// in iconResId. See the sample file BMPVIEW.CPP for an example of painting an icon
/// from a bitmap. You can set the iconResId to one of these predefined values as
/// well as user-defined values:
/// - \c \b IDI_APPLICATION Default icon used for applications
/// - \c \b IDI_ASTERISK Asterisk used for an informative message
/// - \c \b IDI_EXCLAMATION Exclamation mark used for a warning message
/// - \c \b IDI_HAND Hand used for warning messages
/// - \c \b IDI_QUESTION Question mark used for prompting a response
//
bool
TFrameWindow::SetIcon(TModule* module, TResId resId)
{
// Delete old icon if not system icon
//
if (CurIcon && IconModule) {
TUser::DestroyIcon(CurIcon);
CurIcon = 0;
}
IconModule = module;
IconResId = resId;
HINSTANCE hInstance = IconModule ? HINSTANCE(*IconModule) : HINSTANCE(0);
if (IconResId != 0)
CurIcon = TUser::LoadIcon(hInstance, IconResId);
if (CurIcon && IsWindow())
SendMessage(WM_SETICON, true, (LPARAM)(HICON)CurIcon);
return true;
}
//
/// Set the Small Icon (16 x 16)
//
bool
TFrameWindow::SetIconSm(TModule* module, TResId resId)
{
// Delete old small icon
//
if (CurIconSm && IconSmModule) {
TUser::DestroyIcon(CurIconSm);
CurIconSm = 0;
}
IconSmModule = module;
IconSmResId = resId;
HINSTANCE hInstance = IconSmModule ? HINSTANCE(*IconSmModule) : HINSTANCE(0);
if (IconSmResId != 0) {
CurIconSm = (HICON)::LoadImage(hInstance, IconSmResId, IMAGE_ICON,
TUIMetric::CxSmIcon, TUIMetric::CySmIcon,
LR_DEFAULTCOLOR);
if (!CurIconSm)
CurIconSm = TUser::LoadIcon(hInstance, IconSmResId);
}
if (CurIconSm && IsWindow())
SendMessage(WM_SETICON, false, (LPARAM)(HICON)CurIconSm);
return true;
}
//
/// Returns a pointer to the client window. If you are trying to access a
/// window-based object in a TMDIChild (which is a frame window), you can use this
/// function.
//
TWindow*
TFrameWindow::GetClientWindow()
{
return ClientWnd;
}
//
/// Sets the client window to the specified window. Users are responsible for
/// destroying the old client window if they want to eliminate it.
///
/// Assume clientWnd was parented to us.
//
TWindow*
TFrameWindow::SetClientWindow(TWindow* clientWnd)
{
TWindow* oldClientWnd = ClientWnd;
HWND oldWnd = oldClientWnd ? oldClientWnd->GetHandle() : (HWND)0;
RemoveChild(ClientWnd);
if (HWndRestoreFocus == oldWnd)
HWndRestoreFocus = 0;
ClientWnd = clientWnd;
if (ClientWnd) {
ClientWnd->SetParent(this);
if (GetHandle()) {
if (!ClientWnd->GetHandle())
ClientWnd->Create();
ClientWnd->ShowWindow(SW_SHOWNOACTIVATE);
}
SetBkgndColor(NoErase); // no need to erase client area
ResizeClientWindow(true); // !CQ defer repaint?
}
else
SetBkgndColor(NoColor); // will need to erase client area
// Pass the focus to the new client, but only if we have it currently
//
if (ClientWnd && ClientWnd->GetHandle() && GetFocus() == GetHandle()) {
ClientWnd->SetFocus();
HWndRestoreFocus = ClientWnd->GetHandle();
}
return oldClientWnd;
}
//
/// If someone removes our client with a RemoveChild() call, update our client
/// and restore focus ptrs.
//
void
TFrameWindow::RemoveChild(TWindow* child)
{
TWindow::RemoveChild(child);
if (child) {
if (child == ClientWnd)
ClientWnd = 0;
if (child->GetHandle() == HWndRestoreFocus) {
HWndRestoreFocus = 0;
}
}
}
//
/// Overrides TWindow's virtual function. Pastes the number of the view into the
/// caption and then shows the number on the screen. This function can be overridden
/// if you don't want to use the default implementation, which displays a number on
/// the screen. That is, you might want to write "Two" instead of ":2" on the
/// screen. For an example of the behavior of this function, see step 12 of the
/// ObjectWindows tutorial, which renumbers the views if one of them is closed.
///
/// Generates a composite title based on the caption, docname, and index
/// if it is > 0.
/// \code
/// [<Title> - ]<docname>[:<index>]
/// \endcode
//
bool
TFrameWindow::SetDocTitle(LPCTSTR docname, int index)
{
if (index >= 0) {
tstring title;
LPCTSTR c = GetCaption();
if (c && *c) {
title = c;
title += _T(" - ");
}
if (docname)
title += docname;
if (index > 0) {
title += _T(":");
tchar num[10];
_stprintf(num, _T("%d"), index );
title += num;
}
SetWindowText(title.c_str());
}// else if index negative, simply acknowledge that title will display
return true;
}
//
// Obtain the real windows application icon. The IDI_APPLICATION icon is an
// ugly black & white box, but when a class is registered with this icon it
// gets substituted with a better windows icon. Worse case we end up with the
// ugly box icon.
//
static HICON
getAppIcon()
{
static HICON hRealAppIcon = 0;
if (!hRealAppIcon) {
WNDCLASS wndClass;
static tchar className[] = _T("IconSnarfer");
memset(&wndClass, 0, sizeof wndClass);
wndClass.hInstance = GetGlobalModule().GetHandle();
wndClass.hIcon = ::LoadIcon(0, IDI_APPLICATION);
wndClass.lpszClassName = className;
wndClass.lpfnWndProc = ::DefWindowProc;
::RegisterClass(&wndClass);
::GetClassInfo(GetGlobalModule().GetHandle(), className, &wndClass);
hRealAppIcon = wndClass.hIcon;
::UnregisterClass(className, GetGlobalModule().GetHandle());
}
return hRealAppIcon ? hRealAppIcon : ::LoadIcon(0, IDI_APPLICATION);
}
//
/// Responds to a WM_PAINT message in the client window in order to paint the iconic
/// window's icon or to allow client windows a change to paint the icon.
///
/// If iconic, and an icon has been defined then draw that.
/// Or, if iconic & there is a client window, then call its paint function.
///
/// If not iconic, forwards to TWindow for normal paint processing
//
void
TFrameWindow::EvPaint()
{
if (IsIconic() && (IconResId || ClientWnd)) {
TPaintDC dc(GetHandle());
if (IconResId) {
SendMessage(WM_ICONERASEBKGND, TParam1(HDC(dc)));
::DrawIcon(dc, 0, 0, CurIcon ? CurIcon : getAppIcon());
}
else
ClientWnd->Paint(dc, dc.Ps.fErase, *(TRect*)&dc.Ps.rcPaint);
}
else
TWindow::EvPaint();
}
//
/// Response method for an incoming WM_ERASEBKGND message.
/// EvEraseBkgnd erases the background of the window specified in HDC. It returns
/// true if the background is erased; otherwise, it returns false.
///
/// If this frame window is iconic, and there is a client window, then give it
/// a chance to erase the background since it may want to take over painting.
///
/// If not iconic, forward to TWindow for normal erase background processing
//
bool
TFrameWindow::EvEraseBkgnd(HDC hDC)
{
if (IsIconic()) {
if (!IconResId && ClientWnd)
return (bool)ClientWnd->HandleMessage(WM_ERASEBKGND, TParam1(hDC));
HandleMessage(WM_ICONERASEBKGND, TParam1(hDC));
return true;
}
else
return TWindow::EvEraseBkgnd(hDC);
}
//
/// Responds to a WM_QUERYDRAGICON message sent to a minimized (iconic) window that
/// is going to be dragged. Instead of the default icon, EvQueryDragIcon uses the
/// icon that was set using SetIcon.
/// This member is not available under Presentation Manager.
//
HANDLE
TFrameWindow::EvQueryDragIcon()
{
// !JK Consider the following problems:
// !JK (1) If a derived class sets CurIcon (instantiated with something other
// !JK than a module & res id), this function will ignore it! Why do a
// !JK ::LoadIcon again? It won't actually load again anyway (see MS
// !JK Win16/Win32 doc). It doesn't reference count either.
// !JK
// !JK (2) If IconResId is non-zero but bad (i.e., ::LoadIcon fails), getAppIcon()
// !JK is returned; but if IconResId is zero, TWindow::EvQueryDragIcon() is
// !JK returned. What is the rationale behind returning one icon in the case
// !JK of a bad res id and a different icon in the case of a zero res id?
// !JK
// !JK This function body should be:
// !JK return (CurIcon)? CurIcon: TWindow::EvQueryDragIcon();
// !JK -or-
// !JK return (CurIcon)? CurIcon: getAppIcon();
if (IconResId) {
HINSTANCE hInstance = IconModule ? HINSTANCE(*IconModule) : HINSTANCE(0);
HICON hIcon = TUser::LoadIcon(hInstance, IconResId);
return hIcon ? hIcon : getAppIcon();
// !CQ This LoadIcon() may be causing a resource leak. May need to keep icon
// !CQ We are keeping it!!! CurIcon!!!
}
else
return TWindow::EvQueryDragIcon();
}
static inline bool
IsEnabledVisibleChild(long style)
{
return (style & (WS_CHILD | WS_VISIBLE | WS_DISABLED)) == (WS_CHILD | WS_VISIBLE);
}
static TWindow*
SearchForChildWithTab(TWindow* win)
{
TWindow* firstChild = win->GetFirstChild();
if (firstChild) {
TWindow* child = firstChild;
do {
if (child->GetHandle()) {
long style = child->GetWindowLong(GWL_STYLE);
if (IsEnabledVisibleChild(style)) {
if (style & WS_TABSTOP)
return child;
else {
TWindow* result = SearchForChildWithTab(child);
if (result)
return result;
}
}
}
child = child->Next();
} while (child != firstChild);
}
return 0;
}
static bool
EnabledVisibleChild(TWindow* win, void*)
{
return win->GetHandle() ? IsEnabledVisibleChild(win->GetWindowLong(GWL_STYLE)) :
false;
}
//
// If the receiver doesn't have any children then returns 0. Otherwise
// we search for the first child with WS_TABSTOP; If no child has WS_TABSTOP
// then we return the first enabled visible child
//
// Does a depth-first search of nested child windows
//
// NOTE: we stop at the first child with WS_TABSTOP and do not search its
// children...
//
TWindow*
TFrameWindow::FirstChildWithTab()
{
TWindow* win = SearchForChildWithTab(this);
return win ? win : FirstThat(EnabledVisibleChild);
}
//
/// Overrides TWindow's virtual function. Responds to a request by a child window to
/// hold its HWND when it is losing focus. Stores the child's HWND in
/// HwndRestoreFocus.
///
/// return true if caller can stop searching for a window to hold its handle.
//
bool
TFrameWindow::HoldFocusHWnd(HWND hWndLose, HWND hWndGain)
{
if (IsChild(hWndLose)) {
if (!hWndGain || !IsChild(hWndGain))
HWndRestoreFocus = hWndLose;
return true;
}
return hWndLose == GetHandle();
}
//
/// Restores the focus to the active window. hWndLostFocus contains the handle for
/// the window that lost focus.
///
/// Handle WM_SETFOCUS to return focus back to the child that had it most
/// recently, or find the best one to give it to otherwise.
//
void
TFrameWindow::EvSetFocus(HWND hWndLostFocus)
{
TWindow::EvSetFocus(hWndLostFocus);
if (!HWndRestoreFocus) {
HWND cmdTgt = GetCommandTarget();
if (cmdTgt && IsChild(cmdTgt))
HWndRestoreFocus = cmdTgt;
}
// if (HWndRestoreFocus == hWndLostFocus)
// HWndRestoreFocus = GetHandle();
if (HWndRestoreFocus) {
// Set focus to the saved HWND as long as it is still a valid window handle
//
if (::IsWindow(HWndRestoreFocus))
::SetFocus(HWndRestoreFocus);
else
HWndRestoreFocus = 0;
}
}
//
/// Responds to a message to notify the parent window that a given event has
/// occurred. If the client window is destroyed, closes the parent window. If
/// shrinkToClient is set and the child window has changed size, the frame is
/// adjusted.
/// When a TFrameWindow's client window is destroyed, the TFrameWindow object sees
/// the WM_PARENTNOTIFY message and posts a close message to itself. Without this
/// message, an empty frame would remain and the client window would then have to
/// determine how to destroy the frame. If you don't want this to happen, you can
/// derive from the frame window and have your application handle the EvParentNotify
/// or EvClose messages.
//
void
TFrameWindow::EvParentNotify(uint event, TParam1, TParam2 p2)
{
if (event == WM_DESTROY)
{
HWND child = reinterpret_cast<HWND>(p2);
if (ClientWnd && ClientWnd->GetHandle() == child)
PostMessage(WM_CLOSE); // using ShutDownWindow() has side effects
TWindow* c = GetWindowPtr(child);
if (c)
c->ClearFlag(wfFullyCreated);
}
else if (event == WM_SIZE)
{
HWND child = reinterpret_cast<HWND>(p2);
if (IsFlagSet(wfShrinkToClient)
&& ClientWnd
&& ClientWnd->GetHandle() == child
&& !IsIconic())
ResizeClientWindow(true); // !CQ defer repaint?
}
DefaultProcessing();
}
//
/// Forwards the WM_QUERYNEWPALETTE message to the client window.
//
bool
TFrameWindow::EvQueryNewPalette()
{
if (GetClientWindow())
return GetClientWindow()->ForwardMessage();
else
return TWindow::EvQueryNewPalette();
}
//
/// Forwards the WM_PALETTECHANGED message to the client window.
//
void
TFrameWindow::EvPaletteChanged(HWND hWndPalChg)
{
if (GetClientWindow())
GetClientWindow()->ForwardMessage();
else
TWindow::EvPaletteChanged(hWndPalChg);
}
//
// Resize & reposition the client window to fit in this frames client area
// or resize the frame to fit around the client's client area if
// wfShrinkToClient
// Return true if a client was actualy resized.
// Adjust clients styles & make sure they get set.
//
bool
TFrameWindow::ResizeClientWindow(bool repaint)
{
/// bool hasThickFrame = Attr.Style & WS_THICKFRAME;
/// Attr.Style |= WS_THICKFRAME;
// Nothing to resize if there's not Client window
//
if (!ClientWnd)
return false;
// Prevent recursion during resize by ignore calls from EvParentNotify and
// EvSize when we have already been called.
// Do this by disabling notifications while resizing using the
// wfShrinkToClient flag as a semaphore on the client
//
if (ClientWnd->IsFlagSet(wfShrinkToClient))
return true;
ClientWnd->SetFlag(wfShrinkToClient);
bool clientResized = false;
TSize clientAreaSize = GetClientRect().Size();
TSize childSize = ClientWnd->GetWindowRect().Size();
// First time through, strip client window of thick borders.
// If shrink-to-client, then must measure the client size first
// If the client has scrolls bars, we must hide them to obtain the correct
// size.
// Border style is left on & dealt with by hand below
//
const uint32 badClientStyles = WS_DLGFRAME | WS_THICKFRAME | // bad borders
WS_POPUP | WS_OVERLAPPED; // bad parenting
const uint32 badClientExStyles = WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE |
WS_EX_STATICEDGE; // more bad borders
if ((ClientWnd->GetStyle() & badClientStyles) ||
(ClientWnd->GetExStyle() & badClientExStyles)) {
if (IsFlagSet(wfShrinkToClient)) {
TSize tstSize = ClientWnd->GetClientRect().Size();
ClientWnd->ShowScrollBar(SB_BOTH, false);
childSize = ClientWnd->GetClientRect().Size();
if (childSize != tstSize) {
int restore = SB_BOTH;
if (childSize.cx == tstSize.cx)
restore = SB_HORZ;
if (childSize.cy == tstSize.cy)
restore = SB_VERT;
ClientWnd->ShowScrollBar(restore, true);
}
}
if (ClientWnd->GetStyle() & badClientStyles) {
bool reparent = (ClientWnd->GetStyle() & (WS_POPUP|WS_OVERLAPPED)) != 0;
uint32 style = ClientWnd->GetStyle();
style &= ~badClientStyles;
style |= WS_CHILD | WS_BORDER | WS_VISIBLE;
ClientWnd->SetStyle( style );
if (reparent)
::SetParent(*ClientWnd, *this);
}
if (ClientWnd->GetExStyle() & badClientExStyles) {
uint32 exStyle = ClientWnd->GetExStyle();
exStyle &= ~badClientExStyles;
ClientWnd->SetExStyle( exStyle );
}
}
if (ClientWnd->GetStyle() & WS_BORDER) {
childSize = ClientWnd->GetClientRect().Size();
}
if (childSize != clientAreaSize) {
if (IsFlagSet(wfShrinkToClient)) {
TRect outside = GetWindowRect();
TSize border = outside.Size() - clientAreaSize;
SetWindowPos(0, 0, 0,
childSize.cx + border.cx, childSize.cy + border.cy,
SWP_NOACTIVATE|SWP_NOMOVE| (repaint ? 0 : SWP_NOREDRAW));
clientAreaSize = childSize; // Must move client, will not cause an EvSize
}
else {
clientResized = true; // Client will get resized
}
}
// If frame is sizeable, turn off flag so that user can then resize
// after initial setup
//
if (Attr.Style & WS_THICKFRAME && !TYPESAFE_DOWNCAST(this, TFloatingSlip))
ClearFlag(wfShrinkToClient);
/// if (!hasThickFrame) {
/// Attr.Style &= ~WS_THICKFRAME;
/// }
// Handle simple border style by shoving the client's borders under the frame
// This code MUST not resize the client if shrinkToClient
// !CQ use SetWindowPos() to get at SWP_NOSIZE?
//
if (ClientWnd->GetStyle() & WS_BORDER) {
int bx = TUIMetric::CxBorder;
int by = TUIMetric::CyBorder;
ClientWnd->MoveWindow(-bx, -by, clientAreaSize.cx+bx+bx,
clientAreaSize.cy+by+by, repaint);
}
else
ClientWnd->MoveWindow(0, 0, clientAreaSize.cx, clientAreaSize.cy, repaint);
// Turn off semaphore bit
//
ClientWnd->ClearFlag(wfShrinkToClient);
return clientResized;
}
//
/// Calls TWindow::SetUpWindow to create windows in a child list. SetupWindow
/// performs the initial adjustment of the client window if one exists, assigns the
/// frame's menu based on the menu descriptor, and initializes HwndRestoreFocus.
//
void
TFrameWindow::SetupWindow()
{
// Create windows in child list (this includes the client window)
//
TWindow::SetupWindow();
ResizeClientWindow(true); // !CQ defer repaint?
if (MinimizedPos != TPoint(-1,-1)) {
WINDOWPLACEMENT windata;
windata.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(&windata);
windata.flags = WPF_SETMINPOSITION;
windata.showCmd = SW_SHOWNA;
windata.ptMinPosition = MinimizedPos;
SetWindowPlacement(&windata);
}
// If SetMenuDescr() was called before window created, update the menu now
//
if (IsFlagSet(wfMainWindow) && MenuDescr) {
HMENU curMenu = GetMenu();
TMenu newMenu(*MenuDescr, NoAutoDelete);
if (SetMenu(newMenu)) {
if (curMenu)
::DestroyMenu(curMenu);
}
else
::DestroyMenu(newMenu);
}
// If we haven't set THandleRestoreFocus then pick the first child with tabstop
//
if (!HWndRestoreFocus) {
///TH Previous version would be to search for first child with tabstop.
///TH Why not use CommandTarget?
// !BB Because it breaks when GetCommandTarget returns a non-child window
// !BB Please, leave this code AS IS?
#if 1
TWindow* win = FirstChildWithTab();
HWndRestoreFocus = win ? win->GetHandle() : GetHandle();
#else
HWND cmdTgt = GetCommandTarget();
if (cmdTgt && IsChild(cmdTgt))
HWndRestoreFocus = cmdTgt;
#endif
}
if (CurIcon)
SendMessage(WM_SETICON, true, (LPARAM)(HICON)CurIcon);
if (CurIconSm)
SendMessage(WM_SETICON, false, (LPARAM)(HICON)CurIconSm);
}
//
/// Cleans up any associated icons.
//
void
TFrameWindow::CleanupWindow()
{
// icon cleanup
//
SetIcon(0, 0);
SetIconSm(0, 0);
TWindow::CleanupWindow();
}
//
/// Tell child windows frame has minimized/maximized/restored
/// (They may want to change enabled state or release/restore resources)
//
void
TFrameWindow::BroadcastResizeToChildren(uint sizeType, const TSize& size)
{
if (sizeType == SIZE_MINIMIZED
|| sizeType == SIZE_MAXIMIZED
|| sizeType == SIZE_RESTORED)
{
ChildBroadcastMessage(WM_OWLFRAMESIZE, sizeType, reinterpret_cast<TParam2>(&size));
}
}
//
/// Response method for an incoming WM_SIZE message
///
/// Resizes the client window' so that it is equivalent to the client rectangle's
/// size. Calls TWindow::EvSize() in response to an incoming WM_SIZE message.
///
/// If no WM_SIZE sent, forwards WM_SIZE message to client so it can recalc.
//
void
TFrameWindow::EvSize(uint sizeType, const TSize& size)
{
TWindow::EvSize(sizeType, size);
TSize newSize = size;
if (ClientWnd) {
bool sizeSent = false;
if (sizeType != SIZE_MINIMIZED) {
sizeSent = ResizeClientWindow(true); // !CQ defer repaint?
newSize = ClientWnd->GetClientRect().Size();
}
if (!sizeSent)
ClientWnd->ForwardMessage();
}
BroadcastResizeToChildren(sizeType, newSize);
}
//
/// Sets the menu descriptor to the new menu descriptor.
//
void
TFrameWindow::SetMenuDescr(const TMenuDescr& menuDescr)
{
delete MenuDescr;
MenuDescr = new TMenuDescr(menuDescr);
if (IsFlagSet(wfMainWindow) && GetHandle()) {
HMENU curMenu = GetMenu();
TMenu newMenu(*MenuDescr, NoAutoDelete);
if (SetMenu(newMenu))
::DestroyMenu(curMenu);
else
::DestroyMenu(newMenu);
}
}
//
/// Sets the control bar descriptor to the new bar descriptor.
//
void
TFrameWindow::SetBarDescr(TBarDescr* barDescr, TAutoDelete delonClose)
{
if(DeleteBar)
delete BarDescr;
BarDescr = barDescr;
DeleteBar = delonClose == AutoDelete;
if (IsFlagSet(wfMainWindow) && GetHandle())
RestoreBar();
}
//
/// Merges the given menu descriptor with this frame's own menu descriptor and
/// displays the resulting menu in this frame. See TMenuDescr for a description of
/// menu bar types that can be merged.
///
/// Optionally use an existing HMENU to merge into & set
//
bool
TFrameWindow::MergeMenu(const TMenuDescr& childMenuDescr)
{
if (!MenuDescr || !GetHandle())
return false;
MergeModule = childMenuDescr.GetModule();
TMenu curMenu(*this, NoAutoDelete);
TMenu newMenu(NoAutoDelete);
MenuDescr->Merge(childMenuDescr, newMenu);
if (IsFlagSet(wfMainWindow))
GetApplication()->PreProcessMenu(newMenu);
if (SetMenu(newMenu)) {
::DestroyMenu(curMenu);
return true;
}
else {
::DestroyMenu(newMenu);
return false;
}
}
//
// Restores this frame window's menu to the one described by our menu
// descriptor
//
bool
TFrameWindow::RestoreMenu()
{
if (!MenuDescr)
return false;
HMENU curMenu = GetMenu();
TMenu newMenu(*MenuDescr, NoAutoDelete);
if (SetMenu(newMenu)) {
MergeModule = 0;
::DestroyMenu(curMenu);
}
else
::DestroyMenu(newMenu);
return true;
}
IMPLEMENT_STREAMABLE1(TFrameWindow, TWindow);
#if !defined(BI_NO_OBJ_STREAMING)
//
// Reads data of the uninitialized TFrameWindow from the passed ipstream
//
void*
TFrameWindow::Streamer::Read(ipstream& is, uint32 version) const
{
TFrameWindow* o = GetObject();
ReadVirtualBase((TWindow*)o, is);
if (o->IsFlagSet(wfMainWindow))
return o;
is >> o->ClientWnd;
is >> o->KeyboardHandling;
o->HWndRestoreFocus = 0;
bool hasMenuDescr = is.readByte();
if (hasMenuDescr) {
o->MenuDescr = new TMenuDescr;
is >> *o->MenuDescr;
}
else
o->MenuDescr = 0;
o->BarDescr = 0;
if(version > 2){
bool hasBarDescr = is.readByte();
if (hasBarDescr) {
o->BarDescr = new TBarDescr;
is >> *o->BarDescr;
}
}
// stream in window icon information
//
is >> o->IconModule;
is >> o->IconResId;
if (version > 1) {
is >> o->IconSmModule;
is >> o->IconSmResId;
}
else {
o->IconSmModule = 0;
o->IconSmResId = 0;
}
// load the window's icons
//
o->CurIcon = 0;
o->CurIconSm = 0;
o->SetIcon(o->IconModule, o->IconResId);
o->SetIconSm(o->IconSmModule, o->IconSmResId);
is >> o->MergeModule;
is >> o->MinimizedPos;
return o;
}
//
// Writes data of the TFrameWindow to the passed opstream
//
void
TFrameWindow::Streamer::Write(opstream& os) const
{
TFrameWindow* o = GetObject();
WriteVirtualBase((TWindow*)o, os);
if (o->IsFlagSet(wfMainWindow))
return;
os << o->ClientWnd;
os << o->KeyboardHandling;
os.writeByte(uint8(o->MenuDescr ? 1 : 0));
if (o->MenuDescr)
os << *o->MenuDescr;
// added in stream ver 3
os.writeByte(uint8(o->BarDescr ? 1 : 0));
if (o->BarDescr)
os << *o->BarDescr;
os << o->IconModule;
os << o->IconResId;
os << o->IconSmModule; // added in stream ver 2
os << o->IconSmResId; // added in stream ver 2
os << o->MergeModule;
WINDOWPLACEMENT windata;
windata.length = sizeof(WINDOWPLACEMENT);
o->GetWindowPlacement(&windata);
os << TPoint(windata.ptMinPosition);
}
#endif // if !defined(BI_NO_OBJ_STREAMING)
} // OWL namespace
| 29.227957 | 88 | 0.651387 | [
"object"
] |
bf17246e552d1d693871ad1d830898628ad4668a | 1,248 | cpp | C++ | December-09/cpp_aw3someone.cpp | Aw3someOne/A-December-of-Algorithms-2019 | 0b17b3a0360d1906babc141dd8a4b9ac67d1b609 | [
"MIT"
] | null | null | null | December-09/cpp_aw3someone.cpp | Aw3someOne/A-December-of-Algorithms-2019 | 0b17b3a0360d1906babc141dd8a4b9ac67d1b609 | [
"MIT"
] | null | null | null | December-09/cpp_aw3someone.cpp | Aw3someOne/A-December-of-Algorithms-2019 | 0b17b3a0360d1906babc141dd8a4b9ac67d1b609 | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
#include <sstream>
#include <vector>
void readset(std::vector<float>& v, std::istringstream& iss) {
float t;
if (iss.peek() == '{')
iss.ignore();
while (iss >> t >> std::ws) {
v.push_back(t);
if (iss.peek() == ',')
iss.ignore();
}
}
float fx(float x, char op, float k) {
switch (op) {
case '+': return x + k;
case '-': return x - k;
case '*': return x * k;
case '/': return x / k;
case '^': return pow(x, k);
default: return x;
}
}
int main() {
std::vector<float> set1;
std::vector<float> set2;
std::string line;
std::cout << "Set 1: ";
getline(std::cin, line);
std::istringstream iss(line);
readset(set1, iss);
std::cout << "Set 2: ";
getline(std::cin, line);
iss = std::istringstream(line);
readset(set2, iss);
std::cout << "Function: ";
char x, op;
float n;
std::set<float> outputs;
if (set2.size() > set1.size())
goto notonetoone;
if (!(std::cin >> x >> std::ws >> op >> n))
return 1;
for (auto x : set1) {
float y = fx(x, op, n);
if (outputs.find(y) != outputs.end())
goto notonetoone;
outputs.insert(y);
}
std::cout << "Result: It is one to one" << std::endl;
return 0;
notonetoone:
std::cout << "Result: It is not one to one" << std::endl;
}
| 19.5 | 62 | 0.580929 | [
"vector"
] |
bf2068b4708b063da7be3f0b9df678f63dbffbd7 | 18,028 | cpp | C++ | ChromeWorker/handlersmanager.cpp | vadkasevas/BAS | 657f62794451c564c77d6f92b2afa9f5daf2f517 | [
"MIT"
] | 302 | 2016-05-20T12:55:23.000Z | 2022-03-29T02:26:14.000Z | ChromeWorker/handlersmanager.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 9 | 2016-07-21T09:04:50.000Z | 2021-05-16T07:34:42.000Z | ChromeWorker/handlersmanager.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 113 | 2016-05-18T07:48:37.000Z | 2022-02-26T12:59:39.000Z | #include "handlersmanager.h"
#include "include/base/cef_bind.h"
#include "include/wrapper/cef_closure_task.h"
#include "multithreading.h"
#include <functional>
using namespace std::placeholders;
void HandlersManager::Init1(CefRefPtr<MainHandler> Handler,std::function<void(const std::string&)> SendTextResponceCallback,std::function<void(const std::string&, int)> UrlLoadedCallback,std::function<void()> LoadSuccessCallback,std::function<void(char*,int,int)> PaintCallback, std::function<void(int64)> OldestRequestTimeChangedCallback)
{
this->Handler.swap(Handler);
this->Handler->SetHandlersManager(this);
this->SendTextResponceCallback = SendTextResponceCallback;
this->UrlLoadedCallback = UrlLoadedCallback;
this->LoadSuccessCallback = LoadSuccessCallback;
this->PaintCallback = PaintCallback;
this->OldestRequestTimeChangedCallback = OldestRequestTimeChangedCallback;
this->Handler->EventLoadSuccess.push_back(std::bind(&HandlersManager::LoadSuccess,this,_1));
this->Handler->EventPaint.push_back(std::bind(&HandlersManager::Paint,this,_1,_2,_3,_4));
this->Handler->EventSendTextResponce.push_back(std::bind(&HandlersManager::SendTextResponce,this,_1,_2));
this->Handler->EventUrlLoaded.push_back(std::bind(&HandlersManager::UrlLoaded,this,_1,_2,_3));
this->Handler->EventOldestRequestTimeChanged.push_back(std::bind(&HandlersManager::OldestRequestTimeChanged,this,_1,_2));
this->Handler->EventPopupClosed.push_back(std::bind(&HandlersManager::PopupRemoved,this,_1));
this->Handler->EventPopupCreated.push_back(std::bind(&HandlersManager::PopupCreated,this,_1,_2));
}
void HandlersManager::Init2(CefRefPtr<CefBrowser> Browser)
{
OriginalHandler = std::make_shared<HandlerUnitClass>();
OriginalHandler->Handler = this->Handler;
OriginalHandler->Browser = Browser;
OriginalHandler->BrowserId = Browser->GetIdentifier();
OriginalHandler->IsActive = true;
UpdateMapBrowserIdToTabNumber();
UpdateCurrent();
}
void HandlersManager::UpdateCurrent()
{
int PrevBrowserId = CurrentBrowserId;
bool IsPopupActive = false;
if(OriginalHandler && OriginalHandler->ForceShow)
{
IsPopupActive = true;
Handler = OriginalHandler->Handler;
Browser = OriginalHandler->Browser;
}
if(!IsPopupActive)
{
for(HandlerUnit h:HandlerUnits)
{
if(h->ForceShow && h->IsActive && !h->DontUseAsActive && h->IsContextCreated)
{
IsPopupActive = true;
Handler = h->Handler;
Browser = h->Browser;
}
}
}
if(!IsPopupActive)
{
for(HandlerUnit h:HandlerUnits)
{
if(h->IsActive && !h->DontUseAsActive && h->IsContextCreated)
{
IsPopupActive = true;
Handler = h->Handler;
Browser = h->Browser;
}
}
}
if(!IsPopupActive && OriginalHandler)
{
Handler = OriginalHandler->Handler;
Browser = OriginalHandler->Browser;
}
CurrentBrowserId = -1;
if(Browser)
CurrentBrowserId = Browser->GetIdentifier();
if(PrevBrowserId != CurrentBrowserId && Browser)
{
Browser->GetHost()->SendFocusEvent(true);
Browser->GetHost()->Invalidate(PET_VIEW);
}
}
MainHandler* HandlersManager::GetHandler()
{
return Handler.get();
}
CefBrowser* HandlersManager::GetBrowser()
{
return Browser.get();
}
int64 HandlersManager::FindFrameId(const FrameInspectResult& Inspect)
{
if(!Inspect.is_frame)
return -1;
std::vector<int64> identifiers;
GetBrowser()->GetFrameIdentifiers(identifiers);
//Find by url
for(int64 id:identifiers)
{
CefRefPtr<CefFrame> Frame = GetBrowser()->GetFrame(id);
int depth = 0;
{
CefRefPtr<CefFrame> FrameTemp = Frame;
while(true)
{
FrameTemp = FrameTemp->GetParent();
if(FrameTemp.get() == 0)
{
break;
}
depth ++;
}
}
//WORKER_LOG(std::string("FRAME url '") + Frame->GetURL().ToString() + std::string("' name '") + Frame->GetName().ToString() + std::string("' depth '") + std::to_string(depth) + std::string("'") + std::string(" frame_depth '") + std::to_string(Inspect.frame_depth) + std::string("'"));
//WORKER_LOG(std::to_string(id));
if(depth != Inspect.frame_depth)
continue;
if(!Frame->GetURL().ToString().empty() && !Inspect.frame_url.empty() && Inspect.frame_url != "about:blank")
{
std::size_t found = Frame->GetURL().ToString().find(Inspect.frame_url);
if (found!=std::string::npos)
{
//WORKER_LOG("Found by url");
return id;
}
}
}
//Find by name
for(int64 id:identifiers)
{
CefRefPtr<CefFrame> Frame = GetBrowser()->GetFrame(id);
int depth = 0;
{
CefRefPtr<CefFrame> FrameTemp = Frame;
while(true)
{
FrameTemp = FrameTemp->GetParent();
if(FrameTemp.get() == 0)
{
break;
}
depth ++;
}
}
//WORKER_LOG(std::string("FRAME url '") + Frame->GetURL().ToString() + std::string("' name '") + Frame->GetName().ToString() + std::string("' depth '") + std::to_string(depth) + std::string("'") + std::string(" frame_depth '") + std::to_string(Inspect.frame_depth) + std::string("'"));
//WORKER_LOG(std::to_string(id));
if(depth != Inspect.frame_depth)
continue;
if(!Inspect.frame_name.empty() && !Frame->GetName().ToString().empty() && Inspect.frame_name == Frame->GetName().ToString())
{
int FramesNumberWithSameName = 0;
for(int64 id:identifiers)
{
CefRefPtr<CefFrame> Frame = GetBrowser()->GetFrame(id);
//WORKER_LOG(std::string("~~~~~~~~") + Frame->GetName().ToString());
if(Frame->GetName().ToString() == Inspect.frame_name)
FramesNumberWithSameName++;
}
if(FramesNumberWithSameName == 1)
{
//WORKER_LOG(std::string("Found by name ") + Inspect.frame_name);
return id;
}
}
}
//WORKER_LOG("Second frame search frame");
//Find by index
int frame_index = 0;
for(int64 id:identifiers)
{
CefRefPtr<CefFrame> Frame = GetBrowser()->GetFrame(id);
int depth = 0;
{
CefRefPtr<CefFrame> FrameTemp = Frame;
while(true)
{
FrameTemp = FrameTemp->GetParent();
if(FrameTemp.get() == 0)
{
break;
}
depth ++;
}
}
int parent_id = -1;
{
CefRefPtr<CefFrame> Parent = GetBrowser()->GetFrame(id)->GetParent();
if(Parent)
{
parent_id = Parent->GetIdentifier();
if(Parent->GetIdentifier() == GetBrowser()->GetMainFrame()->GetIdentifier())
parent_id = -1;
}
}
//WORKER_LOG(std::string("FRAME url '") + Frame->GetURL().ToString() + std::string("' name '") + Frame->GetName().ToString() + std::string("' parent id '") + std::to_string(parent_id) + std::string("'") + std::string("' depth '") + std::to_string(depth) + std::string("'") + std::string(" frame_depth '") + std::to_string(Inspect.frame_depth) + std::string("'") + std::string(" parent_frame_id '") + std::to_string(Inspect.parent_frame_id) + std::string("'") );
if(depth != Inspect.frame_depth)
continue;
if(parent_id != Inspect.parent_frame_id)
continue;
if(Inspect.frame_index == frame_index)
{
return id;
}
frame_index ++;
}
return -1;
}
void HandlersManager::Timer()
{
std::vector<int> Ids;
{
LOCK_CONTEXT_LIST
Ids = std::move(NewContextCreatedIds);
NewContextCreatedIds.clear();
}
bool Updated = false;
for(HandlerUnit h:HandlerUnits)
{
if(h->Handler.get() && h->IsActive && h->IsContextCreated)
h->Handler->Timer();
if(std::find(Ids.begin(), Ids.end(), h->BrowserId) != Ids.end())
{
h->IsContextCreated = true;
Updated = true;
}
}
if(OriginalHandler.get() && OriginalHandler->Handler.get())
OriginalHandler->Handler->Timer();
auto i = HandlerUnits.begin();
while (i != HandlerUnits.end())
{
if(!(*i)->IsActive && (*i)->Handler->ref_count_.ref_count_ == 2 && (*i)->Handler->GetResourceListLength() == 0)
{
(*i)->Browser = 0;
MainHandler *h = (*i)->Handler.get();
(*i)->Handler = 0;
delete h;
i = HandlerUnits.erase(i);
Updated = true;
if(IsWaitForClosedCurrent)
IsClosedCurrent = true;
}else
{
MainHandler *h = (*i)->Handler.get();
CefPostTask(TID_IO, base::Bind(&MainHandler::CleanResourceHandlerList, h));
++i;
}
}
if(OriginalHandler)
{
MainHandler *h = OriginalHandler->Handler.get();
CefPostTask(TID_IO, base::Bind(&MainHandler::CleanResourceHandlerList, h));
}else
{
MainHandler *h = Handler.get();
CefPostTask(TID_IO, base::Bind(&MainHandler::CleanResourceHandlerList, h));
}
if(Updated)
{
UpdateMapBrowserIdToTabNumber();
UpdateCurrent();
}
}
void HandlersManager::Reset()
{
for(HandlerUnit h:HandlerUnits)
{
h->DontUseAsActive = true;
h->ForceShow = false;
if(h->Browser)
h->Browser->GetMainFrame()->ExecuteJavaScript("window.close();",h->Browser->GetMainFrame()->GetURL(),0);
}
if(OriginalHandler)
OriginalHandler->ForceShow = false;
UpdateCurrent();
}
void HandlersManager::PopupCreated(CefRefPtr<MainHandler> new_handler,CefRefPtr<CefBrowser> new_browser)
{
if(Browser)
{
Browser->GetHost()->SendFocusEvent(false);
}
HandlerUnit p = std::make_shared<HandlerUnitClass>();
p->Handler = new_handler;
p->Browser = new_browser;
p->BrowserId = new_browser->GetIdentifier();
p->IsActive = true;
p->DontUseAsActive = false;
p->Handler->EventLoadSuccess.clear();
p->Handler->EventPaint.clear();
p->Handler->EventSendTextResponce.clear();
p->Handler->EventUrlLoaded.clear();
p->Handler->EventPopupClosed.clear();
p->Handler->EventPopupCreated.clear();
p->Handler->EventOldestRequestTimeChanged.clear();
p->Handler->EventLoadSuccess.push_back(std::bind(&HandlersManager::LoadSuccess,this,_1));
p->Handler->EventPaint.push_back(std::bind(&HandlersManager::Paint,this,_1,_2,_3,_4));
p->Handler->EventSendTextResponce.push_back(std::bind(&HandlersManager::SendTextResponce,this,_1,_2));
p->Handler->EventUrlLoaded.push_back(std::bind(&HandlersManager::UrlLoaded,this,_1,_2,_3));
p->Handler->EventOldestRequestTimeChanged.push_back(std::bind(&HandlersManager::OldestRequestTimeChanged,this,_1,_2));
p->Handler->EventPopupClosed.push_back(std::bind(&HandlersManager::PopupRemoved,this,_1));
p->Handler->EventPopupCreated.push_back(std::bind(&HandlersManager::PopupCreated,this,_1,_2));
HandlerUnits.push_back(p);
OriginalHandler->ForceShow = false;
for(HandlerUnit ht:HandlerUnits)
ht->ForceShow = false;
UpdateMapBrowserIdToTabNumber();
UpdateCurrent();
}
void HandlersManager::PopupRemoved(int BrowserId)
{
for(HandlerUnit h:HandlerUnits)
{
if(h->BrowserId == BrowserId)
{
h->IsActive = false;
//if(DevToolsBorwserId == h->BrowserId)
{
for(auto f:EventNeedToCloseDevTools)
f();
}
}
}
UpdateCurrent();
}
void HandlersManager::SendTextResponce(const std::string& text, int BrowserId)
{
if(CurrentBrowserId == BrowserId)
SendTextResponceCallback(text);
}
void HandlersManager::UrlLoaded(const std::string& url, int status, int BrowserId)
{
if(CurrentBrowserId == BrowserId)
UrlLoadedCallback(url, status);
}
void HandlersManager::LoadSuccess(int BrowserId)
{
if(CurrentBrowserId == BrowserId)
LoadSuccessCallback();
}
void HandlersManager::Paint(char * data, int width, int height, int BrowserId)
{
if(CurrentBrowserId == BrowserId)
PaintCallback(data,width,height);
}
void HandlersManager::OldestRequestTimeChanged(int64 OldestTime, int BrowserId)
{
if(CurrentBrowserId == BrowserId)
OldestRequestTimeChangedCallback(OldestTime);
}
void HandlersManager::NewContextCreated(int ContextId)
{
LOCK_CONTEXT_LIST
NewContextCreatedIds.push_back(ContextId);
}
void HandlersManager::SetDevToolsBorwserId(int DevToolsBorwserId)
{
this->DevToolsBorwserId = DevToolsBorwserId;
}
std::vector<std::string> HandlersManager::GetAllUrls()
{
std::vector<std::string> res;
if(OriginalHandler)
res.push_back(OriginalHandler->Browser->GetMainFrame()->GetURL().ToString());
for(HandlerUnit h:HandlerUnits)
{
if(!h->DontUseAsActive && h->IsContextCreated)
{
res.push_back(h->Browser->GetMainFrame()->GetURL().ToString());
}
}
return res;
}
bool HandlersManager::CloseByIndex(int index)
{
if(index <= 0 || index - 1 >= HandlerUnits.size())
return false;
IsWaitForClosedCurrent = true;
IsClosedCurrent = false;
HandlerUnit h = HandlerUnits[index - 1];
h->DontUseAsActive = true;
h->ForceShow = false;
if(h->Browser)
{
h->Browser->GetMainFrame()->ExecuteJavaScript("window.close();",h->Browser->GetMainFrame()->GetURL(),0);
}
UpdateCurrent();
return true;
}
void HandlersManager::SwitchByIndex(int index)
{
if(Browser)
{
Browser->GetHost()->SendFocusEvent(false);
}
HandlerUnit h;
if(index <= 0)
{
h = OriginalHandler;
}else if(index - 1 < HandlerUnits.size())
{
h = HandlerUnits[index - 1];
}
if(OriginalHandler)
OriginalHandler->ForceShow = false;
for(HandlerUnit ht:HandlerUnits)
ht->ForceShow = false;
if(h && !h->DontUseAsActive)
{
h->ForceShow = true;
}
UpdateCurrent();
}
bool HandlersManager::CheckIsClosed()
{
if(IsWaitForClosedCurrent && IsClosedCurrent)
{
IsWaitForClosedCurrent = false;
IsClosedCurrent = false;
return true;
}
return false;
}
void HandlersManager::UpdateLocalStorageItem(const LocalStorageDataItem& item)
{
std::vector<HandlerUnit> all = HandlerUnits;
if(OriginalHandler)
all.push_back(OriginalHandler);
for(HandlerUnit h:HandlerUnits)
{
if(!h->DontUseAsActive && h->IsContextCreated)
{
all.push_back(h);
}
}
std::string jscode = "try{";
jscode += "BrowserAutomationStudio_UpdateLocalStorage(";
jscode += picojson::value(item.TypeString).serialize();
jscode += ",";
jscode += picojson::value(item.Key).serialize();
jscode += ",";
jscode += picojson::value(item.Value).serialize();
jscode += ",";
jscode += picojson::value(item.Domain).serialize();
jscode += ",";
jscode += picojson::value(double(item.FrameHash)).serialize();
jscode += ",";
jscode += picojson::value(item.Time).serialize();
jscode += ");";
jscode += "}catch(e){};";
for(HandlerUnit h:all)
{
std::vector<int64> identifiers;
h->Browser->GetFrameIdentifiers(identifiers);
for(int64 id:identifiers)
{
h->Browser->GetFrame(id)->ExecuteJavaScript(jscode,"", 0);
}
}
}
void HandlersManager::UpdateLocalStorageString(const std::string& data)
{
std::vector<HandlerUnit> all = HandlerUnits;
if(OriginalHandler)
all.push_back(OriginalHandler);
for(HandlerUnit h:HandlerUnits)
{
if(!h->DontUseAsActive && h->IsContextCreated)
{
all.push_back(h);
}
}
std::string jscode = "try{";
jscode += "BrowserAutomationStudio_RestoreLocalStorage(";
jscode += picojson::value(data).serialize();
jscode += ");";
jscode += "}catch(e){};";
for(HandlerUnit h:all)
{
std::vector<int64> identifiers;
h->Browser->GetFrameIdentifiers(identifiers);
for(int64 id:identifiers)
{
h->Browser->GetFrame(id)->ExecuteJavaScript(jscode,"", 0);
}
}
}
void HandlersManager::UpdateMapBrowserIdToTabNumber()
{
LOCK_MAP_BROWSER_ID_TO_TAB_NUMBER
MapBrowserIdToTabNumber.clear();
int index = 0;
if(OriginalHandler)
{
MapBrowserIdToTabNumber[OriginalHandler->BrowserId] = 0;
index++;
}
for(HandlerUnit h:HandlerUnits)
{
if(h->BrowserId >= 0)
MapBrowserIdToTabNumber[h->BrowserId] = index;
index++;
}
//WORKER_LOG(std::string("UpdateMapBrowserIdToTabNumber ") + std::to_string(MapBrowserIdToTabNumber.size()));
}
int HandlersManager::FindTabIdByBrowserId(int BrowserId)
{
LOCK_MAP_BROWSER_ID_TO_TAB_NUMBER
//WORKER_LOG(std::string("FindTabIdByBrowserIdSize ") + std::to_string(MapBrowserIdToTabNumber.size()));
auto it = MapBrowserIdToTabNumber.find(BrowserId);
if(it == MapBrowserIdToTabNumber.end())
return -1;
else
{
//WORKER_LOG(std::string("FindTabIdByBrowserId ") + std::to_string(it->first));
//WORKER_LOG(std::string("FindTabIdByBrowserId ") + std::to_string(it->second));
return it->second;
}
}
| 29.077419 | 470 | 0.605669 | [
"vector"
] |
bf272a7ef541eee6b5333935fa3e77ca51f4a3c2 | 2,533 | hpp | C++ | saga/impl/engine/io_service_pool.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | saga/impl/engine/io_service_pool.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | saga/impl/engine/io_service_pool.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | // Copyright (c) 2005-2010 Hartmut Kaiser
//
// Parts of this code were taken from the Boost.Asio library
// Copyright (c) 2003-2007 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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(SAGA_IMPL_ENGINE_IO_SERVICE_POOL_HPP)
#define SAGA_IMPL_ENGINE_IO_SERVICE_POOL_HPP
#include <vector>
#include <saga/saga/util.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace saga { namespace impl
{
/// A pool of io_service objects.
class io_service_pool : private boost::noncopyable
{
public:
/// \brief Construct the io_service pool.
/// \param pool_size
/// [in] The number of threads to run to serve incoming
/// requests
/// \param start_thread
/// [in]
explicit io_service_pool(std::size_t pool_size = 1);
/// \brief Run all io_service objects in the pool. If join_threads is true
/// this will also wait for all threads to complete
bool run(bool join_threads = false);
/// \brief Stop all io_service objects in the pool.
void stop();
/// \brief Join all io_service threads in the pool.
void join();
/// \brief Clear all internal data structures
void clear();
/// \brief
bool is_running() const { return !threads_.empty(); }
/// \brief Get an io_service to use.
boost::asio::io_service& get_io_service();
protected:
///
void thread_run(int index);
private:
typedef TR1::shared_ptr<boost::asio::io_service> io_service_ptr;
typedef TR1::shared_ptr<boost::asio::io_service::work> work_ptr;
/// The pool of io_services.
std::vector<io_service_ptr> io_services_;
std::vector<TR1::shared_ptr<boost::thread> > threads_;
/// The work that keeps the io_services running.
std::vector<work_ptr> work_;
/// The next io_service to use for a connection.
std::size_t next_io_service_;
/// set to true if stopped
bool stopped_;
/// initial number of OS threads to execute in this pool
std::size_t pool_size_;
};
}}
#endif
| 31.271605 | 82 | 0.610738 | [
"vector"
] |
bf2cb9858bcc4ba6e542a9001df6c74ecdb20d79 | 2,250 | hpp | C++ | data_structure/segment_tree.hpp | Mohammad-Yasser/competitive-programming-library | 4656ac0d625abce98b901965c7607c1b908b093f | [
"MIT"
] | 3 | 2020-02-09T18:58:30.000Z | 2021-03-19T01:21:24.000Z | data_structure/segment_tree.hpp | Mohammad-Yasser/competitive-programming-library | 4656ac0d625abce98b901965c7607c1b908b093f | [
"MIT"
] | null | null | null | data_structure/segment_tree.hpp | Mohammad-Yasser/competitive-programming-library | 4656ac0d625abce98b901965c7607c1b908b093f | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cassert>
#include <vector>
#include "utils/macros.hpp"
/**
* @brief a segment tree / セグメント木
* @tparam Monoid (commutativity is not required)
*/
template <class Monoid>
struct segment_tree {
typedef typename Monoid::value_type value_type;
const Monoid mon;
int n;
std::vector<value_type> a;
segment_tree() = default;
segment_tree(int n_, const Monoid & mon_ = Monoid()) : mon(mon_) {
n = 1; while (n < n_) n *= 2;
a.resize(2 * n - 1, mon.unit());
}
void point_set(int i, value_type b) { // 0-based
assert (0 <= i and i < n);
a[i + n - 1] = b;
for (i = (i + n) / 2; i > 0; i /= 2) { // 1-based
a[i - 1] = mon.mult(a[2 * i - 1], a[2 * i]);
}
}
value_type range_concat(int l, int r) { // 0-based, [l, r)
assert (0 <= l and l <= r and r <= n);
value_type lacc = mon.unit(), racc = mon.unit();
for (l += n, r += n; l < r; l /= 2, r /= 2) { // 1-based loop, 2x faster than recursion
if (l % 2 == 1) lacc = mon.mult(lacc, a[(l ++) - 1]);
if (r % 2 == 1) racc = mon.mult(a[(-- r) - 1], racc);
}
return mon.mult(lacc, racc);
}
value_type point_get(int i) { // 0-based
assert (0 <= i and i < n);
return a[i + n - 1];
}
/**
* @brief a fast & semigroup-friendly version constructor
* @note $O(n)$
*/
template <class InputIterator>
segment_tree(InputIterator first, InputIterator last, const Monoid & mon_ = Monoid()) : mon(mon_) {
int size = std::distance(first, last);
n = 1; while (n < size) n *= 2;
a.resize(2 * n - 1, mon.unit());
std::copy(first, last, a.begin() + (n - 1));
unsafe_rebuild();
}
/**
* @brief update a leaf node without updating ancestors
* @note $O(1)$
*/
void unsafe_point_set(int i, value_type b) { // 0-based
assert (0 <= i and i < n);
a[i + n - 1] = b;
}
/**
* @brief re-build non-leaf nodes from leaf nodes
* @note $O(n)$
*/
void unsafe_rebuild() {
REP_R (i, n - 1) {
a[i] = mon.mult(a[2 * i + 1], a[2 * i + 2]);
}
}
};
| 30.405405 | 103 | 0.499556 | [
"vector"
] |
bf3baf2817f2d93cc4ed9d64a0eb7a7e42cf2705 | 32,251 | cpp | C++ | src/openms/source/ANALYSIS/ID/ConsensusID.cpp | kreinert/OpenMS | 45455356482ce5ab35e32e445609b291ec78a6d6 | [
"Zlib",
"Apache-2.0"
] | 1 | 2016-12-09T01:45:03.000Z | 2016-12-09T01:45:03.000Z | src/openms/source/ANALYSIS/ID/ConsensusID.cpp | kreinert/OpenMS | 45455356482ce5ab35e32e445609b291ec78a6d6 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/ID/ConsensusID.cpp | kreinert/OpenMS | 45455356482ce5ab35e32e445609b291ec78a6d6 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Sven Nahnsen $
// $Authors: Sven Nahnsen and others $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/ID/ConsensusID.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/DATASTRUCTURES/SeqanIncludeWrapper.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <map>
#include <cmath>
// Extend SeqAn by a user-define scoring matrix.
namespace seqan
{
// We have to create a new specialization of the _ScoringMatrix class
// for amino acids. For this, we first create a new tag.
struct PAM30MS {};
// Then, we specialize the class _ScoringMatrix.
template <>
struct ScoringMatrixData_<int, AminoAcid, PAM30MS>
{
enum
{
VALUE_SIZE = ValueSize<AminoAcid>::VALUE,
TAB_SIZE = VALUE_SIZE * VALUE_SIZE
};
static inline int const * getData()
{
// DEFINE the PAM30MS matrix from Habermann et al. MCP. 2004.
static int const _data[TAB_SIZE] =
{
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -17,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -17,
-17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, -17, 1,
};
/*
{
6,-7,-4,-3,-6,-4,-2,-2,-7,-5,-6,-7,-5,-8,-2,0,-1,-13,-8,-2,-7,-6,0,-17,
-7,8,-6,-10,-8,-2,-9,-9,-2,-5,-7,0,-4,-9,-4,-3,-6,-2,-10,-8,5,-1,0,-17,
-4,-6,8,2,-11,-3,-2,-3,0,-5,-6,-1,-9,-9,-6,0,-2,-8,-4,-8,-4,-2,0,-17,
-3,-10,2,8,-14,-2,2,-3,-4,-7,-10,-4,-11,-15,-8,-4,-5,-15,-11,-8,-7,-3,0,-17,
-6,-8,-11,-14,10,-14,-14,-9,-7,-6,-11,-14,-13,-13,-8,-3,-8,-15,-4,-6,-11,-14,0,-17,
-4,-2,-3,-2,-14,8,1,-7,1,-8,-7,-3,-4,-13,-3,-5,-5,-13,-12,-7,-3,4,0,-17,
-2,-9,-2,2,-14,1,8,-4,-5,-5,-7,-4,-7,-14,-5,-4,-6,-17,-8,-6,-7,-2,0,-17,
-2,-9,-3,-3,-9,-7,-4,6,-9,-11,-11,-7,-8,-9,-6,-2,-6,-15,-14,-5,-8,-7,0,-17,
-7,-2,0,-4,-7,1,-5,-9,9,-9,-8,-6,-10,-6,-4,-6,-7,-7,-3,-6,-4,-3,0,-17,
-5,-5,-5,-7,-6,-8,-5,-11,-9,8,5,-6,-1,-2,-8,-7,-2,-14,-6,2,-6,-7,0,-17,
-6,-7,-6,-10,-11,-7,-7,-11,-8,5,5,-7,0,-3,-8,-8,-5,-10,-7,0,-7,-7,0,-17,
-7,0,-1,-4,-14,-3,-4,-7,-6,-6,-7,7,-2,-14,-6,-4,-3,-12,-9,-9,5,4,0,-17,
-5,-4,-9,-11,-13,-4,-7,-8,-10,-1,0,-2,11,-4,-8,-5,-4,-13,-11,-1,-3,-3,0,-17,
-8,-9,-9,-15,-13,-13,-14,-9,-6,-2,-3,-14,-4,9,-10,-6,-9,-4,2,-8,-12,-14,0,-17,
-2,-4,-6,-8,-8,-3,-5,-6,-4,-8,-8,-6,-8,-10,8,-2,-4,-14,-13,-6,-5,-5,0,-17,
0,-3,0,-4,-3,-5,-4,-2,-6,-7,-8,-4,-5,-6,-2,6,0,-5,-7,-6,-4,-5,0,-17,
-1,-6,-2,-5,-8,-5,-6,-6,-7,-2,-5,-3,-4,-9,-4,0,7,-13,-6,-3,-5,-4,0,-17,
-13,-2,-8,-15,-15,-13,-17,-15,-7,-14,-10,-12,-13,-4,-14,-5,-13,13,-5,-15,-7,-13,0,-17,
-8,-10,-4,-11,-4,-12,-8,-14,-3,-6,-7,-9,-11,2,-13,-7,-6,-5,10,-7,-10,-11,0,-17,
-2,-8,-8,-8,-6,-7,-6,-5,-6,2,0,-9,-1,-8,-6,-6,-3,-15,-7,7,-9,-8,0,-17,
-7,5,-4,-7,-11,-3,-7,-8,-4,-6,-7,5,-3,-12,-5,-4,-5,-7,-10,-9,5,1,0,-17,
-6,-1,-2,-3,-14,4,-2,-7,-3,-7,-7,4,-3,-14,-5,-5,-4,-13,-11,-8,1,4,0,-17,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-17,
-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,1,
};*/
return _data;
}
};
} // namespace seqan
using namespace std;
#define DEBUG_ID_CONSENSUS
#undef DEBUG_ID_CONSENSUS
namespace OpenMS
{
ConsensusID::ConsensusID() :
DefaultParamHandler("ConsensusID")
{
defaults_.setValue("algorithm", "PEPMatrix", "Algorithm used for the consensus scoring.\n"
"ranked -- reorders the hits according to a consensus score computed from the ranks in the input runs. The score is normalized to the interval (0,100). The PeptideIdentifications do not need to have the same score type.\n"
"average -- reorders the hits according to the average score of the input runs. Make sure to use PeptideIdentifications with the same score type only!\n"
"PEPMatrix -- calculates a consensus score based on posterior error probabilities and scoring matrices for siimilarity. This algorithm uses the PAM30MS matrix to score sequences not listed by all engines. Make sure to use PeptideIdentifications with score types converted to PEPs only!\n"
"PEPIons -- calculates a consensus score based on posterior error probabilities and fragment ion siimilarity. Make sure to use PeptideIdentifications with score types converted to PEPs only!\n"
"Minimum -- calculates a consensus score based on the minimal score. Make sure to use PeptideIdentifications with score types converted to PEPs only!\n");
defaults_.setValidStrings("algorithm", ListUtils::create<String>("ranked,average,PEPMatrix,PEPIons,Minimum"));
defaults_.setValue("considered_hits", 10, "The number of top hits that are used for the consensus scoring.");
defaults_.setMinInt("considered_hits", 1);
defaults_.setValue("PEPIons:MinNumberOfFragments", 2, "The minimal number of similar (between two suggested sequences) fragment ion masses that is necessary to evaluate the shared peak count similarity (SPC).");
defaults_.setMinInt("PEPIons:MinNumberOfFragments", 0);
defaults_.setValue("number_of_runs", 0, "The number of runs used as input. This information is used in 'Ranked' and 'Average' to compute the new scores. If not given, the number of input identifications is taken.");
defaults_.setMinInt("number_of_runs", 0);
defaults_.setValue("PEPMatrix:common", 1.1, "Similarity threshold to accept the best score. E.g. for a given spectrum: engine 1 -> pep 1 with score x1 and engine2 -> pep2 with score x2. The better score from {x1,x2} will be used if the degree of similarity between pep1 and pep2 >= common, Note that 0 <= degree of similarity <= 1. Values > 1 will disable this option.");
defaults_.setMinFloat("PEPMatrix:common", 0);
defaults_.setMaxFloat("PEPMatrix:common", 1.1);
defaults_.setValue("PEPMatrix:penalty", 5, "Give the gap penalty (the same penalty will be used for opening and extension) as a positive integer");
defaults_.setValue("PEPIons:common", 1.1, "Similarity threshold to accept the best score. E.g. for a given spectrum: engine 1 -> pep 1 with score x1 and engine2 -> pep2 with score x2. The better score from {x1,x2} will be used if the degree of similarity between pep1 and pep2 >= common, Note that 0 <= degree of similarity <= 1. Values > 1 will disable this option.");
defaults_.setMinFloat("PEPIons:common", 0);
defaults_.setMaxFloat("PEPIons:common", 1.1);
defaultsToParam_();
}
void ConsensusID::apply(vector<PeptideIdentification> & ids)
{
//Abort if no IDs present
if (ids.empty())
{
return;
}
String algorithm = param_.getValue("algorithm");
if (algorithm == "PEPMatrix")
{
PEPMatrix_(ids);
}
else if (algorithm == "PEPIons")
{
PEPIons_(ids);
}
else if (algorithm == "ranked")
{
ranked_(ids);
}
else if (algorithm == "average")
{
average_(ids);
}
else if (algorithm == "Minimum")
{
Minimum_(ids);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__, "Algorithm '" + algorithm + "' was used but is not known! Please fix to something valid: " + ListUtils::concatenate(StringList(defaults_.getEntry("algorithm").valid_strings), ", ") + "!");
}
ids[0].assignRanks();
#ifdef DEBUG_ID_CONSENSUS
const vector<PeptideHit> & hits2 = ids[0].getHits();
for (Size i = 0; i < hits2.size(); ++i)
{
cout << " " << hits2[i].getSequence() << " " << hits2[i].getScore() << endl;
}
#endif
}
void ConsensusID::ranked_(vector<PeptideIdentification> & ids)
{
map<AASequence, DoubleReal> scores;
UInt considered_hits = (UInt)(param_.getValue("considered_hits"));
UInt number_of_runs = (UInt)(param_.getValue("number_of_runs"));
//iterate over the different ID runs
for (vector<PeptideIdentification>::iterator id = ids.begin(); id != ids.end(); ++id)
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - ID run" << endl;
#endif
//make sure that the ranks are present
id->assignRanks();
//iterate over the hits
UInt hit_count = 1;
for (vector<PeptideHit>::const_iterator hit = id->getHits().begin(); hit != id->getHits().end() && hit_count <= considered_hits; ++hit)
{
if (scores.find(hit->getSequence()) == scores.end())
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - New hit: " << hit->getSequence() << " " << hit->getRank() << endl;
#endif
scores.insert(make_pair(hit->getSequence(), DoubleReal(considered_hits + 1 - hit->getRank())));
}
else
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - Added hit: " << hit->getSequence() << " " << hit->getRank() << endl;
#endif
scores[hit->getSequence()] += (considered_hits + 1 - hit->getRank());
}
++hit_count;
}
}
//divide score by the maximum possible score and multiply with 100 => %
Size max_score;
if (number_of_runs == 0)
{
max_score = ids.size() * considered_hits;
}
else
{
max_score = number_of_runs * considered_hits;
}
for (map<AASequence, DoubleReal>::iterator it = scores.begin(); it != scores.end(); ++it)
{
it->second = (it->second * 100.0f / max_score);
}
// replace IDs by consensus
ids.clear();
ids.resize(1);
ids[0].setScoreType("Consensus_averaged");
for (map<AASequence, DoubleReal>::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
PeptideHit hit;
hit.setSequence(it->first);
hit.setScore(it->second);
ids[0].insertHit(hit);
}
}
void ConsensusID::average_(vector<PeptideIdentification> & ids)
{
map<AASequence, DoubleReal> scores;
UInt considered_hits = (UInt)(param_.getValue("considered_hits"));
UInt number_of_runs = (UInt)(param_.getValue("number_of_runs"));
//store the score type (to make sure only IDs of the same type are averaged)
String score_type = ids[0].getScoreType();
bool higher_better = ids[0].isHigherScoreBetter();
//iterate over the different ID runs
for (vector<PeptideIdentification>::iterator id = ids.begin(); id != ids.end(); ++id)
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - ID run" << endl;
#endif
//make sure that the ranks are present
id->assignRanks();
//iterate over the hits
UInt hit_count = 1;
for (vector<PeptideHit>::const_iterator hit = id->getHits().begin(); hit != id->getHits().end() && hit_count <= considered_hits; ++hit)
{
//check the score type
if (id->getScoreType() != score_type)
{
cerr << "Warning: You are averaging different types of scores: '" << score_type << "' and '" << id->getScoreType() << "'" << endl;
}
if (id->isHigherScoreBetter() != higher_better)
{
cerr << "Warning: The score of the identifications have disagreeing score orientation!" << endl;
}
if (scores.find(hit->getSequence()) == scores.end()) //.end zeigt auf ein Element nach dem letzten
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - New hit: " << hit->getSequence() << " " << hit->getScore() << endl;
#endif
scores.insert(make_pair(hit->getSequence(), hit->getScore()));
}
else
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - Summed up: " << hit->getSequence() << " " << hit->getScore() << endl;
#endif
scores[hit->getSequence()] += hit->getScore();
}
++hit_count;
}
}
//normalize score by number of id runs
for (map<AASequence, DoubleReal>::iterator it = scores.begin(); it != scores.end(); ++it)
{
if (number_of_runs == 0)
{
it->second = (it->second / ids.size());
}
else
{
it->second = (it->second / number_of_runs);
}
}
//Replace IDs by consensus
ids.clear();
ids.resize(1);
ids[0].setScoreType(String("Consensus_averaged (") + score_type + ")");
ids[0].setHigherScoreBetter(higher_better);
for (map<AASequence, DoubleReal>::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
PeptideHit hit;
hit.setSequence(it->first);
hit.setScore(it->second);
ids[0].insertHit(hit);
#ifdef DEBUG_ID_CONSENSUS
cout << " - Output hit: " << hit.getSequence() << " " << hit.getScore() << endl;
#endif
}
}
//////////////////////////////////////////PEPMatrix
void ConsensusID::PEPMatrix_(vector<PeptideIdentification> & ids)
{
Map<AASequence, vector<DoubleReal> > scores;
UInt considered_hits = (UInt)(param_.getValue("considered_hits"));
int penalty = (UInt)param_.getValue("PEPMatrix:penalty");
DoubleReal common = (double)param_.getValue("PEPMatrix:common");
String score_type = ids[0].getScoreType();
bool higher_better = ids[0].isHigherScoreBetter();
for (vector<PeptideIdentification>::iterator id = ids.begin(); id != ids.end(); ++id)
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - ID run" << endl;
#endif
//make sure that the ranks are present
id->assignRanks();
//iterate over the hits
UInt hit_count = 1;
for (vector<PeptideHit>::const_iterator hit = id->getHits().begin(); hit != id->getHits().end() && hit_count <= considered_hits; ++hit)
{
//check the score type
if (id->getScoreType() != score_type)
{
cerr << "Warning: You are working with different types of scores: '" << score_type << "' and '" << id->getScoreType() << "'" << endl;
}
if (id->isHigherScoreBetter() != higher_better)
{
cerr << "Warning: The score of the identifications have disagreeing score orientation!" << endl;
}
if (!higher_better)
{
cerr << "You need to calculate posterior error probabilities as input scores!" << endl;
}
DoubleReal a_score = (double)hit->getScore();
DoubleReal a_sim = 1;
DoubleReal NumberAnnots = 1;
set<String> myset;
for (vector<PeptideHit>::const_iterator t = id->getHits().begin(); t != id->getHits().end(); ++t)
{
if (myset.find(t->getMetaValue("scoring")) == myset.end() && hit->getMetaValue("scoring") != t->getMetaValue("scoring"))
{
DoubleReal a = 0;
DoubleReal zz = 0;
vector<DoubleReal> z;
z.push_back((double)hit->getScore());
// find the same or most similar peptide sequence in lists from other search engines
for (vector<PeptideHit>::const_iterator tt = id->getHits().begin(); tt != id->getHits().end(); ++tt)
{
if (! (hit->getMetaValue("scoring") != t->getMetaValue("scoring"))) exit(1);
if (tt->getMetaValue("scoring") == t->getMetaValue("scoring"))
{
//use SEQAN similarity scoring
typedef::seqan::String< ::seqan::AminoAcid > TSequence;
TSequence seq1 = tt->getSequence().toUnmodifiedString().c_str();
TSequence seq2 = hit->getSequence().toUnmodifiedString().c_str();
/////////////////////////introduce scoring with PAM30MS
typedef int TValue;
typedef::seqan::Score<TValue, ::seqan::ScoreMatrix< ::seqan::AminoAcid, ::seqan::Default> > TScoringScheme;
TScoringScheme pam30msScoring(-penalty, -penalty);
::seqan::setDefaultScoreMatrix(pam30msScoring, ::seqan::PAM30MS());
/////////////////////////introduce scoring with PAM30MS
//You can also use normal mutation based matrices, such as BLOSUM or the normal PAM matrix
::seqan::Pam250 pam(-5, -5);
//::seqan::Score<int, ::seqan::Pam<> > pam(30, -10, -10);
::seqan::Align<TSequence, ::seqan::ArrayGaps> align, self1, self2;
::seqan::resize(rows(align), 2);
::seqan::resize(rows(self1), 2);
::seqan::resize(rows(self2), 2);
::seqan::assignSource(row(align, 0), seq1);
::seqan::assignSource(row(align, 1), seq2);
::seqan::assignSource(row(self1, 0), seq1);
::seqan::assignSource(row(self1, 1), seq1);
::seqan::assignSource(row(self2, 0), seq2);
::seqan::assignSource(row(self2, 1), seq2);
vector<DoubleReal> temp;
temp.push_back(globalAlignment(self1, pam30msScoring, ::seqan::NeedlemanWunsch()));
temp.push_back(globalAlignment(self2, pam30msScoring, ::seqan::NeedlemanWunsch()));
DoubleReal c = (DoubleReal)globalAlignment(align, pam30msScoring, ::seqan::NeedlemanWunsch());
DoubleReal b = *(min_element(temp.begin(), temp.end()));
c /= b;
if (c < 0)
{
c = 0;
}
if (c > a)
{
a = c;
if (a >= common)
{
z.push_back((double)tt->getScore());
zz = *(min_element(z.begin(), z.end()));
}
else
{
zz = (double)tt->getScore() * a;
}
}
}
}
if (a >= common)
{
a_sim += 1;
}
else
{
a_sim += a;
}
NumberAnnots += 1;
a_score += zz;
myset.insert(t->getMetaValue("scoring"));
}
}
// the meta value similarity corresponds to the sum of the similarities.
// Note: if similarity equals the number of search engines, the same peptide has been assigned by all engines
//::std::cout <<hit->getSequence()<<" a_score="<<a_score<<" a_sim="<< a_sim <<::std::endl;
vector<DoubleReal> ScoreSim;
//test
ScoreSim.push_back(a_score / (a_sim * a_sim));
ScoreSim.push_back(a_sim);
ScoreSim.push_back(NumberAnnots);
ScoreSim.push_back(hit->getCharge());
scores.insert(make_pair(hit->getSequence(), ScoreSim));
++hit_count;
}
}
//Replace IDs by consensus
ids.clear();
ids.resize(1);
ids[0].setScoreType(String("Consensus_PEPMatrix (") + score_type + ")");
ids[0].setHigherScoreBetter(false);
for (Map<AASequence, vector<DoubleReal> >::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
PeptideHit hit;
hit.setSequence(it->first);
hit.setScore(it->second[0]);
hit.setMetaValue("similarity", it->second[1]);
hit.setMetaValue("Number of annotations", it->second[2]);
hit.setCharge(it->second[3]);
ids[0].insertHit(hit);
#ifdef DEBUG_ID_CONSENSUS
cout << " - Output hit: " << hit.getSequence() << " " << hit.getScore() << endl;
#endif
}
}
///////////////////////////////////////////////PEPIons
void ConsensusID::PEPIons_(vector<PeptideIdentification> & ids)
{
Map<AASequence, vector<DoubleReal> > scores;
UInt considered_hits = (UInt)(param_.getValue("considered_hits"));
UInt MinNumberOfFragments = (UInt)(param_.getValue("PEPIons:MinNumberOfFragments"));
String score_type = ids[0].getScoreType();
bool higher_better = ids[0].isHigherScoreBetter();
DoubleReal common = (double)param_.getValue("PEPIons:common");
for (vector<PeptideIdentification>::iterator id = ids.begin(); id != ids.end(); ++id)
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - ID run" << endl;
#endif
//make sure that the ranks are present
id->assignRanks();
//iterate over the hits
UInt hit_count = 1;
for (vector<PeptideHit>::const_iterator hit = id->getHits().begin(); hit != id->getHits().end() && hit_count <= considered_hits; ++hit)
{
//check the score type
if (id->getScoreType() != score_type)
{
cerr << "Warning: You are working with different types of scores: '" << score_type << "' and '" << id->getScoreType() << "'" << endl;
}
if (id->isHigherScoreBetter() != higher_better)
{
cerr << "Warning: The score of the identifications have disagreeing score orientation!" << endl;
}
if (!higher_better)
{
cerr << "You need to calculate posterior error probabilities as input scores!" << endl;
}
//DoubleReal a_score=(double)hit->getMetaValue("PEP");
DoubleReal a_score = (double)hit->getScore();
DoubleReal a_sim = 1;
DoubleReal NumberAnnots = 1;
set<String> myset;
for (vector<PeptideHit>::const_iterator t = id->getHits().begin(); t != id->getHits().end(); ++t)
{
if (myset.find(t->getMetaValue("scoring")) == myset.end() && hit->getMetaValue("scoring") != t->getMetaValue("scoring"))
{
DoubleReal a = 0;
UInt SumIonSeries = 2;
DoubleReal zz = 0;
vector<DoubleReal> z;
z.push_back((double)hit->getScore());
//find the same or most similar peptide sequence in lists from other search engines
for (vector<PeptideHit>::const_iterator tt = id->getHits().begin(); tt != id->getHits().end(); ++tt)
{
PeptideHit k = *tt;
if (hit->getMetaValue("scoring") != t->getMetaValue("scoring") && tt->getMetaValue("scoring") == t->getMetaValue("scoring"))
{
//use similarity of b and y ion series for scoring
AASequence S1, S2;
S1 = tt->getSequence();
S2 = hit->getSequence();
//compare b and y ion series of S1 and S2
vector<DoubleReal> Yions_S1, Yions_S2, Bions_S1, Bions_S2;
for (UInt r = 1; r <= S1.size(); ++r)
{
Yions_S1.push_back(S1.getPrefix(r).getMonoWeight());
Bions_S1.push_back(S1.getSuffix(r).getMonoWeight());
}
for (UInt r = 1; r <= S2.size(); ++r)
{
Yions_S2.push_back(S2.getPrefix(r).getMonoWeight());
Bions_S2.push_back(S2.getSuffix(r).getMonoWeight());
}
UInt Bs = 0;
UInt Ys = 0;
for (UInt xx = 0; xx < Yions_S1.size(); ++xx)
{
for (UInt yy = 0; yy < Yions_S2.size(); ++yy)
{
if (fabs(Yions_S1[xx] - Yions_S2[yy]) <= 1)
{
Ys += 1;
}
}
}
for (UInt xx = 0; xx < Bions_S1.size(); ++xx)
{
for (UInt yy = 0; yy < Bions_S2.size(); ++yy)
{
if (fabs(Bions_S1[xx] - Bions_S2[yy]) <= 1)
{
Bs += 1;
}
}
}
vector<UInt> tmp;
tmp.push_back(Ys);
tmp.push_back(Bs);
UInt sum_tmp;
sum_tmp = Bs + Ys;
//# matching ions/number of AASeqences(S1)
DoubleReal c, b;
b = *(min_element(tmp.begin(), tmp.end()));
c = b / S1.size();
if (sum_tmp > SumIonSeries && sum_tmp > MinNumberOfFragments)
{
SumIonSeries = sum_tmp;
a = c;
if (a >= common)
{
z.push_back((double)tt->getScore());
zz = *(min_element(z.begin(), z.end()));
}
else
{
zz = (double)tt->getScore() * a;
}
}
}
}
NumberAnnots += 1;
a_score += zz;
a_sim += a;
myset.insert(t->getMetaValue("scoring"));
}
}
//the meta value similarity corresponds to the sum of the similarities. Note that if similarity equals the number of search engines, the
//same peptide has been assigned by all engines
vector<DoubleReal> ScoreSim;
ScoreSim.push_back(a_score / (a_sim * a_sim));
ScoreSim.push_back(a_sim);
ScoreSim.push_back(NumberAnnots);
ScoreSim.push_back(hit->getCharge());
scores.insert(make_pair(hit->getSequence(), ScoreSim));
++hit_count;
}
}
//Replace IDs by consensus
ids.clear();
ids.resize(1);
ids[0].setScoreType(String("Consensus_PEPIons (") + score_type + ")");
ids[0].setHigherScoreBetter(false);
for (Map<AASequence, vector<DoubleReal> >::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
PeptideHit hit;
hit.setSequence(it->first);
hit.setScore(it->second[0]);
hit.setMetaValue("similarity", it->second[1]);
hit.setMetaValue("Number of annotations", it->second[2]);
hit.setCharge(it->second[3]);
ids[0].insertHit(hit);
#ifdef DEBUG_ID_CONSENSUS
cout << " - Output hit: " << hit.getSequence() << " " << hit.getScore() << endl;
#endif
}
}
//////////////////////////////////////////////////////////////////////////////////Minimum
void ConsensusID::Minimum_(vector<PeptideIdentification> & ids)
{
Map<AASequence, DoubleReal> scores;
UInt considered_hits = (UInt)(param_.getValue("considered_hits"));
String score_type = ids[0].getScoreType();
bool higher_better = ids[0].isHigherScoreBetter();
if (higher_better == true)
{
cerr << "Warning: The score orientation is not suitable to take the minimum as the best hit!" << endl;
}
for (vector<PeptideIdentification>::iterator id = ids.begin(); id != ids.end(); ++id)
{
#ifdef DEBUG_ID_CONSENSUS
cout << " - ID run" << endl;
#endif
//make sure that the ranks are present
id->assignRanks();
//iterate over the hits
UInt hit_count = 1;
DoubleReal a_score = 1;
AASequence a_pep;
for (vector<PeptideHit>::const_iterator hit = id->getHits().begin(); hit != id->getHits().end() && hit_count <= considered_hits; ++hit)
{
if (hit->getScore() < a_score)
{
a_score = hit->getScore();
a_pep = hit->getSequence();
}
}
scores.insert(make_pair(a_pep, a_score));
++hit_count;
}
//Replace IDs by consensus
ids.clear();
ids.resize(1);
ids[0].setScoreType(String("Consensus_Minimum(") + score_type + ")");
ids[0].setHigherScoreBetter(false);
for (Map<AASequence, DoubleReal>::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
PeptideHit hit;
hit.setSequence(it->first);
hit.setScore(it->second);
ids[0].insertHit(hit);
}
#ifdef DEBUG_ID_CONSENSUS
cout << " - Output hit: " << hit.getSequence() << " " << hit.getScore() << endl;
#endif
}
/* this is not used by anyone ... delete?? */
void ConsensusID::mapIdentifications_(vector<PeptideIdentification> & sorted_ids, const vector<PeptideIdentification> & ids)
{
DoubleReal mz_delta = 0.01;
DoubleReal rt_delta = 0.01;
for (vector<PeptideIdentification>::const_iterator it1 = ids.begin(); it1 != ids.end(); ++it1)
{
DoubleReal rt1(it1->getMetaValue("RT"));
DoubleReal mz1(it1->getMetaValue("MZ"));
PeptideIdentification new_ids;
for (vector<PeptideIdentification>::const_iterator it2 = it1 + 1; it2 != ids.end(); ++it2)
{
DoubleReal rt2(it2->getMetaValue("RT"));
DoubleReal mz2(it2->getMetaValue("MZ"));
if (fabs(rt1 - rt2) < rt_delta && fabs(mz1 - mz2) < mz_delta)
{
if (new_ids.empty())
{
new_ids = (*it1);
}
else
{
for (vector<PeptideHit>::const_iterator pit = it2->getHits().begin(); pit != it2->getHits().end(); ++pit)
{
new_ids.insertHit(*pit);
}
}
}
}
sorted_ids.push_back(new_ids);
}
return;
}
} // namespace OpenMS
| 41.830091 | 375 | 0.54513 | [
"vector"
] |
bf3cb7c23e5c6b77b503e5e42de84588d460c86f | 1,072 | cpp | C++ | level_1/2016.cpp | nominated93/Algorithm | e930aa454aa052294246384fa232bd00ce530e69 | [
"CECILL-B",
"SGI-B-2.0"
] | null | null | null | level_1/2016.cpp | nominated93/Algorithm | e930aa454aa052294246384fa232bd00ce530e69 | [
"CECILL-B",
"SGI-B-2.0"
] | null | null | null | level_1/2016.cpp | nominated93/Algorithm | e930aa454aa052294246384fa232bd00ce530e69 | [
"CECILL-B",
"SGI-B-2.0"
] | null | null | null | #include <string>
#include <vector>
using namespace std;
string daysArr[] = {
"SUN"
, "MON"
, "TUE"
, "WED"
, "THU"
, "FRI"
, "SAT"
};
int monthsArr[] = {
31
, 28
, 31
, 30
, 31
, 30
, 31
, 31
, 30
, 31
, 30
, 31
};
bool IsLeafYear(int year){
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
return true;
}
return false;
}
string solution(int a, int b) {
const int CUR_YEAR = 2016;
const int YEAR_DAY = 365;
const int WEEK_DAY = 7;
string answer = "";
int yearDay = 0;
if(IsLeafYear(CUR_YEAR)){
monthsArr[1] = 29;
if(a >= 3) { // 해당년도 윤년일 경우 1일 추가 보정
yearDay++;
};
};
int month_day = 0;
for(int i = 0; i < a - 1; i++){
month_day += monthsArr[i];
}
int preYear = CUR_YEAR-1;
yearDay = preYear * YEAR_DAY + (preYear/4 - preYear/100 + preYear/400); // 윤년 일수 보정
answer = daysArr[(yearDay + month_day + b) % WEEK_DAY];
return answer;
}
| 16.492308 | 87 | 0.472948 | [
"vector"
] |
bf41f46ed73db96cf79b8de7e849684c9f75283c | 1,544 | hpp | C++ | include/Core/Castor3D/Render/Technique/Opaque/Lighting/LightPass.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | include/Core/Castor3D/Render/Technique/Opaque/Lighting/LightPass.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | include/Core/Castor3D/Render/Technique/Opaque/Lighting/LightPass.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | /*
See LICENSE file in root folder
*/
#ifndef ___C3D_DeferredLightPass_H___
#define ___C3D_DeferredLightPass_H___
#include "LightingModule.hpp"
#include "Castor3D/Render/ShadowMap/ShadowMapModule.hpp"
#include "Castor3D/Shader/Shaders/SdwModule.hpp"
namespace castor3d
{
class LightPass
{
public:
/**
*\~english
*\brief Retrieves the vertex shader source for this light pass.
*\param[in] sceneFlags The scene flags.
*\return The source.
*\~french
*\brief Récupère le source du vertex shader pour cette passe lumineuse.
*\param[in] sceneFlags Les indicateurs de scène.
*\return Le source.
*/
static ShaderPtr getVertexShaderSource( LightType lightType );
/**
*\~english
*\brief Retrieves the pixel shader source for this light pass.
*\param[in] sceneFlags The scene flags.
*\param[in] lightType The light source type.
*\param[in] shadowType The shadow type.
*\param[in] rsm Tells if RSM are to be generated.
*\return The source.
*\~french
*\brief Récupère le source du pixel shader pour cette passe lumineuse.
*\param[in] sceneFlags Les indicateurs de scène.
*\param[in] lightType Le type de source lumineuse.
*\param[in] shadowType Le type d'ombres.
*\param[in] rsm Dit si les RSM doivent être générées.
*\return Le source.
*/
static ShaderPtr getPixelShaderSource( PassTypeID passType
, RenderSystem const & renderSystem
, SceneFlags const & sceneFlags
, LightType lightType
, ShadowType shadowType
, bool shadows );
};
}
#endif
| 29.132075 | 75 | 0.715674 | [
"render"
] |
bf47b65927158bbc216e4ed4ba4847b8a21f66f6 | 4,303 | hpp | C++ | qd/cae/dyna_cpp/dyna/binout/Binout.hpp | martinventer/musical-dollop | debb36b87551a68fddee16a3d1194f9961d13756 | [
"MIT"
] | 104 | 2017-08-29T19:33:53.000Z | 2022-03-19T11:36:05.000Z | qd/cae/dyna_cpp/dyna/binout/Binout.hpp | martinventer/musical-dollop | debb36b87551a68fddee16a3d1194f9961d13756 | [
"MIT"
] | 72 | 2017-08-10T10:59:43.000Z | 2021-10-06T19:06:50.000Z | qd/cae/dyna_cpp/dyna/binout/Binout.hpp | martinventer/musical-dollop | debb36b87551a68fddee16a3d1194f9961d13756 | [
"MIT"
] | 37 | 2017-11-20T14:00:56.000Z | 2022-03-09T17:19:06.000Z |
#ifndef BINOUT_HPP
#define BINOUT_HPP
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
extern "C"
{
#include <dyna_cpp/dyna/binout/lsda/lsda.h>
}
#include <dyna_cpp/math/Tensor.hpp>
namespace qd {
class Binout
{
public:
enum class EntryType
{
UNKNOWN,
DIRECTORY = 0,
INT8 = 1,
INT16 = 2,
INT32 = 3,
INT64 = 4,
UINT8 = 5,
UINT16 = 6,
UINT32 = 7,
UINT64 = 8,
FLOAT32 = 9,
FLOAT64 = 10,
LINK = 11
};
private:
int fhandle;
std::string filepath;
template<typename T>
bool _type_is_same(EntryType entry_type);
public:
Binout(const std::string& filepath);
~Binout();
void cd(const std::string& _path);
bool exists(const std::string& _path);
bool has_children(const std::string& _path);
bool is_variable(const std::string& _path);
EntryType get_type_id(std::string path);
std::vector<std::string> get_children(const std::string& _folder_name = ".");
template<typename T>
Tensor_ptr<T> read_variable(const std::string& _path);
};
/** Check if LSDA type matches the C++ type
*
* @param entry_type
*/
template<typename T>
bool
Binout::_type_is_same(EntryType entry_type)
{
if (entry_type == EntryType::INT8 && typeid(T) == typeid(int8_t))
return true;
else if (entry_type == EntryType::INT16 && typeid(T) == typeid(int16_t))
return true;
else if (entry_type == EntryType::INT32 && typeid(T) == typeid(int32_t))
return true;
else if (entry_type == EntryType::INT64 && typeid(T) == typeid(int64_t))
return true;
else if (entry_type == EntryType::UINT8 && typeid(T) == typeid(uint8_t))
return true;
else if (entry_type == EntryType::UINT16 && typeid(T) == typeid(uint16_t))
return true;
else if (entry_type == EntryType::UINT32 && typeid(T) == typeid(uint32_t))
return true;
else if (entry_type == EntryType::UINT64 && typeid(T) == typeid(uint64_t))
return true;
else if (entry_type == EntryType::FLOAT32 && typeid(T) == typeid(float))
return true;
else if (entry_type == EntryType::FLOAT64 && typeid(T) == typeid(double))
return true;
else
return false;
}
/** Read the variable data
*
* @param path : path to the variable
* @return tensor_ptr : tensor instance
*/
template<typename T>
Tensor_ptr<T>
Binout::read_variable(const std::string& path)
{
if (!this->exists(path))
throw(std::invalid_argument("Path " + path + " does not exist."));
if (!this->is_variable(path))
throw(
std::invalid_argument("Path " + path + " does not point to a variable."));
auto entry_type = this->get_type_id(path);
if (entry_type == EntryType::UNKNOWN)
throw(std::runtime_error("Path " + path +
" caused an error in Binout.read_variable. This "
"should never happen ..."));
else if (entry_type == EntryType::DIRECTORY)
throw(std::invalid_argument(
"Path " + path + " does point to a DIRECTORY and not to a variable."));
else if (entry_type == EntryType::LINK)
throw(std::invalid_argument(
"Path " + path + " does point to a LINK and not to a variable."));
else if (!this->_type_is_same<T>(entry_type))
throw(std::runtime_error(
"C++ Tensor type does not match Binout variable type."));
size_t length = 0;
int32_t type_id = -1;
int32_t filenum = -1;
lsda_queryvar(this->fhandle, (char*)&path[0], &type_id, &length, &filenum);
if (type_id < 0)
throw(std::invalid_argument(
"Binout.read_variable encountered an error on: " + path));
auto tensor_ptr = std::make_shared<Tensor<T>>();
tensor_ptr->resize({ length });
auto& data = tensor_ptr->get_data();
size_t ret = lsda_lread(this->fhandle,
static_cast<int32_t>(type_id),
(char*)&path[0], // path
0, // offset
length, // length
(void*)&data[0]); // data
// I know this is dumb, but dyna defines an unsigned type with -1 in case of
// an error. Really need to fix this sometime ...
if (ret == (size_t)-1) {
throw(std::runtime_error(
"Error during lsda_realread and I have no clue what happened. Sry."));
}
return tensor_ptr;
}
} // namespace qd
#endif // Binout
| 27.76129 | 80 | 0.626075 | [
"vector"
] |
bf48c6347f9ccd76d0874dd3fd76ce7ae55e15c7 | 8,919 | cc | C++ | ns-allinone-2.35/queue/rem.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2021-04-21T06:39:42.000Z | 2021-04-21T06:39:42.000Z | ns-allinone-2.35/queue/rem.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2019-01-20T17:35:23.000Z | 2019-01-22T21:41:38.000Z | ns-allinone-2.35/queue/rem.cc | nitishk017/ns2project | f037b796ff10300ffe0422580be5855c37d0b140 | [
"MIT"
] | 1 | 2021-09-29T16:06:57.000Z | 2021-09-29T16:06:57.000Z | /* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */
/*
* Copyright (c) 1990-1997 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Computer Systems
* Engineering Group at Lawrence Berkeley Laboratory.
* 4. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
*
* ns-2 code written by: Sanjeewa Athuraliya (sanjeewa@caltech.edu)
* Caltech, Pasadena,
* CA 91125
* Victor Li
* University of Melbourne, Parkville
* Vic., Australia.
*
* Ref: Active Queue Management (REM), IEEE Network, May/June 2001.
* http://netlab.caltech.edu
*/
#include <math.h>
#include <sys/types.h>
#include "config.h"
#include "template.h"
#include "random.h"
#include "flags.h"
#include "delay.h"
#include "rem.h"
#include <iostream>
static class REMClass : public TclClass {
public:
REMClass() : TclClass("Queue/REM") {}
TclObject* create(int, const char*const*) {
return (new REMQueue);
}
} class_rem;
void REMQueue :: set_update_timer()
{
rem_timer_.resched(remp_.p_updtime);
}
void REMQueue :: timeout()
{
//do price update
run_updaterule();
set_update_timer();
}
void REMTimer :: expire (Event *) {
a_->timeout();
}
REMQueue::REMQueue() : link_(NULL), tchan_(0), rem_timer_(this)
{
bind("gamma_", &remp_.p_gamma);
bind("phi_", &remp_.p_phi);
bind("inw_", &remp_.p_inw);
bind("mean_pktsize_", &remp_.p_pktsize);
bind("pupdtime_", &remp_.p_updtime);
bind("pbo_", &remp_.p_bo);
bind("prob_", &remv_.v_prob); // dropping probability
bind("curq_", &curq_); // current queue size
bind("pmark_", &pmark_); //number of packets being marked
bind_bool("markpkts_", &markpkts_); /* Whether to mark or drop? Default is drop */
bind_bool("qib_", &qib_); /* queue in bytes? */
q_ = new PacketQueue(); // underlying queue
pq_ = q_;
reset();
#ifdef notdef
print_remp();
print_remv();
#endif
}
void REMQueue::reset()
{
/*
* Compute the "packet time constant" if we know the
* link bandwidth. The ptc is the max number of
* pkts per second which can be placed on the link.
* The link bw is given in bits/sec, so scale psize
* accordingly.
*/
if (link_)
remp_.p_ptc = link_->bandwidth() / (8.0 * remp_.p_pktsize);
remv_.v_pl = 0.0;
remv_.v_prob = 0.0;
remv_.v_in = 0.0;
remv_.v_ave = 0.0;
remv_.v_count = 0.0;
remv_.v_pl1 = 0.0;
remv_.v_pl2 = 0.0;
remv_.v_in1 = 0.0;
remv_.v_in2 = 0.0;
pmark_ = 0.0;
bcount_ = 0;
//Queue::reset();
set_update_timer();
}
/*
* Compute the average input rate, the price and the marking prob..
*/
void REMQueue::run_updaterule()
{
double in, in_avg, nqueued, pl, pr;
// link price, the congestion measure
pl = remv_.v_pl;
// in is the number of bytes (if qib_ is true) or packets (otherwise)
// arriving at the link (input rate) during one update time interval
in = remv_.v_count;
// in_avg is the low pss filtered input rate
// which is in bytes if qib_ is true and in packets otherwise.
in_avg = remv_.v_ave;
in_avg *= (1.0 - remp_.p_inw);
if (qib_) {
in_avg += remp_.p_inw*in/remp_.p_pktsize;
nqueued = bcount_/remp_.p_pktsize;
}
else {
in_avg += remp_.p_inw*in;
nqueued = q_ -> length();
}
// c measures the maximum number of packets that
// could be sent during one update interval.
double c = remp_.p_updtime*remp_.p_ptc;
pl = pl + remp_.p_gamma*( in_avg + 0.1*(nqueued-remp_.p_bo) - c );
if ( pl < 0.0) {
pl = 0.0;
}
double pow1 = pow (remp_.p_phi, -pl);
pr = 1.0-pow1;
remv_.v_count = 0.0;
remv_.v_ave = in_avg;
remv_.v_pl = pl;
remv_.v_prob = pr;
}
/*
* Return the next packet in the queue for transmission.
*/
Packet* REMQueue::deque()
{
Packet *p = q_->deque();
if (p != 0) {
bcount_ -= hdr_cmn::access(p)->size ();
}
if (markpkts_) {
double u = Random::uniform();
if (p!=0) {
double pro = remv_.v_prob;
if (qib_) {
int size = hdr_cmn::access(p)->size ();
pro = remv_.v_prob*size/remp_.p_pktsize;
}
if ( u <= pro ) {
hdr_flags* hf = hdr_flags::access(p);
if(hf->ect() == 1) {
hf->ce() = 1;
pmark_++;
}
}
}
}
double qlen = qib_ ? bcount_ : q_->length();
curq_ = (int) qlen;
return (p);
}
/*
* Receive a new packet arriving at the queue.
* The packet is dropped if the maximum queue size is exceeded.
*/
void REMQueue::enque(Packet* pkt)
{
hdr_cmn* ch = hdr_cmn::access(pkt);
double qlen;
if (qib_) {
remv_.v_count += ch->size();
}
else {
++remv_.v_count;
}
double qlim = qib_ ? (qlim_*remp_.p_pktsize) : qlim_ ;
q_ -> enque(pkt);
bcount_ += ch->size();
qlen = qib_ ? bcount_ : q_->length();
if (qlen >= qlim) {
q_->remove(pkt);
bcount_ -= ch->size();
drop(pkt);
}
else {
if (!markpkts_) {
double u = Random::uniform();
double pro = remv_.v_prob;
if (qib_) {
pro = remv_.v_prob*ch->size()/remp_.p_pktsize;
}
if ( u <= pro ) {
q_->remove(pkt);
bcount_ -= ch->size();
drop(pkt);
}
}
}
qlen = qib_ ? bcount_ : q_->length();
curq_ = (int) qlen;
}
int REMQueue::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 2) {
if (strcmp(argv[1], "reset") == 0) {
reset();
return (TCL_OK);
}
} else if (argc == 3) {
// attach a file for variable tracing
if (strcmp(argv[1], "attach") == 0) {
int mode;
const char* id = argv[2];
tchan_ = Tcl_GetChannel(tcl.interp(), (char*)id, &mode);
if (tchan_ == 0) {
tcl.resultf("REM: trace: can't attach %s for writing", id);
return (TCL_ERROR);
}
return (TCL_OK);
}
// tell REM about link stats
if (strcmp(argv[1], "link") == 0) {
LinkDelay* del = (LinkDelay*)TclObject::lookup(argv[2]);
if (del == 0) {
tcl.resultf("REM: no LinkDelay object %s",
argv[2]);
return(TCL_ERROR);
}
// set ptc now
link_ = del;
remp_.p_ptc = link_->bandwidth() /
(8. * remp_.p_pktsize);
return (TCL_OK);
}
if (!strcmp(argv[1], "packetqueue-attach")) {
delete q_;
if (!(q_ = (PacketQueue*) TclObject::lookup(argv[2])))
return (TCL_ERROR);
else {
pq_ = q_;
return (TCL_OK);
}
}
}
return (Queue::command(argc, argv));
}
/*
* Routine called by TracedVar facility when variables change values.
* Currently used to trace values of avg queue size, drop probability,
* and the instantaneous queue size seen by arriving packets.
* Note that the tracing of each var must be enabled in tcl to work.
*/
void
REMQueue::trace(TracedVar* v)
{
char wrk[500];
const char *p;
if (((p = strstr(v->name(), "ave")) == NULL) &&
((p = strstr(v->name(), "prob")) == NULL) &&
((p = strstr(v->name(), "curq")) == NULL)) {
fprintf(stderr, "REM:unknown trace var %s\n",
v->name());
return;
}
if (tchan_) {
int n;
double t = Scheduler::instance().clock();
if (*p == 'c') {
sprintf(wrk, "Q %g %d", t, int(*((TracedInt*) v)));
} else {
sprintf(wrk, "%c %g %g", *p, t,
double(*((TracedDouble*) v)));
}
n = strlen(wrk);
wrk[n] = '\n';
wrk[n+1] = 0;
(void)Tcl_Write(tchan_, wrk, n+1);
}
return;
}
/* for debugging help */
void REMQueue::print_remp()
{
printf("=========\n");
}
void REMQueue::print_remv()
{
printf("=========\n");
}
| 24.040431 | 84 | 0.631125 | [
"object"
] |
bf4b7cc8c76de8414ff8afe30a18b31dc2f186cd | 10,319 | cpp | C++ | Source/KernelRunner/ComputeLayer.cpp | Fillo7/KTT | a0c252efb75a8366450e2df589f0ae641f015312 | [
"MIT"
] | 32 | 2017-09-12T23:52:52.000Z | 2020-12-09T07:13:24.000Z | Source/KernelRunner/ComputeLayer.cpp | Fillo7/KTT | a0c252efb75a8366450e2df589f0ae641f015312 | [
"MIT"
] | 23 | 2017-05-11T14:38:45.000Z | 2021-02-03T13:45:14.000Z | Source/KernelRunner/ComputeLayer.cpp | Fillo7/KTT | a0c252efb75a8366450e2df589f0ae641f015312 | [
"MIT"
] | 5 | 2017-11-06T12:40:05.000Z | 2020-06-16T13:11:24.000Z | #include <Api/KttException.h>
#include <KernelRunner/ComputeLayer.h>
#include <Utility/ErrorHandling/Assert.h>
#include <Utility/Logger/Logger.h>
#include <Utility/Timer/Timer.h>
#include <Utility/StlHelpers.h>
namespace ktt
{
ComputeLayer::ComputeLayer(ComputeEngine& engine, KernelArgumentManager& argumentManager) :
m_ComputeEngine(engine),
m_ArgumentManager(argumentManager),
m_ActiveKernel(InvalidKernelId)
{}
void ComputeLayer::RunKernel(const KernelDefinitionId id)
{
const auto actionId = RunKernelAsync(id, GetDefaultQueue());
WaitForComputeAction(actionId);
}
void ComputeLayer::RunKernel(const KernelDefinitionId id, const DimensionVector& globalSize,
const DimensionVector& localSize)
{
const auto actionId = RunKernelAsync(id, GetDefaultQueue(), globalSize, localSize);
WaitForComputeAction(actionId);
}
ComputeActionId ComputeLayer::RunKernelAsync(const KernelDefinitionId id, const QueueId queue)
{
const auto& data = GetComputeData(id);
return m_ComputeEngine.RunKernelAsync(data, queue);
}
ComputeActionId ComputeLayer::RunKernelAsync(const KernelDefinitionId id, const QueueId queue, const DimensionVector& globalSize,
const DimensionVector& localSize)
{
auto data = GetComputeData(id);
data.SetGlobalSize(globalSize);
data.SetLocalSize(localSize);
return m_ComputeEngine.RunKernelAsync(data, queue);
}
void ComputeLayer::WaitForComputeAction(const ComputeActionId id)
{
const auto result = m_ComputeEngine.WaitForComputeAction(id);
GetData().AddPartialResult(result);
}
void ComputeLayer::RunKernelWithProfiling(const KernelDefinitionId id)
{
if (!GetData().IsProfilingEnabled(id))
{
throw KttException("Profiling is not enabled for kernel definition with id " + std::to_string(id));
}
const auto& data = GetComputeData(id);
const auto result = m_ComputeEngine.RunKernelWithProfiling(data, GetDefaultQueue());
GetData().AddPartialResult(result);
}
void ComputeLayer::RunKernelWithProfiling(const KernelDefinitionId id, const DimensionVector& globalSize,
const DimensionVector& localSize)
{
if (!GetData().IsProfilingEnabled(id))
{
throw KttException("Profiling is not enabled for kernel definition with id " + std::to_string(id));
}
auto data = GetComputeData(id);
data.SetGlobalSize(globalSize);
data.SetLocalSize(localSize);
const auto result = m_ComputeEngine.RunKernelWithProfiling(data, GetDefaultQueue());
GetData().AddPartialResult(result);
}
uint64_t ComputeLayer::GetRemainingProfilingRuns(const KernelDefinitionId id) const
{
if (!GetData().IsProfilingEnabled(id))
{
throw KttException("Profiling is not enabled for kernel definition with id " + std::to_string(id));
}
const auto& data = GetComputeData(id);
return m_ComputeEngine.GetRemainingProfilingRuns(data.GetUniqueIdentifier());
}
uint64_t ComputeLayer::GetRemainingProfilingRuns() const
{
uint64_t result = 0;
for (const auto* definition : GetData().GetKernel().GetDefinitions())
{
result += GetRemainingProfilingRuns(definition->GetId());
}
return result;
}
QueueId ComputeLayer::GetDefaultQueue() const
{
return m_ComputeEngine.GetDefaultQueue();
}
std::vector<QueueId> ComputeLayer::GetAllQueues() const
{
return m_ComputeEngine.GetAllQueues();
}
void ComputeLayer::SynchronizeQueue(const QueueId queue)
{
m_ComputeEngine.SynchronizeQueue(queue);
}
void ComputeLayer::SynchronizeDevice()
{
m_ComputeEngine.SynchronizeDevice();
}
const DimensionVector& ComputeLayer::GetCurrentGlobalSize(const KernelDefinitionId id) const
{
return GetComputeData(id).GetGlobalSize();
}
const DimensionVector& ComputeLayer::GetCurrentLocalSize(const KernelDefinitionId id) const
{
return GetComputeData(id).GetLocalSize();
}
const KernelConfiguration& ComputeLayer::GetCurrentConfiguration() const
{
return GetData().GetConfiguration();
}
void ComputeLayer::ChangeArguments(const KernelDefinitionId id, const std::vector<ArgumentId>& arguments)
{
if (!ContainsUniqueElements(arguments))
{
throw KttException("Kernel arguments for a single kernel definition must be unique");
}
auto newArguments = m_ArgumentManager.GetArguments(arguments);
GetData().ChangeArguments(id, newArguments);
}
void ComputeLayer::SwapArguments(const KernelDefinitionId id, const ArgumentId first, const ArgumentId second)
{
GetData().SwapArguments(id, first, second);
}
void ComputeLayer::UpdateScalarArgument(const ArgumentId id, const void* data)
{
const auto& argument = m_ArgumentManager.GetArgument(id);
if (argument.GetMemoryType() != ArgumentMemoryType::Scalar)
{
throw KttException("Argument with id " + std::to_string(id) + " is not a scalar argument");
}
auto argumentOverride = argument;
argumentOverride.SetOwnedData(data, argument.GetDataSize());
GetData().AddArgumentOverride(id, argumentOverride);
}
void ComputeLayer::UpdateLocalArgument(const ArgumentId id, const size_t dataSize)
{
const auto& argument = m_ArgumentManager.GetArgument(id);
if (argument.GetMemoryType() != ArgumentMemoryType::Local)
{
throw KttException("Argument with id " + std::to_string(id) + " is not a local memory argument");
}
auto argumentOverride = argument;
argumentOverride.SetOwnedData(nullptr, dataSize);
GetData().AddArgumentOverride(id, argumentOverride);
}
void ComputeLayer::UploadBuffer(const ArgumentId id)
{
Timer timer;
timer.Start();
const auto actionId = UploadBufferAsync(id, GetDefaultQueue());
WaitForTransferAction(actionId);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
TransferActionId ComputeLayer::UploadBufferAsync(const ArgumentId id, const QueueId queue)
{
auto& argument = m_ArgumentManager.GetArgument(id);
return m_ComputeEngine.UploadArgument(argument, queue);
}
void ComputeLayer::DownloadBuffer(const ArgumentId id, void* destination, const size_t dataSize)
{
Timer timer;
timer.Start();
const auto actionId = DownloadBufferAsync(id, GetDefaultQueue(), destination, dataSize);
WaitForTransferAction(actionId);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
TransferActionId ComputeLayer::DownloadBufferAsync(const ArgumentId id, const QueueId queue, void* destination,
const size_t dataSize)
{
return m_ComputeEngine.DownloadArgument(id, queue, destination, dataSize);
}
void ComputeLayer::UpdateBuffer(const ArgumentId id, const void* data, const size_t dataSize)
{
Timer timer;
timer.Start();
const auto actionId = UpdateBufferAsync(id, GetDefaultQueue(), data, dataSize);
WaitForTransferAction(actionId);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
TransferActionId ComputeLayer::UpdateBufferAsync(const ArgumentId id, const QueueId queue, const void* data,
const size_t dataSize)
{
return m_ComputeEngine.UpdateArgument(id, queue, data, dataSize);
}
void ComputeLayer::CopyBuffer(const ArgumentId destination, const ArgumentId source, const size_t dataSize)
{
Timer timer;
timer.Start();
const auto actionId = CopyBufferAsync(destination, source, GetDefaultQueue(), dataSize);
WaitForTransferAction(actionId);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
TransferActionId ComputeLayer::CopyBufferAsync(const ArgumentId destination, const ArgumentId source, const QueueId queue,
const size_t dataSize)
{
return m_ComputeEngine.CopyArgument(destination, queue, source, dataSize);
}
void ComputeLayer::WaitForTransferAction(const TransferActionId id)
{
m_ComputeEngine.WaitForTransferAction(id);
}
void ComputeLayer::ResizeBuffer(const ArgumentId id, const size_t newDataSize, const bool preserveData)
{
Timer timer;
timer.Start();
m_ComputeEngine.ResizeArgument(id, newDataSize, preserveData);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
void ComputeLayer::ClearBuffer(const ArgumentId id)
{
Timer timer;
timer.Start();
m_ComputeEngine.ClearBuffer(id);
timer.Stop();
GetData().IncreaseOverhead(timer.GetElapsedTime());
}
bool ComputeLayer::HasBuffer(const ArgumentId id)
{
return m_ComputeEngine.HasBuffer(id);
}
void ComputeLayer::GetUnifiedMemoryBufferHandle(const ArgumentId id, UnifiedBufferMemory& memoryHandle)
{
m_ComputeEngine.GetUnifiedMemoryBufferHandle(id, memoryHandle);
}
void ComputeLayer::SetActiveKernel(const KernelId id)
{
KttAssert(m_ActiveKernel == InvalidKernelId, "Unpaired call to set / clear active kernel");
m_ActiveKernel = id;
}
void ComputeLayer::ClearActiveKernel()
{
KttAssert(m_ActiveKernel != InvalidKernelId, "Unpaired call to set / clear active kernel");
m_ActiveKernel = InvalidKernelId;
}
void ComputeLayer::ClearComputeEngineData(const KernelDefinitionId id)
{
const auto computeId = GetData().GetComputeData(id).GetUniqueIdentifier();
m_ComputeEngine.ClearData(computeId);
}
void ComputeLayer::ClearComputeEngineData()
{
for (const auto* definition : GetData().GetKernel().GetDefinitions())
{
ClearComputeEngineData(definition->GetId());
}
}
void ComputeLayer::AddData(const Kernel& kernel, const KernelConfiguration& configuration)
{
m_Data[kernel.GetId()] = std::make_unique<ComputeLayerData>(kernel, configuration);
}
void ComputeLayer::ClearData(const KernelId id)
{
m_Data.erase(id);
}
KernelResult ComputeLayer::GenerateResult(const KernelId id, const Nanoseconds launcherDuration) const
{
KttAssert(ContainsKey(m_Data, id), "Invalid compute layer data access");
return m_Data.find(id)->second->GenerateResult(launcherDuration);
}
const ComputeLayerData& ComputeLayer::GetData() const
{
KttAssert(m_ActiveKernel != InvalidKernelId, "Retrieving kernel compute data requires valid active kernel");
return *m_Data.find(m_ActiveKernel)->second;
}
ComputeLayerData& ComputeLayer::GetData()
{
return const_cast<ComputeLayerData&>(static_cast<const ComputeLayer*>(this)->GetData());
}
const KernelComputeData& ComputeLayer::GetComputeData(const KernelDefinitionId id) const
{
return GetData().GetComputeData(id);
}
} // namespace ktt
| 29.482857 | 129 | 0.755112 | [
"vector"
] |
bf53e490eb5133568c66344f815d9fb462017a56 | 8,174 | cpp | C++ | lib/eval/holdem_class_vector_cache.cpp | mastermind88/CandyPoker | 37b502ce6ea8733ce0b70476fcf32930961923a8 | [
"MIT"
] | null | null | null | lib/eval/holdem_class_vector_cache.cpp | mastermind88/CandyPoker | 37b502ce6ea8733ce0b70476fcf32930961923a8 | [
"MIT"
] | null | null | null | lib/eval/holdem_class_vector_cache.cpp | mastermind88/CandyPoker | 37b502ce6ea8733ce0b70476fcf32930961923a8 | [
"MIT"
] | null | null | null | /*
CandyPoker
https://github.com/sweeterthancandy/CandyPoker
MIT License
Copyright (c) 2019 Gerry Candy
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 "ps/eval/holdem_class_vector_cache.h"
#include "ps/support/persistent_impl.h"
#include "ps/base/algorithm.h"
#include "ps/eval/class_cache.h"
namespace{
using namespace ps;
struct n_player_impl : support::persistent_memory_impl_serializer<holdem_class_vector_pair_cache>{
explicit n_player_impl(size_t N):N_{N}{}
virtual std::string name()const override{
return "n_player_impl@" + boost::lexical_cast<std::string>(N_);
}
virtual std::shared_ptr<holdem_class_vector_pair_cache> make()const override{
auto ptr = std::make_shared<holdem_class_vector_pair_cache>();
std::vector<holdem_class_vector_cache_item> cache;
double total_count = 0.0;
size_t n = 0;
class_cache cc;
std::string cache_name{".cc.bin"};
cc.load(cache_name);
holdem_class_vector_cache_item_pair* head = nullptr;
for(holdem_class_perm_iterator iter(N_),end;iter!=end;++iter){
auto const& cv = *iter;
size_t count = 0;
switch(N_){
case 2:
{
auto const& A = holdem_class_decl::get(cv[0]).get_hand_set() ;
auto const& B = holdem_class_decl::get(cv[1]).get_hand_set() ;
for( auto const& a : A ){
for( auto const& b : B ){
if( ! disjoint(a,b) )
continue;
++count;
}
}
if( count == 0 )
continue;
break;
}
case 3:
{
auto const& A = holdem_class_decl::get(cv[0]).get_hand_set() ;
auto const& B = holdem_class_decl::get(cv[1]).get_hand_set() ;
auto const& C = holdem_class_decl::get(cv[2]).get_hand_set() ;
for( auto const& a : A ){
for( auto const& b : B ){
if( ! disjoint(a,b) )
continue;
for( auto const& c : C ){
if( ! disjoint(a,b,c) )
continue;
++count;
}
}
}
if( count == 0 )
continue;
break;
}
default:
{
throw std::domain_error("not implemented");
}
}
total_count += count;
auto ev = cc.LookupVector(cv);
if( head == nullptr || head->cid != cv[0] ){
ptr->emplace_back();
head = &ptr->back();
head->cid = cv[0];
}
head->vec.emplace_back();
head->vec.back().cv = *iter;
head->vec.back().count = count;
head->vec.back().ev.resize(N_);
for(size_t idx=0;idx!=N_;++idx){
head->vec.back().ev[idx] = ev[idx];
}
++n;
double factor = std::pow(169.0, 1.0 * N_);
if( n % 169 == 0 )
std::cout << "n * 100.0 / factor => " << n * 100.0 / factor << "\n"; // __CandyPrint__(cxx-print-scalar,n * 100.0 / factor)
}
for(auto& group : *ptr){
for(auto& _ : group.vec){
_.prob = _.count / total_count;
}
}
return ptr;
}
virtual void display(std::ostream& ostr)const override{
auto const& obj = *reinterpret_cast<holdem_class_vector_pair_cache const*>(ptr());
double sigma = 0.0;
for(auto& group : obj){
for(auto& _ : group.vec){
std::cout << _ << "\n";
sigma += _.prob;
}
}
std::cout << "sigma => " << sigma << "\n"; // __CandyPrint__(cxx-print-scalar,sigma)
}
private:
size_t N_;
};
} // end namespace anon
namespace ps{
static support::persistent_memory_decl<holdem_class_vector_pair_cache> Memory_ThreePlayerClassVector( std::make_unique<n_player_impl>(3) );
static support::persistent_memory_decl<holdem_class_vector_pair_cache> Memory_TwoPlayerClassVector( std::make_unique<n_player_impl>(2) );
support::persistent_memory_decl<holdem_class_vector_pair_cache> const& get_Memory_ThreePlayerClassVector()
{
return Memory_ThreePlayerClassVector;
}
support::persistent_memory_decl<holdem_class_vector_pair_cache> const& get_Memory_TwoPlayerClassVector()
{
return Memory_TwoPlayerClassVector;
}
} // end namespace ps
| 51.0875 | 163 | 0.397602 | [
"vector"
] |
bf5520955c9c199b56b04746c4f215604ebbb25f | 93,148 | cc | C++ | src/vendor/mariadb-10.6.7/sql/filesort.cc | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/sql/filesort.cc | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/sql/filesort.cc | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
Copyright (c) 2009, 2020, MariaDB
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; version 2 of the 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
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-1335 USA */
/**
@file
@brief
Sorts a database
*/
#include "mariadb.h"
#include "sql_priv.h"
#include "filesort.h"
#include <m_ctype.h>
#include "sql_sort.h"
#include "probes_mysql.h"
#include "sql_base.h"
#include "sql_test.h" // TEST_filesort
#include "opt_range.h" // SQL_SELECT
#include "bounded_queue.h"
#include "filesort_utils.h"
#include "sql_select.h"
#include "debug_sync.h"
/* functions defined in this file */
static uchar *read_buffpek_from_file(IO_CACHE *buffer_file, uint count,
uchar *buf);
static ha_rows find_all_keys(THD *thd, Sort_param *param, SQL_SELECT *select,
SORT_INFO *fs_info,
IO_CACHE *buffer_file,
IO_CACHE *tempfile,
Bounded_queue<uchar, uchar> *pq,
ha_rows *found_rows);
static bool write_keys(Sort_param *param, SORT_INFO *fs_info,
uint count, IO_CACHE *buffer_file, IO_CACHE *tempfile);
static uint make_sortkey(Sort_param *param, uchar *to, uchar *ref_pos,
bool using_packed_sortkeys= false);
static uint make_sortkey(Sort_param *param, uchar *to);
static uint make_packed_sortkey(Sort_param *param, uchar *to);
static void register_used_fields(Sort_param *param);
static bool save_index(Sort_param *param, uint count,
SORT_INFO *table_sort);
static uint suffix_length(ulong string_length);
static uint sortlength(THD *thd, Sort_keys *sortorder,
bool *allow_packing_for_sortkeys);
static Addon_fields *get_addon_fields(TABLE *table, uint sortlength,
uint *addon_length,
uint *m_packable_length);
static bool check_if_pq_applicable(Sort_param *param, SORT_INFO *info,
TABLE *table,
ha_rows records, size_t memory_available);
static void store_key_part_length(uint32 num, uchar *to, uint bytes)
{
switch(bytes) {
case 1: *to= (uchar)num; break;
case 2: int2store(to, num); break;
case 3: int3store(to, num); break;
case 4: int4store(to, num); break;
default: DBUG_ASSERT(0);
}
}
static uint32 read_keypart_length(const uchar *from, uint bytes)
{
switch(bytes) {
case 1: return from[0];
case 2: return uint2korr(from);
case 3: return uint3korr(from);
case 4: return uint4korr(from);
default: DBUG_ASSERT(0); return 0;
}
}
// @param sortlen [Maximum] length of the sort key
void Sort_param::init_for_filesort(uint sortlen, TABLE *table,
ha_rows maxrows, Filesort *filesort)
{
DBUG_ASSERT(addon_fields == NULL);
sort_length= sortlen;
ref_length= table->file->ref_length;
accepted_rows= filesort->accepted_rows;
if (!(table->file->ha_table_flags() & HA_FAST_KEY_READ) &&
!table->fulltext_searched && !filesort->sort_positions)
{
/*
Get the descriptors of all fields whose values are appended
to sorted fields and get its total length in addon_buf.length
*/
addon_fields= get_addon_fields(table, sort_length, &addon_length,
&m_packable_length);
}
if (using_addon_fields())
{
DBUG_ASSERT(addon_length < UINT_MAX32);
res_length= addon_length;
}
else
{
res_length= ref_length;
/*
The reference to the record is considered
as an additional sorted field
*/
sort_length+= ref_length;
}
rec_length= sort_length + addon_length;
max_rows= maxrows;
}
void Sort_param::try_to_pack_addons(ulong max_length_for_sort_data)
{
if (!using_addon_fields() || // no addons, or
using_packed_addons()) // already packed
return;
if (!Addon_fields::can_pack_addon_fields(res_length))
return;
const uint sz= Addon_fields::size_of_length_field;
// Heuristic: skip packing if potential savings are less than 10 bytes.
if (m_packable_length < (10 + sz))
return;
SORT_ADDON_FIELD *addonf= addon_fields->begin();
for (;addonf != addon_fields->end(); ++addonf)
{
addonf->offset+= sz;
addonf->null_offset+= sz;
}
addon_fields->set_using_packed_addons(true);
m_using_packed_addons= true;
m_packed_format= true;
addon_length+= sz;
res_length+= sz;
rec_length+= sz;
}
/**
Sort a table.
Creates a set of pointers that can be used to read the rows
in sorted order. This should be done with the functions
in records.cc.
Before calling filesort, one must have done
table->file->info(HA_STATUS_VARIABLE)
The result set is stored in
filesort_info->io_cache or
filesort_info->record_pointers.
@param thd Current thread
@param table Table to sort
@param filesort How to sort the table
@param[out] found_rows Store the number of found rows here.
This is the number of found rows after
applying WHERE condition.
@note
If we sort by position (like if filesort->sort_positions==true)
filesort() will call table->prepare_for_position().
@retval
0 Error
# SORT_INFO
*/
SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort,
Filesort_tracker* tracker, JOIN *join,
table_map first_table_bit)
{
int error;
DBUG_ASSERT(thd->variables.sortbuff_size <= SIZE_T_MAX);
size_t memory_available= (size_t)thd->variables.sortbuff_size;
uint maxbuffer;
Merge_chunk *buffpek;
ha_rows num_rows= HA_POS_ERROR, not_used=0;
IO_CACHE tempfile, buffpek_pointers, *outfile;
Sort_param param;
bool allow_packing_for_sortkeys;
Bounded_queue<uchar, uchar> pq;
SQL_SELECT *const select= filesort->select;
ha_rows max_rows= filesort->limit;
uint s_length= 0, sort_len;
Sort_keys *sort_keys;
DBUG_ENTER("filesort");
if (!(sort_keys= filesort->make_sortorder(thd, join, first_table_bit)))
DBUG_RETURN(NULL); /* purecov: inspected */
s_length= static_cast<uint>(sort_keys->size());
DBUG_EXECUTE("info",TEST_filesort(filesort->sortorder, s_length););
#ifdef SKIP_DBUG_IN_FILESORT
DBUG_PUSH_EMPTY; /* No DBUG here */
#endif
SORT_INFO *sort;
TABLE_LIST *tab= table->pos_in_table_list;
Item_subselect *subselect= tab ? tab->containing_subselect() : 0;
MYSQL_FILESORT_START(table->s->db.str, table->s->table_name.str);
DEBUG_SYNC(thd, "filesort_start");
if (!(sort= new SORT_INFO))
return 0;
if (subselect && subselect->filesort_buffer.is_allocated())
{
// Reuse cache from last call
sort->filesort_buffer= subselect->filesort_buffer;
sort->buffpek= subselect->sortbuffer;
subselect->filesort_buffer.reset();
subselect->sortbuffer.str=0;
}
DBUG_ASSERT(sort->sorted_result_in_fsbuf == FALSE ||
sort->record_pointers == NULL);
outfile= &sort->io_cache;
my_b_clear(&tempfile);
my_b_clear(&buffpek_pointers);
buffpek=0;
error= 1;
sort->found_rows= HA_POS_ERROR;
param.sort_keys= sort_keys;
sort_len= sortlength(thd, sort_keys, &allow_packing_for_sortkeys);
param.init_for_filesort(sort_len, table, max_rows, filesort);
if (!param.accepted_rows)
param.accepted_rows= ¬_used;
param.set_all_read_bits= filesort->set_all_read_bits;
param.unpack= filesort->unpack;
sort->addon_fields= param.addon_fields;
sort->sort_keys= param.sort_keys;
if (select && select->quick)
thd->inc_status_sort_range();
else
thd->inc_status_sort_scan();
thd->query_plan_flags|= QPLAN_FILESORT;
tracker->report_use(thd, max_rows);
// If number of rows is not known, use as much of sort buffer as possible.
num_rows= table->file->estimate_rows_upper_bound();
if (check_if_pq_applicable(¶m, sort,
table, num_rows, memory_available))
{
DBUG_PRINT("info", ("filesort PQ is applicable"));
thd->query_plan_flags|= QPLAN_FILESORT_PRIORITY_QUEUE;
status_var_increment(thd->status_var.filesort_pq_sorts_);
tracker->incr_pq_used();
param.using_pq= true;
const size_t compare_length= param.sort_length;
DBUG_ASSERT(param.using_packed_sortkeys() == false);
/*
For PQ queries (with limit) we know exactly how many pointers/records
we have in the buffer, so to simplify things, we initialize
all pointers here. (We cannot pack fields anyways, so there is no
point in doing lazy initialization).
*/
sort->init_record_pointers();
if (pq.init(param.max_rows,
true, // max_at_top
NULL, // compare_function
compare_length,
&make_sortkey, ¶m, sort->get_sort_keys()))
{
/*
If we fail to init pq, we have to give up:
out of memory means my_malloc() will call my_error().
*/
DBUG_PRINT("info", ("failed to allocate PQ"));
DBUG_ASSERT(thd->is_error());
goto err;
}
}
else
{
DBUG_PRINT("info", ("filesort PQ is not applicable"));
if (allow_packing_for_sortkeys)
param.try_to_pack_sortkeys();
param.try_to_pack_addons(thd->variables.max_length_for_sort_data);
tracker->report_sort_keys_format(param.using_packed_sortkeys());
param.using_pq= false;
size_t min_sort_memory= MY_MAX(MIN_SORT_MEMORY,
param.sort_length*MERGEBUFF2);
set_if_bigger(min_sort_memory, sizeof(Merge_chunk*)*MERGEBUFF2);
while (memory_available >= min_sort_memory)
{
ulonglong keys= memory_available / (param.rec_length + sizeof(char*));
param.max_keys_per_buffer= (uint) MY_MAX(MERGEBUFF2,
MY_MIN(num_rows, keys));
sort->alloc_sort_buffer(param.max_keys_per_buffer, param.rec_length);
if (sort->sort_buffer_size() > 0)
break;
size_t old_memory_available= memory_available;
memory_available= memory_available/4*3;
if (memory_available < min_sort_memory &&
old_memory_available > min_sort_memory)
memory_available= min_sort_memory;
}
if (memory_available < min_sort_memory)
{
my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERROR_LOG + ME_FATAL));
goto err;
}
tracker->report_sort_buffer_size(sort->sort_buffer_size());
}
if (param.using_addon_fields())
{
// report information whether addon fields are packed or not
tracker->report_addon_fields_format(param.using_packed_addons());
}
if (param.tmp_buffer.alloc(param.sort_length))
goto err;
if (open_cached_file(&buffpek_pointers,mysql_tmpdir,TEMP_PREFIX,
DISK_BUFFER_SIZE, MYF(MY_WME)))
goto err;
param.sort_form= table;
param.local_sortorder=
Bounds_checked_array<SORT_FIELD>(filesort->sortorder, s_length);
num_rows= find_all_keys(thd, ¶m, select,
sort,
&buffpek_pointers,
&tempfile,
pq.is_initialized() ? &pq : NULL,
&sort->found_rows);
if (num_rows == HA_POS_ERROR)
goto err;
maxbuffer= (uint) (my_b_tell(&buffpek_pointers)/sizeof(*buffpek));
tracker->report_merge_passes_at_start(thd->query_plan_fsort_passes);
tracker->report_row_numbers(param.examined_rows, sort->found_rows, num_rows);
if (maxbuffer == 0) // The whole set is in memory
{
if (save_index(¶m, (uint) num_rows, sort))
goto err;
}
else
{
/* filesort cannot handle zero-length records during merge. */
DBUG_ASSERT(param.sort_length != 0);
if (sort->buffpek.str && sort->buffpek.length < maxbuffer)
{
my_free(sort->buffpek.str);
sort->buffpek.str= 0;
}
if (param.using_addon_fields())
{
DBUG_ASSERT(sort->addon_fields);
if (!sort->addon_fields->allocate_addon_buf(param.addon_length))
goto err;
}
if (!(sort->buffpek.str=
(char *) read_buffpek_from_file(&buffpek_pointers, maxbuffer,
(uchar*) sort->buffpek.str)))
goto err;
sort->buffpek.length= maxbuffer;
buffpek= (Merge_chunk *) sort->buffpek.str;
close_cached_file(&buffpek_pointers);
/* Open cached file if it isn't open */
if (! my_b_inited(outfile) &&
open_cached_file(outfile,mysql_tmpdir,TEMP_PREFIX,READ_RECORD_BUFFER,
MYF(MY_WME)))
goto err;
if (reinit_io_cache(outfile,WRITE_CACHE,0L,0,0))
goto err;
/*
Use also the space previously used by string pointers in sort_buffer
for temporary key storage.
*/
param.max_keys_per_buffer= static_cast<uint>(sort->sort_buffer_size()) /
param.rec_length;
set_if_bigger(param.max_keys_per_buffer, 1);
maxbuffer--; // Offset from 0
if (merge_many_buff(¶m, sort->get_raw_buf(),
buffpek,&maxbuffer,
&tempfile))
goto err;
if (flush_io_cache(&tempfile) ||
reinit_io_cache(&tempfile,READ_CACHE,0L,0,0))
goto err;
if (merge_index(¶m,
sort->get_raw_buf(),
buffpek,
maxbuffer,
&tempfile,
outfile))
goto err;
}
if (num_rows > param.max_rows)
{
// If find_all_keys() produced more results than the query LIMIT.
num_rows= param.max_rows;
}
error= 0;
err:
if (!subselect || !subselect->is_uncacheable())
{
if (!param.using_addon_fields())
sort->free_sort_buffer();
my_free(sort->buffpek.str);
}
else
{
/* Remember sort buffers for next subquery call */
subselect->filesort_buffer= sort->filesort_buffer;
subselect->sortbuffer= sort->buffpek;
sort->filesort_buffer.reset(); // Don't free this*/
}
sort->buffpek.str= 0;
close_cached_file(&tempfile);
close_cached_file(&buffpek_pointers);
if (my_b_inited(outfile))
{
if (flush_io_cache(outfile))
error=1;
{
my_off_t save_pos=outfile->pos_in_file;
/* For following reads */
if (reinit_io_cache(outfile,READ_CACHE,0L,0,0))
error=1;
outfile->end_of_file=save_pos;
}
}
tracker->report_merge_passes_at_end(thd, thd->query_plan_fsort_passes);
if (unlikely(error))
{
int kill_errno= thd->killed_errno();
DBUG_ASSERT(thd->is_error() || kill_errno || thd->killed == ABORT_QUERY);
my_printf_error(ER_FILSORT_ABORT,
"%s: %s",
MYF(0),
ER_THD(thd, ER_FILSORT_ABORT),
kill_errno ? ER_THD(thd, kill_errno) :
thd->killed == ABORT_QUERY ? "" :
thd->get_stmt_da()->message());
if ((thd->killed == ABORT_QUERY || kill_errno) &&
global_system_variables.log_warnings > 1)
{
sql_print_warning("%s, host: %s, user: %s, thread: %lu, query: %-.4096s",
ER_THD(thd, ER_FILSORT_ABORT),
thd->security_ctx->host_or_ip,
&thd->security_ctx->priv_user[0],
(ulong) thd->thread_id,
thd->query());
}
}
else
thd->inc_status_sort_rows(num_rows);
sort->examined_rows= param.examined_rows;
sort->return_rows= num_rows;
#ifdef SKIP_DBUG_IN_FILESORT
DBUG_POP_EMPTY; /* Ok to DBUG */
#endif
DBUG_PRINT("exit",
("num_rows: %lld examined_rows: %lld found_rows: %lld",
(longlong) sort->return_rows, (longlong) sort->examined_rows,
(longlong) sort->found_rows));
MYSQL_FILESORT_DONE(error, num_rows);
if (unlikely(error))
{
delete sort;
sort= 0;
}
DBUG_RETURN(sort);
} /* filesort */
void Filesort::cleanup()
{
if (select && own_select)
{
select->cleanup();
select= NULL;
}
}
/*
Create the Sort_keys array and fill the sort_keys[i]->{item|field}.
This indicates which field/item values will be used as sort keys.
Attributes like lengths are not filled yet.
*/
Sort_keys*
Filesort::make_sortorder(THD *thd, JOIN *join, table_map first_table_bit)
{
uint count;
SORT_FIELD *sort,*pos;
ORDER *ord;
DBUG_ENTER("make_sortorder");
count=0;
for (ord = order; ord; ord= ord->next)
count++;
if (sortorder)
DBUG_RETURN(sort_keys);
DBUG_ASSERT(sort_keys == NULL);
sortorder= (SORT_FIELD*) thd->alloc(sizeof(SORT_FIELD) * count);
pos= sort= sortorder;
if (!pos)
DBUG_RETURN(0);
sort_keys= new Sort_keys(sortorder, count);
if (!sort_keys)
DBUG_RETURN(0);
pos= sort_keys->begin();
for (ord= order; ord; ord= ord->next, pos++)
{
Item *first= ord->item[0];
/*
It is possible that the query plan is to read table t1, while the
sort criteria actually has "ORDER BY t2.col" and the WHERE clause has
a multi-equality(t1.col, t2.col, ...).
The optimizer detects such cases (grep for
UseMultipleEqualitiesToRemoveTempTable to see where), but doesn't
perform equality substitution in the order->item. We need to do the
substitution here ourselves.
*/
table_map item_map= first->used_tables();
if (join && (item_map & ~join->const_table_map) &&
!(item_map & first_table_bit) && join->cond_equal &&
first->get_item_equal())
{
/*
Ok, this is the case descibed just above. Get the first element of the
multi-equality.
*/
Item_equal *item_eq= first->get_item_equal();
first= item_eq->get_first(NO_PARTICULAR_TAB, NULL);
}
Item *item= first->real_item();
pos->field= 0; pos->item= 0;
if (item->type() == Item::FIELD_ITEM)
pos->field= ((Item_field*) item)->field;
else if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
{
// Aggregate, or Item_aggregate_ref
DBUG_ASSERT(first->type() == Item::SUM_FUNC_ITEM ||
(first->type() == Item::REF_ITEM &&
static_cast<Item_ref*>(first)->ref_type() ==
Item_ref::AGGREGATE_REF));
pos->field= first->get_tmp_table_field();
}
else if (item->type() == Item::COPY_STR_ITEM)
{ // Blob patch
pos->item= ((Item_copy*) item)->get_item();
}
else
pos->item= *ord->item;
pos->reverse= (ord->direction == ORDER::ORDER_DESC);
DBUG_ASSERT(pos->field != NULL || pos->item != NULL);
}
DBUG_RETURN(sort_keys);
}
/** Read 'count' number of buffer pointers into memory. */
static uchar *read_buffpek_from_file(IO_CACHE *buffpek_pointers, uint count,
uchar *buf)
{
size_t length= sizeof(Merge_chunk)*count;
uchar *tmp= buf;
DBUG_ENTER("read_buffpek_from_file");
if (count > UINT_MAX/sizeof(Merge_chunk))
return 0; /* sizeof(BUFFPEK)*count will overflow */
if (!tmp)
tmp= (uchar *)my_malloc(key_memory_Filesort_info_merge, length,
MYF(MY_WME | MY_THREAD_SPECIFIC));
if (tmp)
{
if (reinit_io_cache(buffpek_pointers,READ_CACHE,0L,0,0) ||
my_b_read(buffpek_pointers, (uchar*) tmp, length))
{
my_free(tmp);
tmp=0;
}
}
DBUG_RETURN(tmp);
}
#ifndef DBUG_OFF
/* Buffer where record is returned */
char dbug_print_row_buff[512];
/* Temporary buffer for printing a column */
char dbug_print_row_buff_tmp[512];
/*
Print table's current row into a buffer and return a pointer to it.
This is intended to be used from gdb:
(gdb) p dbug_print_table_row(table)
$33 = "SUBQUERY2_t1(col_int_key,col_varchar_nokey)=(7,c)"
(gdb)
Only columns in table->read_set are printed
*/
const char* dbug_print_table_row(TABLE *table)
{
Field **pfield;
String tmp(dbug_print_row_buff_tmp,
sizeof(dbug_print_row_buff_tmp),&my_charset_bin);
String output(dbug_print_row_buff, sizeof(dbug_print_row_buff),
&my_charset_bin);
output.length(0);
output.append(table->alias);
output.append('(');
bool first= true;
for (pfield= table->field; *pfield ; pfield++)
{
const LEX_CSTRING *name;
if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index))
continue;
if (first)
first= false;
else
output.append(',');
name= (*pfield)->field_name.str ? &(*pfield)->field_name: &NULL_clex_str;
output.append(name);
}
output.append(STRING_WITH_LEN(")=("));
first= true;
for (pfield= table->field; *pfield ; pfield++)
{
Field *field= *pfield;
if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index))
continue;
if (first)
first= false;
else
output.append(',');
if (field->is_null())
output.append(&NULL_clex_str);
else
{
if (field->type() == MYSQL_TYPE_BIT)
(void) field->val_int_as_str(&tmp, 1);
else
field->val_str(&tmp);
output.append(tmp.ptr(), tmp.length());
}
}
output.append(')');
return output.c_ptr_safe();
}
const char* dbug_print_row(TABLE *table, uchar *rec)
{
table->move_fields(table->field, rec, table->record[0]);
const char* ret= dbug_print_table_row(table);
table->move_fields(table->field, table->record[0], rec);
return ret;
}
/*
Print a text, SQL-like record representation into dbug trace.
Note: this function is a work in progress: at the moment
- column read bitmap is ignored (can print garbage for unused columns)
- there is no quoting
*/
static void dbug_print_record(TABLE *table, bool print_rowid)
{
char buff[1024];
Field **pfield;
String tmp(buff,sizeof(buff),&my_charset_bin);
DBUG_LOCK_FILE;
fprintf(DBUG_FILE, "record (");
for (pfield= table->field; *pfield ; pfield++)
fprintf(DBUG_FILE, "%s%s", (*pfield)->field_name.str,
(pfield[1])? ", ":"");
fprintf(DBUG_FILE, ") = ");
fprintf(DBUG_FILE, "(");
for (pfield= table->field; *pfield ; pfield++)
{
Field *field= *pfield;
if (field->is_null())
fwrite("NULL", sizeof(char), 4, DBUG_FILE);
if (field->type() == MYSQL_TYPE_BIT)
(void) field->val_int_as_str(&tmp, 1);
else
field->val_str(&tmp);
fwrite(tmp.ptr(),sizeof(char),tmp.length(),DBUG_FILE);
if (pfield[1])
fwrite(", ", sizeof(char), 2, DBUG_FILE);
}
fprintf(DBUG_FILE, ")");
if (print_rowid)
{
fprintf(DBUG_FILE, " rowid ");
for (uint i=0; i < table->file->ref_length; i++)
{
fprintf(DBUG_FILE, "%x", (uchar)table->file->ref[i]);
}
}
fprintf(DBUG_FILE, "\n");
DBUG_UNLOCK_FILE;
}
#endif
/**
Search after sort_keys, and write them into tempfile
(if we run out of space in the sort_keys buffer).
All produced sequences are guaranteed to be non-empty.
@param param Sorting parameter
@param select Use this to get source data
@param sort_keys Array of pointers to sort key + addon buffers.
@param buffpek_pointers File to write BUFFPEKs describing sorted segments
in tempfile.
@param tempfile File to write sorted sequences of sortkeys to.
@param pq If !NULL, use it for keeping top N elements
@param [out] found_rows The number of FOUND_ROWS().
For a query with LIMIT, this value will typically
be larger than the function return value.
@note
Basic idea:
@verbatim
while (get_next_sortkey())
{
if (using priority queue)
push sort key into queue
else
{
if (no free space in sort_keys buffers)
{
sort sort_keys buffer;
dump sorted sequence to 'tempfile';
dump BUFFPEK describing sequence location into 'buffpek_pointers';
}
put sort key into 'sort_keys';
}
}
if (sort_keys has some elements && dumped at least once)
sort-dump-dump as above;
else
don't sort, leave sort_keys array to be sorted by caller.
@endverbatim
@retval
Number of records written on success.
@retval
HA_POS_ERROR on error.
*/
static ha_rows find_all_keys(THD *thd, Sort_param *param, SQL_SELECT *select,
SORT_INFO *fs_info,
IO_CACHE *buffpek_pointers,
IO_CACHE *tempfile,
Bounded_queue<uchar, uchar> *pq,
ha_rows *found_rows)
{
int error, quick_select;
uint idx, indexpos;
uchar *ref_pos, *next_pos, ref_buff[MAX_REFLENGTH];
TABLE *sort_form;
handler *file;
MY_BITMAP *save_read_set, *save_write_set;
Item *sort_cond;
ha_rows num_records= 0;
const bool packed_format= param->is_packed_format();
const bool using_packed_sortkeys= param->using_packed_sortkeys();
DBUG_ENTER("find_all_keys");
DBUG_PRINT("info",("using: %s",
(select ? select->quick ? "ranges" : "where":
"every row")));
idx=indexpos=0;
error=quick_select=0;
sort_form=param->sort_form;
file=sort_form->file;
ref_pos= ref_buff;
quick_select=select && select->quick;
*found_rows= 0;
ref_pos= &file->ref[0];
next_pos=ref_pos;
DBUG_EXECUTE_IF("show_explain_in_find_all_keys",
dbug_serve_apcs(thd, 1);
);
if (!quick_select)
{
next_pos=(uchar*) 0; /* Find records in sequence */
DBUG_EXECUTE_IF("bug14365043_1",
DBUG_SET("+d,ha_rnd_init_fail"););
if (unlikely(file->ha_rnd_init_with_error(1)))
DBUG_RETURN(HA_POS_ERROR);
file->extra_opt(HA_EXTRA_CACHE, thd->variables.read_buff_size);
}
/* Remember original bitmaps */
save_read_set= sort_form->read_set;
save_write_set= sort_form->write_set;
/* Set up temporary column read map for columns used by sort */
DBUG_ASSERT(save_read_set != &sort_form->tmp_set);
bitmap_clear_all(&sort_form->tmp_set);
sort_form->column_bitmaps_set(&sort_form->tmp_set, &sort_form->tmp_set);
register_used_fields(param);
if (quick_select)
select->quick->add_used_key_part_to_set();
sort_cond= (!select ? 0 :
(!select->pre_idx_push_select_cond ?
select->cond : select->pre_idx_push_select_cond));
if (sort_cond)
sort_cond->walk(&Item::register_field_in_read_map, 1, sort_form);
sort_form->file->column_bitmaps_signal();
if (quick_select)
{
if (select->quick->reset())
goto err;
}
if (param->set_all_read_bits)
sort_form->column_bitmaps_set(save_read_set, save_write_set);
DEBUG_SYNC(thd, "after_index_merge_phase1");
for (;;)
{
if (quick_select)
error= select->quick->get_next();
else /* Not quick-select */
{
error= file->ha_rnd_next(sort_form->record[0]);
if (param->unpack)
param->unpack(sort_form);
}
if (unlikely(error))
break;
file->position(sort_form->record[0]);
DBUG_EXECUTE_IF("debug_filesort", dbug_print_record(sort_form, TRUE););
if (unlikely(thd->check_killed()))
{
DBUG_PRINT("info",("Sort killed by user"));
if (!quick_select)
{
(void) file->extra(HA_EXTRA_NO_CACHE);
file->ha_rnd_end();
}
goto err; /* purecov: inspected */
}
bool write_record= false;
if (likely(error == 0))
{
param->examined_rows++;
if (select && select->cond)
{
/*
If the condition 'select->cond' contains a subquery, restore the
original read/write sets of the table 'sort_form' because when
SQL_SELECT::skip_record evaluates this condition. it may include a
correlated subquery predicate, such that some field in the subquery
refers to 'sort_form'.
PSergey-todo: discuss the above with Timour.
*/
MY_BITMAP *tmp_read_set= sort_form->read_set;
MY_BITMAP *tmp_write_set= sort_form->write_set;
if (select->cond->with_subquery())
sort_form->column_bitmaps_set(save_read_set, save_write_set);
write_record= (select->skip_record(thd) > 0);
if (select->cond->with_subquery())
sort_form->column_bitmaps_set(tmp_read_set, tmp_write_set);
}
else
write_record= true;
}
if (write_record)
{
if (pq)
pq->push(ref_pos);
else
{
if (fs_info->isfull())
{
if (write_keys(param, fs_info, idx, buffpek_pointers, tempfile))
goto err;
idx= 0;
indexpos++;
}
if (idx == 0)
fs_info->init_next_record_pointer();
uchar *start_of_rec= fs_info->get_next_record_pointer();
const uint rec_sz= make_sortkey(param, start_of_rec,
ref_pos, using_packed_sortkeys);
if (packed_format && rec_sz != param->rec_length)
fs_info->adjust_next_record_pointer(rec_sz);
idx++;
}
num_records++;
(*param->accepted_rows)++;
}
/* It does not make sense to read more keys in case of a fatal error */
if (unlikely(thd->is_error()))
break;
/*
We need to this after checking the error as the transaction may have
rolled back in case of a deadlock
*/
if (!write_record)
file->unlock_row();
}
if (!quick_select)
{
(void) file->extra(HA_EXTRA_NO_CACHE); /* End caching of records */
if (!next_pos)
file->ha_rnd_end();
}
/* Signal we should use original column read and write maps */
sort_form->column_bitmaps_set(save_read_set, save_write_set);
if (unlikely(thd->is_error()))
DBUG_RETURN(HA_POS_ERROR);
DBUG_PRINT("test",("error: %d indexpos: %d",error,indexpos));
if (unlikely(error != HA_ERR_END_OF_FILE))
{
file->print_error(error,MYF(ME_ERROR_LOG));
DBUG_RETURN(HA_POS_ERROR);
}
if (indexpos && idx &&
write_keys(param, fs_info, idx, buffpek_pointers, tempfile))
DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */
(*found_rows)= num_records;
if (pq)
num_records= pq->num_elements();
DBUG_PRINT("info", ("find_all_keys return %llu", (ulonglong) num_records));
DBUG_RETURN(num_records);
err:
sort_form->column_bitmaps_set(save_read_set, save_write_set);
DBUG_RETURN(HA_POS_ERROR);
} /* find_all_keys */
/**
@details
Sort the buffer and write:
-# the sorted sequence to tempfile
-# a BUFFPEK describing the sorted sequence position to buffpek_pointers
(was: Skriver en buffert med nycklar till filen)
@param param Sort parameters
@param sort_keys Array of pointers to keys to sort
@param count Number of elements in sort_keys array
@param buffpek_pointers One 'BUFFPEK' struct will be written into this file.
The BUFFPEK::{file_pos, count} will indicate where
the sorted data was stored.
@param tempfile The sorted sequence will be written into this file.
@retval
0 OK
@retval
1 Error
*/
static bool
write_keys(Sort_param *param, SORT_INFO *fs_info, uint count,
IO_CACHE *buffpek_pointers, IO_CACHE *tempfile)
{
Merge_chunk buffpek;
DBUG_ENTER("write_keys");
fs_info->sort_buffer(param, count);
if (!my_b_inited(tempfile) &&
open_cached_file(tempfile, mysql_tmpdir, TEMP_PREFIX, DISK_BUFFER_SIZE,
MYF(MY_WME)))
DBUG_RETURN(1); /* purecov: inspected */
/* check we won't have more buffpeks than we can possibly keep in memory */
if (my_b_tell(buffpek_pointers) + sizeof(Merge_chunk) > (ulonglong)UINT_MAX)
DBUG_RETURN(1);
buffpek.set_file_position(my_b_tell(tempfile));
if ((ha_rows) count > param->max_rows)
count=(uint) param->max_rows; /* purecov: inspected */
buffpek.set_rowcount(static_cast<ha_rows>(count));
for (uint ix= 0; ix < count; ++ix)
{
uchar *record= fs_info->get_sorted_record(ix);
if (my_b_write(tempfile, record, param->get_record_length(record)))
DBUG_RETURN(1); /* purecov: inspected */
}
if (my_b_write(buffpek_pointers, (uchar*) &buffpek, sizeof(buffpek)))
DBUG_RETURN(1);
DBUG_RETURN(0);
} /* write_keys */
/**
Store length in high-byte-first order.
*/
void store_length(uchar *to, uint length, uint pack_length)
{
switch (pack_length) {
case 1:
*to= (uchar) length;
break;
case 2:
mi_int2store(to, length);
break;
case 3:
mi_int3store(to, length);
break;
default:
mi_int4store(to, length);
break;
}
}
void
Type_handler_string_result::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
CHARSET_INFO *cs= item->collation.collation;
bool maybe_null= item->maybe_null();
if (maybe_null)
*to++= 1;
String *res= item->str_result(¶m->tmp_buffer);
if (!res)
{
if (maybe_null)
memset(to - 1, 0, sort_field->length + 1);
else
{
/* purecov: begin deadcode */
/*
This should only happen during extreme conditions if we run out
of memory or have an item marked not null when it can be null.
This code is here mainly to avoid a hard crash in this case.
*/
DBUG_ASSERT(0);
DBUG_PRINT("warning",
("Got null on something that shouldn't be null"));
memset(to, 0, sort_field->length); // Avoid crash
/* purecov: end */
}
return;
}
if (use_strnxfrm(cs))
{
#ifdef DBUG_ASSERT_EXISTS
size_t tmp_length=
#endif
cs->strnxfrm(to, sort_field->length,
item->max_char_length() * cs->strxfrm_multiply,
(uchar*) res->ptr(), res->length(),
MY_STRXFRM_PAD_WITH_SPACE |
MY_STRXFRM_PAD_TO_MAXLEN);
DBUG_ASSERT(tmp_length == sort_field->length);
}
else
{
uint diff;
uint sort_field_length= sort_field->length - sort_field->suffix_length;
uint length= res->length();
if (sort_field_length < length)
{
diff= 0;
length= sort_field_length;
}
else
diff= sort_field_length - length;
if (sort_field->suffix_length)
{
/* Store length last in result_string */
store_length(to + sort_field_length, length, sort_field->suffix_length);
}
/* apply cs->sort_order for case-insensitive comparison if needed */
cs->strnxfrm((uchar*)to, length, (const uchar*) res->ptr(), length);
char fill_char= ((cs->state & MY_CS_BINSORT) ? (char) 0 : ' ');
cs->fill((char *) to + length, diff, fill_char);
}
}
void
Type_handler_int_result::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
longlong value= item->val_int_result();
make_sort_key_longlong(to, item->maybe_null(), item->null_value,
item->unsigned_flag, value);
}
void
Type_handler_temporal_result::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
MYSQL_TIME buf;
// This is a temporal type. No nanoseconds. Rounding mode is not important.
DBUG_ASSERT(item->cmp_type() == TIME_RESULT);
static const Temporal::Options opt(TIME_INVALID_DATES, TIME_FRAC_NONE);
if (item->get_date_result(current_thd, &buf, opt))
{
DBUG_ASSERT(item->maybe_null());
DBUG_ASSERT(item->null_value);
make_sort_key_longlong(to, item->maybe_null(), true,
item->unsigned_flag, 0);
}
else
make_sort_key_longlong(to, item->maybe_null(), false,
item->unsigned_flag, pack_time(&buf));
}
void
Type_handler_timestamp_common::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
THD *thd= current_thd;
uint binlen= my_timestamp_binary_length(item->decimals);
Timestamp_or_zero_datetime_native_null native(thd, item);
if (native.is_null() || native.is_zero_datetime())
{
// NULL or '0000-00-00 00:00:00'
bzero(to, item->maybe_null() ? binlen + 1 : binlen);
}
else
{
if (item->maybe_null())
*to++= 1;
if (native.length() != binlen)
{
/*
Some items can return native representation with a different
number of fractional digits, e.g.: GREATEST(ts_3, ts_4) can
return a value with 3 fractional digits, although its fractional
precision is 4. Re-pack with a proper precision now.
*/
Timestamp(native).to_native(&native, item->datetime_precision(thd));
}
DBUG_ASSERT(native.length() == binlen);
memcpy((char *) to, native.ptr(), binlen);
}
}
void
Type_handler::store_sort_key_longlong(uchar *to, bool unsigned_flag,
longlong value) const
{
to[7]= (uchar) value;
to[6]= (uchar) (value >> 8);
to[5]= (uchar) (value >> 16);
to[4]= (uchar) (value >> 24);
to[3]= (uchar) (value >> 32);
to[2]= (uchar) (value >> 40);
to[1]= (uchar) (value >> 48);
if (unsigned_flag) /* Fix sign */
to[0]= (uchar) (value >> 56);
else
to[0]= (uchar) (value >> 56) ^ 128; /* Reverse signbit */
}
void
Type_handler::make_sort_key_longlong(uchar *to,
bool maybe_null,
bool null_value,
bool unsigned_flag,
longlong value) const
{
if (maybe_null)
{
if (null_value)
{
memset(to, 0, 9);
return;
}
*to++= 1;
}
store_sort_key_longlong(to, unsigned_flag, value);
}
uint
Type_handler::make_packed_sort_key_longlong(uchar *to, bool maybe_null,
bool null_value, bool unsigned_flag,
longlong value,
const SORT_FIELD_ATTR *sort_field) const
{
if (maybe_null)
{
if (null_value)
{
*to++= 0;
return 0;
}
*to++= 1;
}
store_sort_key_longlong(to, unsigned_flag, value);
DBUG_ASSERT(sort_field->original_length == sort_field->length);
return sort_field->original_length;
}
void
Type_handler_decimal_result::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf);
if (item->maybe_null())
{
if (item->null_value)
{
memset(to, 0, sort_field->length + 1);
return;
}
*to++= 1;
}
dec_val->to_binary(to, item->max_length - (item->decimals ? 1 : 0),
item->decimals);
}
void
Type_handler_real_result::make_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
double value= item->val_result();
if (item->maybe_null())
{
if (item->null_value)
{
memset(to, 0, sort_field->length + 1);
return;
}
*to++= 1;
}
change_double_for_sort(value, to);
}
/** Make a sort-key from record. */
static uint make_sortkey(Sort_param *param, uchar *to, uchar *ref_pos,
bool using_packed_sortkeys)
{
uchar *orig_to= to;
to+= using_packed_sortkeys ?
make_packed_sortkey(param, to) :
make_sortkey(param, to);
if (param->using_addon_fields())
{
/*
Save field values appended to sorted fields.
First null bit indicators are appended then field values follow.
In this implementation we use fixed layout for field values -
the same for all records.
*/
SORT_ADDON_FIELD *addonf= param->addon_fields->begin();
uchar *nulls= to;
uchar *p_len= to;
DBUG_ASSERT(addonf != 0);
const bool packed_addon_fields= param->addon_fields->using_packed_addons();
uint32 res_len= addonf->offset;
memset(nulls, 0, addonf->offset);
to+= addonf->offset;
for ( ; addonf != param->addon_fields->end() ; addonf++)
{
Field *field= addonf->field;
if (addonf->null_bit && field->is_null())
{
nulls[addonf->null_offset]|= addonf->null_bit;
if (!packed_addon_fields)
to+= addonf->length;
}
else
{
uchar *end= field->pack(to, field->ptr);
DBUG_ASSERT(end >= to);
uint sz= static_cast<uint>(end - to);
res_len += sz;
if (packed_addon_fields)
to+= sz;
else
{
if (addonf->length > sz)
bzero(end, addonf->length - sz); // Make Valgrind/MSAN happy
to+= addonf->length;
}
}
}
if (packed_addon_fields)
Addon_fields::store_addon_length(p_len, res_len);
}
else
{
/* Save filepos last */
memcpy((uchar*) to, ref_pos, (size_t) param->ref_length);
to+= param->ref_length;
}
return static_cast<uint>(to - orig_to);
}
/*
Register fields used by sorting in the sorted table's read set
*/
static void register_used_fields(Sort_param *param)
{
SORT_FIELD *sort_field;
TABLE *table=param->sort_form;
for (sort_field= param->local_sortorder.begin() ;
sort_field != param->local_sortorder.end() ;
sort_field++)
{
Field *field;
if ((field= sort_field->field))
{
if (field->table == table)
field->register_field_in_read_map();
}
else
{ // Item
sort_field->item->walk(&Item::register_field_in_read_map, 1, table);
}
}
if (param->using_addon_fields())
{
SORT_ADDON_FIELD *addonf= param->addon_fields->begin();
for ( ; (addonf != param->addon_fields->end()) ; addonf++)
{
Field *field= addonf->field;
field->register_field_in_read_map();
}
}
else
{
/* Save filepos last */
table->prepare_for_position();
}
}
static bool save_index(Sort_param *param, uint count,
SORT_INFO *table_sort)
{
uint offset,res_length, length;
uchar *to;
DBUG_ENTER("save_index");
DBUG_ASSERT(table_sort->record_pointers == 0);
table_sort->sort_buffer(param, count);
if (param->using_addon_fields())
{
table_sort->sorted_result_in_fsbuf= TRUE;
table_sort->set_sort_length(param->sort_length);
DBUG_RETURN(0);
}
bool using_packed_sortkeys= param->using_packed_sortkeys();
res_length= param->res_length;
offset= param->rec_length-res_length;
if (!(to= table_sort->record_pointers=
(uchar*) my_malloc(key_memory_Filesort_info_record_pointers,
res_length*count, MYF(MY_WME | MY_THREAD_SPECIFIC))))
DBUG_RETURN(1); /* purecov: inspected */
for (uint ix= 0; ix < count; ++ix)
{
uchar *record= table_sort->get_sorted_record(ix);
length= using_packed_sortkeys ?
Sort_keys::read_sortkey_length(record) : offset;
memcpy(to, record + length, res_length);
to+= res_length;
}
DBUG_RETURN(0);
}
/**
Test whether priority queue is worth using to get top elements of an
ordered result set. If it is, then allocates buffer for required amount of
records
@param param Sort parameters.
@param filesort_info Filesort information.
@param table Table to sort.
@param num_rows Estimate of number of rows in source record set.
@param memory_available Memory available for sorting.
DESCRIPTION
Given a query like this:
SELECT ... FROM t ORDER BY a1,...,an LIMIT max_rows;
This function tests whether a priority queue should be used to keep
the result. Necessary conditions are:
- estimate that it is actually cheaper than merge-sort
- enough memory to store the <max_rows> records.
If we don't have space for <max_rows> records, but we *do* have
space for <max_rows> keys, we may rewrite 'table' to sort with
references to records instead of additional data.
(again, based on estimates that it will actually be cheaper).
@retval
true - if it's ok to use PQ
false - PQ will be slower than merge-sort, or there is not enough memory.
*/
static bool check_if_pq_applicable(Sort_param *param,
SORT_INFO *filesort_info,
TABLE *table, ha_rows num_rows,
size_t memory_available)
{
DBUG_ENTER("check_if_pq_applicable");
/*
How much Priority Queue sort is slower than qsort.
Measurements (see unit test) indicate that PQ is roughly 3 times slower.
*/
const double PQ_slowness= 3.0;
if (param->max_rows == HA_POS_ERROR)
{
DBUG_PRINT("info", ("No LIMIT"));
DBUG_RETURN(false);
}
if (param->max_rows + 2 >= UINT_MAX)
{
DBUG_PRINT("info", ("Too large LIMIT"));
DBUG_RETURN(false);
}
size_t num_available_keys=
memory_available / (param->rec_length + sizeof(char*));
// We need 1 extra record in the buffer, when using PQ.
param->max_keys_per_buffer= (uint) param->max_rows + 1;
if (num_rows < num_available_keys)
{
// The whole source set fits into memory.
if (param->max_rows < num_rows/PQ_slowness )
{
filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->rec_length);
DBUG_RETURN(filesort_info->sort_buffer_size() != 0);
}
else
{
// PQ will be slower.
DBUG_RETURN(false);
}
}
// Do we have space for LIMIT rows in memory?
if (param->max_keys_per_buffer < num_available_keys)
{
filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->rec_length);
DBUG_RETURN(filesort_info->sort_buffer_size() != 0);
}
// Try to strip off addon fields.
if (param->addon_fields)
{
const size_t row_length=
param->sort_length + param->ref_length + sizeof(char*);
num_available_keys= memory_available / row_length;
// Can we fit all the keys in memory?
if (param->max_keys_per_buffer < num_available_keys)
{
const double sort_merge_cost=
get_merge_many_buffs_cost_fast(num_rows,
num_available_keys,
(uint)row_length);
/*
PQ has cost:
(insert + qsort) * log(queue size) / TIME_FOR_COMPARE_ROWID +
cost of file lookup afterwards.
The lookup cost is a bit pessimistic: we take scan_time and assume
that on average we find the row after scanning half of the file.
A better estimate would be lookup cost, but note that we are doing
random lookups here, rather than sequential scan.
*/
const double pq_cpu_cost=
(PQ_slowness * num_rows + param->max_keys_per_buffer) *
log((double) param->max_keys_per_buffer) / TIME_FOR_COMPARE_ROWID;
const double pq_io_cost=
param->max_rows * table->file->scan_time() / 2.0;
const double pq_cost= pq_cpu_cost + pq_io_cost;
if (sort_merge_cost < pq_cost)
DBUG_RETURN(false);
filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->sort_length + param->ref_length);
if (filesort_info->sort_buffer_size() > 0)
{
/* Make attached data to be references instead of fields. */
my_free(filesort_info->addon_fields);
filesort_info->addon_fields= NULL;
param->addon_fields= NULL;
param->res_length= param->ref_length;
param->sort_length+= param->ref_length;
param->rec_length= param->sort_length;
DBUG_RETURN(true);
}
}
}
DBUG_RETURN(false);
}
/** Merge buffers to make < MERGEBUFF2 buffers. */
int merge_many_buff(Sort_param *param, Sort_buffer sort_buffer,
Merge_chunk *buffpek, uint *maxbuffer, IO_CACHE *t_file)
{
uint i;
IO_CACHE t_file2,*from_file,*to_file,*temp;
Merge_chunk *lastbuff;
DBUG_ENTER("merge_many_buff");
if (*maxbuffer < MERGEBUFF2)
DBUG_RETURN(0); /* purecov: inspected */
if (flush_io_cache(t_file) ||
open_cached_file(&t_file2,mysql_tmpdir,TEMP_PREFIX,DISK_BUFFER_SIZE,
MYF(MY_WME)))
DBUG_RETURN(1); /* purecov: inspected */
from_file= t_file ; to_file= &t_file2;
while (*maxbuffer >= MERGEBUFF2)
{
if (reinit_io_cache(from_file,READ_CACHE,0L,0,0))
goto cleanup;
if (reinit_io_cache(to_file,WRITE_CACHE,0L,0,0))
goto cleanup;
lastbuff=buffpek;
for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF)
{
if (merge_buffers(param,from_file,to_file,sort_buffer, lastbuff++,
buffpek+i,buffpek+i+MERGEBUFF-1,0))
goto cleanup;
}
if (merge_buffers(param,from_file,to_file,sort_buffer, lastbuff++,
buffpek+i,buffpek+ *maxbuffer,0))
break; /* purecov: inspected */
if (flush_io_cache(to_file))
break; /* purecov: inspected */
temp=from_file; from_file=to_file; to_file=temp;
*maxbuffer= (uint) (lastbuff-buffpek)-1;
}
cleanup:
close_cached_file(to_file); // This holds old result
if (to_file == t_file)
{
*t_file=t_file2; // Copy result file
}
DBUG_RETURN(*maxbuffer >= MERGEBUFF2); /* Return 1 if interrupted */
} /* merge_many_buff */
/**
Read data to buffer.
@retval Number of bytes read
(ulong)-1 if something goes wrong
*/
ulong read_to_buffer(IO_CACHE *fromfile, Merge_chunk *buffpek,
Sort_param *param, bool packed_format)
{
ha_rows count;
uint rec_length= param->rec_length;
if ((count= MY_MIN(buffpek->max_keys(),buffpek->rowcount())))
{
size_t bytes_to_read;
if (packed_format)
{
count= buffpek->rowcount();
bytes_to_read= MY_MIN(buffpek->buffer_size(),
static_cast<size_t>(fromfile->end_of_file -
buffpek->file_position()));
}
else
bytes_to_read= rec_length * static_cast<size_t>(count);
if (unlikely(my_b_pread(fromfile, buffpek->buffer_start(),
bytes_to_read, buffpek->file_position())))
return ((ulong) -1);
size_t num_bytes_read;
if (packed_format)
{
/*
The last record read is most likely not complete here.
We need to loop through all the records, reading the length fields,
and then "chop off" the final incomplete record.
*/
uchar *record= buffpek->buffer_start();
uint ix= 0;
uint size_of_addon_length= param->using_packed_addons() ?
Addon_fields::size_of_length_field : 0;
uint size_of_sort_length= param->using_packed_sortkeys() ?
Sort_keys::size_of_length_field : 0;
for (; ix < count; ++ix)
{
if (record + size_of_sort_length > buffpek->buffer_end())
break;
uint sort_length= param->using_packed_sortkeys() ?
Sort_keys::read_sortkey_length(record) :
param->sort_length;
DBUG_ASSERT(sort_length <= param->sort_length);
if (record + sort_length + size_of_addon_length >
buffpek->buffer_end())
break; // Incomplete record.
uchar *plen= record + sort_length;
uint res_length= param->get_result_length(plen);
if (plen + res_length > buffpek->buffer_end())
break; // Incomplete record.
DBUG_ASSERT(res_length > 0);
DBUG_ASSERT(sort_length + res_length <= param->rec_length);
record+= sort_length;
record+= res_length;
}
DBUG_ASSERT(ix > 0);
count= ix;
num_bytes_read= record - buffpek->buffer_start();
DBUG_PRINT("info", ("read %llu bytes of complete records",
static_cast<ulonglong>(bytes_to_read)));
}
else
num_bytes_read= bytes_to_read;
buffpek->init_current_key();
buffpek->advance_file_position(num_bytes_read); /* New filepos */
buffpek->decrement_rowcount(count);
buffpek->set_mem_count(count);
return (ulong) num_bytes_read;
}
return 0;
} /* read_to_buffer */
/**
Put all room used by freed buffer to use in adjacent buffer.
Note, that we can't simply distribute memory evenly between all buffers,
because new areas must not overlap with old ones.
@param[in] queue list of non-empty buffers, without freed buffer
@param[in] reuse empty buffer
@param[in] key_length key length
*/
void reuse_freed_buff(QUEUE *queue, Merge_chunk *reuse, uint key_length)
{
for (uint i= queue_first_element(queue);
i <= queue_last_element(queue);
i++)
{
Merge_chunk *bp= (Merge_chunk *) queue_element(queue, i);
if (reuse->merge_freed_buff(bp))
return;
}
DBUG_ASSERT(0);
}
/**
Merge buffers to one buffer.
@param param Sort parameter
@param from_file File with source data (BUFFPEKs point to this file)
@param to_file File to write the sorted result data.
@param sort_buffer Buffer for data to store up to MERGEBUFF2 sort keys.
@param lastbuff OUT Store here BUFFPEK describing data written to to_file
@param Fb First element in source BUFFPEKs array
@param Tb Last element in source BUFFPEKs array
@param flag 0 <=> write {sort_key, addon_fields} pairs as further
sorting will be performed
1 <=> write just addon_fields as this is the final
merge pass
@retval
0 OK
@retval
1 ERROR
*/
bool merge_buffers(Sort_param *param, IO_CACHE *from_file,
IO_CACHE *to_file, Sort_buffer sort_buffer,
Merge_chunk *lastbuff, Merge_chunk *Fb, Merge_chunk *Tb,
int flag)
{
bool error= 0;
uint rec_length,res_length,offset;
size_t sort_length;
ulong maxcount, bytes_read;
ha_rows max_rows,org_max_rows;
my_off_t to_start_filepos;
uchar *strpos;
Merge_chunk *buffpek;
QUEUE queue;
qsort2_cmp cmp;
void *first_cmp_arg;
element_count dupl_count= 0;
uchar *src;
uchar *unique_buff= param->unique_buff;
const bool killable= !param->not_killable;
THD* const thd=current_thd;
DBUG_ENTER("merge_buffers");
thd->inc_status_sort_merge_passes();
thd->query_plan_fsort_passes++;
rec_length= param->rec_length;
res_length= param->res_length;
sort_length= param->sort_length;
uint dupl_count_ofs= rec_length-sizeof(element_count);
uint min_dupl_count= param->min_dupl_count;
bool check_dupl_count= flag && min_dupl_count;
offset= (rec_length-
(flag && min_dupl_count ? sizeof(dupl_count) : 0)-res_length);
uint wr_len= flag ? res_length : rec_length;
uint wr_offset= flag ? offset : 0;
const bool using_packed_sortkeys= param->using_packed_sortkeys();
bool offset_for_packing= (flag == 1 && using_packed_sortkeys);
const bool packed_format= param->is_packed_format();
maxcount= (ulong) (param->max_keys_per_buffer/((uint) (Tb-Fb) +1));
to_start_filepos= my_b_tell(to_file);
strpos= sort_buffer.array();
org_max_rows=max_rows= param->max_rows;
set_if_bigger(maxcount, 1);
if (unique_buff)
{
cmp= param->compare;
first_cmp_arg= (void *) ¶m->cmp_context;
}
else
{
cmp= param->get_compare_function();
first_cmp_arg= param->get_compare_argument(&sort_length);
}
if (unlikely(init_queue(&queue, (uint) (Tb-Fb)+1,
offsetof(Merge_chunk,m_current_key), 0,
(queue_compare) cmp, first_cmp_arg, 0, 0)))
DBUG_RETURN(1); /* purecov: inspected */
const size_t chunk_sz = (sort_buffer.size()/((uint) (Tb-Fb) +1));
for (buffpek= Fb ; buffpek <= Tb ; buffpek++)
{
buffpek->set_buffer(strpos, strpos + chunk_sz);
buffpek->set_max_keys(maxcount);
bytes_read= read_to_buffer(from_file, buffpek, param, packed_format);
if (unlikely(bytes_read == (ulong) -1))
goto err; /* purecov: inspected */
strpos+= chunk_sz;
// If less data in buffers than expected
buffpek->set_max_keys(buffpek->mem_count());
queue_insert(&queue, (uchar*) buffpek);
}
if (unique_buff)
{
/*
Called by Unique::get()
Copy the first argument to unique_buff for unique removal.
Store it also in 'to_file'.
*/
buffpek= (Merge_chunk*) queue_top(&queue);
memcpy(unique_buff, buffpek->current_key(), rec_length);
if (min_dupl_count)
memcpy(&dupl_count, unique_buff+dupl_count_ofs,
sizeof(dupl_count));
buffpek->advance_current_key(rec_length);
buffpek->decrement_mem_count();
if (buffpek->mem_count() == 0)
{
if (unlikely(!(bytes_read= read_to_buffer(from_file, buffpek,
param, packed_format))))
{
(void) queue_remove_top(&queue);
reuse_freed_buff(&queue, buffpek, rec_length);
}
else if (unlikely(bytes_read == (ulong) -1))
goto err; /* purecov: inspected */
}
queue_replace_top(&queue); // Top element has been used
}
else
cmp= 0; // Not unique
while (queue.elements > 1)
{
if (killable && unlikely(thd->check_killed()))
goto err; /* purecov: inspected */
for (;;)
{
buffpek= (Merge_chunk*) queue_top(&queue);
src= buffpek->current_key();
if (cmp) // Remove duplicates
{
uchar *current_key= buffpek->current_key();
if (!(*cmp)(first_cmp_arg, &unique_buff, ¤t_key))
{
if (min_dupl_count)
{
element_count cnt;
memcpy(&cnt, buffpek->current_key() + dupl_count_ofs, sizeof(cnt));
dupl_count+= cnt;
}
goto skip_duplicate;
}
if (min_dupl_count)
{
memcpy(unique_buff+dupl_count_ofs, &dupl_count,
sizeof(dupl_count));
}
src= unique_buff;
}
{
param->get_rec_and_res_len(buffpek->current_key(),
&rec_length, &res_length);
const uint bytes_to_write= (flag == 0) ? rec_length : res_length;
/*
Do not write into the output file if this is the final merge called
for a Unique object used for intersection and dupl_count is less
than min_dupl_count.
If the Unique object is used to intersect N sets of unique elements
then for any element:
dupl_count >= N <=> the element is occurred in each of these N sets.
*/
if (!check_dupl_count || dupl_count >= min_dupl_count)
{
if(my_b_write(to_file,
src + (offset_for_packing ?
rec_length - res_length : // sort length
wr_offset),
bytes_to_write))
goto err; /* purecov: inspected */
}
if (cmp)
{
memcpy(unique_buff, buffpek->current_key(), rec_length);
if (min_dupl_count)
memcpy(&dupl_count, unique_buff+dupl_count_ofs,
sizeof(dupl_count));
}
if (!--max_rows)
{
/* Nothing more to do */
goto end; /* purecov: inspected */
}
}
skip_duplicate:
buffpek->advance_current_key(rec_length);
buffpek->decrement_mem_count();
if (buffpek->mem_count() == 0)
{
if (unlikely(!(bytes_read= read_to_buffer(from_file, buffpek,
param, packed_format))))
{
(void) queue_remove_top(&queue);
reuse_freed_buff(&queue, buffpek, rec_length);
break; /* One buffer have been removed */
}
else if (unlikely(bytes_read == (ulong) -1))
goto err; /* purecov: inspected */
}
queue_replace_top(&queue); /* Top element has been replaced */
}
}
buffpek= (Merge_chunk*) queue_top(&queue);
buffpek->set_buffer(sort_buffer.array(),
sort_buffer.array() + sort_buffer.size());
buffpek->set_max_keys(param->max_keys_per_buffer);
/*
As we know all entries in the buffer are unique, we only have to
check if the first one is the same as the last one we wrote
*/
if (cmp)
{
uchar *current_key= buffpek->current_key();
if (!(*cmp)(first_cmp_arg, &unique_buff, ¤t_key))
{
if (min_dupl_count)
{
element_count cnt;
memcpy(&cnt, buffpek->current_key() + dupl_count_ofs, sizeof(cnt));
dupl_count+= cnt;
}
buffpek->advance_current_key(rec_length);
buffpek->decrement_mem_count();
}
if (min_dupl_count)
memcpy(unique_buff+dupl_count_ofs, &dupl_count,
sizeof(dupl_count));
if (!check_dupl_count || dupl_count >= min_dupl_count)
{
src= unique_buff;
if (my_b_write(to_file, src+wr_offset, wr_len))
goto err; /* purecov: inspected */
if (!--max_rows)
goto end;
}
}
do
{
if (buffpek->mem_count() > max_rows)
{ /* Don't write too many records */
buffpek->set_mem_count(max_rows);
buffpek->set_rowcount(0); /* Don't read more */
}
max_rows-= buffpek->mem_count();
for (uint ix= 0; ix < buffpek->mem_count(); ++ix)
{
uchar *src= buffpek->current_key();
param->get_rec_and_res_len(src,
&rec_length, &res_length);
const uint bytes_to_write= (flag == 0) ? rec_length : res_length;
if (check_dupl_count)
{
memcpy((uchar *) &dupl_count,
buffpek->current_key() + offset + dupl_count_ofs,
sizeof(dupl_count));
if (dupl_count < min_dupl_count)
continue;
}
if(my_b_write(to_file,
src + (offset_for_packing ?
rec_length - res_length : // sort length
wr_offset),
bytes_to_write))
goto err;
buffpek->advance_current_key(rec_length);
}
}
while (likely(!(error=
(bytes_read= read_to_buffer(from_file, buffpek, param,
packed_format)) == (ulong) -1)) &&
bytes_read != 0);
end:
lastbuff->set_rowcount(MY_MIN(org_max_rows-max_rows, param->max_rows));
lastbuff->set_file_position(to_start_filepos);
cleanup:
delete_queue(&queue);
DBUG_RETURN(error);
err:
error= 1;
goto cleanup;
} /* merge_buffers */
/* Do a merge to output-file (save only positions) */
int merge_index(Sort_param *param, Sort_buffer sort_buffer,
Merge_chunk *buffpek, uint maxbuffer,
IO_CACHE *tempfile, IO_CACHE *outfile)
{
DBUG_ENTER("merge_index");
if (merge_buffers(param, tempfile, outfile, sort_buffer, buffpek, buffpek,
buffpek + maxbuffer, 1))
DBUG_RETURN(1); /* purecov: inspected */
DBUG_RETURN(0);
} /* merge_index */
static uint suffix_length(ulong string_length)
{
if (string_length < 256)
return 1;
if (string_length < 256L*256L)
return 2;
if (string_length < 256L*256L*256L)
return 3;
return 4; // Can't sort longer than 4G
}
void
Type_handler_string_result::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
CHARSET_INFO *cs;
sortorder->set_length_and_original_length(thd, item->max_length);
if (use_strnxfrm((cs= item->collation.collation)))
{
sortorder->length= (uint) cs->strnxfrmlen(sortorder->length);
}
else if (cs == &my_charset_bin)
{
/* Store length last to be able to sort blob/varbinary */
sortorder->suffix_length= suffix_length(item->max_length);
DBUG_ASSERT(sortorder->length <= UINT_MAX32 - sortorder->suffix_length);
sortorder->length+= sortorder->suffix_length;
if (sortorder->original_length >= UINT_MAX32 - sortorder->suffix_length)
sortorder->original_length= UINT_MAX32;
else
sortorder->original_length+= sortorder->suffix_length;
}
}
void
Type_handler_temporal_result::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->original_length= sortorder->length= 8; // Sizof intern longlong
}
void
Type_handler_timestamp_common::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length= my_timestamp_binary_length(item->decimals);
sortorder->original_length= sortorder->length;
}
void
Type_handler_int_result::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->original_length= sortorder->length= 8; // Sizof intern longlong
}
void
Type_handler_real_result::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->original_length= sortorder->length= sizeof(double);
}
void
Type_handler_decimal_result::sort_length(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length=
my_decimal_get_binary_size(item->max_length - (item->decimals ? 1 : 0),
item->decimals);
sortorder->original_length= sortorder->length;
}
/**
Calculate length of sort key.
@param thd Thread handler
@param sortorder Order of items to sort
@param s_length Number of items to sort
@param allow_packing_for_sortkeys [out] set to false if packing sort keys is not
allowed
@note
* sortorder->length and other members are updated for each sort item.
* TODO what is the meaning of this value if some fields are using packing while
others are not?
@return
Total length of sort buffer in bytes
*/
static uint
sortlength(THD *thd, Sort_keys *sort_keys, bool *allow_packing_for_sortkeys)
{
uint length;
*allow_packing_for_sortkeys= true;
bool allow_packing_for_keys= true;
length=0;
uint nullable_cols=0;
if (sort_keys->is_parameters_computed())
{
*allow_packing_for_sortkeys= sort_keys->using_packed_sortkeys();
return sort_keys->get_sort_length_with_memcmp_values();
}
for (SORT_FIELD *sortorder= sort_keys->begin();
sortorder != sort_keys->end();
sortorder++)
{
sortorder->suffix_length= 0;
sortorder->length_bytes= 0;
if (sortorder->field)
{
Field *field= sortorder->field;
CHARSET_INFO *cs= sortorder->field->sort_charset();
sortorder->type= field->is_packable() ?
SORT_FIELD_ATTR::VARIABLE_SIZE :
SORT_FIELD_ATTR::FIXED_SIZE;
sortorder->set_length_and_original_length(thd, field->sort_length());
sortorder->suffix_length= sortorder->field->sort_suffix_length();
sortorder->cs= cs;
if (use_strnxfrm((cs=sortorder->field->sort_charset())))
sortorder->length= (uint) cs->strnxfrmlen(sortorder->length);
if (sortorder->is_variable_sized() && allow_packing_for_keys)
{
allow_packing_for_keys= sortorder->check_if_packing_possible(thd);
sortorder->length_bytes=
number_storage_requirement(MY_MIN(sortorder->original_length,
thd->variables.max_sort_length));
}
if ((sortorder->maybe_null= sortorder->field->maybe_null()))
nullable_cols++; // Place for NULL marker
}
else
{
sortorder->type= sortorder->item->type_handler()->is_packable() ?
SORT_FIELD_ATTR::VARIABLE_SIZE :
SORT_FIELD_ATTR::FIXED_SIZE;
sortorder->item->type_handler()->sort_length(thd, sortorder->item,
sortorder);
sortorder->cs= sortorder->item->collation.collation;
if (sortorder->is_variable_sized() && allow_packing_for_keys)
{
allow_packing_for_keys= sortorder->check_if_packing_possible(thd);
sortorder->length_bytes=
number_storage_requirement(MY_MIN(sortorder->original_length,
thd->variables.max_sort_length));
}
if ((sortorder->maybe_null= sortorder->item->maybe_null()))
nullable_cols++; // Place for NULL marker
}
if (sortorder->is_variable_sized())
{
set_if_smaller(sortorder->length, thd->variables.max_sort_length);
set_if_smaller(sortorder->original_length, thd->variables.max_sort_length);
}
length+=sortorder->length;
sort_keys->increment_size_of_packable_fields(sortorder->length_bytes);
sort_keys->increment_original_sort_length(sortorder->original_length);
}
// add bytes for nullable_cols
sort_keys->increment_original_sort_length(nullable_cols);
*allow_packing_for_sortkeys= allow_packing_for_keys;
sort_keys->set_sort_length_with_memcmp_values(length + nullable_cols);
sort_keys->set_parameters_computed(true);
DBUG_PRINT("info",("sort_length: %d",length));
return length + nullable_cols;
}
/*
Check whether addon fields can be used or not.
@param table Table structure
@param sortlength Length of sort key [strxfrm form]
@param length [OUT] Max length of addon fields
@param fields [OUT] Number of addon fields
@param null_fields [OUT] Number of nullable addon fields
@param packable_length [OUT] Max length of addon fields that can be
packed
@retval
TRUE Addon fields can be used
FALSE Otherwise
*/
bool filesort_use_addons(TABLE *table, uint sortlength,
uint *length, uint *fields, uint *null_fields,
uint *packable_length)
{
Field **pfield, *field;
*length= *fields= *null_fields= *packable_length= 0;
uint field_length=0;
for (pfield= table->field; (field= *pfield) ; pfield++)
{
if (!bitmap_is_set(table->read_set, field->field_index))
continue;
if (field->flags & BLOB_FLAG)
return false;
field_length= field->max_packed_col_length(field->pack_length());
(*length)+= field_length;
if (field->maybe_null() || field->is_packable())
(*packable_length)+= field_length;
if (field->maybe_null())
(*null_fields)++;
(*fields)++;
}
if (!*fields)
return false;
(*length)+= (*null_fields+7)/8;
/*
sortlength used here is unpacked key length (the strxfrm form). This is
done because unpacked key length is a good upper bound for packed sort
key length.
But for some collations the max packed length may be greater than the
length obtained from the strxfrm form.
Example: for utf8_general_ci, the original string form can be longer than
its mem-comparable form (note that this is rarely achieved in practice).
*/
return *length + sortlength <
table->in_use->variables.max_length_for_sort_data;
}
/**
Get descriptors of fields appended to sorted fields and
calculate its total length.
The function first finds out what fields are used in the result set.
Then it calculates the length of the buffer to store the values of
these fields together with the value of sort values.
If the calculated length is not greater than max_length_for_sort_data
the function allocates memory for an array of descriptors containing
layouts for the values of the non-sorted fields in the buffer and
fills them.
@param table Table structure
@param sortlength Total length of sorted fields
@param addon_length [OUT] Length of addon fields
@param m_packable_length [OUT] Length of the addon fields that can be
packed
@note
The null bits for the appended values are supposed to be put together
and stored the buffer just ahead of the value of the first field.
@return
Pointer to the layout descriptors for the appended fields, if any
@retval
NULL if we do not store field values with sort data.
*/
static Addon_fields*
get_addon_fields(TABLE *table, uint sortlength,
uint *addon_length, uint *m_packable_length)
{
Field **pfield;
Field *field;
uint length, fields, null_fields, packable_length;
MY_BITMAP *read_set= table->read_set;
DBUG_ENTER("get_addon_fields");
/*
If there is a reference to a field in the query add it
to the the set of appended fields.
Note for future refinement:
This this a too strong condition.
Actually we need only the fields referred in the
result set. And for some of them it makes sense to use
the values directly from sorted fields.
But beware the case when item->cmp_type() != item->result_type()
*/
// see remove_const() for HA_SLOW_RND_POS explanation
if (table->file->ha_table_flags() & HA_SLOW_RND_POS)
sortlength= 0;
void *raw_mem_addon_field, *raw_mem;
if (!filesort_use_addons(table, sortlength, &length, &fields, &null_fields,
&packable_length) ||
!(my_multi_malloc(PSI_INSTRUMENT_ME, MYF(MY_WME | MY_THREAD_SPECIFIC),
&raw_mem, sizeof(Addon_fields),
&raw_mem_addon_field,
sizeof(SORT_ADDON_FIELD) * fields,
NullS)))
DBUG_RETURN(0);
Addon_fields_array
addon_array(static_cast<SORT_ADDON_FIELD*>(raw_mem_addon_field), fields);
Addon_fields *addon_fields= new (raw_mem) Addon_fields(addon_array);
DBUG_ASSERT(addon_fields);
(*addon_length)= length;
(*m_packable_length)= packable_length;
length= (null_fields+7)/8;
null_fields= 0;
SORT_ADDON_FIELD* addonf= addon_fields->begin();
for (pfield= table->field; (field= *pfield) ; pfield++)
{
if (!bitmap_is_set(read_set, field->field_index))
continue;
addonf->field= field;
addonf->offset= length;
if (field->maybe_null())
{
addonf->null_offset= null_fields/8;
addonf->null_bit= 1<<(null_fields & 7);
null_fields++;
}
else
{
addonf->null_offset= 0;
addonf->null_bit= 0;
}
addonf->length= field->max_packed_col_length(field->pack_length());
length+= addonf->length;
addonf++;
}
DBUG_PRINT("info",("addon_length: %d",length));
DBUG_RETURN(addon_fields);
}
/*
** functions to change a double or float to a sortable string
** The following should work for IEEE
*/
#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
void change_double_for_sort(double nr,uchar *to)
{
uchar *tmp=(uchar*) to;
if (nr == 0.0)
{ /* Change to zero string */
tmp[0]=(uchar) 128;
memset(tmp+1, 0, sizeof(nr)-1);
}
else
{
#ifdef WORDS_BIGENDIAN
memcpy(tmp, &nr, sizeof(nr));
#else
{
uchar *ptr= (uchar*) &nr;
#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN)
tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
tmp[4]= ptr[7]; tmp[5]=ptr[6]; tmp[6]= ptr[5]; tmp[7]=ptr[4];
#else
tmp[0]= ptr[7]; tmp[1]=ptr[6]; tmp[2]= ptr[5]; tmp[3]=ptr[4];
tmp[4]= ptr[3]; tmp[5]=ptr[2]; tmp[6]= ptr[1]; tmp[7]=ptr[0];
#endif
}
#endif
if (tmp[0] & 128) /* Negative */
{ /* make complement */
uint i;
for (i=0 ; i < sizeof(nr); i++)
tmp[i]=tmp[i] ^ (uchar) 255;
}
else
{ /* Set high and move exponent one up */
ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
(ushort) 32768);
exp_part+= (ushort) 1 << (16-1-DBL_EXP_DIG);
tmp[0]= (uchar) (exp_part >> 8);
tmp[1]= (uchar) exp_part;
}
}
}
bool SORT_INFO::using_packed_addons()
{
return addon_fields != NULL && addon_fields->using_packed_addons();
}
void SORT_INFO::free_addon_buff()
{
if (addon_fields)
addon_fields->free_addon_buff();
}
/*
Check if packed sortkeys are used or not
*/
bool SORT_INFO::using_packed_sortkeys()
{
return sort_keys != NULL && sort_keys->using_packed_sortkeys();
}
/**
Free SORT_INFO
*/
SORT_INFO::~SORT_INFO()
{
DBUG_ENTER("~SORT_INFO::SORT_INFO()");
free_data();
DBUG_VOID_RETURN;
}
void Sort_param::try_to_pack_sortkeys()
{
#ifdef WITHOUT_PACKED_SORT_KEYS
return;
#endif
uint size_of_packable_fields= sort_keys->get_size_of_packable_fields();
/*
Disable packing when all fields are fixed-size fields.
*/
if (size_of_packable_fields == 0)
return;
const uint sz= Sort_keys::size_of_length_field;
uint sort_len= sort_keys->get_sort_length_with_original_values();
/*
Heuristic introduced, skip packing sort keys if saving less than 128 bytes
*/
if (sort_len < 128 + sz + size_of_packable_fields)
return;
sort_keys->set_using_packed_sortkeys(true);
m_packed_format= true;
m_using_packed_sortkeys= true;
sort_length= sort_len + sz + size_of_packable_fields +
(using_addon_fields() ? 0 : res_length);
/* Only the record length needs to be updated, the res_length does not need
to be updated
*/
rec_length= sort_length + addon_length;
}
uint
Type_handler_string_result::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
CHARSET_INFO *cs= item->collation.collation;
bool maybe_null= item->maybe_null();
if (maybe_null)
*to++= 1;
Binary_string *res= item->str_result(¶m->tmp_buffer);
if (!res)
{
if (maybe_null)
{
*(to-1)= 0;
return 0;
}
else
{
/* purecov: begin deadcode */
/*
This should only happen during extreme conditions if we run out
of memory or have an item marked not null when it can be null.
This code is here mainly to avoid a hard crash in this case.
*/
DBUG_ASSERT(0);
DBUG_PRINT("warning",
("Got null on something that shouldn't be null"));
memset(to, 0, sort_field->length); // Avoid crash
/* purecov: end */
return sort_field->original_length;
}
}
return sort_field->pack_sort_string(to, res, cs);
}
uint
Type_handler_int_result::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
longlong value= item->val_int_result();
return make_packed_sort_key_longlong(to, item->maybe_null(),
item->null_value, item->unsigned_flag,
value, sort_field);
}
uint
Type_handler_decimal_result::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf);
if (item->maybe_null())
{
if (item->null_value)
{
*to++=0;
return 0;
}
*to++= 1;
}
dec_val->to_binary(to, item->max_length - (item->decimals ? 1 : 0),
item->decimals);
DBUG_ASSERT(sort_field->original_length == sort_field->length);
return sort_field->original_length;
}
uint
Type_handler_real_result::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
double value= item->val_result();
if (item->maybe_null())
{
if (item->null_value)
{
*to++=0;
return 0;
}
*to++= 1;
}
change_double_for_sort(value, to);
DBUG_ASSERT(sort_field->original_length == sort_field->length);
return sort_field->original_length;
}
uint
Type_handler_temporal_result::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
MYSQL_TIME buf;
// This is a temporal type. No nanoseconds. Rounding mode is not important.
DBUG_ASSERT(item->cmp_type() == TIME_RESULT);
static const Temporal::Options opt(TIME_INVALID_DATES, TIME_FRAC_NONE);
if (item->get_date_result(current_thd, &buf, opt))
{
DBUG_ASSERT(item->maybe_null());
DBUG_ASSERT(item->null_value);
return make_packed_sort_key_longlong(to, item->maybe_null(), true,
item->unsigned_flag, 0, sort_field);
}
return make_packed_sort_key_longlong(to, item->maybe_null(), false,
item->unsigned_flag, pack_time(&buf),
sort_field);
}
uint
Type_handler_timestamp_common::make_packed_sort_key_part(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
THD *thd= current_thd;
uint binlen= my_timestamp_binary_length(item->decimals);
Timestamp_or_zero_datetime_native_null native(thd, item);
if (native.is_null() || native.is_zero_datetime())
{
// NULL or '0000-00-00 00:00:00'
if (item->maybe_null())
{
*to++=0;
return 0;
}
else
{
bzero(to, binlen);
return binlen;
}
}
else
{
if (item->maybe_null())
*to++= 1;
if (native.length() != binlen)
{
/*
Some items can return native representation with a different
number of fractional digits, e.g.: GREATEST(ts_3, ts_4) can
return a value with 3 fractional digits, although its fractional
precision is 4. Re-pack with a proper precision now.
*/
Timestamp(native).to_native(&native, item->datetime_precision(thd));
}
DBUG_ASSERT(native.length() == binlen);
memcpy((char *) to, native.ptr(), binlen);
return binlen;
}
}
/*
@brief
Reverse the key for DESC clause
@param to buffer where values are written
@param maybe_null nullability of a column
@param sort_field Sort field structure
@details
used for mem-comparable sort keys
*/
void reverse_key(uchar *to, const SORT_FIELD_ATTR *sort_field)
{
uint length;
if (sort_field->maybe_null && (to[-1]= !to[-1]))
{
to+= sort_field->length; // don't waste the time reversing all 0's
return;
}
length=sort_field->length;
while (length--)
{
*to = (uchar) (~ *to);
to++;
}
}
/*
@brief
Check if packing sort keys is allowed
@param THD thread structure
@retval
TRUE packing allowed
FALSE packing not allowed
*/
bool SORT_FIELD_ATTR::check_if_packing_possible(THD *thd) const
{
/*
Packing not allowed when original length is greater than max_sort_length
and we have a complex collation because cutting a prefix is not safe in
such a case
*/
if (original_length > thd->variables.max_sort_length &&
cs->state & MY_CS_NON1TO1)
return false;
return true;
}
void SORT_FIELD_ATTR::set_length_and_original_length(THD *thd, uint length_arg)
{
length= length_arg;
if (is_variable_sized())
set_if_smaller(length, thd->variables.max_sort_length);
original_length= length_arg;
}
/*
Compare function used for packing sort keys
*/
qsort2_cmp get_packed_keys_compare_ptr()
{
return (qsort2_cmp) compare_packed_sort_keys;
}
/*
Compare two varstrings.
The strings are in this data format:
[null_byte] [length of string + suffix_bytes] [the string] [suffix_bytes]
suffix_bytes are used only for binary columns.
*/
int SORT_FIELD_ATTR::compare_packed_varstrings(uchar *a, size_t *a_len,
uchar *b, size_t *b_len)
{
int retval;
size_t a_length, b_length;
if (maybe_null)
{
*a_len= *b_len= 1; // NULL bytes are always stored
if (*a != *b)
{
// Note we don't return a proper value in *{a|b}_len for the non-NULL
// value but that's ok
if (*a == 0)
return -1;
else
return 1;
}
else
{
if (*a == 0)
return 0;
}
a++;
b++;
}
else
*a_len= *b_len= 0;
a_length= read_keypart_length(a, length_bytes);
b_length= read_keypart_length(b, length_bytes);
*a_len+= length_bytes + a_length;
*b_len+= length_bytes + b_length;
retval= cs->strnncollsp(a + length_bytes,
a_length - suffix_length,
b + length_bytes,
b_length - suffix_length);
if (!retval && suffix_length)
{
DBUG_ASSERT(cs == &my_charset_bin);
// comparing the length stored in suffix bytes for binary strings
a= a + length_bytes + a_length - suffix_length;
b= b + length_bytes + b_length - suffix_length;
retval= memcmp(a, b, suffix_length);
}
return retval;
}
/*
A value comparison function that has a signature that's suitable for
comparing packed values, but actually compares fixed-size values with memcmp.
This is used for ordering fixed-size columns when the sorting procedure used
packed-value format.
*/
int SORT_FIELD_ATTR::compare_packed_fixed_size_vals(uchar *a, size_t *a_len,
uchar *b, size_t *b_len)
{
if (maybe_null)
{
*a_len=1;
*b_len=1;
if (*a != *b)
{
if (*a == 0)
return -1;
else
return 1;
}
else
{
if (*a == 0)
return 0;
}
a++;
b++;
}
else
*a_len= *b_len= 0;
*a_len+= length;
*b_len+= length;
return memcmp(a,b, length);
}
/*
@brief
Comparison function to compare two packed sort keys
@param sort_param cmp argument
@param a_ptr packed sort key
@param b_ptr packed sort key
@retval
>0 key a_ptr greater than b_ptr
=0 key a_ptr equal to b_ptr
<0 key a_ptr less than b_ptr
*/
int compare_packed_sort_keys(void *sort_param,
unsigned char **a_ptr, unsigned char **b_ptr)
{
int retval= 0;
size_t a_len, b_len;
Sort_param *param= (Sort_param*)sort_param;
Sort_keys *sort_keys= param->sort_keys;
uchar *a= *a_ptr;
uchar *b= *b_ptr;
a+= Sort_keys::size_of_length_field;
b+= Sort_keys::size_of_length_field;
for (SORT_FIELD *sort_field= sort_keys->begin();
sort_field != sort_keys->end(); sort_field++)
{
retval= sort_field->is_variable_sized() ?
sort_field->compare_packed_varstrings(a, &a_len, b, &b_len) :
sort_field->compare_packed_fixed_size_vals(a, &a_len, b, &b_len);
if (retval)
return sort_field->reverse ? -retval : retval;
a+= a_len;
b+= b_len;
}
/*
this comparison is done for the case when the sort keys is appended with
the ROW_ID pointer. For such cases we don't have addon fields
so we can make a memcmp check over both the sort keys
*/
if (!param->using_addon_fields())
retval= memcmp(a, b, param->res_length);
return retval;
}
/*
@brief
Store a packed string in the buffer
@param to buffer
@param str packed string value
@param cs character set
@details
This function writes to the buffer the packed value of a key_part
of the sort key.
The values written to the buffer are in this order
- value for null byte
- length of the string
- value of the string
- suffix length (for binary character set)
*/
uint
SORT_FIELD_ATTR::pack_sort_string(uchar *to, const Binary_string *str,
CHARSET_INFO *cs) const
{
uchar *orig_to= to;
uint32 length, data_length;
DBUG_ASSERT(str->length() <= UINT32_MAX);
length= (uint32) str->length();
if (length + suffix_length <= original_length)
data_length= length;
else
data_length= original_length - suffix_length;
// length stored in lowendian form
store_key_part_length(data_length + suffix_length, to, length_bytes);
to+= length_bytes;
// copying data length bytes to the buffer
memcpy(to, (uchar*)str->ptr(), data_length);
to+= data_length;
if (cs == &my_charset_bin && suffix_length)
{
// suffix length stored in bigendian form
store_bigendian(length, to, suffix_length);
to+= suffix_length;
}
return static_cast<uint>(to - orig_to);
}
/*
@brief
Create a mem-comparable sort key
@param param sort param structure
@param to buffer where values are written
@retval
length of the bytes written including the NULL bytes
*/
static uint make_sortkey(Sort_param *param, uchar *to)
{
Field *field;
SORT_FIELD *sort_field;
uchar *orig_to= to;
for (sort_field=param->local_sortorder.begin() ;
sort_field != param->local_sortorder.end() ;
sort_field++)
{
bool maybe_null=0;
if ((field=sort_field->field))
{
// Field
field->make_sort_key_part(to, sort_field->length);
if ((maybe_null= field->maybe_null()))
to++;
}
else
{ // Item
sort_field->item->type_handler()->make_sort_key_part(to,
sort_field->item,
sort_field, param);
if ((maybe_null= sort_field->item->maybe_null()))
to++;
}
if (sort_field->reverse)
reverse_key(to, sort_field);
to+= sort_field->length;
}
DBUG_ASSERT(static_cast<uint>(to - orig_to) <= param->sort_length);
return static_cast<uint>(to - orig_to);
}
/*
@brief
create a compact sort key which can be compared with a comparison
function. They are called packed sort keys
@param param sort param structure
@param to buffer where values are written
@retval
length of the bytes written including the NULL bytes
*/
static uint make_packed_sortkey(Sort_param *param, uchar *to)
{
Field *field;
SORT_FIELD *sort_field;
uint length;
uchar *orig_to= to;
to+= Sort_keys::size_of_length_field;
for (sort_field=param->local_sortorder.begin() ;
sort_field != param->local_sortorder.end() ;
sort_field++)
{
bool maybe_null=0;
if ((field=sort_field->field))
{
// Field
length= field->make_packed_sort_key_part(to, sort_field);
if ((maybe_null= field->maybe_null()))
to++;
}
else
{ // Item
Item *item= sort_field->item;
length= item->type_handler()->make_packed_sort_key_part(to, item,
sort_field,
param);
if ((maybe_null= sort_field->item->maybe_null()))
to++;
}
to+= length;
}
length= static_cast<int>(to - orig_to);
DBUG_ASSERT(length <= param->sort_length);
Sort_keys::store_sortkey_length(orig_to, length);
return length;
}
| 29.970399 | 84 | 0.618403 | [
"object"
] |
bf5562467cdb2b2df63113084f2eb72c5ea94d3f | 2,191 | hpp | C++ | tools/Vitis-AI-Runtime/VART/vart/dpu-controller/runner-assistant/include/vart/assistant/batch_tensor_buffer.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tools/Vitis-AI-Runtime/VART/vart/dpu-controller/runner-assistant/include/vart/assistant/batch_tensor_buffer.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tools/Vitis-AI-Runtime/VART/vart/dpu-controller/runner-assistant/include/vart/assistant/batch_tensor_buffer.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <xir/tensor/tensor.hpp>
#include "vart/tensor_buffer.hpp"
namespace vart {
namespace assistant {
/// @brief BatchTensorBuffer does not own the underlying tensor buffers.
class BatchTensorBuffer : public vart::TensorBuffer {
public:
static std::unique_ptr<vart::TensorBuffer> create(
const std::vector<vart::TensorBuffer*>& tensor_buffers);
public:
explicit BatchTensorBuffer(
const std::vector<vart::TensorBuffer*>& tensor_buffers);
virtual ~BatchTensorBuffer();
public:
virtual std::pair<uint64_t, size_t> data(
const std::vector<int> idx = {}) override;
virtual std::pair<uint64_t, size_t> data_phy(
const std::vector<std::int32_t> idx) override;
TensorBuffer* get_tensor_buffer(size_t idx) { return tensor_buffers_[idx]; }
virtual vart::TensorBuffer::location_t get_location() const override;
virtual void sync_for_read(uint64_t offset, size_t size) override;
virtual void sync_for_write(uint64_t offset, size_t size) override;
virtual void copy_from_host(size_t batch_idx, const void* buf, size_t size,
size_t offset) override;
virtual void copy_to_host(size_t batch_idx, void* buf, size_t size,
size_t offset) override;
private:
std::pair<uint64_t, size_t> xdata(const std::vector<int>& idx, int is_phy);
std::pair<int, int> get_tb_idx(size_t batch_idx);
private:
std::vector<TensorBuffer*> tensor_buffers_;
std::unique_ptr<xir::Tensor> tensor_;
vart::TensorBuffer::location_t location_;
};
} // namespace assistant
} // namespace vart
| 33.707692 | 78 | 0.724783 | [
"vector"
] |
bf578d8bac9d76de2f5027c7e48cf858611e74c1 | 10,250 | cpp | C++ | src/plugins/poshuku/plugins/onlinebookmarks/plugins/readitlater/readitlaterservice.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/poshuku/plugins/onlinebookmarks/plugins/readitlater/readitlaterservice.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/poshuku/plugins/onlinebookmarks/plugins/readitlater/readitlaterservice.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2010-2011 Oleg Linkin
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "readitlaterservice.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QSettings>
#include <QtDebug>
#include <util/xpc/util.h>
#include "readitlaterauthwidget.h"
#include "readitlaterapi.h"
#include "readitlateraccount.h"
namespace LeechCraft
{
namespace Poshuku
{
namespace OnlineBookmarks
{
namespace ReadItLater
{
ReadItLaterService::ReadItLaterService (ICoreProxy_ptr proxy)
: CoreProxy_ (proxy)
, ReadItLaterApi_ (new ReadItLaterApi)
{
}
void ReadItLaterService::Prepare ()
{
RestoreAccounts ();
}
IBookmarksService::Features ReadItLaterService::GetFeatures () const
{
return FCanRegisterAccount;
}
QObject* ReadItLaterService::GetQObject ()
{
return this;
}
QString ReadItLaterService::GetServiceName () const
{
return "Read It Later";
}
QIcon ReadItLaterService::GetServiceIcon () const
{
return QIcon ("lcicons:/poshuku/onlinebookmarks:readitlater/resources/images/readitlater.ico");
}
QWidget* ReadItLaterService::GetAuthWidget ()
{
return new ReadItLaterAuthWidget ();
}
void ReadItLaterService::CheckAuthData (const QVariantMap& map)
{
const QString login = map ["Login"].toString ();
const QString password = map ["Password"].toString ();
if (login.isEmpty () || password.isEmpty ())
return;
Request req;
req.Type_ = OTAuth;
req.Login_ = login;
req.Password_ = password;
SendRequest (ReadItLaterApi_->GetAuthUrl (),
ReadItLaterApi_->GetAuthPayload (login, password),
req);
}
void ReadItLaterService::RegisterAccount(const QVariantMap& map)
{
const QString login = map ["Login"].toString ();
const QString password = map ["Password"].toString ();
if (login.isEmpty () || password.isEmpty ())
return;
Request req;
req.Type_ = OTRegister;
req.Login_ = login;
req.Password_ = password;
SendRequest (ReadItLaterApi_->GetRegisterUrl (),
ReadItLaterApi_->GetRegisterPayload (login, password),
req);
}
void ReadItLaterService::UploadBookmarks (QObject *accObj, const QVariantList& bookmarks)
{
IAccount *account = qobject_cast<IAccount*> (accObj);
if (!account)
{
qWarning () << Q_FUNC_INFO
<< "isn't an IAccount object"
<< accObj;
return;
}
QByteArray uploadBookmarks = ReadItLaterApi_->GetUploadPayload (account->GetLogin(),
account->GetPassword (), bookmarks);
if (uploadBookmarks.isEmpty ())
return;
Request req;
req.Type_ = OTUpload;
req.Login_ = account->GetLogin ();
req.Password_ = account->GetPassword ();
SendRequest (ReadItLaterApi_->GetUploadUrl (),
uploadBookmarks,
req);
}
void ReadItLaterService::DownloadBookmarks (QObject *accObj, const QDateTime& from)
{
IAccount *account = qobject_cast<IAccount*> (accObj);
if (!account)
{
qWarning () << Q_FUNC_INFO
<< "isn't an IAccount object"
<< accObj;
return;
}
QByteArray downloadBookmarks = ReadItLaterApi_->GetDownloadPayload (account->GetLogin(),
account->GetPassword (), from);
Request req;
req.Type_ = OTDownload;
req.Login_ = account->GetLogin ();
req.Password_ = account->GetPassword ();
Account2ReplyContent_ [account].clear ();
SendRequest (ReadItLaterApi_->GetDownloadUrl (),
downloadBookmarks,
req);
}
ReadItLaterAccount* ReadItLaterService::GetAccountByName (const QString& login)
{
Q_FOREACH (ReadItLaterAccount *account, Accounts_)
if (account->GetLogin () == login)
return account;
return 0;
}
void ReadItLaterService::SendRequest (const QString& urlSting,
const QByteArray& payload, Request req)
{
QUrl url = QUrl::fromEncoded (urlSting.toUtf8 () + payload);
QNetworkRequest request (url);
QNetworkReply *reply = CoreProxy_->
GetNetworkAccessManager ()->get (request);
Reply2Request_ [reply] = req;
connect (reply,
SIGNAL (finished ()),
this,
SLOT (getReplyFinished ()));
connect (reply,
SIGNAL (readyRead ()),
this,
SLOT (readyReadReply ()));
}
void ReadItLaterService::RestoreAccounts ()
{
QSettings settings (QSettings::IniFormat, QSettings::UserScope,
QCoreApplication::organizationName (),
QCoreApplication::applicationName () +
"_Poshuku_OnlineBookmarks_ReadItLater_Accounts");
QObjectList list;
int size = settings.beginReadArray ("Accounts");
for (int i = 0; i < size; ++i)
{
settings.setArrayIndex (i);
QByteArray data = settings
.value ("SerializedData").toByteArray ();
ReadItLaterAccount *acc = ReadItLaterAccount::Deserialize (data, this);
if (!acc)
{
qWarning () << Q_FUNC_INFO
<< "unserializable acount"
<< i;
continue;
}
Accounts_ << acc;
list << acc->GetQObject ();
}
emit accountAdded (list);
}
void ReadItLaterService::getReplyFinished ()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
if (!reply)
{
qWarning () << Q_FUNC_INFO
<< sender ()
<< "isn't a QNetworkReply";
return;
}
if (Reply2Request_ [reply].Type_ == OTDownload)
{
ReadItLaterAccount *account = GetAccountByName (Reply2Request_ [reply].Login_);
if (account)
{
QVariantList downloadedBookmarks = ReadItLaterApi_->
GetDownloadedBookmarks (Account2ReplyContent_ [account]);
if (!downloadedBookmarks.isEmpty ())
{
account->AppendDownloadedBookmarks (downloadedBookmarks);
account->SetLastDownloadDateTime (QDateTime::currentDateTime ());
emit gotBookmarks (account, downloadedBookmarks);
}
}
}
reply->deleteLater ();
}
void ReadItLaterService::readyReadReply ()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
if (!reply)
{
qWarning () << Q_FUNC_INFO
<< sender ()
<< "isn't a QNetworkReply";
return;
}
const QVariant& result = reply->attribute (QNetworkRequest::HttpStatusCodeAttribute);
Entity e;
QString msg;
Priority priority = PInfo_;
switch (result.toInt ())
{
case 200:
if (Reply2Request_ [reply].Type_ == OTAuth ||
Reply2Request_ [reply].Type_ == OTRegister)
{
ReadItLaterAccount *account =
new ReadItLaterAccount (Reply2Request_ [reply].Login_,
this);
account->SetPassword (Reply2Request_ [reply].Password_);
Accounts_ << account;
saveAccounts ();
emit accountAdded (QObjectList () << account->GetQObject ());
switch (Reply2Request_ [reply].Type_)
{
case OTAuth:
priority = PInfo_;
msg = tr ("Authentication has finished successfully.");
break;
case OTRegister:
priority = PInfo_;
msg = tr ("Registration has finished successfully.");
break;
case OTDownload:
break;
case OTUpload:
break;
}
}
else
switch (Reply2Request_ [reply].Type_)
{
case OTAuth:
break;
case OTRegister:
break;
case OTDownload:
Account2ReplyContent_ [GetAccountByName (Reply2Request_ [reply].Login_)]
.append (reply->readAll ());
break;
case OTUpload:
ReadItLaterAccount *account = GetAccountByName (Reply2Request_ [reply].Login_);
if (account)
account->SetLastUploadDateTime (QDateTime::currentDateTime ());
emit bookmarksUploaded ();
break;
}
break;
case 400:
qWarning () << Q_FUNC_INFO
<< "X-Error contents:"
<< reply->rawHeader ("X-Error");
msg = tr ("Invalid request. Please report to developers.");
priority = PWarning_;
break;
case 401:
msg = tr ("Incorrect username or password.");
priority = PWarning_;
break;
case 403:
msg = tr ("Rate limit exceeded, please wait a little bit before resubmitting.");
priority = PWarning_;
break;
case 503:
msg = tr ("Read It Later's sync server is down for scheduled maintenance.");
priority = PWarning_;
break;
}
e = Util::MakeNotification ("OnlineBookmarks",
msg,
priority);
emit gotEntity (e);
}
void ReadItLaterService::saveAccounts () const
{
QSettings settings (QSettings::IniFormat, QSettings::UserScope,
QCoreApplication::organizationName (),
QCoreApplication::applicationName () +
"_Poshuku_OnlineBookmarks_ReadItLater_Accounts");
settings.beginWriteArray ("Accounts");
for (int i = 0, size = Accounts_.size (); i < size; ++i)
{
settings.setArrayIndex (i);
settings.setValue ("SerializedData",
Accounts_.at (i)->Serialize ());
}
settings.endArray ();
settings.sync ();
}
void ReadItLaterService::removeAccount (QObject* accObj)
{
ReadItLaterAccount *account = qobject_cast<ReadItLaterAccount*> (accObj);
if (Accounts_.removeAll (account))
{
accObj->deleteLater ();
saveAccounts ();
}
}
}
}
}
}
| 26.762402 | 97 | 0.68478 | [
"object"
] |
bf5a62a91ceb34eeef6f9575614efd0178eeebed | 1,376 | cpp | C++ | engine/Ecs/Components/Acceleration.cpp | ledocool/snail_engine | 0114a62dbecbbe58348fbe7083d9182bc1bd8c3c | [
"Apache-2.0"
] | null | null | null | engine/Ecs/Components/Acceleration.cpp | ledocool/snail_engine | 0114a62dbecbbe58348fbe7083d9182bc1bd8c3c | [
"Apache-2.0"
] | null | null | null | engine/Ecs/Components/Acceleration.cpp | ledocool/snail_engine | 0114a62dbecbbe58348fbe7083d9182bc1bd8c3c | [
"Apache-2.0"
] | 1 | 2018-08-11T14:31:27.000Z | 2018-08-11T14:31:27.000Z | /*
* Copyright 2019 LedoCool.
*
* 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.
*/
/*
* File: Acceleration.cpp
* Author: LedoCool
*
* Created on January 2, 2019, 6:21 PM
*/
#include "Acceleration.h"
#include "ComponentTypes.h"
Acceleration::Acceleration()
{
_vector.set(0.f, 0.f);
_rotation = 0.f;
}
Acceleration::Acceleration(const Vector2<float> & acceleration, const float rotation)
{
_vector = acceleration;
_rotation = rotation;
}
Acceleration::~ Acceleration()
{
}
void Acceleration::vector(Vector2<float> & data)
{
_vector = data;
}
Vector2<float> Acceleration::vector()
{
return _vector;
}
void Acceleration::rotation(float rotation)
{
_rotation = rotation;
}
float Acceleration::rotation()
{
return _rotation;
}
unsigned int Acceleration::GetComponentId()
{
return ComponentTypes::ACCELERATION;
}
| 20.235294 | 85 | 0.707122 | [
"vector"
] |
bf5aca2b591076254e8aa83a5f79b4e33dc3dd13 | 6,779 | cc | C++ | shill/dbus/service_dbus_adaptor.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | shill/dbus/service_dbus_adaptor.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | shill/dbus/service_dbus_adaptor.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shill/dbus/service_dbus_adaptor.h"
#include <map>
#include <string>
#include <utility>
#include <base/strings/string_number_conversions.h>
#include "shill/error.h"
#include "shill/logging.h"
#include "shill/service.h"
using std::map;
using std::string;
using std::vector;
namespace {
const char kDBusRpcReasonString[] = "D-Bus RPC";
} // namespace
namespace shill {
namespace Logging {
static auto kModuleLogScope = ScopeLogger::kDBus;
static string ObjectID(const ServiceDBusAdaptor* s) {
return s->GetRpcIdentifier().value() + " (" + s->service()->log_name() + ")";
}
} // namespace Logging
// static
const char ServiceDBusAdaptor::kPath[] = "/service/";
ServiceDBusAdaptor::ServiceDBusAdaptor(const scoped_refptr<dbus::Bus>& bus,
Service* service)
: org::chromium::flimflam::ServiceAdaptor(this),
DBusAdaptor(bus, kPath + service->GetDBusObjectPathIdentifer()),
service_(service) {
// Register DBus object.
RegisterWithDBusObject(dbus_object());
dbus_object()->RegisterAndBlock();
}
ServiceDBusAdaptor::~ServiceDBusAdaptor() {
dbus_object()->UnregisterAsync();
service_ = nullptr;
}
void ServiceDBusAdaptor::EmitBoolChanged(const string& name, bool value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitUint8Changed(const string& name, uint8_t value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitUint16Changed(const string& name, uint16_t value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitUint16sChanged(const string& name,
const Uint16s& value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitUintChanged(const string& name, uint32_t value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitIntChanged(const string& name, int value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitRpcIdentifierChanged(const string& name,
const RpcIdentifier& value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitStringChanged(const string& name,
const string& value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
void ServiceDBusAdaptor::EmitStringmapChanged(const string& name,
const Stringmap& value) {
SLOG(this, 2) << __func__ << ": " << name;
SendPropertyChangedSignal(name, brillo::Any(value));
}
bool ServiceDBusAdaptor::GetProperties(brillo::ErrorPtr* error,
brillo::VariantDictionary* properties) {
SLOG(this, 2) << __func__;
return DBusAdaptor::GetProperties(service_->store(), properties, error);
}
bool ServiceDBusAdaptor::SetProperty(brillo::ErrorPtr* error,
const string& name,
const brillo::Any& value) {
SLOG(this, 2) << __func__ << ": " << name;
return DBusAdaptor::SetProperty(service_->mutable_store(), name, value,
error);
}
bool ServiceDBusAdaptor::SetProperties(brillo::ErrorPtr* error,
const brillo::VariantDictionary& args) {
SLOG(this, 2) << __func__;
KeyValueStore args_store = KeyValueStore::ConvertFromVariantDictionary(args);
Error configure_error;
service_->Configure(args_store, &configure_error);
return !configure_error.ToChromeosError(error);
}
bool ServiceDBusAdaptor::ClearProperty(brillo::ErrorPtr* error,
const string& name) {
SLOG(this, 2) << __func__ << ": " << name;
bool status =
DBusAdaptor::ClearProperty(service_->mutable_store(), name, error);
if (status) {
service_->OnPropertyChanged(name);
}
return status;
}
bool ServiceDBusAdaptor::ClearProperties(brillo::ErrorPtr* /*error*/,
const vector<string>& names,
vector<bool>* results) {
SLOG(this, 2) << __func__;
for (const auto& name : names) {
results->push_back(ClearProperty(nullptr, name));
}
return true;
}
bool ServiceDBusAdaptor::Connect(brillo::ErrorPtr* error) {
SLOG(this, 2) << __func__;
Error e;
service_->UserInitiatedConnect(kDBusRpcReasonString, &e);
return !e.ToChromeosError(error);
}
bool ServiceDBusAdaptor::Disconnect(brillo::ErrorPtr* error) {
SLOG(this, 2) << __func__;
Error e;
service_->UserInitiatedDisconnect(kDBusRpcReasonString, &e);
return !e.ToChromeosError(error);
}
bool ServiceDBusAdaptor::Remove(brillo::ErrorPtr* error) {
SLOG(this, 2) << __func__;
Error e;
service_->Remove(&e);
return !e.ToChromeosError(error);
}
bool ServiceDBusAdaptor::ActivateCellularModem(brillo::ErrorPtr* error,
const string& carrier) {
SLOG(this, 2) << __func__;
Error e;
Error::PopulateAndLog(FROM_HERE, &e, Error::kNotSupported,
"Service doesn't support cellular modem activation.");
return !e.ToChromeosError(error);
}
bool ServiceDBusAdaptor::CompleteCellularActivation(brillo::ErrorPtr* error) {
SLOG(this, 2) << __func__;
Error e;
service_->CompleteCellularActivation(&e);
return !e.ToChromeosError(error);
}
bool ServiceDBusAdaptor::GetLoadableProfileEntries(
brillo::ErrorPtr* /*error*/, map<dbus::ObjectPath, string>* entries) {
SLOG(this, 2) << __func__;
map<RpcIdentifier, string> profile_entry_strings =
service_->GetLoadableProfileEntries();
for (const auto& entry : profile_entry_strings) {
(*entries)[dbus::ObjectPath(entry.first)] = entry.second;
}
return true;
}
bool ServiceDBusAdaptor::GetWiFiPassphrase(brillo::ErrorPtr* error,
std::string* out_passphrase) {
SLOG(this, 2) << __func__;
Error e;
std::string passphrase = service_->GetWiFiPassphrase(&e);
if (!e.IsSuccess()) {
return !e.ToChromeosError(error);
}
*out_passphrase = passphrase;
return true;
}
} // namespace shill
| 32.591346 | 80 | 0.654816 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.