sampler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "util/sampler.h"
  24. #include "core/util/safeDelete.h"
  25. #include "core/util/tVector.h"
  26. #include "core/stream/fileStream.h"
  27. #include "console/console.h"
  28. #include "console/consoleTypes.h"
  29. /// Bookkeeping structure for registered sampling keys.
  30. struct SampleKey
  31. {
  32. bool mEnabled;
  33. const char* mName;
  34. bool matchesPattern( const char* pattern )
  35. {
  36. U32 indexInName = 0;
  37. U32 indexInPattern = 0;
  38. while( mName[ indexInName ] != '\0' )
  39. {
  40. if( pattern[ indexInPattern ] == '\0' )
  41. break;
  42. else if( dToupper( mName[ indexInName ] ) == dToupper( pattern[ indexInPattern ] ) )
  43. {
  44. indexInName ++;
  45. indexInPattern ++;
  46. }
  47. else if( pattern[ indexInPattern ] == '*' )
  48. {
  49. // Handle senseless concatenation of wildcards.
  50. while( pattern[ indexInPattern ] == '*' )
  51. indexInPattern ++;
  52. // Skip to next slash in name.
  53. while( mName[ indexInName ] && mName[ indexInName ] != '/' )
  54. indexInName ++;
  55. }
  56. else
  57. return false;
  58. }
  59. return ( pattern[ indexInPattern ] == '\0'
  60. || ( indexInPattern > 0 && pattern[ indexInPattern ] == '*' ) );
  61. }
  62. };
  63. /// A sampler backend is responsible for storing the actual sampling data.
  64. struct ISamplerBackend
  65. {
  66. virtual ~ISamplerBackend() {}
  67. virtual bool init( const char* location ) = 0;
  68. virtual void beginFrame() = 0;
  69. virtual void endFrame() = 0;
  70. virtual void sample( U32 key, bool value ) = 0;
  71. virtual void sample( U32 key, S32 value ) = 0;
  72. virtual void sample( U32 key, F32 value ) = 0;
  73. virtual void sample( U32 key, const char* value ) = 0;
  74. };
  75. static bool gSamplerRunning;
  76. static S32 gSamplingFrequency = 1; ///< Frequency = samples taken every nth frame.
  77. static U32 gCurrentFrameDelta;
  78. static Vector< SampleKey > gSampleKeys( __FILE__, __LINE__ );
  79. static ISamplerBackend* gSamplerBackend;
  80. //--------------------------------------------------------------------------------
  81. // CSV Backend.
  82. //--------------------------------------------------------------------------------
  83. /// A sampler backend that outputs samples to a CSV file.
  84. class CSVSamplerBackend : public ISamplerBackend
  85. {
  86. /// Value holder for an individual sample. Unfortunately, since the
  87. /// order in which samples arrive at the sampler may vary from frame to
  88. /// frame, we cannot emit data immediately but rather have to buffer
  89. /// it in these sample records and then flush them to disk once we receive
  90. /// the endFrame call.
  91. struct SampleRecord
  92. {
  93. U32 mKey;
  94. U32 mType; //< Console type code.
  95. bool mSet;
  96. union
  97. {
  98. bool mBool;
  99. S32 mS32;
  100. F32 mF32;
  101. const char* mString;
  102. } mValue;
  103. SampleRecord() {}
  104. SampleRecord( U32 key )
  105. : mKey( key ), mSet( false ) {}
  106. void set( bool value )
  107. {
  108. mType = TypeBool;
  109. mValue.mBool = value;
  110. mSet = true;
  111. }
  112. void set( S32 value )
  113. {
  114. mType = TypeS32;
  115. mValue.mS32 = value;
  116. mSet = true;
  117. }
  118. void set( F32 value )
  119. {
  120. mType = TypeF32;
  121. mValue.mF32 = value;
  122. mSet = true;
  123. }
  124. void set( const char* str )
  125. {
  126. mType = TypeString;
  127. mValue.mString = dStrdup( str );
  128. mSet = true;
  129. }
  130. void clean()
  131. {
  132. if( mType == TypeString )
  133. dFree( ( void* ) mValue.mString );
  134. mSet = false;
  135. }
  136. };
  137. FileStream mStream;
  138. Vector< SampleRecord > mRecords;
  139. ~CSVSamplerBackend()
  140. {
  141. mStream.close();
  142. }
  143. /// Open the file and emit a row with the names of all enabled keys.
  144. virtual bool init( const char* fileName )
  145. {
  146. if( !mStream.open( fileName, Torque::FS::File::Write ) )
  147. {
  148. Con::errorf( "CSVSamplerBackend::init -- could not open '%s' for writing", fileName );
  149. return false;
  150. }
  151. Con::printf( "CSVSamplerBackend::init -- writing samples to '%s'", fileName );
  152. bool first = true;
  153. for( U32 i = 0; i < gSampleKeys.size(); ++ i )
  154. {
  155. SampleKey& key = gSampleKeys[ i ];
  156. if( key.mEnabled )
  157. {
  158. if( !first )
  159. mStream.write( 1, "," );
  160. mRecords.push_back( SampleRecord( i + 1 ) );
  161. mStream.write( dStrlen( key.mName ), key.mName );
  162. first = false;
  163. }
  164. }
  165. newline();
  166. return true;
  167. }
  168. virtual void beginFrame()
  169. {
  170. }
  171. virtual void endFrame()
  172. {
  173. char buffer[ 256 ];
  174. for( U32 i = 0; i < mRecords.size(); ++ i )
  175. {
  176. if( i != 0 )
  177. mStream.write( 1, "," );
  178. SampleRecord& record = mRecords[ i ];
  179. if( record.mSet )
  180. {
  181. if( record.mType == TypeBool )
  182. {
  183. if( record.mValue.mBool )
  184. mStream.write( 4, "true" );
  185. else
  186. mStream.write( 5, "false" );
  187. }
  188. else if( record.mType == TypeS32 )
  189. {
  190. dSprintf( buffer, sizeof( buffer ), "%d", record.mValue.mS32 );
  191. mStream.write( dStrlen( buffer ), buffer );
  192. }
  193. else if( record.mType == TypeF32 )
  194. {
  195. dSprintf( buffer, sizeof( buffer ), "%f", record.mValue.mF32 );
  196. mStream.write( dStrlen( buffer ), buffer );
  197. }
  198. else if( record.mType == TypeString )
  199. {
  200. //FIXME: does not do doubling of double quotes in the string at the moment
  201. mStream.write( 1, "\"" );
  202. mStream.write( dStrlen( record.mValue.mString ), record.mValue.mString );
  203. mStream.write( 1, "\"" );
  204. }
  205. else
  206. AssertWarn( false, "CSVSamplerBackend::endFrame - bug: invalid sample type" );
  207. }
  208. record.clean();
  209. }
  210. newline();
  211. }
  212. void newline()
  213. {
  214. mStream.write( 1, "\n" );
  215. }
  216. SampleRecord* lookup( U32 key )
  217. {
  218. //TODO: do this properly with a binary search (the mRecords array is already sorted by key)
  219. for( U32 i = 0; i < mRecords.size(); ++ i )
  220. if( mRecords[ i ].mKey == key )
  221. return &mRecords[ i ];
  222. AssertFatal( false, "CSVSamplerBackend::lookup - internal error: sample key not found" );
  223. return NULL; // silence compiler
  224. }
  225. virtual void sample( U32 key, bool value )
  226. {
  227. lookup( key )->set( value );
  228. }
  229. virtual void sample( U32 key, S32 value )
  230. {
  231. lookup( key )->set( value );
  232. }
  233. virtual void sample( U32 key, F32 value )
  234. {
  235. lookup( key )->set( value );
  236. }
  237. virtual void sample( U32 key, const char* value )
  238. {
  239. lookup( key )->set( value );
  240. }
  241. };
  242. //--------------------------------------------------------------------------------
  243. // Internal Functions.
  244. //--------------------------------------------------------------------------------
  245. static void stopSampling()
  246. {
  247. if( gSamplerRunning )
  248. {
  249. SAFE_DELETE( gSamplerBackend );
  250. gSamplerRunning = false;
  251. }
  252. }
  253. static void beginSampling( const char* location, const char* backend )
  254. {
  255. if( gSamplerRunning )
  256. stopSampling();
  257. if( dStricmp( backend, "CSV" ) == 0 )
  258. gSamplerBackend = new CSVSamplerBackend;
  259. else
  260. {
  261. Con::errorf( "beginSampling -- No backend called '%s'", backend );
  262. return;
  263. }
  264. if( !gSamplerBackend->init( location ) )
  265. {
  266. SAFE_DELETE( gSamplerBackend );
  267. }
  268. else
  269. {
  270. gSamplerRunning = true;
  271. gCurrentFrameDelta = 0;
  272. }
  273. }
  274. //--------------------------------------------------------------------------------
  275. // Sampler Functions.
  276. //--------------------------------------------------------------------------------
  277. void Sampler::init()
  278. {
  279. Con::addVariable( "Sampler::frequency", TypeS32, &gSamplingFrequency, "Samples taken every nth frame.\n"
  280. "@ingroup Rendering");
  281. }
  282. void Sampler::beginFrame()
  283. {
  284. gCurrentFrameDelta ++;
  285. if( gSamplerBackend && gCurrentFrameDelta == gSamplingFrequency )
  286. gSamplerBackend->beginFrame();
  287. }
  288. void Sampler::endFrame()
  289. {
  290. if( gSamplerBackend && gCurrentFrameDelta == gSamplingFrequency )
  291. {
  292. gSamplerBackend->endFrame();
  293. gCurrentFrameDelta = 0;
  294. }
  295. }
  296. void Sampler::destroy()
  297. {
  298. if( gSamplerBackend )
  299. SAFE_DELETE( gSamplerBackend );
  300. }
  301. U32 Sampler::registerKey( const char* name )
  302. {
  303. gSampleKeys.push_back( SampleKey() );
  304. U32 index = gSampleKeys.size();
  305. SampleKey& key = gSampleKeys.last();
  306. key.mName = name;
  307. key.mEnabled = false;
  308. return index;
  309. }
  310. void Sampler::enableKeys( const char* pattern, bool state )
  311. {
  312. if( gSamplerRunning )
  313. {
  314. Con::errorf( "Sampler::enableKeys -- cannot change key states while sampling" );
  315. return;
  316. }
  317. for( U32 i = 0; i < gSampleKeys.size(); ++ i )
  318. if( gSampleKeys[ i ].matchesPattern( pattern ) )
  319. {
  320. gSampleKeys[ i ].mEnabled = state;
  321. Con::printf( "Sampler::enableKeys -- %s %s", state ? "enabling" : "disabling",
  322. gSampleKeys[ i ].mName );
  323. }
  324. }
  325. #define SAMPLE_FUNC( type ) \
  326. void Sampler::sample( U32 key, type value ) \
  327. { \
  328. if( gSamplerRunning \
  329. && gCurrentFrameDelta == gSamplingFrequency \
  330. && gSampleKeys[ key - 1 ].mEnabled ) \
  331. gSamplerBackend->sample( key, value ); \
  332. }
  333. SAMPLE_FUNC( bool );
  334. SAMPLE_FUNC( S32 );
  335. SAMPLE_FUNC( F32 );
  336. SAMPLE_FUNC( const char* );
  337. //--------------------------------------------------------------------------------
  338. // Console Functions.
  339. //--------------------------------------------------------------------------------
  340. ConsoleFunction( beginSampling, void, 2, 3, "(location, [backend]) -"
  341. "@brief Takes a string informing the backend where to store "
  342. "sample data and optionally a name of the specific logging "
  343. "backend to use. The default is the CSV backend. In most "
  344. "cases, the logging store will be a file name."
  345. "@tsexample\n"
  346. "beginSampling( \"mysamples.csv\" );\n"
  347. "@endtsexample\n\n"
  348. "@ingroup Rendering")
  349. {
  350. const char* location = argv[ 1 ];
  351. const char* backend = "CSV";
  352. if( argc > 2 )
  353. backend = argv[ 2 ];
  354. beginSampling( location, backend );
  355. }
  356. ConsoleFunction( stopSampling, void, 1, 1, "()"
  357. "@brief Stops the rendering sampler\n\n"
  358. "@ingroup Rendering\n")
  359. {
  360. stopSampling();
  361. }
  362. ConsoleFunction( enableSamples, void, 2, 3, "(pattern, [state]) -"
  363. "@brief Enable sampling for all keys that match the given name "
  364. "pattern. Slashes are treated as separators.\n\n"
  365. "@ingroup Rendering")
  366. {
  367. const char* pattern = argv[ 1 ];
  368. bool state = true;
  369. if( argc > 2 )
  370. state = dAtob( argv[ 2 ] );
  371. Sampler::enableKeys( pattern, state );
  372. }