�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �4}   �� ���@*@*��9��|��|��|�8�|�>���")/5<CJQX_fmsz������������������� $+29@GMSZ`gnu|������������������ "(/6=CJQX_fmt{������������������� !(.5<CIPW^elsy������������������� &-4;BIPW^elsz�������������������  '.5<CIPW^djqw}������������������� %,3:AHOV]dkqx������������������� $+29@GNU\cjqw}������������������� &-4:@GNU\cjqw~�������������������    % , 3 : A H O V ] d k r y � � � � � � � � � � � � � � � � � � � �     & - 4 ; B I O V ] d k r x  � � � � � � � � � � � � � � � � � �     % , 2 9 @ G N U \ c j q x  � � � � � � � � � � � � � � � � � � �    & - 4 ; B H O V ] d j p w ~ � � � � � � � � � � � � � � � � � � �    ! ( / 6 < C J Q X _ e l s z � � � � � � � � � � � � � � � � � � � ")07<CJPW^elsz�������������������  '.5<CJQX_elsz������������������� $+18>ELSZahov}������������������$+28?DKRX_ekry�������������������  '.5<CJQX_fmt{�������������������  '.5<BIPW^elry������������������� $+29@GNU\cjpw~�������������������  '.4;AHOV]djqx������������������� %,3:@GNU\cjpw~������������������� ")/6=DKRX_fmt{�������������������  &,18?FMT[bipv}������������������#*17>ELSY`gnu|������������������� !(/6<CJQW^elsy����53033452368123483415379772557085183007238529063405486452164512676031491966490904016056444669136130152945740358753061204477505302563516894373820574617358848373163995925263263201429288955298754116362759415331921231357333747320486089722313297174946470702459942615844633216743146965153965616415574760511576548343238314643535178374315897137104040909548752046278663561330352892175508182457319751822612806554214634348583056912296070027605138752775552823120519412124208424837291235191456785382886547502982129966042823365531867521914739746861355680198201291869649010841307436108764466414719808795519564592950050280924538521185369655408913182545162669715081763065823194193312720166306218499930126984325689747447806021247572821437456730114534437011245640190387799038355238211613919234468318015900071238723348468721740479673912534017323515222193316349004543220520559326534686010840208515159930945510223927042213876135695284599239583500124758835757618891568137954337988901491351486627460433227981372012147529331630015281545025275771532211093921608452509634967682989652405470612806981492870271996656533385604136445019130911945033250306666229714343539470186639861712765804224811970479435055385774364701157427912379452954563321077485171612232466212426336019056943032421536307539842814575701116585787327861371132513180442438459603289341129830057692195312210200017491127338213715880686535023381290438051545083534030677772045442993315848226675196906351862252222175621493028426784202315443240154671240755825932241923187587906705808626457844836242014948627043429205583085474470929823881272491416002681522121725223385160478330270338159251000919535847444970064440131545628319076653439544758432975140221568762371334015682504761326195418525781760727251955650158171687818354894366907457511342511944089574925918546953367563115415451571177127423379930231504434818504913017401292296842332983261495741919219424390253639174770886625989671467998733840933215543489219052934740665990863703659692449166850566120417327325189988410326116958593848036399162479909017038041149807472519451607675767681234273257542947045211205513630504456829398732353566326404573513549605662143655222247912542879525142838390505995355590069514127384011012235023433395241370466846643208893110160222304540715171767831565201202430844151365116784728121521438531932539751264876431072354039120616218046568345661086399765044295723159754462976456405675284525394288456584251368178206414856087003751172701239583858333828775418339449459524316275858031820444539138155153177207674042135942314929465004528360419329412290957472695239511324990728216310547398954140977349333017584654574965294601714163304553608502292279765241452571425004309464025109022741003265658496123941935834459593306162756208719134355958729285708237522694627144192846952825894092533540701834881286265838291509555690520722584428530386507640587903245913543706647431514279045484528361495610990495894425439759522640924187711259413558436705574351612094923452988035662840345972869420572278536258896335453715239162768459448935690910442877334580244298816243056881700331158552755456231612683406476518533113814335215499258100145280923653895534355176433360208439008095215081391506355399361144804430075898796329503827191742073278561564646229723659113650993266951813057082511206496624411829126872449265732986143379390247861629924215047221136270463852651506643845002222693532304141401341103386458736109285905666577263596339113212222259402976951845727738003688286101940740249016285710186653864467497495012359071619022599335174161555409775930247237401851306634108339437025417079336070720399844694681370879034344728575105321172021739206933712486741064069202066618122419798615192632892433076679518341351382191402962605652443923655465271178442121101357314642994765550417833846947574932365269698846777186215215858526434551832795323294388359069222884299493505783802113771762537843312940668774056209421874628071801093564630422112236321612707416104458763266343354375278340302415072684234087373736747780745639727851750850766113192402637810663834193789393843432291144181580453396218846513821137414297941468184173335323226814306102984043611398426195646183228546654370499563348610788186362819882134669636283461960676284899932262590338705312735159513661443994104421126368142548479152186169422848293210013865894579240582725326303646204337516758926950435678166473659040036222200936511194258791332069742210905641437404907194407026939574673619103970832432424751910246682314588159512678177009847725911779299948277289469856748608821509054027786554162017733029273442664755515523367821547561767696645868695937577215891073468260017131264264299845040370212823461380099356359406048768440069944543791725180571475515566602426066363506510767812697227145237919774984911157182755524562541326275564574027229171331386555387933942610158572914124367842545735364159623508923560845603203911870601171208284492211890252222257279285625351644816325269355810323894590937594032512526005176991215987336888046590852392576402375218721905869362775746459043522087244532820530075856312072270681688434442270923835752630122617653139368661071312696279374010031209636252794377212540809556195291634009128645834397567592905627377105167831345393697234441973023261303455006132851613958843252241334057321464154398183035268249508912989935422361340023511258189980161653913190342631192642164372197182544526460056285892516767165771248897762640493512816155369951990000347700824980754811746310754333114002242563064071592943628946035270511936711626790757548061085092548614152058143497623923506124328750086146247692005164352451124226759184935670094457505536051724575715275316344205579663308569638143752653737161307673729097883773977333638862682672425561456046244595863798226921104235847834612061338114502473222711875790232830520574582034565232985307425494335149062952592949884246692561641249901992749843107811314940052745521324244428670117959272177166484870918053997796963696057310976928324262499731170012620873501300733926762523588820466701216953634235690050327402173665264425328962689355351109437071341499196290704627012945845132221955736040508801759369263686442349404931930771117929252241816222101813231611833619748422001481545668324615650376433525665503111905840182808698721895641330912426467413008819213587637034642623689259150757141533166312236653633960731796634942185125941687541950078501811866263471694298048807244246212155458339803711110206326900220785205690091595406415530585136470196707427495855684751615591720282252649076496012233067916635522312105375676317814847577073730520629125947689744779079425834841995061958009383482648783964930084101956390964716487705007967508243822240552972065452077186863339304611172296472273840745321368105196595542810482138285879467210701856433603924510958584571129127434824260672561557259339522405754853620472654269786321877794284481424351730796189�x&&)�=�FoI�MyO�V�^�^�k�A�~�Y�����k���������A!�"�GZd�dSe�u��l�ރ/�����+�CJ�&)o/t8�=m#��������(�,4/�@A�B�EoG�X����>����������*�����2�E�G�I9�����w �J$ =Ӎ�����G��� �|n�a1�H�VAagk5zH|#��_�J��(�[��]�bV���E�X�� I P 6 K wP �X �e l >p �� �� ۉ �� @�  4 � � �: D Zk �� |� d� � j� � κ D� �� �� >� � / i � a v! �+ / y3 �6 B �F Ei p �� �� t� �� �� \� > � �- �2 F3 z: ## �s � � �� Կ N� "� k� �� q� 0;�(���V���\�2�6�>p9�:�H&J���v�׷z�S�����Q�m�U�7�=��Q����<��#g;_F�d�8��������#l�#1�#E�#~�#$�#$�$G$3p$��$+�$��$��$ �$%B%LE%?H%�J% M%T%�V%X%�^%Hm%��%q�%o�%˫%��%��%�%��%��%�"&�?&JC&�L& O&JS&�x&b�&�&��&��&�'&'�$'v7'�C'G'�n'bp'��'�'��'.�'�'��'�(�(3((�/(�2(A(KC(VH(U�(�(j�(I�(p�(�&)2D)cR)�k)��)��)J�)��)��)@�)qc*b�*��*Ȟ* �*��*��*K�*�+�+�+Y+++�?+]a+&n+�n+�t+�x+�+c,n,%,R-,o0,�8,T>,:e,q,Du,��,��,��,��,g�,C�,ƿ,��,��,E#-�&-�~-٢-��-�3'�32�3x�3��3�3#�3��3D�3\44~t4��4�5�!5�.5�/5�0585}>5 B5{F5GO5�S5ZT5�c5Nj5��5��5ҷ5��5J�56+ 6�6cF6-�8�8�8@�:��: ;<;N;�T;�~;��;��;W�;��;��;��;��;��;K <� =�=j1=�6=K;=�<= P=U=�=��=�=Ӽ=0�=�=��=��=��==�=7+>>->+1>�<>mN>�l>�p>��>��>��>��>Q?�Q?�[?@�?'�?F�?�?��?c�?�@�@�@�@־@n�@S�@��@�VA<]A�^AY�A��Ak�A�A^�A�B�=B�NBHdBfB��B�Bp�B~%C�GC[C ]C�^CI�C��D��D��DQ�D:�D��D9E{-E62EGYE�]Ez`E%�E��E�E�E��EP�E��E�E�E?�E�+FO?F�lF}F��Fg�Fy�F�CG�DG�FG�HG�UG(VG�fGF�G1�G��G�H'Hi"H�&H�'H*1Ht7H�pHCsH�uH��H��H£H�lIWtIӛIR�I��I��Iz�I 7J�EJ�RJ�VJ�XJ(ZJ�eJ�gJ�gJ�jJ�kJ�mJ�qJ��K��KɣK۲K��K��K��K��K��K��K[ L�Lk"Lj&L1*Lu�L��L�L�L(�L"�L��L�M,MS9M�?Mg�ML�M�Ny1NV5N[6N,=N�ZN�^N�OUO�)O_1O�dOVgOskO�wO��O�:P�IPZP�[P�kP"�P��P��P�PO�PU�P��P��P�Q�Q QxQ�/QeRQ�VQ�WQjjQ��Qc�Q>�Q �Q 4Rl=R�=R�GR��R�R��R�S�S�'Sb(S�,S�QS�XS:�Sc�S.�S}�S�T TlT�7T�AT�TTy\T�^TP`TkT��T��T��T��T@�T�U� U�~U@�U��UM!V�'V�?V�@VKV�eV�fV�~V��Vh�Vz�V5�V1�V^.W`9W'NW�SW�qW�|Wo�W{�Wk�W�X�]X�]X�aX�bXiX vX��X��X��XD�XѿX��X��X�Y Yl YD3YϐYL�Y5�YBAZTBZ�KZ�Z9�Zn�Z�ZL�Z��Z!9[q-\=�\;�\�\F�\��\ت\ܺ\Ż\k�\ ]�']�*]�]�]G^8 ^&k^+_W�_f�_�_��_�_�_�`�`�``�`V-`1`�G`RK`#T`sq`�z`p�`ܓ`��`Ե`��`.�`&�`y�`��`��`qa:a~a��a��a��aAbg b{b�-b{ab��b��b�3cDDc�Xc cc�ocAuc�wczc��cưc�c3�c��cc�ct�cnd�d d�!dU4d�Od��dV�dοd �d��d��df�d�&e�{e�e��em�eмeV�e��e��e�e8�e1�e{�e��eI�e_f�f� f`fz4fPf Rf:Uf"`fsf��fv�fJ�f5�f��fW�f��f'g��g��g{�gS�g�h�h�$h�$he5hHZh�[h�^h dh;zh��h�h��h��h��h\�h��h6�h��hq�h��hCi�.i�xax[dx�ex^lx�nx:rxh�x6�x�Tz�wz��z<�z@�z�z�zŹz��z�z$�z�z�{�.{�L{M{Lb{�r{��{�{�M|�Z|g|Bh|fi|'q|[u|]�|7�|K�|��|/** * BCL to FASTQ file converter * Copyright (c) 2007-2017 Illumina, Inc. * * This software is covered by the accompanying EULA * and certain third party copyright/licenses, and any user of this * source file is bound by the terms therein. * * \file testGzipCompressor.cpp * * \brief GzipCompressor cppunit test declarations. * * \author */ #include "RegistryName.hh" #include "testGzipCompressor.hh" #include "io/GzipCompressor.hh" #include CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(TestGzipCompressor, registryName("GzipCompressor")); void TestGzipCompressor::setUp() { } void TestGzipCompressor::tearDown() { } void TestGzipCompressor::writeCompressedBlock(const std::string& uncompressedData, bool useBgzf, std::vector& compressedData) { bcl2fastq::io::GzipCompressor(compressedData, useBgzf).write(uncompressedData.c_str(), uncompressedData.size()); } void TestGzipCompressor::decompressData(const std::vector::const_iterator& compressedData, size_t compressedSize, std::vector& decompressedData) { boost::iostreams::filtering_ostream os; os.push(boost::iostreams::gzip_decompressor()); os.push(boost::iostreams::back_inserter(decompressedData)); boost::iostreams::write(os, &(*compressedData), compressedSize); } void TestGzipCompressor::writeAllCompressedBlocks(std::vector& uncompressedData, bool useBgzf, std::vector< std::vector >& compressedData, std::vector& allCompressedBlocks) { std::string fullString; BOOST_FOREACH(const std::string& uncompressedString, std::make_pair(uncompressedData.begin(), uncompressedData.end())) { compressedData.push_back(std::vector()); writeCompressedBlock(uncompressedString, useBgzf, compressedData.back()); allCompressedBlocks.insert(allCompressedBlocks.end(), compressedData.back().begin(), compressedData.back().end()); } } void TestGzipCompressor::createUncompressedData(std::vector& uncompressedData, std::string& fullString) { uncompressedData.push_back("Hello. This is a test. "); uncompressedData.push_back("Here is a second message to compress. " " " " Long string x" ); uncompressedData.push_back("And one more."); BOOST_FOREACH(const std::string& uncompressedString, std::make_pair(uncompressedData.begin(), uncompressedData.end())) { fullString += uncompressedString; } } void TestGzipCompressor::locateAndDecompressBlocks(const std::vector& uncompressedData, const std::vector< std::vector >& compressedData, const std::vector& allCompressedBlocks) { int offset = 0; for (size_t i = 0; i < uncompressedData.size(); ++i) { // 4th byte should be the flags field. CPPUNIT_ASSERT(allCompressedBlocks.at(offset + 3) & 0x04); // 11th and 12th bytes are the length of the extra field. CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 10)), 4 + (int)bcl2fastq::io::GzipCompressor::SUBFIELD_LENGTH); CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 11)), 0); // 13th and 14th bytes are the subfield identifier. CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 12)), 66); CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 13)), 67); // 15th and 16th bytes are the length of the subfield data. // This is completely redundant with 11th and 12th bytes, but that's the expected format. CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 14)), (int)bcl2fastq::io::GzipCompressor::SUBFIELD_LENGTH); CPPUNIT_ASSERT_EQUAL(static_cast(allCompressedBlocks.at(offset + 15)), 0); // The next 8 bytes give the size of the compressed block. size_t compressedSize = 0; for (size_t j = (16 + bcl2fastq::io::GzipCompressor::SUBFIELD_LENGTH - 1); j >= 16; --j) { compressedSize <<= 8; compressedSize |= allCompressedBlocks.at(offset + j); } // bgzf uses size-1, so we will too. compressedSize += 1; CPPUNIT_ASSERT_EQUAL(compressedSize, compressedData[i].size()); // Decompress a single block. std::vector decompressedData; decompressData(allCompressedBlocks.begin()+offset, compressedSize, decompressedData); CPPUNIT_ASSERT_EQUAL(std::string(decompressedData.begin(), decompressedData.end()), uncompressedData[i]); offset += compressedSize; } } void TestGzipCompressor::testBgzf() { std::vector uncompressedData; std::string fullString; createUncompressedData(uncompressedData, fullString); std::vector< std::vector > compressedData; std::vector allCompressedBlocks; writeAllCompressedBlocks(uncompressedData, true, compressedData, allCompressedBlocks); // Try decompressing all blocks at once std::vector decompressedAll; decompressData(allCompressedBlocks.begin(), allCompressedBlocks.size(), decompressedAll); CPPUNIT_ASSERT_EQUAL(std::string(decompressedAll.begin(), decompressedAll.end()), fullString); // Test our ability to locate individual compressed blocks locateAndDecompressBlocks(uncompressedData, compressedData, allCompressedBlocks); } void TestGzipCompressor::testSingleBlock() { std::vector uncompressedData; std::string fullString; createUncompressedData(uncompressedData, fullString); std::vector< std::vector > compressedData; std::vector allCompressedBlocks; writeAllCompressedBlocks(uncompressedData, false, compressedData, allCompressedBlocks); // Try decompressing all blocks at once std::vector decompressedAll; decompressData(allCompressedBlocks.begin(), allCompressedBlocks.size(), decompressedAll); CPPUNIT_ASSERT_EQUAL(std::string(decompressedAll.begin(), decompressedAll.end()), fullString); } CPPTinkerings/src/stlstats/basic_stats.hpp #ifndef __BASIC_STATS_HPP_ #define __BASIC_STATS_HPP_ #include namespace stlstats { double mean(const std::vector&); double var(const std::vector&); double stdev(const std::vector&); double skew(const std::vector&); double kurtosis(const std::vector&); } #endif #include "pxt.h" #include "dtmfService.h" #include "Ticker.h" #include "dtmf.h" using namespace pxt; namespace zkm { static DtmfService *_dtmfService = NULL; static Action _handler[DTMF_TONE_COUNT]; TwoTone DTMFTONES[DTMF_TONE_COUNT] = { {FREQ_L1, FREQ_H1}, // DtmfTone::Tone_1 {FREQ_L1, FREQ_H2}, // DtmfTone::Tone_2 {FREQ_L1, FREQ_H3}, // DtmfTone::Tone_3 {FREQ_L2, FREQ_H1}, // DtmfTone::Tone_4 {FREQ_L2, FREQ_H2}, // DtmfTone::Tone_5 {FREQ_L2, FREQ_H3}, // DtmfTone::Tone_6 {FREQ_L3, FREQ_H1}, // DtmfTone::Tone_7 {FREQ_L3, FREQ_H2}, // DtmfTone::Tone_8 {FREQ_L3, FREQ_H3}, // DtmfTone::Tone_9 {FREQ_H4, FREQ_H2}, // DtmfTone::Tone_0 {FREQ_L1, FREQ_H4}, // DtmfTone::Tone_A {FREQ_L2, FREQ_H4}, // DtmfTone::Tone_B {FREQ_L3, FREQ_H4}, // DtmfTone::Tone_C {FREQ_L4, FREQ_H4}, // DtmfTone::Tone_D {FREQ_H4, FREQ_H1}, // DtmfTone::Tone_STAR {FREQ_H4, FREQ_H3}, // DtmfTone::Tone_HASH }; void dtmfTick() { _dtmfService->tick(); // TODO ??? fiber_sleep(_pService->getPeriod()); } //% void startDtmfService(int dtmfPin1, int dtmfPin2) { if (NULL != _dtmfService) { return; } MicroBitPin *pin1 = getPin(dtmfPin1); if (!pin1) { return; } MicroBitPin *pin2 = getPin(dtmfPin2); if (!pin2) { return; } _dtmfService = new DtmfService(pin1->name, pin2->name); create_fiber(dtmfTick); } //% void playTone(DtmfTone tone, int duration) { if (NULL == _dtmfService) { return; } TwoTone twoTone = DTMFTONES[tone]; _dtmfService->playTone(twoTone, duration); } //% void onTone(DtmfTone tone, Action handler) { _handler[tone] = handler; pxt::incr(_handler[tone]); } void notifyToneDetected(DtmfTone tone) { Action handler = _handler[tone]; if (handler) { pxt::runAction0(handler); } } TwoTone getTwoTone(DtmfTone tone) { return DTMFTONES[tone]; } }medeiroslucas/lo-and-behold-pp #include using namespace std; int main(){ int words[30], n; memset(words, 0, sizeof(words)); string in; vector ans; cin >> n; cin >> in; for(auto c:in){ words[c-'a']++; } while(words['o'-'a'] and words['n'-'a'] and words['e'-'a']){ ans.push_back(1); words['o'-'a']--; words['n'-'a']--; words['e'-'a']--; } while(words['z'-'a'] and words['e'-'a'] and words['r'-'a'] and words['o'-'a']){ ans.push_back(0); words['z'-'a']--; words['e'-'a']--; words['r'-'a']--; words['o'-'a']--; } for(int i=0; i0 #include #include #include "init/InitFindscholarships.hpp" #include "fetch/FetcherDbworld.h" #include "fetch/FetcherScholarshipLinks.h" #include "fetch/FetcherScholarshipPositions.h" #include "utilities/ConfigurationFindscholarships.h" #include "utilities/Logger.h" #include "utilities/ProgramOptions.h" using namespace findscholarships; void fetchDbworld() { FetcherDbworld fd(ConfigurationFindscholarships::instance()->pathTemp(), ConfigurationFindscholarships::instance()->pathDatabase(), ConfigurationFindscholarships::instance()->markerDbworld(), ConfigurationFindscholarships::instance()->inputDbworld()); fd.fetch(); } void fetchScholarshipLinks() { FetcherScholarshipLinks fsl(ConfigurationFindscholarships::instance()->pathTemp(), ConfigurationFindscholarships::instance()->pathDatabase(), ConfigurationFindscholarships::instance()->htmlScholarshipLinksGmail(), ConfigurationFindscholarships::instance()->inputScholarshipLinksGmail()); fsl.fetch(); } void fetchScholarshipPositions() { FetcherScholarshipPositions fsp(ConfigurationFindscholarships::instance()->pathTemp(), ConfigurationFindscholarships::instance()->pathDatabase(), ConfigurationFindscholarships::instance()->htmlScholarshipPositionsGmail(), ConfigurationFindscholarships::instance()->inputScholarshipPositionsGmail()); fsp.fetch(); } int main(int argc, char *argv[]) { std::string fetch_from = "spgmail"; /* std::string fetch_from = "all"; const char *help_description = "\nUsage: fetch [--from=all/manual/dbworld/spgmail/slgmail]\n"; boost::program_options::options_description desc(help_description); desc.add_options() (HELP, "produce help and usage message") (FROM, boost::program_options::value(&fetch_from)->default_value("all"), "choose fetching source") ; 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::cerr << desc << std::endl; exit(1); }*/ DBGINIT(std::cerr, Logger::INFO | Logger::ERRO | Logger::VERB | Logger::DEBU); InitFindscholarships init; init.init(); DBGINFO("Fetching starts..."); if (fetch_from == "dbworld") { DBGDEBUG("inputDatabase = " << ConfigurationFindscholarships::instance()->pathDatabase()) DBGDEBUG("markerDbworld = " << ConfigurationFindscholarships::instance()->markerDbworld()) DBGDEBUG("inputDbworld = " << ConfigurationFindscholarships::instance()->inputDbworld()) fetchDbworld(); } else if (fetch_from == "spgmail") // Scholarship Positions Gmail. { DBGDEBUG("inputDatabase = " << ConfigurationFindscholarships::instance()->pathDatabase()) DBGDEBUG("pathTemp = " << ConfigurationFindscholarships::instance()->pathTemp()) DBGDEBUG("htmlSPGmail = " << ConfigurationFindscholarships::instance()->htmlScholarshipPositionsGmail()) DBGDEBUG("inputSPGmail = " << ConfigurationFindscholarships::instance()->inputScholarshipPositionsGmail()) fetchScholarshipPositions(); } else if (fetch_from == "slgmail") // Scholarship Links Gmail. { DBGDEBUG("inputDatabase = " << ConfigurationFindscholarships::instance()->pathDatabase()) DBGDEBUG("pathTemp = " << ConfigurationFindscholarships::instance()->pathTemp()) DBGDEBUG("htmlSLGmail = " << ConfigurationFindscholarships::instance()->htmlScholarshipLinksGmail()) DBGDEBUG("inputSLGmail = " << ConfigurationFindscholarships::instance()->inputScholarshipLinksGmail()) fetchScholarshipLinks(); } else { assert (fetch_from == "all"); DBGDEBUG("pathTemp = " << ConfigurationFindscholarships::instance()->pathTemp()) DBGDEBUG("inputDatabase = " << ConfigurationFindscholarships::instance()->pathDatabase()) //DBGDEBUG("inputLinks = " << ConfigurationFindscholarships::instance()->inputLinks()) //DBGDEBUG("inputFetched = " << ConfigurationFindscholarships::instance()->inputFetched()) DBGDEBUG("markerDbworld = " << ConfigurationFindscholarships::instance()->markerDbworld()) DBGDEBUG("htmlSLGmail = " << ConfigurationFindscholarships::instance()->htmlScholarshipLinksGmail()) DBGDEBUG("inputSLGmail = " << ConfigurationFindscholarships::instance()->inputScholarshipLinksGmail()) DBGDEBUG("htmlSPGmail = " << ConfigurationFindscholarships::instance()->htmlScholarshipPositionsGmail()) DBGDEBUG("inputSPGmail = " << ConfigurationFindscholarships::instance()->inputScholarshipPositionsGmail()) //fetchManual(); fetchDbworld(); fetchScholarshipLinks(); fetchScholarshipPositions(); } DBGINFO("Fetching finished..."); } #include "common.h" #include "lua_wrapper.h" #include "google/protobuf/message.h" #include using namespace google::protobuf; void TestCreate() { LuaProtobuf::GetLuaProtobuf().LoadRootProto(PROTOFILE, PROTOPATH); Message* msg = LuaProtobuf::GetLuaProtobuf().CreateMessage("tTestProto"); if (!msg) { std::cerr << "创建protobuf类型:" << "tTestProto" << "失败" << std::endl; } else { std::cout << "创建protobuf类型:" << "tTestProto" << "成功" << std::endl; } delete msg; msg = NULL; } static int UpdateRootProto(lua_State* pState) { const char* fileName = luaL_checkstring(pState, 1); const char* filePath = NULL; if (lua_gettop(pState) > 1) { filePath = luaL_checkstring(pState, 2); } LuaProtobuf::GetLuaProtobuf().LoadRootProto(fileName, filePath == NULL ? SOURCEPATH : filePath); lua_pushboolean(pState, true); return 1; } static int PBEncode(lua_State* pState) { const char* pbName = luaL_checkstring(pState, 1); google::protobuf::Message* message = LuaProtobuf::GetLuaProtobuf().LuaToProtobuf(pbName, pState, 2); if (message) { std::string b; message->SerializeToString(&b); lua_pushlstring(pState, b.c_str(), b.size()); delete message; message = NULL; return 1; } else { std::cerr << "转换pb失败" << pbName << std::endl; } return 0; } static int PBDecode(lua_State* pState) { const char* pbName = luaL_checkstring(pState, 1); size_t size = 0; const char* msg = luaL_checklstring(pState, 2, &size); std::string parseString; parseString.assign(msg, size); google::protobuf::Message* pbMsg = LuaProtobuf::GetLuaProtobuf().CreateMessage(pbName); if (pbMsg) { if (pbMsg->ParseFromString(parseString)) { LuaProtobuf::GetLuaProtobuf().PushProtobufToLuaTable(pState, pbMsg); return 1; } else { std::cerr << "parse failed name =" << pbName << std::endl; } } else { std::cerr << "cant create pb type. name = " << pbName << std::endl; } return 0; } static void RegisterProto2Lua() { RegistFuntion2Lua(UpdateRootProto); RegistFuntion2Lua(PBEncode); RegistFuntion2Lua(PBDecode); } void TestLuaProto() { gLuaManager.InitScript(); RegisterProto2Lua(); gLuaManager.LoadScript(SOURCEPATH, "proto_main.lua"); } int main() { TestCreate(); TestLuaProto(); return 0; } DabbyG/cpp-lsh #include "DataSet.hpp" using namespace MetricSpace::Euclidean; DataSet::DataSet(Matrix&& m) : mVectors(std::move(m)) {} DataSet::DataSet(DataSet&& other) : mVectors(std::move(other.mVectors)) {} DataSet::DataSet(const DataSet& other) : mVectors(other.mVectors) {} DataSet& DataSet::operator= (DataSet other) { std::swap(mVectors, other.mVectors); return *this; } DataSet::ConstPointRef DataSet::operator[] (unsigned int i) const { return mVectors.row(i); } unsigned int DataSet::getPointNum() const { return mVectors.getColSize(); } unsigned int DataSet::getVectorDim() const { return mVectors.getRowSize(); } #include "MyString.h" using namespace std; int main() { MyString obj1 {"Hello"}; // Deep copy constructor called MyString obj2 = obj1; // obj1.display(); cout << obj1 << endl; // obj2.display(); cout << obj2 << endl; // Move assignment operator called obj1 = ""; // obj1.display(); cout << obj1 << endl; obj1 = -obj1; // obj1.display(); cout << obj1 << endl; obj1 = obj1 + ", HERO"; // obj1.display(); cout << obj1 << endl; obj1 += " TADA"; // obj1.display(); cout << obj1 << endl; obj1++; // obj1.display(); cout << obj1 << endl; MyString obj3 {"hi"}; obj3++; // obj3.display(); cout << obj3 << endl; obj3 = obj3 * 4; // obj3.display(); cout << obj3 << endl; cout << boolalpha; cout << (obj3 == obj1) << endl; cout << (obj3 != obj1) << endl; cout << (obj2 == obj1) << endl; cout << (obj3 > obj1) << endl; cout << (obj3 < obj1) << endl; MyString obj4; cin >> obj4; cout << obj4 << endl; return 0; } class buf { public: char *buffer; }; class packet { public: buf data; }; typedef long ssize_t; ssize_t argument_source(void *buf); void sink(char *b); void handlePacket(packet *p) { sink(p->data.buffer); // $ast $f-:ir } void f(buf* b) { char *raw; packet p; argument_source(raw); argument_source(b->buffer); argument_source(p.data.buffer); sink(raw); // $ast $f-:ir sink(b->buffer); // $ast $f-:ir handlePacket(&p); }/// #include #include #include #include #include #include "indicators.hpp" #include "fs.hpp" #include "baulk.hpp" namespace baulk::zip { // avoid filename too long int32_t OnEntry(void *handle, void *userdata, mz_zip_file *file_info, const char *path) { auto termsz = reinterpret_cast(userdata); if (termsz == nullptr || termsz->columns <= 8) { return 0; } auto suglen = static_cast(termsz->columns) - 8; auto filename = bela::ToWide(std::string_view{file_info->filename, file_info->filename_size}); if (auto n = bela::StringWidth(filename); n <= suglen) { bela::FPrintF(stderr, L"\x1b[2K\r\x1b[33mx %s\x1b[0m", filename); return 0; } auto basename = bela::BaseName(filename); auto n = bela::StringWidth(basename); if (n <= suglen) { bela::FPrintF(stderr, L"\x1b[2K\r\x1b[33mx ...\\%s\x1b[0m", basename); return 0; } bela::FPrintF(stderr, L"\x1b[2K\r\x1b[33mx ...%s\x1b[0m", basename.substr(n - suglen)); return 0; } bool Decompress(std::wstring_view src, std::wstring_view outdir, bela::error_code &ec) { bela::terminal::terminal_size termsz{0}; baulk::archive::zip::zip_closure closure{nullptr}; if (!baulk::IsQuietMode) { if (bela::terminal::IsSameTerminal(stderr)) { if (auto cygwinterminal = bela::terminal::IsCygwinTerminal(stderr); cygwinterminal) { CygwinTerminalSize(termsz); } else { bela::terminal::TerminalSize(stderr, termsz); } } closure.userdata = &termsz; closure.entry = OnEntry; } if (!baulk::archive::zip::ZipExtract(src, outdir, ec, &closure)) { return false; } if (!baulk::IsQuietMode) { bela::FPrintF(stderr, L"\n"); } return true; } } // namespace baulk::zip /* ================================================================== * * FILE: tclshrl.c * $Id: b4713753d4536865a148877773f7a0df7275e8ab $ * --- * tclreadline -- gnu readline for tcl * https://github.com/flightaware/tclreadline/ * Copyright (c) 1998 - 2014, <> * This software is copyright under the BSD license. * ================================================================== */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include #include #include #include namespace open_edi { namespace gui { extern int Tclreadline_Init(Tcl_Interp *interp); extern int Tclreadline_SafeInit(Tcl_Interp *interp); extern void TclsetHistoryPath(const char* historyPath); int TclreadlineAppInit(Tcl_Interp* interp, const char* installPath) { char rcPath[0xff] = {0}; char setupPath[0xff] = {0}; char completerPath[0xff] = {0}; int status; if (TCL_ERROR == Tclreadline_Init(interp)) { return TCL_ERROR; } Tcl_StaticPackage(interp, "tclreadline", Tclreadline_Init, Tclreadline_SafeInit); TclsetHistoryPath(installPath); strcpy(rcPath,installPath); strcat(rcPath,"share/etc/tcl/init.tcl"); Tcl_SetVar(interp, "tcl_rcFileName", rcPath, TCL_GLOBAL_ONLY); Tcl_Eval(interp,"::tclreadline::readline customcompleter ::tclreadline::ScriptCompleter"); strcpy(setupPath,installPath); strcat(setupPath,"share/etc/tcl/tclreadlineSetup.tcl"); if ((status = Tcl_EvalFile(interp,setupPath))) { fprintf(stderr, "(tclreadlineSetup) unable to eval %s\n", setupPath); exit (EXIT_FAILURE); } strcpy(completerPath,installPath); strcat(completerPath,"share/etc/tcl/tclreadlineCompleter.tcl"); if ((status = Tcl_EvalFile(interp,completerPath))) { fprintf(stderr, "(tclreadlineCompleter) unable to eval %s\n", completerPath); exit (EXIT_FAILURE); } return TCL_OK; } } // namespace gui } // namespace open_edi 1-10 #include "StdAfx.h" #pragma comment(lib, "shlwapi.lib")// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "VRExpansionPluginPrivatePCH.h" #include "Runtime/Engine/Private/EnginePrivate.h" #include "VRCharacter.h" AVRCharacter::AVRCharacter(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer.DoNotCreateDefaultSubobject(ACharacter::MeshComponentName).SetDefaultSubobjectClass(ACharacter::CapsuleComponentName).SetDefaultSubobjectClass(ACharacter::CharacterMovementComponentName)) { VRRootReference = NULL; if (GetCapsuleComponent()) { VRRootReference = Cast(GetCapsuleComponent()); VRRootReference->SetCapsuleSize(20.0f, 96.0f); } VRMovementReference = NULL; if (GetMovementComponent()) { VRMovementReference = Cast(GetMovementComponent()); } VRReplicatedCamera = CreateDefaultSubobject(TEXT("VR Replicated Camera")); if (VRReplicatedCamera) { VRReplicatedCamera->SetupAttachment(RootComponent); // By default this will tick after the root, root will be one tick behind on position. Doubt it matters much } ParentRelativeAttachment = CreateDefaultSubobject(TEXT("Parent Relative Attachment")); if (ParentRelativeAttachment && VRReplicatedCamera) { ParentRelativeAttachment->SetupAttachment(VRReplicatedCamera); /*if (GetMesh()) { GetMesh()->SetupAttachment(ParentRelativeAttachment); }*/ } LeftMotionController = CreateDefaultSubobject(TEXT("Left Grip Motion Controller")); if (LeftMotionController) { LeftMotionController->SetupAttachment(RootComponent); LeftMotionController->Hand = EControllerHand::Left; // Keep the controllers ticking after movement if (this->GetCharacterMovement()) { LeftMotionController->AddTickPrerequisiteComponent(this->GetCharacterMovement()); } } RightMotionController = CreateDefaultSubobject(TEXT("Right Grip Motion Controller")); if (RightMotionController) { RightMotionController->SetupAttachment(RootComponent); RightMotionController->Hand = EControllerHand::Right; // Keep the controllers ticking after movement if (this->GetCharacterMovement()) { RightMotionController->AddTickPrerequisiteComponent(this->GetCharacterMovement()); } } } FVector AVRCharacter::GetTeleportLocation(FVector OriginalLocation) { FVector modifier = VRRootReference->GetVRLocation() - this->GetActorLocation(); modifier.Z = 0.0f; // Null out Z return OriginalLocation - modifier; } bool AVRCharacter::TeleportTo(const FVector& DestLocation, const FRotator& DestRotation, bool bIsATest, bool bNoCheck) { bool bTeleportSucceeded = Super::TeleportTo(DestLocation, DestRotation, bIsATest, bNoCheck); if (bTeleportSucceeded) { NotifyOfTeleport(); } return bTeleportSucceeded; } void AVRCharacter::NotifyOfTeleport_Implementation() { if (LeftMotionController) LeftMotionController->PostTeleportMoveGrippedActors(); if (RightMotionController) RightMotionController->PostTeleportMoveGrippedActors(); // Regenerate the capsule offset location if (VRRootReference) VRRootReference->GenerateOffsetToWorld(); } frc1418/allwpilib // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "frc/filter/LinearFilter.h" // NOLINT(build/include_order) #include #include #include #include #include #include #include "gtest/gtest.h" #include "units/time.h" // Filter constants static constexpr auto kFilterStep = 5_ms; static constexpr auto kFilterTime = 2_s; static constexpr double kSinglePoleIIRTimeConstant = 0.015915; static constexpr double kSinglePoleIIRExpectedOutput = -3.2172003; static constexpr double kHighPassTimeConstant = 0.006631; static constexpr double kHighPassExpectedOutput = 10.074717; static constexpr int32_t kMovAvgTaps = 6; static constexpr double kMovAvgExpectedOutput = -10.191644; enum LinearFilterOutputTestType { kTestSinglePoleIIR, kTestHighPass, kTestMovAvg, kTestPulse }; static double GetData(double t) { return 100.0 * std::sin(2.0 * wpi::numbers::pi * t) + 20.0 * std::cos(50.0 * wpi::numbers::pi * t); } static double GetPulseData(double t) { if (std::abs(t - 1.0) < 0.001) { return 1.0; } else { return 0.0; } } /** * A fixture that includes a consistent data source wrapped in a filter */ class LinearFilterOutputTest : public testing::TestWithParam { protected: frc::LinearFilter m_filter = [=] { switch (GetParam()) { case kTestSinglePoleIIR: return frc::LinearFilter::SinglePoleIIR( kSinglePoleIIRTimeConstant, kFilterStep); break; case kTestHighPass: return frc::LinearFilter::HighPass(kHighPassTimeConstant, kFilterStep); break; case kTestMovAvg: return frc::LinearFilter::MovingAverage(kMovAvgTaps); break; default: return frc::LinearFilter::MovingAverage(kMovAvgTaps); break; } }(); std::function m_data; double m_expectedOutput = 0.0; LinearFilterOutputTest() { switch (GetParam()) { case kTestSinglePoleIIR: { m_data = GetData; m_expectedOutput = kSinglePoleIIRExpectedOutput; break; } case kTestHighPass: { m_data = GetData; m_expectedOutput = kHighPassExpectedOutput; break; } case kTestMovAvg: { m_data = GetData; m_expectedOutput = kMovAvgExpectedOutput; break; } case kTestPulse: { m_data = GetPulseData; m_expectedOutput = 0.0; break; } } } }; /** * Test if the linear filters produce consistent output for a given data set. */ TEST_P(LinearFilterOutputTest, Output) { double filterOutput = 0.0; for (auto t = 0_s; t < kFilterTime; t += kFilterStep) { filterOutput = m_filter.Calculate(m_data(t.value())); } RecordProperty("LinearFilterOutput", filterOutput); EXPECT_FLOAT_EQ(m_expectedOutput, filterOutput) << "Filter output didn't match expected value"; } INSTANTIATE_TEST_SUITE_P(Tests, LinearFilterOutputTest, testing::Values(kTestSinglePoleIIR, kTestHighPass, kTestMovAvg, kTestPulse)); template void AssertCentralResults(F&& f, DfDx&& dfdx, units::second_t h, double min, double max) { static_assert(Samples % 2 != 0, "Number of samples must be odd."); // Generate stencil points from -(samples - 1)/2 to (samples - 1)/2 wpi::array stencil{wpi::empty_array}; for (int i = 0; i < Samples; ++i) { stencil[i] = -(Samples - 1) / 2 + i; } auto filter = frc::LinearFilter::FiniteDifference(stencil, h); for (int i = min / h.value(); i < max / h.value(); ++i) { // Let filter initialize if (i < static_cast(min / h.value()) + Samples) { filter.Calculate(f(i * h.value())); continue; } // For central finite difference, the derivative computed at this point is // half the window size in the past. // The order of accuracy is O(h^(N - d)) where N is number of stencil // points and d is order of derivative EXPECT_NEAR(dfdx((i - static_cast((Samples - 1) / 2)) * h.value()), filter.Calculate(f(i * h.value())), std::pow(h.value(), Samples - Derivative)); } } template void AssertBackwardResults(F&& f, DfDx&& dfdx, units::second_t h, double min, double max) { auto filter = frc::LinearFilter::BackwardFiniteDifference( h); for (int i = min / h.value(); i < max / h.value(); ++i) { // Let filter initialize if (i < static_cast(min / h.value()) + Samples) { filter.Calculate(f(i * h.value())); continue; } // The order of accuracy is O(h^(N - d)) where N is number of stencil // points and d is order of derivative EXPECT_NEAR(dfdx(i * h.value()), filter.Calculate(f(i * h.value())), 10.0 * std::pow(h.value(), Samples - Derivative)); } } /** * Test central finite difference. */ TEST(LinearFilterOutputTest, CentralFiniteDifference) { constexpr auto h = 5_ms; AssertCentralResults<1, 3>( [](double x) { // f(x) = x² return x * x; }, [](double x) { // df/dx = 2x return 2.0 * x; }, h, -20.0, 20.0); AssertCentralResults<1, 3>( [](double x) { // f(x) = std::sin(x) return std::sin(x); }, [](double x) { // df/dx = std::cos(x) return std::cos(x); }, h, -20.0, 20.0); AssertCentralResults<1, 3>( [](double x) { // f(x) = ln(x) return std::log(x); }, [](double x) { // df/dx = 1/x return 1.0 / x; }, h, 1.0, 20.0); AssertCentralResults<2, 5>( [](double x) { // f(x) = x² return x * x; }, [](double x) { // d²f/dx² = 2 return 2.0; }, h, -20.0, 20.0); AssertCentralResults<2, 5>( [](double x) { // f(x) = std::sin(x) return std::sin(x); }, [](double x) { // d²f/dx² = -std::sin(x) return -std::sin(x); }, h, -20.0, 20.0); AssertCentralResults<2, 5>( [](double x) { // f(x) = ln(x) return std::log(x); }, [](double x) { // d²f/dx² = -1/x² return -1.0 / (x * x); }, h, 1.0, 20.0); } /** * Test backward finite difference. */ TEST(LinearFilterOutputTest, BackwardFiniteDifference) { constexpr auto h = 5_ms; AssertBackwardResults<1, 2>( [](double x) { // f(x) = x² return x * x; }, [](double x) { // df/dx = 2x return 2.0 * x; }, h, -20.0, 20.0); AssertBackwardResults<1, 2>( [](double x) { // f(x) = std::sin(x) return std::sin(x); }, [](double x) { // df/dx = std::cos(x) return std::cos(x); }, h, -20.0, 20.0); AssertBackwardResults<1, 2>( [](double x) { // f(x) = ln(x) return std::log(x); }, [](double x) { // df/dx = 1/x return 1.0 / x; }, h, 1.0, 20.0); AssertBackwardResults<2, 4>( [](double x) { // f(x) = x² return x * x; }, [](double x) { // d²f/dx² = 2 return 2.0; }, h, -20.0, 20.0); AssertBackwardResults<2, 4>( [](double x) { // f(x) = std::sin(x) return std::sin(x); }, [](double x) { // d²f/dx² = -std::sin(x) return -std::sin(x); }, h, -20.0, 20.0); AssertBackwardResults<2, 4>( [](double x) { // f(x) = ln(x) return std::log(x); }, [](double x) { // d²f/dx² = -1/x² return -1.0 / (x * x); }, h, 1.0, 20.0); } huanghongxun/ACM1-10 #include #include #include #define N 105 #define M 10005 using namespace std; int p[N], l[N], x[N]; int m, n; int dist[N]; bool vis[N]; int pre[N]; int head[N], next[M], to[M], wei[M], cnt = 0; void spfa(int src) { queue q; q.push(src); memset(vis, 0, sizeof(vis)); memset(dist, 63, sizeof(dist)); vis[src] = 1; dist[src] = 0; pre[src] = -1; while(!q.empty()) { int u = q.front(); q.pop(); for(int i = head[u]; i != -1; i = next[i]) { int v = to[i]; if(dist[v] > dist[u] + wei[i] && l[v] <= l[u]) { for(int j = u; j != -1; j = pre[j]) if(l[j] - l[v] > m) { v = -1; break; } if(v == -1) continue; dist[v] = dist[u] + wei[i]; pre[v] = u; if(!vis[v]) { q.push(v); vis[v] = 1; } } } vis[u] = 0; } } void add(int u, int v, int w) { next[cnt] = head[u]; to[cnt] = v; wei[cnt] = w; head[u] = cnt++; } int main() { scanf("%d%d", &m, &n); memset(head, -1, sizeof(head)); int i, a, b, x; for(i = 1; i <= n; i++) { scanf("%d%d%d", &p[i], &l[i], &x); while(x--) { scanf("%d%d", &a, &b); add(i, a, b); } } spfa(1); int mi = 0x7ffffff; for(i = 1; i <= n; i++) { if(dist[i] + p[i] < mi) mi = dist[i] + p[i]; } printf("%d", mi); return 0; }// WL_TEXT.C #include "wl_def.h" #pragma hdrstop /* ============================================================================= TEXT FORMATTING COMMANDS ------------------------ ^C Change text color ^E[enter] End of layout (all pages) ^G,,[enter] Draw a graphic and push margins ^P[enter] start new page, must be the first chars in a layout ^L,[ENTER] Locate to a specific spot, x in pixels, y in lines ============================================================================= */ /* ============================================================================= LOCAL CONSTANTS ============================================================================= */ #ifndef SPEAR #define BACKCOLOR 0x11 #define WORDLIMIT 80 #define FONTHEIGHT 10 #define TOPMARGIN 16 #define BOTTOMMARGIN 32 #define LEFTMARGIN 16 #define RIGHTMARGIN 16 #define PICMARGIN 8 #define TEXTROWS ((200-TOPMARGIN-BOTTOMMARGIN)/FONTHEIGHT) #define SPACEWIDTH 7 #define SCREENPIXWIDTH 320 #define SCREENMID (SCREENPIXWIDTH/2) /* ============================================================================= LOCAL VARIABLES ============================================================================= */ static int pagenum; static int numpages; static unsigned leftmargin[TEXTROWS]; static unsigned rightmargin[TEXTROWS]; static char* text; static unsigned rowon; static int picx; static int picy; static int picnum; static int picdelay; static boolean layoutdone; //=========================================================================== #ifndef JAPAN /* ===================== = = RipToEOL = ===================== */ void RipToEOL (void) { while (*text++ != '\n') // scan to end of line ; } /* ===================== = = ParseNumber = ===================== */ int ParseNumber (void) { char ch; char num[80]; char *numptr; // // scan until a number is found // ch = *text; while (ch < '0' || ch >'9') ch = *++text; // // copy the number out // numptr = num; do { *numptr++ = ch; ch = *++text; } while (ch >= '0' && ch <= '9'); *numptr = 0; return atoi (num); } /* ===================== = = ParsePicCommand = = Call with text pointing just after a ^P = Upon exit text points to the start of next line = ===================== */ void ParsePicCommand (void) { picy=ParseNumber(); picx=ParseNumber(); picnum=ParseNumber(); RipToEOL (); } void ParseTimedCommand (void) { picy=ParseNumber(); picx=ParseNumber(); picnum=ParseNumber(); picdelay=ParseNumber(); RipToEOL (); } /* ===================== = = TimedPicCommand = = Call with text pointing just after a ^P = Upon exit text points to the start of next line = ===================== */ void TimedPicCommand (void) { ParseTimedCommand (); // // update the screen, and wait for time delay // VW_UpdateScreen (); // // wait for time // Delay(picdelay); // // draw pic // VWB_DrawPic (picx&~7,picy,picnum); } /* ===================== = = HandleCommand = ===================== */ void HandleCommand (void) { int i,margin,top,bottom; int picwidth,picheight,picmid; switch (toupper(*++text)) { case 'B': picy=ParseNumber(); picx=ParseNumber(); picwidth=ParseNumber(); picheight=ParseNumber(); VWB_Bar(picx,picy,picwidth,picheight,BACKCOLOR); RipToEOL(); break; case ';': // comment RipToEOL(); break; case 'P': // ^P is start of next page, ^E is end of file case 'E': layoutdone = true; text--; // back up to the '^' break; case 'C': // ^c changes text color i = toupper(*++text); if (i>='0' && i<='9') fontcolor = i-'0'; else if (i>='A' && i<='F') fontcolor = i-'A'+10; fontcolor *= 16; i = toupper(*++text); if (i>='0' && i<='9') fontcolor += i-'0'; else if (i>='A' && i<='F') fontcolor += i-'A'+10; text++; break; case '>': px = 160; text++; break; case 'L': py=ParseNumber(); rowon = (py-TOPMARGIN)/FONTHEIGHT; py = TOPMARGIN+rowon*FONTHEIGHT; px=ParseNumber(); while (*text++ != '\n') // scan to end of line ; break; case 'T': // ^Tyyy,xxx,ppp,ttt waits ttt tics, then draws pic TimedPicCommand (); break; case 'G': // ^Gyyy,xxx,ppp draws graphic ParsePicCommand (); VWB_DrawPic (picx&~7,picy,picnum); picwidth = pictable[picnum-STARTPICS].width; picheight = pictable[picnum-STARTPICS].height; // // adjust margins // picmid = picx + picwidth/2; if (picmid > SCREENMID) margin = picx-PICMARGIN; // new right margin else margin = picx+picwidth+PICMARGIN; // new left margin top = (picy-TOPMARGIN)/FONTHEIGHT; if (top<0) top = 0; bottom = (picy+picheight-TOPMARGIN)/FONTHEIGHT; if (bottom>=TEXTROWS) bottom = TEXTROWS-1; for (i=top;i<=bottom;i++) if (picmid > SCREENMID) rightmargin[i] = margin; else leftmargin[i] = margin; // // adjust this line if needed // if (px < (int) leftmargin[rowon]) px = leftmargin[rowon]; break; } } /* ===================== = = NewLine = ===================== */ void NewLine (void) { char ch; if (++rowon == TEXTROWS) { // // overflowed the page, so skip until next page break // layoutdone = true; do { if (*text == '^') { ch = toupper(*(text+1)); if (ch == 'E' || ch == 'P') { layoutdone = true; return; } } text++; } while (1); } px = leftmargin[rowon]; py+= FONTHEIGHT; } /* ===================== = = HandleCtrls = ===================== */ void HandleCtrls (void) { char ch; ch = *text++; // get the character and advance if (ch == '\n') { NewLine (); return; } } /* ===================== = = HandleWord = ===================== */ void HandleWord (void) { char wword[WORDLIMIT]; int wordindex; word wwidth,wheight,newpos; // // copy the next word into [word] // wword[0] = *text++; wordindex = 1; while (*text>32) { wword[wordindex] = *text++; if (++wordindex == WORDLIMIT) Quit ("PageLayout: Word limit exceeded"); } wword[wordindex] = 0; // stick a null at end for C // // see if it fits on this line // VW_MeasurePropString (wword,&wwidth,&wheight); while (px+wwidth > (int) rightmargin[rowon]) { NewLine (); if (layoutdone) return; // overflowed page } // // print it // newpos = px+wwidth; VWB_DrawPropString (wword); px = newpos; // // suck up any extra spaces // while (*text == ' ') { px += SPACEWIDTH; text++; } } /* ===================== = = PageLayout = = Clears the screen, draws the pics on the page, and word wraps the text. = Returns a pointer to the terminating command = ===================== */ void PageLayout (boolean shownumber) { int i,oldfontcolor; char ch; oldfontcolor = fontcolor; fontcolor = 0; // // clear the screen // VWB_Bar (0,0,320,200,BACKCOLOR); VWB_DrawPic (0,0,H_TOPWINDOWPIC); VWB_DrawPic (0,8,H_LEFTWINDOWPIC); VWB_DrawPic (312,8,H_RIGHTWINDOWPIC); VWB_DrawPic (8,176,H_BOTTOMINFOPIC); for (i=0; i1) { #ifndef JAPAN BackPage (); BackPage (); #else pagenum--; #endif newpage = true; } TicDelay(20); break; case dir_South: case dir_East: if (pagenum &preorder, vector &inorder) { for (int i = 0; i < inorder.size(); ++i) { m[inorder[i]] = i; } return _buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } TreeNode *_buildTree(vector &preorder, int id1, int id2, vector &inorder, int id3, int id4) { if (id1 > id2) { return NULL; } TreeNode *root = new TreeNode(preorder[id1]); int i = m[preorder[id1]]; root->left = _buildTree(preorder, id1 + 1, id1 + i - id3, inorder, id3, i - 1); root->right = _buildTree(preorder, id1 + i - id3 + 1, id2, inorder, i + 1, id4); return root; } private: unordered_map m; }; // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc. #include "ApplicationInfo.h" #include "ApplicationStore.h" #include "gtest/gtest.h" #include "ProfilerMockedInterface.h" using ::testing::ReturnRef; TEST(ApplicationStoreTest, GetDefaultName) { auto [configuration, mockConfiguration] = CreateConfiguration(); const std::string expectedServiceName = "DefaultServiceName"; const std::string expectedVersion = "DefaultVersion"; const std::string expectedEnvironment = "DefaultEnvironment"; EXPECT_CALL(mockConfiguration, GetServiceName()).WillRepeatedly(ReturnRef(expectedServiceName)); EXPECT_CALL(mockConfiguration, GetVersion()).WillRepeatedly(ReturnRef(expectedVersion)); EXPECT_CALL(mockConfiguration, GetEnvironment()).WillRepeatedly(ReturnRef(expectedEnvironment)); ApplicationStore applicationStore(configuration.get()); const auto& info = applicationStore.GetApplicationInfo("{82F18E9B-138D-4202-8D21-7BE1AF82EC8B}"); ASSERT_EQ(info.ServiceName, expectedServiceName); ASSERT_EQ(info.Version, expectedVersion); ASSERT_EQ(info.Environment, expectedEnvironment); } TEST(ApplicationStoreTest, SetName) { auto [configuration, mockConfiguration] = CreateConfiguration(); ApplicationStore applicationStore(configuration.get()); const auto runtimeId = "{82F18E9B-138D-4202-8D21-7BE1AF82EC8B}"; const auto expectedApplicationInfo = ApplicationInfo( "ExpectedServiceName", "ExpectedEnvironment", "ExpectedVersion" ); applicationStore.SetApplicationInfo( runtimeId, expectedApplicationInfo.ServiceName, expectedApplicationInfo.Environment, expectedApplicationInfo.Version); const auto& info = applicationStore.GetApplicationInfo(runtimeId); ASSERT_EQ(info.Environment, expectedApplicationInfo.Environment); ASSERT_EQ(info.ServiceName, expectedApplicationInfo.ServiceName); ASSERT_EQ(info.Version, expectedApplicationInfo.Version); }0 #include #include #include #include int main() { std::vector my_vector(9, 0); std::deque my_deque(9, 0); std::cout << "Vector capacity: " << my_vector.capacity() << std::endl; for (int i = 0; i < my_vector.size(); i++) { std::cout << my_vector[i] << " " << &my_vector[i] << std::endl; } std::cout << std::endl; for (int i = 0; i < my_deque.size(); i++) { std::cout << my_deque[i] << " " << &my_deque[i] << std::endl; } std::cout << std::endl; ///////////////// my_vector.push_back(9); std::cout << "Vector capacity: " << my_vector.capacity() << std::endl; for (int i = 0; i < my_vector.size(); i++) { std::cout << my_vector[i] << " " << &my_vector[i] << std::endl; } std::cout << std::endl; my_deque.push_back(9); my_deque.push_back(10); my_deque.pop_front(); for (int i = 0; i < my_deque.size(); i++) { std::cout << my_deque[i] << " " << &my_deque[i] << std::endl; } std::cout << std::endl; return 0; }eduardorasgado/Cpp-AdvancedTopics #include #include #include // inline function through a macro // if it is not handling correctly it will create bugs //#define Square(A) (A*A) // In c++ instead a macro we use inline functions // inline keyword tells the compiler to substitute the caller of the function in // where inline function is been using(e.g int result = Square(val) ) // and replace it with the body of the function(in compiler time) inline int Square(int x) { return x * x; } // new name for type pair: type definition typedef std::pair par; int main() { // creating a map using a smart pointer auto myMap = std::make_shared>(); // inserting elements to map myMap->insert(par(0, "0x200")); myMap->insert(par(1, "0x420")); //showing the map // creating an iterator for stl map object std::map::iterator i = myMap->begin(); for(i; i != myMap->end();++i) std::cout << "map[" << i->first <<"]: " << i->second << "\n"; // inline functions int val = 5; // with inline function, the arguments passed here are firstly evaluated and then // passed to the function int result = Square(val + 1); std::cout << result << std::endl; int result2 = Square((val * 2) +1); // 11 and 11*11 = 121 std::cout << result2 << std::endl; /* INLINE FUNCTIONS: -Only a request to the compiler -Certain functions may nto be inlined large functions functions having too many conditional statements recursive functions functions invoked through pointers etc -Diferent compilers have different rules - Modern compilers may automatically inline even non-inline functions -Excessive inlining may increase binary size MACROS VS INLINE macro is text substitution | the call is replaced with the body error prone due to substitution | safe to use as it has func semantics does not have an address | has an address difficult to use with multiple lines of code | can have multiple line of codes */ return 0; } /* * example.cpp * Copyright (C) 2019 <> * * Distributed under terms of the GPL license. */ #include #include "solution.hpp" void run_example() { Solution sln; vector arr { 5, 7, 11, 13 }; std::cout << sln.missingNumber( arr ) << std::endl; } #include #include class background_task { public: void operator() () const { do_something(); do_something_else(); } private: void do_something() const { std::cout << "do_something\n"; } void do_something_else() const { std::cout << "do_something_else\n"; } }; int main() { // it is a function std::thread my_thread1(background_task()); std::thread my_thread2 {background_task()}; my_thread2.join(); return 0; } sapper-trle/trview #include "gtest/gtest.h" #include using namespace trview; using namespace DirectX::SimpleMath; /// Tests that when the camera is in alignment mode it moves relative the world axis. TEST(FreeCamera, Alignment) { FreeCamera camera(Size(100, 100)); // Set the camera to be slightly pitched, so that moving up in camera mode // would move the camera away from 0,0 on the x/z axis. camera.set_rotation_pitch(0.45f); // Ensure the camera is in axis mode. camera.set_alignment(FreeCamera::Alignment::Axis); const auto current_position = camera.position(); ASSERT_EQ(Vector3::Zero, camera.position()); camera.move(Vector3(0, 1, 0)); // Check that the camera has moved up. const auto new_position = camera.position(); ASSERT_EQ(0.0f, new_position.x); ASSERT_NE(0.0f, new_position.y); ASSERT_EQ(0.0f, new_position.z); } /// Tests that setting the position actually moves the camera. TEST(FreeCamera, Position) { FreeCamera camera(Size(100, 100)); const auto target_position = Vector3(1, 2, 3); camera.set_position(target_position); const auto new_position = camera.position(); ASSERT_EQ(target_position, new_position); }AnkilP/codeforces #include #include #include #include #include #include #include #include #include #include #include #include #include #include bool isCycle(const std::string &){ } long long solution(const int & t, const std::string & f){ std::map> adj_list; for(int i = 0; i < f.length(); ++i){ if(f[i] == '-'){ adj_list[i].emplace_back((i + 1) % t); adj_list[(i + 1) % t].emplace_back(i); } else if(f[i] == '>'){ adj_list[i].emplace_back((i + 1) % t); } else{ adj_list[(i + 1) % t].emplace_back(i); } } long long sum = 0; for(int i = 0; i < t; ++i){ std::vector visited(t, 0); std::queue bfs_queue; while(!bfs_queue.empty()){ auto x = bfs_queue.front(); bfs_queue.pop(); visited[x]++; } if(visited[i] > 0){ sum++; } } return sum; } int main(){ std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::string stones; std::string conveyor; // //assuming that input txt doc is argv[1] // std::string inputTxt = argv[1]; // // output txt doc is argv[2] // std::string outputTxt = argv[2]; // std::ifstream inputFile(inputTxt); // std::ofstream outputFile(outputTxt); std::string T; std::getline(std::cin,T); int testcases = stoi(T); for(int i = 0; i < testcases; ++i){ std::getline(std::cin, stones); std::getline(std::cin, conveyor); auto sol = solution(stoi(stones), conveyor); std::cout << std::to_string(sol) << "\n"; } // outputFile.close(); // inputFile.close(); return 0; }/****************************************************************************** * Copyright 2018 The Apollo Authors. 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 "modules/planning/reference_line/cos_theta_reference_line_smoother.h" #include #include "IpIpoptApplication.hpp" #include "IpSolveStatistics.hpp" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common/time/time.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/smoothing_spline/spline_2d_solver.h" #include "modules/planning/reference_line/cos_theta_problem_interface.h" #include "modules/planning/reference_line/qp_spline_reference_line_smoother.h" namespace apollo { namespace planning { using apollo::common::time::Clock; CosThetaReferenceLineSmoother::CosThetaReferenceLineSmoother( const ReferenceLineSmootherConfig& config) : ReferenceLineSmoother(config) { CHECK(cyber::common::GetProtoFromFile(FLAGS_reopt_smoother_config_filename, &reopt_smoother_config_)) << "Failed to load smoother config file " << FLAGS_reopt_smoother_config_filename; reopt_qp_smoother_.reset( new QpSplineReferenceLineSmoother(reopt_smoother_config_)); max_point_deviation_ = config.cos_theta().max_point_deviation(); num_of_iterations_ = config.cos_theta().num_of_iteration(); weight_cos_included_angle_ = config.cos_theta().weight_cos_included_angle(); acceptable_tol_ = config.cos_theta().acceptable_tol(); relax_ = config.cos_theta().relax(); reopt_qp_bound_ = config.cos_theta().reopt_qp_bound(); } bool CosThetaReferenceLineSmoother::Smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { const double start_timestamp = Clock::NowInSeconds(); std::vector smoothed_point2d; std::vector raw_point2d; std::vector anchorpoints_lateralbound; for (const auto& anchor_point : anchor_points_) { raw_point2d.emplace_back(anchor_point.path_point.x(), anchor_point.path_point.y()); anchorpoints_lateralbound.emplace_back(anchor_point.lateral_bound); } if (anchor_points_.front().enforced) { has_start_point_constraint_ = true; start_x_derivative_ = anchor_points_.front().path_point.x_derivative(); start_y_derivative_ = anchor_points_.front().path_point.y_derivative(); } if (anchor_points_.back().enforced) { has_end_point_constraint_ = true; } Smooth(raw_point2d, anchorpoints_lateralbound, &smoothed_point2d); // load the results by cosTheta as anchor points and put it into qp_spline to // do the interpolation reopt_anchor_points_.clear(); for (const auto& p : smoothed_point2d) { common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({p.x(), p.y()}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < 0 || ref_sl_point.s() > raw_reference_line.Length()) { continue; } double heading = p.theta(); double s = p.s(); AnchorPoint anchor; anchor.longitudinal_bound = reopt_qp_bound_; anchor.lateral_bound = reopt_qp_bound_; anchor.path_point = apollo::common::util::MakePathPoint( p.x(), p.y(), 0.0, heading, 0.0, 0.0, 0.0); anchor.path_point.set_s(s); reopt_anchor_points_.emplace_back(anchor); } reopt_qp_smoother_->SetAnchorPoints(reopt_anchor_points_); if (!reopt_qp_smoother_->Smooth(raw_reference_line, smoothed_reference_line)) { AERROR << "Failed to reopt smooth reference line with anchor points by " "cosTheta"; return false; } const double end_timestamp = Clock::NowInSeconds(); AINFO << "cos_theta reference line smoother time: " << (end_timestamp - start_timestamp) * 1000 << " ms."; return true; } bool CosThetaReferenceLineSmoother::Smooth( const std::vector& scaled_point2d, const std::vector& lateral_bounds, std::vector* ptr_smoothed_point2d) { std::vector x; std::vector y; CosThetaProbleminterface* ptop = new CosThetaProbleminterface(scaled_point2d, lateral_bounds); ptop->set_default_max_point_deviation(max_point_deviation_); ptop->set_weight_cos_included_angle(weight_cos_included_angle_); ptop->set_relax_end_constraint(relax_); if (has_start_point_constraint_) { ptop->set_start_point(scaled_point2d.front().x(), scaled_point2d.front().y()); } if (has_end_point_constraint_) { ptop->set_end_point(scaled_point2d.back().x(), scaled_point2d.back().y()); } Ipopt::SmartPtr problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr app = IpoptApplicationFactory(); app->Options()->SetIntegerValue("print_level", 1); app->Options()->SetIntegerValue("max_iter", static_cast(num_of_iterations_)); app->Options()->SetNumericValue("acceptable_tol", acceptable_tol_); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AINFO << "*** Error during initialization!"; return false; } status = app->OptimizeTNLP(problem); if (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Ipopt::Index iter_count = app->Statistics()->IterationCount(); ADEBUG << "*** The problem solved in " << iter_count << " iterations!"; } else { AINFO << "Return status: " << int(status); } ptop->get_optimization_results(&x, &y); // load the point position and estimated derivatives at each point if (x.size() < 2 || y.size() < 2) { AINFO << "Return by IPOPT is wrong. Size smaller than 2 "; return false; } for (size_t i = 0; i < x.size(); ++i) { // reverse back to the unscaled points double start_x = x[i] + zero_x_; double start_y = y[i] + zero_y_; double x_derivative = 0.0; double y_derivative = 0.0; if (i == 0) { x_derivative = (x[i + 1] - x[i]); y_derivative = (y[i + 1] - y[i]); if (has_start_point_constraint_) { x_derivative = 0.5 * (start_x_derivative_ + x_derivative); y_derivative = 0.5 * (start_y_derivative_ + y_derivative); } } else if (i == x.size() - 1) { x_derivative = (x[i] - x[i - 1]); y_derivative = (y[i] - y[i - 1]); } else { x_derivative = 0.5 * (x[i + 1] - x[i - 1]); y_derivative = 0.5 * (y[i + 1] - y[i - 1]); } ptr_smoothed_point2d->emplace_back( to_path_point(start_x, start_y, x_derivative, y_derivative)); } // load the accumulated s at each point ptr_smoothed_point2d->front().set_s(0.0); double accumulated_s = 0.0; double Fx = ptr_smoothed_point2d->front().x(); double Fy = ptr_smoothed_point2d->front().y(); double Nx = 0.0; double Ny = 0.0; for (size_t i = 1; i < ptr_smoothed_point2d->size(); i++) { Nx = ptr_smoothed_point2d->at(i).x(); Ny = ptr_smoothed_point2d->at(i).y(); double end_segment_s = std::sqrt((Fx - Nx) * (Fx - Nx) + (Fy - Ny) * (Fy - Ny)); ptr_smoothed_point2d->at(i).set_s(end_segment_s + accumulated_s); accumulated_s += end_segment_s; Fx = Nx; Fy = Ny; } return status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level; } common::PathPoint CosThetaReferenceLineSmoother::to_path_point( const double x, const double y, const double x_derivative, const double y_derivative) const { common::PathPoint point; point.set_x(x); point.set_y(y); point.set_x_derivative(x_derivative); point.set_y_derivative(y_derivative); return point; } void CosThetaReferenceLineSmoother::SetAnchorPoints( const std::vector& anchor_points) { anchor_points_ = std::move(anchor_points); CHECK_GT(anchor_points_.size(), 1); zero_x_ = anchor_points_.front().path_point.x(); zero_y_ = anchor_points_.front().path_point.y(); std::for_each(anchor_points_.begin(), anchor_points_.end(), [this](AnchorPoint& p) { auto curr_x = p.path_point.x(); auto curr_y = p.path_point.y(); p.path_point.set_x(curr_x - zero_x_); p.path_point.set_y(curr_y - zero_y_); }); } } // namespace planning } // namespace apollo Chepik/SpaceInvaders1 #include "event_source_lambda.h" void EventSourceLambda::RegisterListener( TEventHandler const & listener) { m_listeners.push_back(listener); } void EventSourceLambda::NotifyListeners() { for (auto & listener : m_listeners) { listener(); } } std::size_t EventSourceLambda::Count() const { return m_listeners.size(); } #pragma once #include namespace bbzy { namespace type { namespace detail { template struct IsTypeExist { enum { value = std::is_same::value }; }; } using detail::IsTypeExist; template using TExist = IsTypeExist; } }/* Cafu Engine, http://www.cafu.de/ Copyright (c) and other contributors. This project is licensed under the terms of the MIT license. */ #include "OrthoBspTree.hpp" #include "MapElement.hpp" #include "wx/log.h" OrthoBspTreeT::NodeT::NodeT(const BoundingBox3fT& BB) : m_PlaneType(NONE), m_PlaneDist(0.0f), m_Parent(NULL), // m_Children(), m_Elems(), m_BB(BB) { m_Children[0]=NULL; m_Children[1]=NULL; } OrthoBspTreeT::NodeT::~NodeT() { delete m_Children[0]; delete m_Children[1]; } unsigned long OrthoBspTreeT::NodeT::GetNumNodes() const { const NodeT* Node =this; unsigned long Count=0; while (true) { Count++; if (Node->m_PlaneType==NONE) break; Count+=Node->m_Children[1]->GetNumNodes(); Node=Node->m_Children[0]; } return Count; } bool OrthoBspTreeT::NodeT::DetermineSplitPlane() { const float MIN_NODE_SIZE=512.0f; PlaneTypeE PlaneTypes_SBLE[3]={ ALONG_X, ALONG_Y, ALONG_Z }; Vector3fT NodeBBSize_SBLE =m_BB.Max-m_BB.Min; // SBLE: "Sorted by largest extent" :-) for (int i=0; i<2; i++) { if (NodeBBSize_SBLE[i] < NodeBBSize_SBLE[i+1]) { std::swap(PlaneTypes_SBLE[i], PlaneTypes_SBLE[i+1]); std::swap(NodeBBSize_SBLE[i], NodeBBSize_SBLE[i+1]); i=-1; } } // A split of a node that is normally too small for further splits is forced anyway if there are more than 100 map elements inside it. const bool ForceSplit=(NodeBBSize_SBLE[0]100); // Try to find an axis-aligned split plane. // This is achieved by trying all the bounding-box planes of the contents of this node AND ALL ANCESTOR nodes. // For best results, planes that are orthogonal to the axis with the largest extent are tried first. for (int i=0; i<3; i++) { const PlaneTypeE CurrentPlaneType=PlaneTypes_SBLE[i]; // Currently considered plane type. Ideally we never consider PlaneTypes_SBLE[1] and PlaneTypes_SBLE[2]. float BestOffset =NodeBBSize_SBLE[i]; // Two times the distance from the center of our m_BB. // If the node has reached the minimum size (and is not forcibly split), then stop: We've reached a leaf. if (!ForceSplit && BestOffsetm_Parent) { for (unsigned long ElemNr=0; ElemNrm_Elems.Size(); ElemNr++) { const BoundingBox3fT ElemBB=Ancestor->m_Elems[ElemNr]->GetBB(); for (unsigned int Side=0; Side<2; Side++) { const float CurrentPlaneDist=(Side==0) ? ElemBB.Min[CurrentPlaneType] : ElemBB.Max[CurrentPlaneType]; // The split plane must intersect our bounding-box per definition. if (CurrentPlaneDist >= m_BB.Max[CurrentPlaneType] || CurrentPlaneDist <= m_BB.Min[CurrentPlaneType]) continue; // Offset is (two times) the distance of the plane from the center of m_BB. const float CurrentOffset=fabs((m_BB.Max[CurrentPlaneType]-CurrentPlaneDist) - (CurrentPlaneDist-m_BB.Min[CurrentPlaneType])); if (CurrentOffset MIN_NODE_SIZE*0.5f) && (m_PlaneDist-m_BB.Min[CurrentPlaneType] > MIN_NODE_SIZE*0.5f)) return true; } } // No split plane was found. m_PlaneType=NONE; m_PlaneDist=0.0f; return false; } bool OrthoBspTreeT::NodeT::IntersectsAllChildren(const BoundingBox3fT& BB) const { if (m_PlaneType!=NONE) { if (BB.Min[m_PlaneType] >= m_PlaneDist) return false; if (BB.Max[m_PlaneType] <= m_PlaneDist) return false; if (!m_Children[0]->IntersectsAllChildren(BB)) return false; if (!m_Children[1]->IntersectsAllChildren(BB)) return false; } return true; } void OrthoBspTreeT::NodeT::FindMismatches(ArrayT& Mismatches) const { const NodeT* Node=this; while (true) { for (unsigned long ElemNr=0; ElemNrm_Elems.Size(); ElemNr++) { MapElementT* Elem =Node->m_Elems[ElemNr]; const BoundingBox3fT ElemBB=Elem->GetBB(); // If ElemBB intersects (or touches) the bounding-box of the node as well as all of the nodes children, // the map element is in the right place and there is no need to update it. // We must also allow "touches", because some ElemBBs have zero volume (e.g. those from "flat" Bezier patches). if (ElemBB.IntersectsOrTouches(Node->m_BB) && Node->IntersectsAllChildren(ElemBB)) continue; // Otherwise, Elem is a mismatch. Add it to the Mismatches list if not already there. if (Mismatches.Find(Elem)==-1) Mismatches.PushBack(Elem); } // If Node is a leaf node, we're done. if (Node->m_PlaneType==NONE) break; // Recurse into the children. Node->m_Children[1]->FindMismatches(Mismatches); Node=Node->m_Children[0]; } } void OrthoBspTreeT::NodeT::Insert(MapElementT* Elem) { NodeT* Node =this; const BoundingBox3fT ElemBB=Elem->GetBB(); while (Node->m_PlaneType!=NONE && !Node->IntersectsAllChildren(ElemBB)) { if (ElemBB.Min[Node->m_PlaneType] >= Node->m_PlaneDist) { Node=Node->m_Children[0]; } else if (ElemBB.Max[Node->m_PlaneType] <= Node->m_PlaneDist) { Node=Node->m_Children[1]; } else { Node->m_Children[1]->Insert(Elem); Node=Node->m_Children[0]; } } wxASSERT(Node->m_Elems.Find(Elem)==-1); Node->m_Elems.PushBack(Elem); } void OrthoBspTreeT::NodeT::Remove(MapElementT* Elem) { NodeT* Node=this; while (true) { // Remove Elem from the Node->m_Elems array. for (unsigned long ElemNr=0; ElemNrm_Elems.Size(); ElemNr++) if (Node->m_Elems[ElemNr]==Elem) { Node->m_Elems.RemoveAt(ElemNr); ElemNr--; } // If Node is a leaf node, we're done. if (Node->m_PlaneType==NONE) break; // Recurse into the children. Node->m_Children[1]->Remove(Elem); Node=Node->m_Children[0]; } } OrthoBspTreeT::OrthoBspTreeT(const ArrayT& Elems, const BoundingBox3fT& BB) : m_RootNode(new NodeT(BB)) { m_RootNode->m_Elems=Elems; BuildTree(m_RootNode); wxLogDebug("Created OrthoBspTreeT with %lu elements in %lu nodes.", Elems.Size(), m_RootNode->GetNumNodes()); wxASSERT(Update()==0); } OrthoBspTreeT::~OrthoBspTreeT() { delete m_RootNode; } unsigned long OrthoBspTreeT::Update() { static ArrayT Mismatches; Mismatches.Overwrite(); m_RootNode->FindMismatches(Mismatches); for (unsigned long ElemNr=0; ElemNrRemove(Mismatches[ElemNr]); // TODO: Insert with creating new splitplanes, if necessary? m_RootNode->Insert(Mismatches[ElemNr]); } return Mismatches.Size(); } void OrthoBspTreeT::BuildTree(NodeT* Node) { if (!Node->DetermineSplitPlane()) return; // Create a front child for Node. BoundingBox3fT FrontBB=Node->m_BB; FrontBB.Min[Node->m_PlaneType]=Node->m_PlaneDist; NodeT* FrontNode=new NodeT(FrontBB); FrontNode->m_Parent =Node; FrontNode->m_PlaneType=NodeT::NONE; Node->m_Children[0]=FrontNode; // Create a back child for Node. BoundingBox3fT BackBB=Node->m_BB; BackBB.Max[Node->m_PlaneType]=Node->m_PlaneDist; NodeT* BackNode=new NodeT(BackBB); BackNode->m_Parent =Node; BackNode->m_PlaneType=NodeT::NONE; Node->m_Children[1]=BackNode; // Insert the elements in Node at their proper place into the tree. for (NodeT* Ancestor=Node; Ancestor!=NULL; Ancestor=Ancestor->m_Parent) { for (unsigned long ElemNr=0; ElemNrm_Elems.Size(); ElemNr++) { MapElementT* Elem=Ancestor->m_Elems[ElemNr]; if (!Ancestor->IntersectsAllChildren(Elem->GetBB())) { Ancestor->Insert(Elem); Ancestor->m_Elems.RemoveAt(ElemNr); ElemNr--; } } } // Recurse. BuildTree(FrontNode); BuildTree(BackNode); } Projects/constraint_wallBricks/wallbricks_constraint_layout.cxx ////////////////////////////////////////////////////////////////////////////////////////////////// // // file: wallbricks_constraint_layout.cpp // // Author (Neill3d) // // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// //--- Class declaration #include "wallbricks_constraint_layout.h" //--- Registration defines #define WALLBRICKSCONSTRAINT__LAYOUT WallBricksConstraintLayout //--- implementation and registration FBConstraintLayoutImplementation( WALLBRICKSCONSTRAINT__LAYOUT ); FBRegisterConstraintLayout ( WALLBRICKSCONSTRAINT__LAYOUT, ORCONSTRAINTWALLBRICKS__CLASSSTR, FB_DEFAULT_SDK_ICON ); // Icon filename (default=Open Reality icon) /************************************************ * Creation function.. ************************************************/ bool WallBricksConstraintLayout::FBCreate() { // Assign handle onto constraint (cast generic pointer). mConstraint = (ORConstraintWallBricks*) (FBConstraint*) Constraint; // build & configure layout UICreate (); UIConfigure (); UIReset(); return true; } /************************************************ * Destructor for layout. ************************************************/ void WallBricksConstraintLayout::FBDestroy() { } /************************************************ * UI Creation function. * Create UI regions and assign them to UI elements ************************************************/ void WallBricksConstraintLayout::UICreate() { int lS, lH, lB, lW; // space, width, height lS = 4; lB = 5; lH = 20; lW = 120; AddRegion( "ButtonReset", "ButtonReset", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachNone, "", 1.0, lW, kFBAttachNone, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "ButtonLoad", "ButtonLoad", lB, kFBAttachRight, "ButtonReset", 1.0, lB, kFBAttachNone, "", 1.0, lW, kFBAttachNone, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "ButtonSave", "ButtonSave", lB, kFBAttachRight, "ButtonLoad", 1.0, lB, kFBAttachNone, "", 1.0, lW, kFBAttachNone, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "ButtonHelp", "ButtonHelp", lB, kFBAttachRight, "ButtonSave", 1.0, lB, kFBAttachNone, "", 1.0, lW, kFBAttachNone, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "ButtonAbout", "ButtonAbout", lB, kFBAttachRight, "ButtonHelp", 1.0, lB, kFBAttachNone, "", 1.0, lW, kFBAttachNone, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditPosX", "EditPosX", lB, kFBAttachLeft, "", 1.0, lB*2, kFBAttachBottom,"ButtonReset", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditPosY", "EditPosY", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditPosX", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditPosZ", "EditPosZ", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditPosY", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditRotX", "EditRotX", lB, kFBAttachLeft, "", 1.0, lB*2, kFBAttachBottom,"EditPosZ", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditRotY", "EditRotY", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditRotX", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditRotZ", "EditRotZ", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditRotY", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditSclX", "EditSclX", lB, kFBAttachLeft, "", 1.0, lB*2, kFBAttachBottom,"EditRotZ", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditSclY", "EditSclY", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditSclX", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); AddRegion( "EditSclZ", "EditSclZ", lB, kFBAttachLeft, "", 1.0, lB, kFBAttachBottom,"EditSclY", 1.0, -lB, kFBAttachRight, "", 1.0, lH, kFBAttachNone, "", 1.0 ); // // SetControl( "ButtonReset", mButtonReset ); SetControl( "ButtonLoad", mButtonLoad ); SetControl( "ButtonSave", mButtonSave ); SetControl( "ButtonHelp", mButtonHelp ); SetControl( "ButtonAbout", mButtonAbout ); SetControl( "EditPosX", mEditPositionX ); SetControl( "EditPosY", mEditPositionY ); SetControl( "EditPosZ", mEditPositionZ ); SetControl( "EditRotX", mEditRotationX ); SetControl( "EditRotY", mEditRotationY ); SetControl( "EditRotZ", mEditRotationZ ); SetControl( "EditSclX", mEditScalingX ); SetControl( "EditSclY", mEditScalingY ); SetControl( "EditSclZ", mEditScalingZ ); } /************************************************ * UI Configuration function. * Assign properties & callbacks for UI elements ************************************************/ void WallBricksConstraintLayout::UIConfigure() { const int captionSize = 0; mButtonReset.Property = &mConstraint->ExpressionReset; mButtonReset.CaptionSize = captionSize; mButtonReset.Caption = "Reset"; mButtonLoad.Property = &mConstraint->ExpressionLoad; mButtonLoad.CaptionSize = 40; mButtonLoad.Caption = "Load"; mButtonSave.Property = &mConstraint->ExpressionSave; mButtonSave.CaptionSize = captionSize; mButtonSave.Caption = "Save"; mButtonHelp.Property = &mConstraint->Help; mButtonHelp.CaptionSize = captionSize; mButtonHelp.Caption = "Help"; mButtonAbout.Property = &mConstraint->About; mButtonAbout.CaptionSize = captionSize; mButtonAbout.Caption = "About"; mEditPositionX.Property = &mConstraint->ScriptPositionX; mEditPositionX.Caption = "PositionX:"; mEditPositionY.Property = &mConstraint->ScriptPositionY; mEditPositionY.Caption = "PositionY:"; mEditPositionZ.Property = &mConstraint->ScriptPositionZ; mEditPositionZ.Caption = "PositionZ:"; mEditRotationX.Property = &mConstraint->ScriptRotationX; mEditRotationX.Caption = "RotationX:"; mEditRotationY.Property = &mConstraint->ScriptRotationY; mEditRotationY.Caption = "RotationY:"; mEditRotationZ.Property = &mConstraint->ScriptRotationZ; mEditRotationZ.Caption = "RotationZ:"; mEditScalingX.Property = &mConstraint->ScriptScalingX; mEditScalingX.Caption = "ScalingX:"; mEditScalingY.Property = &mConstraint->ScriptScalingY; mEditScalingY.Caption = "ScalingY:"; mEditScalingZ.Property = &mConstraint->ScriptScalingZ; mEditScalingZ.Caption = "ScalingZ:"; } void WallBricksConstraintLayout::UIReset() { } #include "StdAfx.h" CGameObject::CGameObject() : Position{} { } CGameObject::CGameObject(int x, int y) : Position{ x, y } { } #include "eight/ast.h" using namespace std; using namespace Eight; AST::AST(const std::string &name) : m_name(name) {} google/cloud/artifactregistry/artifact_registry_connection.cc // Copyright 2022 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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/devtools/artifactregistry/v1/service.proto #include "google/cloud/artifactregistry/artifact_registry_connection.h" #include "google/cloud/artifactregistry/artifact_registry_options.h" #include "google/cloud/artifactregistry/internal/artifact_registry_connection_impl.h" #include "google/cloud/artifactregistry/internal/artifact_registry_option_defaults.h" #include "google/cloud/artifactregistry/internal/artifact_registry_stub_factory.h" #include "google/cloud/background_threads.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/pagination_range.h" #include namespace google { namespace cloud { namespace artifactregistry { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ArtifactRegistryConnection::~ArtifactRegistryConnection() = default; StreamRange ArtifactRegistryConnection::ListDockerImages( google::devtools::artifactregistry::v1:: ListDockerImagesRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange>(); } StreamRange ArtifactRegistryConnection::ListRepositories( google::devtools::artifactregistry::v1:: ListRepositoriesRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange>(); } StatusOr ArtifactRegistryConnection::GetRepository( google::devtools::artifactregistry::v1::GetRepositoryRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } std::shared_ptr MakeArtifactRegistryConnection( Options options) { internal::CheckExpectedOptions(options, __func__); options = artifactregistry_internal::ArtifactRegistryDefaultOptions( std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); auto stub = artifactregistry_internal::CreateDefaultArtifactRegistryStub( background->cq(), options); return std::make_shared< artifactregistry_internal::ArtifactRegistryConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace artifactregistry } // namespace cloud } // namespace google namespace google { namespace cloud { namespace artifactregistry_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr MakeArtifactRegistryConnection(std::shared_ptr stub, Options options) { options = ArtifactRegistryDefaultOptions(std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); return std::make_shared< artifactregistry_internal::ArtifactRegistryConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace artifactregistry_internal } // namespace cloud } // namespace google src/WAM/get.cpp0 // // get.cpp // russWAM // // Created by on 11/21/15. // Copyright (c) 2015 . // Distributed under the MIT License // #include "WAM.h" using namespace std; void WAM::get_variable (RegType t, int regId, int argRegId) { DataCell* reg = getRegister (t, regId); // Ai <- Vn *reg = *getGlobalReg (regId); m_P = m_P + 1; } void WAM::get_value (RegType t, int regId, int argRegId) { bool unifySuccess; DataCell* reg = getRegister (t, regId); unifySuccess = unify (reg, getGlobalReg (argRegId)); if (unifySuccess) { m_P = m_P + 1; } else { backtrack (); } } void WAM::get_structure (int functorId, int argRegId) { bool getStructureSuccess = true; DataCell* reg = getGlobalReg (argRegId); DataCell* address = deref (reg); switch (address->tag) { case REF: // HEAP[H] <- (STR, H+1) m_H->tag = STR; m_H->ref = m_H + 1; // HEAP[H+1] <- f m_H = m_H + 1; m_H->tag = FUN; m_H->functorId = functorId; bind (address, m_H - 1); m_H = m_H + 1; m_Mode = WRITE; break; case STR: if (address->ref->functorId == functorId) { m_S = address + 1; m_Mode = READ; } else { getStructureSuccess = false; } break; default: getStructureSuccess = false; break; }; if (getStructureSuccess) { m_P = m_P + 1; } else { backtrack (); } } void WAM::get_list (int argRegId) { bool getListSuccess = true; DataCell* reg = getGlobalReg (argRegId); DataCell* address = deref (reg); switch (address->tag) { case REF: // HEAP[H] <- (LIS, H+1) m_H->tag = LIS; m_H->ref = m_H + 1; bind (address, m_H); m_H = m_H + 1; m_Mode = WRITE; break; case LIS: m_S = address; m_Mode = READ; break; default: getListSuccess = false; break; }; if (getListSuccess) { m_P = m_P + 1; } else { backtrack (); } } void WAM::get_constant (int functorId, int argRegId) { bool getConstantSuccess = true; DataCell* reg = getGlobalReg (argRegId); DataCell* address = deref (reg); switch (address->tag) { case REF: address->tag = CON; address->functorId = functorId; trail (address); break; case CON: getConstantSuccess = (address->functorId == functorId); break; default: getConstantSuccess = false; break; } if (getConstantSuccess) { m_P = m_P + 1; } else { backtrack (); } } #include using namespace std; int main() { int n; cin >> n; int arr[n]; for(int i = 0; i < n; i++) { cin >> arr[i]; } for(int i = 1; i < n; i++) { int current = arr[i]; int j = i - 1; while(arr[j] > current && j >=0) { arr[j+1] = arr [j]; j--; } arr[j + 1] = current; } for(int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; } zfang399/LeetCode-Problems class Solution { public: int maxProfit(vector& prices) { if(prices.size()==0) return 0; int ans=0,minbuy=prices[0]; for(int i=0;ians) ans=prices[i]-minbuy; if(prices[i]("/prometheus/planning/goal", 1, &Global_Planner::goal_cb, this); // 订阅开关 planner_enable = planner_enable_default; planner_switch_sub = nh.subscribe("/prometheus/switch/global_planner", 10, &Global_Planner::planner_switch_cb, this); // 订阅 无人机状态 drone_state_sub = nh.subscribe("/prometheus/drone_state", 10, &Global_Planner::drone_state_cb, this); // 根据map_input选择地图更新方式,目前只支持 0 if(map_input == 0) { Gpointcloud_sub = nh.subscribe("/prometheus/global_planning/global_pcl", 1, &Global_Planner::Gpointcloud_cb, this); //groundtruth点云、SLAM全局点云 }else if(map_input == 1) { Lpointcloud_sub = nh.subscribe("/prometheus/global_planning/local_pcl", 1, &Global_Planner::Lpointcloud_cb, this); //RGBD相机、三维激光雷达 }else if(map_input == 2) { laserscan_sub = nh.subscribe("/prometheus/global_planning/laser_scan", 1, &Global_Planner::laser_cb, this); //2维激光雷达 } // 发布 路径指令 command_pub = nh.advertise("/prometheus/control_command", 10); // 发布提示消息 message_pub = nh.advertise("/prometheus/message/global_planner", 10); // 发布路径用于显示 path_cmd_pub = nh.advertise("/prometheus/global_planning/path_cmd", 10); // 定时器 安全检测 // safety_timer = nh.createTimer(ros::Duration(2.0), &Global_Planner::safety_cb, this); // 定时器 规划器算法执行周期 mainloop_timer = nh.createTimer(ros::Duration(0.2), &Global_Planner::mainloop_cb, this); // 路径追踪循环,快速移动场景应当适当提高执行频率 // time_per_path track_path_timer = nh.createTimer(ros::Duration(time_per_path), &Global_Planner::track_path_cb, this); // 选择避障算法 if(algorithm_mode==0){ global_alg_ptr.reset(new Astar); global_alg_ptr->init(nh); pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME, "A_star init."); } else if(algorithm_mode==1) { global_alg_ptr.reset(new KinodynamicAstar); global_alg_ptr->init(nh); pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME, "Kinodynamic A_star init."); } // 规划器状态参数初始化 exec_state = EXEC_STATE::WAIT_GOAL; odom_ready = false; drone_ready = false; goal_ready = false; sensor_ready = false; is_safety = true; is_new_path = false; // 初始化发布的指令 Command_Now.header.stamp = ros::Time::now(); Command_Now.Mode = prometheus_msgs::ControlCommand::Idle; Command_Now.Command_ID = 0; Command_Now.source = NODE_NAME; desired_yaw = 0.0; // 仿真模式下直接发送切换模式与起飞指令 if(sim_mode == true) { // Waiting for input int start_flag = 0; while(start_flag == 0) { cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Global Planner<<<<<<<<<<<<<<<<<<<<<<<<<<< "<< endl; cout << "Please input 1 for start:"<> start_flag; } // 起飞 Command_Now.header.stamp = ros::Time::now(); Command_Now.Mode = prometheus_msgs::ControlCommand::Idle; Command_Now.Command_ID = Command_Now.Command_ID + 1; Command_Now.source = NODE_NAME; Command_Now.Reference_State.yaw_ref = 999; command_pub.publish(Command_Now); cout << "Switch to OFFBOARD and arm ..."<data){ pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME,"Planner is enable."); }else if (planner_enable && !msg->data){ pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME,"Planner is disable."); exec_state = EXEC_STATE::WAIT_GOAL; } planner_enable = msg->data; } void Global_Planner::goal_cb(const geometry_msgs::PoseStampedConstPtr& msg) { if (is_2D == true) { goal_pos << msg->pose.position.x, msg->pose.position.y, fly_height_2D; }else { if(msg->pose.position.z < 1.0) goal_pos << msg->pose.position.x, msg->pose.position.y, 1.0; // 最低要求 else goal_pos << msg->pose.position.x, msg->pose.position.y, msg->pose.position.z; } goal_vel.setZero(); goal_ready = true; // 获得新目标点 if(planner_enable){ pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME,"Get a new goal point"); cout << "Get a new goal point:"<< goal_pos(0) << " [m] " << goal_pos(1) << " [m] " << goal_pos(2)<< " [m] " <position[0], msg->position[1], fly_height_2D; start_vel << msg->velocity[0], msg->velocity[1], 0.0; if(abs(fly_height_2D - msg->position[2]) > 0.2) { //pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME,"Drone is not in the desired height."); } }else { start_pos << msg->position[0], msg->position[1], msg->position[2]; start_vel << msg->velocity[0], msg->velocity[1], msg->velocity[2]; } start_acc << 0.0, 0.0, 0.0; odom_ready = true; if (_DroneState.connected == true && _DroneState.armed == true ) { drone_ready = true; }else { drone_ready = false; } Drone_odom.header = _DroneState.header; Drone_odom.child_frame_id = "base_link"; Drone_odom.pose.pose.position.x = _DroneState.position[0]; Drone_odom.pose.pose.position.y = _DroneState.position[1]; Drone_odom.pose.pose.position.z = _DroneState.position[2]; Drone_odom.pose.pose.orientation = _DroneState.attitude_q; Drone_odom.twist.twist.linear.x = _DroneState.velocity[0]; Drone_odom.twist.twist.linear.y = _DroneState.velocity[1]; Drone_odom.twist.twist.linear.z = _DroneState.velocity[2]; } // 根据全局点云更新地图 // 情况:groundtruth点云、SLAM全局点云 void Global_Planner::Gpointcloud_cb(const sensor_msgs::PointCloud2ConstPtr &msg) { /* need odom_ for center radius sensing */ if (!odom_ready) { return; } sensor_ready = true; if(!map_groundtruth) { // 对Astar中的地图进行更新 global_alg_ptr->Occupy_map_ptr->map_update_gpcl(msg); // 并对地图进行膨胀 global_alg_ptr->Occupy_map_ptr->inflate_point_cloud(); }else { static int update_num=0; update_num++; // 此处改为根据循环时间计算的数值 if(update_num == 10) { // 对Astar中的地图进行更新 global_alg_ptr->Occupy_map_ptr->map_update_gpcl(msg); // 并对地图进行膨胀 global_alg_ptr->Occupy_map_ptr->inflate_point_cloud(); update_num = 0; } } } // 根据局部点云更新地图 // 情况:RGBD相机、三维激光雷达 void Global_Planner::Lpointcloud_cb(const sensor_msgs::PointCloud2ConstPtr &msg) { /* need odom_ for center radius sensing */ if (!odom_ready) { return; } sensor_ready = true; // 对Astar中的地图进行更新(局部地图+odom) global_alg_ptr->Occupy_map_ptr->map_update_lpcl(msg); // 并对地图进行膨胀 global_alg_ptr->Occupy_map_ptr->inflate_point_cloud(); } // 根据2维雷达数据更新地图 // 情况:2维激光雷达 void Global_Planner::laser_cb(const sensor_msgs::LaserScanConstPtr &msg) { /* need odom_ for center radius sensing */ if (!odom_ready) { return; } sensor_ready = true; // 对Astar中的地图进行更新(laser+odom) global_alg_ptr->Occupy_map_ptr->map_update_laser(msg); // 并对地图进行膨胀 global_alg_ptr->Occupy_map_ptr->inflate_point_cloud(); } void Global_Planner::track_path_cb(const ros::TimerEvent& e) { if (!planner_enable_default) return; static ros::Time last_cmd_pub_time = ros::Time::now(); if(!path_ok) { if (control_yaw_flag && exec_state == EXEC_STATE::WAIT_GOAL ){ Command_Now.header.stamp = ros::Time::now(); Command_Now.Mode = prometheus_msgs::ControlCommand::Move; Command_Now.Command_ID = Command_Now.Command_ID + 1; Command_Now.source = NODE_NAME; Command_Now.Reference_State.Move_mode = prometheus_msgs::PositionReference::XY_VEL_Z_POS; Command_Now.Reference_State.Move_frame = prometheus_msgs::PositionReference::ENU_FRAME; Command_Now.Reference_State.position_ref[2] = _DroneState.position[2]; Command_Now.Reference_State.velocity_ref[0] = 0.0; Command_Now.Reference_State.velocity_ref[1] = 0.0; desired_yaw = desired_yaw + 0.5*(ros::Time::now()-last_cmd_pub_time).toSec(); if(desired_yaw>M_PI) desired_yaw -= 2*M_PI; Command_Now.Reference_State.yaw_ref = desired_yaw; command_pub.publish(Command_Now); last_cmd_pub_time = ros::Time::now(); } return; } // if(!is_safety) // { // // 若无人机与障碍物之间的距离小于安全距离,则停止执行路径 // // 但如何脱离该点呢? // pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME, "Drone Position Dangerous! STOP HERE and wait for new goal."); // Command_Now.header.stamp = ros::Time::now(); // Command_Now.Mode = prometheus_msgs::ControlCommand::Hold; // Command_Now.Command_ID = Command_Now.Command_ID + 1; // Command_Now.source = NODE_NAME; // command_pub.publish(Command_Now); // goal_ready = false; // exec_state = EXEC_STATE::WAIT_GOAL; // return; // } is_new_path = false; // 抵达终点 if(cur_id == Num_total_wp - 1) { Command_Now.header.stamp = ros::Time::now(); Command_Now.Mode = prometheus_msgs::ControlCommand::Move; Command_Now.Command_ID = Command_Now.Command_ID + 1; Command_Now.source = NODE_NAME; Command_Now.Reference_State.Move_mode = prometheus_msgs::PositionReference::XYZ_POS; Command_Now.Reference_State.Move_frame = prometheus_msgs::PositionReference::ENU_FRAME; Command_Now.Reference_State.position_ref[0] = goal_pos[0]; Command_Now.Reference_State.position_ref[1] = goal_pos[1]; Command_Now.Reference_State.position_ref[2] = goal_pos[2]; Command_Now.Reference_State.yaw_ref = desired_yaw; command_pub.publish(Command_Now); planner_enable = planner_enable_default; if (planner_enable_default) pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME, "Reach the goal! The planner will be disable automatically."); else pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME, "Reach the goal! The planner is still enable."); // 停止执行 path_ok = false; // 转换状态为等待目标 exec_state = EXEC_STATE::WAIT_GOAL; return; } // 计算距离开始追踪轨迹时间 //tra_running_time = get_time_in_sec(tra_start_time); int i = cur_id; cout << "Moving to waypoint: [ " << cur_id << " / "<< Num_total_wp<< " ] "<double { return v<0.0? -1.0:1.0; }; // Eigen::Vector3d ref_vel; // ref_vel[0] = _DroneState.velocity[0]; // ref_vel[1] = _DroneState.velocity[1]; // ref_vel[2] = 0.0; Eigen::Vector3d ref_pos; ref_pos[0] = path_cmd.poses[i].pose.position.x; ref_pos[1] = path_cmd.poses[i].pose.position.y; ref_pos[2] = 0.0; Eigen::Vector3d curr_pos; curr_pos[0] = _DroneState.position[0]; curr_pos[1] = _DroneState.position[1]; curr_pos[2] = 0.0; Eigen::Vector3d diff_pos = ref_pos - curr_pos; // 更新期望偏航角 if (diff_pos.norm()>1e-3) { // float next_desired_yaw_vel = sign(ref_vel(1)) * acos(ref_vel(0) / ref_vel.norm()); float next_desired_yaw_pos = sign(diff_pos(1)) * acos(diff_pos(0) / diff_pos.norm()); if (fabs(desired_yaw-next_desired_yaw_pos)M_PI) desired_yaw -= 2*M_PI; else if (desired_yaw<-M_PI) desired_yaw += 2*M_PI; } }else desired_yaw = 0.0; Command_Now.Reference_State.yaw_ref = desired_yaw; command_pub.publish(Command_Now); last_cmd_pub_time = ros::Time::now(); cur_id = cur_id + 1; } // 主循环 void Global_Planner::mainloop_cb(const ros::TimerEvent& e) { static int exec_num=0; exec_num++; // 检查当前状态,不满足规划条件则直接退出主循环 // 此处打印消息与后面的冲突了,逻辑上存在问题 if(!odom_ready || !drone_ready || !sensor_ready ||!planner_enable) { // 此处改为根据循环时间计算的数值 if(exec_num == 10) { if(!planner_enable) { message = "Planner is disable by default! If you want to enable it, pls set the param [global_planner/enable] as true!"; }else if(!odom_ready) { message = "Need Odom."; }else if(!drone_ready) { message = "Drone is not ready."; }else if(!sensor_ready) { message = "Need sensor info."; } pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME, message); exec_num=0; } return; }else { // 对检查的状态进行重置 odom_ready = false; drone_ready = false; sensor_ready = false; } switch (exec_state) { case WAIT_GOAL: { path_ok = false; if(!goal_ready) { if(exec_num == 10) { message = "Waiting for a new goal."; pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME,message); exec_num=0; } }else { // 获取到目标点后,生成新轨迹 exec_state = EXEC_STATE::PLANNING; goal_ready = false; } break; } case PLANNING: { // 重置规划器 global_alg_ptr->reset(); // 使用规划器执行搜索,返回搜索结果 // Astar algorithm int astar_state; if(algorithm_mode==0) astar_state = global_alg_ptr->search(start_pos, Eigen::Vector3d(0,0,0), Eigen::Vector3d(0,0,0), goal_pos, Eigen::Vector3d(0,0,0), false, false, 0); else if(algorithm_mode==1) astar_state = global_alg_ptr->search(start_pos, start_vel, start_acc, goal_pos, goal_vel, false, false, 0); // 未寻找到路径 if(astar_state==Astar::NO_PATH) { path_ok = false; exec_state = EXEC_STATE::WAIT_GOAL; pub_message(message_pub, prometheus_msgs::Message::WARN, NODE_NAME, "Planner can't find path, please reset the goal!"); } else { path_ok = true; is_new_path = true; path_cmd = global_alg_ptr->get_ros_path(); Num_total_wp = path_cmd.poses.size(); start_point_index = get_start_point_id(); cur_id = start_point_index; tra_start_time = ros::Time::now(); exec_state = EXEC_STATE::TRACKING; path_cmd_pub.publish(path_cmd); pub_message(message_pub, prometheus_msgs::Message::NORMAL, NODE_NAME, "Get a new path!"); } break; } case TRACKING: { if((ros::Time::now() - tra_start_time).toSec() >= replan_time) { exec_state = EXEC_STATE::PLANNING; exec_num = 0; } break; } case LANDING: { Command_Now.header.stamp = ros::Time::now(); Command_Now.Mode = prometheus_msgs::ControlCommand::Land; Command_Now.Command_ID = Command_Now.Command_ID + 1; Command_Now.source = NODE_NAME; command_pub.publish(Command_Now); break; } } } // 【获取当前时间函数】 单位:秒 float Global_Planner::get_time_in_sec(const ros::Time& begin_time) { ros::Time time_now = ros::Time::now(); float currTimeSec = time_now.sec - begin_time.sec; float currTimenSec = time_now.nsec / 1e9 - begin_time.nsec / 1e9; return (currTimeSec + currTimenSec); } void Global_Planner::safety_cb(const ros::TimerEvent& e) { Eigen::Vector3d cur_pos(_DroneState.position[0], _DroneState.position[1], _DroneState.position[2]); is_safety = global_alg_ptr->check_safety(cur_pos, safe_distance); } int Global_Planner::get_start_point_id(void) { // 选择与当前无人机所在位置最近的点,并从该点开始追踪 int id = 0; float distance_to_wp_min = abs(path_cmd.poses[0].pose.position.x - _DroneState.position[0]) + abs(path_cmd.poses[0].pose.position.y - _DroneState.position[1]) + abs(path_cmd.poses[0].pose.position.z - _DroneState.position[2]); float distance_to_wp; for (int j=1; jcomponents/storage/blockdevice/COMPONENT_I2CEE/I2CEEBlockDevice.cpp /* Simple access class for I2C EEPROM chips like Microchip 24LC * Copyright (c) 2015 * SPDX-License-Identifier: Apache-2.0 * * 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 "I2CEEBlockDevice.h" #include "rtos/ThisThread.h" using namespace mbed; #define I2CEE_TIMEOUT 10000 I2CEEBlockDevice::I2CEEBlockDevice( PinName sda, PinName scl, uint8_t addr, bd_size_t size, bd_size_t block, int freq, bool address_is_eight_bit) : _i2c_addr(addr), _size(size), _block(block), _address_is_eight_bit(address_is_eight_bit) { _i2c = new (_i2c_buffer) I2C(sda, scl); _i2c->frequency(freq); } I2CEEBlockDevice::I2CEEBlockDevice( I2C *i2c_obj, uint8_t addr, bd_size_t size, bd_size_t block, bool address_is_eight_bit) : _i2c_addr(addr), _size(size), _block(block), _address_is_eight_bit(address_is_eight_bit) { _i2c = i2c_obj; } I2CEEBlockDevice::~I2CEEBlockDevice() { if (_i2c == (I2C *)_i2c_buffer) { _i2c->~I2C(); } } int I2CEEBlockDevice::init() { return _sync(); } int I2CEEBlockDevice::deinit() { return 0; } int I2CEEBlockDevice::read(void *buffer, bd_addr_t addr, bd_size_t size) { // Check the address and size fit onto the chip. MBED_ASSERT(is_valid_read(addr, size)); auto *pBuffer = static_cast(buffer); _i2c->start(); if (1 != _i2c->write(get_paged_device_address(addr))) { return BD_ERROR_DEVICE_ERROR; } if (!_address_is_eight_bit && 1 != _i2c->write((char)(addr >> 8u))) { return BD_ERROR_DEVICE_ERROR; } if (1 != _i2c->write((char)(addr & 0xffu))) { return BD_ERROR_DEVICE_ERROR; } _i2c->stop(); if (0 != _i2c->read(_i2c_addr, pBuffer, size)) { return BD_ERROR_DEVICE_ERROR; } return BD_ERROR_OK; } int I2CEEBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t size) { // Check the addr and size fit onto the chip. MBED_ASSERT(is_valid_program(addr, size)); const auto *pBuffer = static_cast(buffer); // While we have some more data to write. while (size > 0) { uint32_t off = addr % _block; uint32_t chunk = (off + size < _block) ? size : (_block - off); _i2c->start(); if (1 != _i2c->write(get_paged_device_address(addr))) { return BD_ERROR_DEVICE_ERROR; } if (!_address_is_eight_bit && 1 != _i2c->write((char)(addr >> 8u))) { return BD_ERROR_DEVICE_ERROR; } if (1 != _i2c->write((char)(addr & 0xffu))) { return BD_ERROR_DEVICE_ERROR; } for (unsigned i = 0; i < chunk; i++) { if (1 != _i2c->write(pBuffer[i])) { return BD_ERROR_DEVICE_ERROR; } } _i2c->stop(); int err = _sync(); if (err) { return err; } addr += chunk; size -= chunk; pBuffer += chunk; } return BD_ERROR_OK; } int I2CEEBlockDevice::erase(bd_addr_t addr, bd_size_t size) { // No erase needed return 0; } int I2CEEBlockDevice::_sync() { // The chip doesn't ACK while writing to the actual EEPROM // so loop trying to do a zero byte write until it is ACKed // by the chip. for (int i = 0; i < I2CEE_TIMEOUT; i++) { if (_i2c->write(_i2c_addr | 0, 0, 0) < 1) { return 0; } rtos::ThisThread::sleep_for(1); } return BD_ERROR_DEVICE_ERROR; } bd_size_t I2CEEBlockDevice::get_read_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_program_size() const { return 1; } bd_size_t I2CEEBlockDevice::get_erase_size() const { return 1; } bd_size_t I2CEEBlockDevice::size() const { return _size; } const char *I2CEEBlockDevice::get_type() const { return "I2CEE"; } uint8_t I2CEEBlockDevice::get_paged_device_address(bd_addr_t address) { if (!_address_is_eight_bit) { return _i2c_addr; } else { // Use the three least significant bits of the 2nd byte as the page // The page will be bits 2-4 of the user defined addresses. return _i2c_addr | ((address & 0x0700u) >> 7u); } } 10-100 //+--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation, 1998. // // Class: CMshtmlEdFactory // // Contents: Implementation of Class Factory for Mshtmled // // History: 7-Jan-98 raminh Created //---------------------------------------------------------------------------- #include "headers.hxx" #ifndef X_EFACTORY_HXX_ #define X_EFACTORY_HXX_ #include "efactory.hxx" #endif #ifndef X_MSHTMLED_HXX_ #define X_MSHTMLED_HXX_ #include "mshtmled.hxx" #endif extern long g_cServerLocks; // Count of locks MtDefine(CMshtmlEdFactory, Utilities, "CMshtmlEdFactory") //+---------------------------------------------------------------------------- // // Class Factory Implementation // //+---------------------------------------------------------------------------- STDMETHODIMP CMshtmlEdFactory::QueryInterface(const IID& iid, void** ppv) { if ((iid == IID_IUnknown) || (iid == IID_IClassFactory)) { *ppv = static_cast(this) ; } else { *ppv = NULL ; return E_NOINTERFACE ; } reinterpret_cast(*ppv)->AddRef() ; return S_OK ; } STDMETHODIMP_(ULONG) CMshtmlEdFactory::AddRef() { return InterlockedIncrement(&_ulRefs) ; } STDMETHODIMP_(ULONG) CMshtmlEdFactory::Release() { if (InterlockedDecrement(&_ulRefs) == 0) { delete this ; return 0 ; } return _ulRefs ; } STDMETHODIMP CMshtmlEdFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void** ppv) { // Cannot aggregate. if (pUnknownOuter != NULL) { return CLASS_E_NOAGGREGATION ; } // Create component. CMshtmlEd* pMshtmled = new CMshtmlEd ; if (pMshtmled == NULL) { return E_OUTOFMEMORY ; } // Get the requested interface. HRESULT hr = pMshtmled->QueryInterface(iid, ppv) ; // Release the IUnknown pointer. pMshtmled->Release() ; return hr ; } STDMETHODIMP CMshtmlEdFactory::LockServer(BOOL bLock) { if (bLock) { InterlockedIncrement(&g_cServerLocks) ; } else { InterlockedDecrement(&g_cServerLocks) ; } return S_OK ; } #pragma once #include class Resource { public: explicit Resource(const std::string& path); virtual ~Resource() = default; virtual void load() = 0; const std::string& getFilename() const; const std::string& getFileExtension() const; const std::string& getPath() const; private: std::string _filename; std::string _fileExtension; std::string _path; }; /* TyTools - public domain <> https://koromix.dev/tytools This software is in the public domain. Where that dedication is not recognized, you are granted a perpetual, irrevocable license to copy, distribute, and modify this file as you see fit. See the LICENSE file for more details. */ #ifdef _WIN32 #include #endif #include #include #include #include #include "arduino_dialog.hpp" #include "tycommander.hpp" using namespace std; ArduinoDialog::ArduinoDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f) { setupUi(this); connect(closeButton, &QPushButton::clicked, this, &ArduinoDialog::close); connect(arduinoPath, &QLineEdit::editingFinished, this, [=]() { install_.setPath(arduinoPath->text()); }); connect(browseButton, &QPushButton::clicked, this, &ArduinoDialog::browseForArduino); connect(integrateButton, &QPushButton::clicked, this, &ArduinoDialog::integrate); connect(restoreButton, &QPushButton::clicked, this, &ArduinoDialog::restore); connect(&install_, &ArduinoInstallation::changed, this, &ArduinoDialog::refresh); connect(&install_, &ArduinoInstallation::log, this, &ArduinoDialog::addLog); connect(&install_, &ArduinoInstallation::error, this, &ArduinoDialog::addError); refresh(); } void ArduinoDialog::keyPressEvent(QKeyEvent *ev) { // Easy way to disable the "default button" feature of QDialog, without changing each button if(ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return) return; QDialog::keyPressEvent(ev); } void ArduinoDialog::refresh() { statusLabel->setVisible(!install_.path().isEmpty()); integrateButton->setEnabled(false); restoreButton->setEnabled(false); if (install_.path().isEmpty()) return; const char *color = NULL; QString text; if (install_.isIntegrated()) { color = "green"; text = tr("Arduino %1 / Teensyduino %2\nAlready using TyCommander") .arg(install_.arduinoVersion(), install_.teensyduinoVersion()); if (!background_process_) restoreButton->setEnabled(true); } else if (install_.isValid()) { color = "orange"; text = tr("Arduino %1 / Teensyduino %2\nNot using TyCommander") .arg(install_.arduinoVersion(), install_.teensyduinoVersion()); if (!background_process_) integrateButton->setEnabled(true); } else { color = "red"; text = tr("Not a valid Arduino/Teensyduino directory"); } QPalette pal; if (color) pal.setColor(QPalette::WindowText, color); statusLabel->setPalette(pal); statusLabel->setText(text); } void ArduinoDialog::addLog(const QString &msg) { appendMessage(msg); } void ArduinoDialog::addError(const QString &msg) { QTextCharFormat fmt; fmt.setForeground(QColor("red")); appendMessage(msg, fmt); } void ArduinoDialog::browseForArduino() { #ifdef __APPLE__ auto path = QFileDialog::getOpenFileName(this, tr("Select Arduino application"), "", tr("Applications (*.app)")); #else auto path = QFileDialog::getExistingDirectory(this, tr("Select Arduino directory")); #endif if (path.isEmpty()) return; path = QDir::toNativeSeparators(path); arduinoPath->setText(path); install_.setPath(path); } void ArduinoDialog::integrate() { if (background_process_) return; logText->clear(); if (!install_.integrate()) executeAsRoot("integrate"); } void ArduinoDialog::restore() { if (background_process_) return; logText->clear(); if (!install_.restore()) executeAsRoot("restore"); } void ArduinoDialog::appendMessage(const QString &msg, const QTextCharFormat &fmt) { auto document = logText->document(); QTextCursor cursor(document); cursor.movePosition(QTextCursor::End); if (!document->isEmpty()) cursor.insertBlock(); cursor.insertText(msg, fmt); } void ArduinoDialog::executeAsRoot(const QString &command) { #ifdef _WIN32 if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) { installWithUAC(command); return; } #endif QTextCharFormat fmt; fmt.setFontItalic(true); appendMessage(""); appendMessage(tr("Try to restart this command as root with :")); appendMessage(tr("\"%1\" %2 \"%3\"").arg(QDir::toNativeSeparators(TyCommander::clientFilePath()), command, install_.absolutePath()), fmt); } #ifdef _WIN32 void ArduinoDialog::installWithUAC(const QString &command) { addLog("Trying with elevated rights"); QCoreApplication::processEvents(QEventLoop::AllEvents | QEventLoop::WaitForMoreEvents, 1000); SHELLEXECUTEINFO info = {}; info.cbSize = sizeof(info); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = "runas"; info.lpFile = "cmd"; info.nShow = SW_SHOW; auto parameters = QString("/C \"\"%1\" %2 \"%3\" & pause\"") .arg(QDir::toNativeSeparators(TyCommander::clientFilePath()), command, QDir::toNativeSeparators(install_.absolutePath())).toLocal8Bit(); info.lpParameters = parameters.constData(); BOOL success = ShellExecuteEx(&info); if (!success) { addLog("Cannot execute with Administrator rights"); return; } if (!info.hProcess) return; background_process_ = true; auto notifier = new QWinEventNotifier(info.hProcess, this); connect(notifier, &QWinEventNotifier::activated, this, [=](HANDLE h) { Q_UNUSED(h); background_process_ = false; install_.update(); notifier->setEnabled(false); notifier->deleteLater(); }); notifier->setEnabled(true); } #endif haiwen/seafile-shell-extextensions/class-factory.cpp #include "ext-common.h" #include "class-factory.h" #include "shell-ext.h" #include "log.h" ShellExtClassFactory::ShellExtClassFactory(seafile::SyncStatus status) { m_cRef = 0L; status_ = status; // seaf_ext_log ("new ShellExtClassFactory created for status %d\n", int(status)); InterlockedIncrement(&g_cRefThisDll); } ShellExtClassFactory::~ShellExtClassFactory() { InterlockedDecrement(&g_cRefThisDll); } STDMETHODIMP ShellExtClassFactory::QueryInterface(REFIID riid, LPVOID FAR *ppv) { if (ppv == 0) return E_POINTER; *ppv = NULL; // Any interface on this object is the object pointer if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) { *ppv = static_cast(this); AddRef(); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) ShellExtClassFactory::AddRef() { return ++m_cRef; } STDMETHODIMP_(ULONG) ShellExtClassFactory::Release() { if (--m_cRef) return m_cRef; delete this; return 0L; } STDMETHODIMP ShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, LPVOID *ppvObj) { if(ppvObj == 0) return E_POINTER; *ppvObj = NULL; // Shell extensions typically don't support aggregation (inheritance) if (pUnkOuter) return CLASS_E_NOAGGREGATION; // Create the main shell extension object. The shell will then call // QueryInterface with IID_IShellExtInit--this is how shell extensions are // initialized. ShellExt* pShellExt = new ShellExt(status_); // Create the ShellExt object const HRESULT hr = pShellExt->QueryInterface(riid, ppvObj); if(FAILED(hr)) delete pShellExt; return hr; } STDMETHODIMP ShellExtClassFactory::LockServer(BOOL /*fLock*/) { return E_NOTIMPL; } EchoInMirror/EIM1-10 #include "Track.h" #include "ProcessorBase.h" Track::Track(): SynchronizedAudioProcessorGraph() { setChannelLayoutOfBus(true, 0, juce::AudioChannelSet::canonicalChannelSet(2)); setChannelLayoutOfBus(false, 0, juce::AudioChannelSet::canonicalChannelSet(2)); auto input = addNode(std::make_unique(juce::AudioProcessorGraph::AudioGraphIOProcessor::audioInputNode)); begin = addNode(std::make_unique()); end = addNode(std::make_unique(juce::AudioProcessorGraph::AudioGraphIOProcessor::audioOutputNode)); midiIn = addNode(std::make_unique(juce::AudioProcessorGraph::AudioGraphIOProcessor::midiInputNode))->nodeID; auto midiOut = addNode(std::make_unique(juce::AudioProcessorGraph::AudioGraphIOProcessor::midiOutputNode))->nodeID; addConnection({ { input->nodeID, 0 }, { begin->nodeID, 0 } }); addConnection({ { input->nodeID, 1 }, { begin->nodeID, 1 } }); addConnection({ { begin->nodeID, 0 }, { end->nodeID, 0 } }); addConnection({ { begin->nodeID, 1 }, { end->nodeID, 1 } }); addConnection({ { midiIn, juce::AudioProcessorGraph::midiChannelIndex }, { midiOut, juce::AudioProcessorGraph::midiChannelIndex } }); } void Track::setGenerator(std::unique_ptr instance) { auto node = addNode(std::move(instance)); addConnection({ { node->nodeID, 0 }, { end->nodeID, 0 } }); addConnection({ { node->nodeID, 1 }, { end->nodeID, 1 } }); addConnection({ { midiIn, juce::AudioProcessorGraph::midiChannelIndex }, { node->nodeID, juce::AudioProcessorGraph::midiChannelIndex } }); } void Track::setRateAndBufferSizeDetails(double newSampleRate, int newBlockSize) { SynchronizedAudioProcessorGraph::setRateAndBufferSizeDetails(newSampleRate, newBlockSize); messageCollector.reset(newSampleRate); } void Track::processBlock(juce::AudioBuffer& buffer, juce::MidiBuffer& midiMessages) { messageCollector.removeNextBlockOfMessages(midiMessages, buffer.getNumSamples()); SynchronizedAudioProcessorGraph::processBlock(buffer, midiMessages); } void Track::processBlock(juce::AudioBuffer& buffer, juce::MidiBuffer& midiMessages) { messageCollector.removeNextBlockOfMessages(midiMessages, buffer.getNumSamples()); SynchronizedAudioProcessorGraph::processBlock(buffer, midiMessages); } PaoloCanofari/Mosquitto-subscriber-Example1-10 // // Created by on 01/09/19. // #include #include "mqtt_wrapper/mqtt_wrapper.h" int main(int argc, const char* argv[]) { const char *id = "device01"; const char *topic = "/sensors/test"; const char* host = "localhost"; int port = 1883; const char* username = "username"; const char* password = "password"; mqtt_wrapper *wrapper = new mqtt_wrapper(id, topic, host, port, username, password); return 0; }0 #pragma once #include #include "function_info.hh" #include "type_info.hh" #include "variable_info.hh" #include "utils/map.hh" namespace Cougar::Meta { class _built_in_tag; class Scope { public: Scope(std::string_view name, Scope *parent) : mName(name), mParent(parent) { if (!name.empty() && parent) { mQualification = parent->mQualification; mQualification.appendScope(name); } } Scope(const _built_in_tag &) { mIsBuiltIn = true; } void dump(int indent = 0) const; TypeInfo *addType(TypeInfo::Simple s, std::uint64_t flags) { return mTypes.emplace(s.name, s, flags, mQualification); } TypeInfo *findType(std::string_view name) { return mTypes.find(name); } Scope *parent() { return mParent; } Scope *addNamedChild(std::string_view name) { return mNamedChildren.emplace(name, name, this); } FunctionInfo *addFunction(std::string_view name) { return mFunctions.emplace(name, name); } FunctionInfo *findFunction(std::string_view name) { return mFunctions.find(name); } VariableInfo *addVariable(std::string_view name) { return mVariables.emplace(name, name); } VariableInfo *findVariable(std::string_view name) { return mVariables.find(name); } private: std::string_view mName; Scope *mParent = nullptr; bool mIsBuiltIn = false; Utils::Map mTypes; Utils::Map mFunctions; Utils::Map mNamedChildren; Utils::Map mVariables; Utils::Qualification mQualification; }; } // namespace Cougar::Meta #include #include #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layers/loss/softmax_loss_layer.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { template class SoftmaxWithLossLayerTest : public ::testing::Test { typedef TypeParam Dtype; protected: SoftmaxWithLossLayerTest() : blob_bottom_0_(new Blob()),blob_bottom_1_(new Blob()), blob_top_(new Blob()) { caffe::Caffe::parallel_workspace_.resize(48); for (int i=0;i<12;i++) caffe::Caffe::parallel_workspace_[i] = new caffe::Blob(); } virtual void SetUp() { blob_bottom_0_->Reshape(2, 5, 3, 4); blob_bottom_1_->Reshape(2, 1, 3, 4); caffe_rng_gaussian(this->blob_bottom_0_->count(), Dtype(2), Dtype(1), this->blob_bottom_0_->mutable_cpu_data()); for (int i=0;icount();i++) blob_bottom_1_->mutable_cpu_data()[i] = caffe_rng_rand()%5; blob_bottom_vec_.push_back(blob_bottom_0_); blob_bottom_vec_.push_back(blob_bottom_1_); blob_top_vec_.push_back(blob_top_); } virtual ~SoftmaxWithLossLayerTest() { delete blob_bottom_0_; delete blob_bottom_1_; delete blob_top_; } Blob* const blob_bottom_0_; Blob* const blob_bottom_1_; Blob* const blob_top_; vector*> blob_bottom_vec_; vector*> blob_top_vec_; }; typedef testing::Types myTypes; TYPED_TEST_CASE(SoftmaxWithLossLayerTest, myTypes); TYPED_TEST(SoftmaxWithLossLayerTest, TestGradient) { typedef TypeParam Dtype; LayerParameter layer_param; layer_param.mutable_loss_param()->set_ignore_label(255); SoftmaxWithLossLayer layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Reshape(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); GradientChecker checker(1e-2, 1e-2); //checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_,0); checker.CheckSecGradientExhaustive(&layer, this->blob_top_vec_, this->blob_bottom_vec_,0); } } // namespace caffe #pragma once #include #include #include #include #include #include #include #include #include #include namespace sf { class RenderTarget; } class Fractal final : public sf::Drawable { public: explicit Fractal(const sf::Vector2u& size, unsigned int parallelization = std::thread::hardware_concurrency()); void reset(const sf::Vector2u& size, unsigned int parallelization = std::thread::hardware_concurrency()); void update(const sf::Vector2i& first, const sf::Vector2i& second); void resize(const sf::Vector2u& size); void precision(const long double& precision); const long double& precision() const; private: void draw(sf::RenderTarget& target, sf::RenderStates states) const override; sf::Uint8 color(unsigned int c, long double z, sf::Uint8 x, sf::Uint8 sX, int sign) const; void generate(sf::Rect section); void generateParallel(); // Drawing std::vector m_pixels; sf::Texture m_texture; sf::Sprite m_fractal; // Parameters unsigned int m_parallelization; sf::Vector3 m_position; float m_pFactor; long double m_precision; sf::Color m_x; sf::Color m_sX; }; // Copyright (c) 2013 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 "chromeos/dbus/power_policy_controller.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos { namespace { // Appends a description of |field|, a field within |delays|, a // power_manager::PowerManagementPolicy::Delays object, to |str|, an // std::string, if the field is set. |name| is a char* describing the // field. #define APPEND_DELAY(str, delays, field, name) \ { \ if (delays.has_##field()) \ str += base::StringPrintf(name "=%" PRId64 " ", delays.field()); \ } // Appends descriptions of all of the set delays in |delays|, a // power_manager::PowerManagementPolicy::Delays object, to |str|, an // std::string. |prefix| should be a char* containing either "ac" or // "battery". #define APPEND_DELAYS(str, delays, prefix) \ { \ APPEND_DELAY(str, delays, screen_dim_ms, prefix "_screen_dim_ms"); \ APPEND_DELAY(str, delays, screen_off_ms, prefix "_screen_off_ms"); \ APPEND_DELAY(str, delays, screen_lock_ms, prefix "_screen_lock_ms"); \ APPEND_DELAY(str, delays, idle_warning_ms, prefix "_idle_warning_ms"); \ APPEND_DELAY(str, delays, idle_ms, prefix "_idle_ms"); \ } // Returns the power_manager::PowerManagementPolicy_Action value // corresponding to |action|. power_manager::PowerManagementPolicy_Action GetProtoAction( PowerPolicyController::Action action) { switch (action) { case PowerPolicyController::ACTION_SUSPEND: return power_manager::PowerManagementPolicy_Action_SUSPEND; case PowerPolicyController::ACTION_STOP_SESSION: return power_manager::PowerManagementPolicy_Action_STOP_SESSION; case PowerPolicyController::ACTION_SHUT_DOWN: return power_manager::PowerManagementPolicy_Action_SHUT_DOWN; case PowerPolicyController::ACTION_DO_NOTHING: return power_manager::PowerManagementPolicy_Action_DO_NOTHING; default: NOTREACHED() << "Unhandled action " << action; return power_manager::PowerManagementPolicy_Action_DO_NOTHING; } } } // namespace const int PowerPolicyController::kScreenLockAfterOffDelayMs = 10000; // 10 sec. // -1 is interpreted as "unset" by powerd, resulting in powerd's default // delays being used instead. There are no similarly-interpreted values // for the other fields, unfortunately (but the constructor-assigned values // will only reach powerd if Chrome messes up and forgets to override them // with the pref-assigned values). PowerPolicyController::PrefValues::PrefValues() : ac_screen_dim_delay_ms(-1), ac_screen_off_delay_ms(-1), ac_screen_lock_delay_ms(-1), ac_idle_warning_delay_ms(-1), ac_idle_delay_ms(-1), battery_screen_dim_delay_ms(-1), battery_screen_off_delay_ms(-1), battery_screen_lock_delay_ms(-1), battery_idle_warning_delay_ms(-1), battery_idle_delay_ms(-1), ac_idle_action(ACTION_SUSPEND), battery_idle_action(ACTION_SUSPEND), lid_closed_action(ACTION_SUSPEND), use_audio_activity(true), use_video_activity(true), ac_brightness_percent(-1.0), battery_brightness_percent(-1.0), allow_screen_wake_locks(true), enable_screen_lock(false), presentation_screen_dim_delay_factor(1.0), user_activity_screen_dim_delay_factor(1.0), wait_for_initial_user_activity(false) {} // static std::string PowerPolicyController::GetPolicyDebugString( const power_manager::PowerManagementPolicy& policy) { std::string str; if (policy.has_ac_delays()) APPEND_DELAYS(str, policy.ac_delays(), "ac"); if (policy.has_battery_delays()) APPEND_DELAYS(str, policy.battery_delays(), "battery"); if (policy.has_ac_idle_action()) str += base::StringPrintf("ac_idle=%d ", policy.ac_idle_action()); if (policy.has_battery_idle_action()) str += base::StringPrintf("battery_idle=%d ", policy.battery_idle_action()); if (policy.has_lid_closed_action()) str += base::StringPrintf("lid_closed=%d ", policy.lid_closed_action()); if (policy.has_use_audio_activity()) str += base::StringPrintf("use_audio=%d ", policy.use_audio_activity()); if (policy.has_use_video_activity()) str += base::StringPrintf("use_video=%d ", policy.use_audio_activity()); if (policy.has_ac_brightness_percent()) { str += base::StringPrintf("ac_brightness_percent=%f ", policy.ac_brightness_percent()); } if (policy.has_battery_brightness_percent()) { str += base::StringPrintf("battery_brightness_percent=%f ", policy.battery_brightness_percent()); } if (policy.has_presentation_screen_dim_delay_factor()) { str += base::StringPrintf("presentation_screen_dim_delay_factor=%f ", policy.presentation_screen_dim_delay_factor()); } if (policy.has_user_activity_screen_dim_delay_factor()) { str += base::StringPrintf("user_activity_screen_dim_delay_factor=%f ", policy.user_activity_screen_dim_delay_factor()); } if (policy.has_wait_for_initial_user_activity()) { str += base::StringPrintf("wait_for_initial_user_activity=%d ", policy.wait_for_initial_user_activity()); } if (policy.has_reason()) str += base::StringPrintf("reason=\"%s\" ", policy.reason().c_str()); TrimWhitespace(str, TRIM_TRAILING, &str); return str; } PowerPolicyController::PowerPolicyController() : manager_(NULL), client_(NULL), prefs_were_set_(false), honor_screen_wake_locks_(true), next_wake_lock_id_(1) { } PowerPolicyController::~PowerPolicyController() { DCHECK(manager_); // The power manager's policy is reset before this point, in // OnDBusThreadManagerDestroying(). At the time that // PowerPolicyController is destroyed, PowerManagerClient's D-Bus proxy // to the power manager is already gone. client_->RemoveObserver(this); client_ = NULL; manager_->RemoveObserver(this); manager_ = NULL; } void PowerPolicyController::Init(DBusThreadManager* manager) { manager_ = manager; manager_->AddObserver(this); client_ = manager_->GetPowerManagerClient(); client_->AddObserver(this); SendCurrentPolicy(); } void PowerPolicyController::ApplyPrefs(const PrefValues& values) { prefs_policy_.Clear(); power_manager::PowerManagementPolicy::Delays* delays = prefs_policy_.mutable_ac_delays(); delays->set_screen_dim_ms(values.ac_screen_dim_delay_ms); delays->set_screen_off_ms(values.ac_screen_off_delay_ms); delays->set_screen_lock_ms(values.ac_screen_lock_delay_ms); delays->set_idle_warning_ms(values.ac_idle_warning_delay_ms); delays->set_idle_ms(values.ac_idle_delay_ms); // If screen-locking is enabled, ensure that the screen is locked soon // after it's turned off due to user inactivity. int64 lock_ms = delays->screen_off_ms() + kScreenLockAfterOffDelayMs; if (values.enable_screen_lock && delays->screen_off_ms() > 0 && (delays->screen_lock_ms() <= 0 || lock_ms < delays->screen_lock_ms()) && lock_ms < delays->idle_ms()) { delays->set_screen_lock_ms(lock_ms); } delays = prefs_policy_.mutable_battery_delays(); delays->set_screen_dim_ms(values.battery_screen_dim_delay_ms); delays->set_screen_off_ms(values.battery_screen_off_delay_ms); delays->set_screen_lock_ms(values.battery_screen_lock_delay_ms); delays->set_idle_warning_ms(values.battery_idle_warning_delay_ms); delays->set_idle_ms(values.battery_idle_delay_ms); lock_ms = delays->screen_off_ms() + kScreenLockAfterOffDelayMs; if (values.enable_screen_lock && delays->screen_off_ms() > 0 && (delays->screen_lock_ms() <= 0 || lock_ms < delays->screen_lock_ms()) && lock_ms < delays->idle_ms()) { delays->set_screen_lock_ms(lock_ms); } prefs_policy_.set_ac_idle_action(GetProtoAction(values.ac_idle_action)); prefs_policy_.set_battery_idle_action( GetProtoAction(values.battery_idle_action)); prefs_policy_.set_lid_closed_action(GetProtoAction(values.lid_closed_action)); prefs_policy_.set_use_audio_activity(values.use_audio_activity); prefs_policy_.set_use_video_activity(values.use_video_activity); if (values.ac_brightness_percent >= 0.0) prefs_policy_.set_ac_brightness_percent(values.ac_brightness_percent); if (values.battery_brightness_percent >= 0.0) { prefs_policy_.set_battery_brightness_percent( values.battery_brightness_percent); } prefs_policy_.set_presentation_screen_dim_delay_factor( values.presentation_screen_dim_delay_factor); prefs_policy_.set_user_activity_screen_dim_delay_factor( values.user_activity_screen_dim_delay_factor); prefs_policy_.set_wait_for_initial_user_activity( values.wait_for_initial_user_activity); honor_screen_wake_locks_ = values.allow_screen_wake_locks; prefs_were_set_ = true; SendCurrentPolicy(); } void PowerPolicyController::ClearPrefs() { prefs_policy_.Clear(); honor_screen_wake_locks_ = true; prefs_were_set_ = false; SendCurrentPolicy(); } int PowerPolicyController::AddScreenWakeLock(const std::string& reason) { int id = next_wake_lock_id_++; screen_wake_locks_[id] = reason; SendCurrentPolicy(); return id; } int PowerPolicyController::AddSystemWakeLock(const std::string& reason) { int id = next_wake_lock_id_++; system_wake_locks_[id] = reason; SendCurrentPolicy(); return id; } void PowerPolicyController::RemoveWakeLock(int id) { if (!screen_wake_locks_.erase(id) && !system_wake_locks_.erase(id)) LOG(WARNING) << "Ignoring request to remove nonexistent wake lock " << id; else SendCurrentPolicy(); } void PowerPolicyController::OnDBusThreadManagerDestroying( DBusThreadManager* manager) { DCHECK_EQ(manager, manager_); SendEmptyPolicy(); } void PowerPolicyController::PowerManagerRestarted() { SendCurrentPolicy(); } void PowerPolicyController::SendCurrentPolicy() { std::string reason; power_manager::PowerManagementPolicy policy = prefs_policy_; if (prefs_were_set_) reason = "Prefs"; if (honor_screen_wake_locks_ && !screen_wake_locks_.empty()) { policy.mutable_ac_delays()->set_screen_dim_ms(0); policy.mutable_ac_delays()->set_screen_off_ms(0); policy.mutable_ac_delays()->set_screen_lock_ms(0); policy.mutable_battery_delays()->set_screen_dim_ms(0); policy.mutable_battery_delays()->set_screen_off_ms(0); policy.mutable_battery_delays()->set_screen_lock_ms(0); } if (!screen_wake_locks_.empty() || !system_wake_locks_.empty()) { if (!policy.has_ac_idle_action() || policy.ac_idle_action() == power_manager::PowerManagementPolicy_Action_SUSPEND) { policy.set_ac_idle_action( power_manager::PowerManagementPolicy_Action_DO_NOTHING); } if (!policy.has_battery_idle_action() || policy.battery_idle_action() == power_manager::PowerManagementPolicy_Action_SUSPEND) { policy.set_battery_idle_action( power_manager::PowerManagementPolicy_Action_DO_NOTHING); } } for (WakeLockMap::const_iterator it = screen_wake_locks_.begin(); it != screen_wake_locks_.end(); ++it) { reason += (reason.empty() ? "" : ", ") + it->second; } for (WakeLockMap::const_iterator it = system_wake_locks_.begin(); it != system_wake_locks_.end(); ++it) { reason += (reason.empty() ? "" : ", ") + it->second; } if (!reason.empty()) policy.set_reason(reason); client_->SetPolicy(policy); } void PowerPolicyController::SendEmptyPolicy() { client_->SetPolicy(power_manager::PowerManagementPolicy()); } } // namespace chromeos /* Copyright (c) 2019-2020, Stanford University * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include #include #include "StringUtil.h" namespace Homa { namespace Drivers { namespace Fake { namespace { TEST(FakeDriverTest, constructor) { uint32_t nextAddressId = FakeDriver().localAddressId + 1; FakeDriver driver; EXPECT_EQ(nextAddressId, driver.localAddressId); } TEST(FakeDriverTest, allocPacket) { FakeDriver driver; Driver::Packet* packet = driver.allocPacket(); // allocPacket doesn't do much so we just need to make sure we can call it. delete container_of(packet, &FakePacket::base); } TEST(FakeDriverTest, sendPackets) { FakeDriver driver1; FakeDriver driver2; Driver::Packet* packets[4]; IpAddress destinations[4]; int prio[4]; for (int i = 0; i < 4; ++i) { packets[i] = driver1.allocPacket(); destinations[i] = driver2.getLocalAddress(); prio[i] = i; } destinations[2] = IpAddress{42}; EXPECT_EQ(0U, driver2.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(1).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(3).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(4).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(7).size()); driver1.sendPacket(packets[0], destinations[0], prio[0]); EXPECT_EQ(1U, driver2.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(1).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(3).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(4).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(7).size()); { FakePacket* packet = driver2.nic.priorityQueue.at(0).front(); EXPECT_EQ(driver1.getLocalAddress(), packet->sourceIp); } for (int i = 0; i < 4; ++i) { driver1.sendPacket(packets[i], destinations[i], prio[i]); } EXPECT_EQ(2U, driver2.nic.priorityQueue.at(0).size()); EXPECT_EQ(1U, driver2.nic.priorityQueue.at(1).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(2).size()); EXPECT_EQ(1U, driver2.nic.priorityQueue.at(3).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(4).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver2.nic.priorityQueue.at(7).size()); delete container_of(packets[2], &FakePacket::base); } TEST(FakeDriverTest, receivePackets) { std::string addressStr("42"); FakeDriver driver; Driver::Packet* packets[4]; IpAddress srcAddrs[4]; // 3 packets at priority 7 for (int i = 0; i < 3; ++i) driver.nic.priorityQueue.at(7).push_back(new FakePacket); // 3 packets at priority 5 for (int i = 0; i < 3; ++i) driver.nic.priorityQueue.at(5).push_back(new FakePacket); // 1 packet at priority 4 driver.nic.priorityQueue.at(4).push_back(new FakePacket); // 1 packet at priority 2 driver.nic.priorityQueue.at(2).push_back(new FakePacket); EXPECT_EQ(0U, driver.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(1).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(3).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(4).size()); EXPECT_EQ(3U, driver.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(6).size()); EXPECT_EQ(3U, driver.nic.priorityQueue.at(7).size()); EXPECT_EQ(4U, driver.receivePackets(4, packets, srcAddrs)); driver.releasePackets(packets, 4); EXPECT_EQ(0U, driver.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(1).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(3).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(4).size()); EXPECT_EQ(2U, driver.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(7).size()); EXPECT_EQ(1U, driver.receivePackets(1, packets, srcAddrs)); driver.releasePackets(packets, 1); EXPECT_EQ(0U, driver.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(1).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(3).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(4).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(7).size()); driver.nic.priorityQueue.at(7).push_back(new FakePacket); EXPECT_EQ(0U, driver.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(1).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(3).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(4).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(6).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(7).size()); EXPECT_EQ(1U, driver.receivePackets(1, packets, srcAddrs)); driver.releasePackets(packets, 1); EXPECT_EQ(0U, driver.nic.priorityQueue.at(0).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(1).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(2).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(3).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(4).size()); EXPECT_EQ(1U, driver.nic.priorityQueue.at(5).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(6).size()); EXPECT_EQ(0U, driver.nic.priorityQueue.at(7).size()); EXPECT_EQ(3U, driver.receivePackets(4, packets, srcAddrs)); driver.releasePackets(packets, 3); } TEST(FakeDriverTest, releasePackets) { // releasePackets is well testing in receivePackets test. } TEST(FakeDriverTest, getHighestPacketPriority) { FakeDriver driver; EXPECT_EQ(7, driver.getHighestPacketPriority()); } TEST(FakeDriverTest, getMaxPayloadSize) { FakeDriver driver; EXPECT_EQ(MAX_PAYLOAD_SIZE, driver.getMaxPayloadSize()); } TEST(FakeDriverTest, getBandwidth) { FakeDriver driver; EXPECT_EQ(10000U, driver.getBandwidth()); } TEST(FakeDriverTest, getLocalAddress) { uint32_t nextAddressId = FakeDriver().localAddressId + 1; FakeDriver driver; EXPECT_EQ(nextAddressId, (uint32_t)driver.getLocalAddress()); } } // namespace } // namespace Fake } // namespace Drivers } // namespace Homa// Copyright 2015 Open Source Robotics Foundation, 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. #include #include #include #include #include #include #include "ament_index_cpp/get_package_prefix.hpp" #include "ament_index_cpp/get_package_share_directory.hpp" #include "ament_index_cpp/get_packages_with_prefixes.hpp" #include "ament_index_cpp/get_resource.hpp" #include "ament_index_cpp/get_resources.hpp" #include "ament_index_cpp/get_search_paths.hpp" #include "ament_index_cpp/has_resource.hpp" std::string generate_subfolder_path(std::string subfolder) { // Get base path of this file std::string base_path = __FILE__; const std::string filename = "utest.cpp"; base_path = base_path.substr(0, base_path.length() - filename.length() - 1); // Generate the base path of the subfolder in this directory return base_path + "/" + subfolder; } void set_ament_prefix_path(std::list subfolders) { std::string ament_prefix_path; // Generate a joined string of all absolute paths // Subfolders later in the list are searched later in the index for (auto subfolder : subfolders) { std::string path = generate_subfolder_path(subfolder); if (!ament_prefix_path.empty()) { #ifndef _WIN32 ament_prefix_path += ":"; #else ament_prefix_path += ";"; #endif } ament_prefix_path += path; } // Set environment variable #ifndef _WIN32 int retcode = setenv("AMENT_PREFIX_PATH", ament_prefix_path.c_str(), 1); #else errno_t retcode = _putenv_s("AMENT_PREFIX_PATH", ament_prefix_path.c_str()); #endif if (retcode) { throw std::runtime_error("Failed to set environment variable 'AMENT_PREFIX_PATH'"); } } TEST(AmentIndexCpp, empty_search_paths) { std::list subfolders; set_ament_prefix_path(subfolders); EXPECT_THROW(ament_index_cpp::get_search_paths(), std::runtime_error); } TEST(AmentIndexCpp, search_paths) { std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); std::list search_paths = ament_index_cpp::get_search_paths(); EXPECT_EQ(search_paths.size(), 2UL); } TEST(AmentIndexCpp, not_existing_search_paths) { std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("not_existing_prefix"); set_ament_prefix_path(subfolders); std::list search_paths = ament_index_cpp::get_search_paths(); EXPECT_EQ(search_paths.size(), 1UL); } TEST(AmentIndexCpp, get_empty_resources) { EXPECT_THROW(ament_index_cpp::get_resources(""), std::runtime_error); } TEST(AmentIndexCpp, get_unknown_resources) { std::list subfolders; subfolders.push_back("prefix1"); set_ament_prefix_path(subfolders); std::map resources = ament_index_cpp::get_resources("unknown_resource_type"); EXPECT_EQ(resources.size(), 0UL); } TEST(AmentIndexCpp, get_resources) { // Ensure that if multiple resources of a particular type exist, all are found std::list subfolders; subfolders.push_back("prefix1"); set_ament_prefix_path(subfolders); // There are two resources of this type std::map resources = ament_index_cpp::get_resources("resource_type1"); EXPECT_EQ(resources.size(), 2UL); for (auto it : resources) { EXPECT_EQ(it.second, generate_subfolder_path("prefix1")); EXPECT_TRUE(it.first == "foo" || it.first == "bar"); } } TEST(AmentIndexCpp, get_resources_overlay) { // Ensure that a resource type found in two prefixes returns two paths std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); // This resource type is found in prefix1 and prefix2 std::map resources = ament_index_cpp::get_resources("resource_type2"); EXPECT_EQ(resources.size(), 2UL); for (auto it : resources) { EXPECT_TRUE(it.first == "foo" || it.first == "bar"); } } TEST(AmentIndexCpp, get_resources_underlay) { // Ensure that a resource only found in one prefix only returns one path std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); // This resource type is only found in prefix2 std::map resources = ament_index_cpp::get_resources("resource_type3"); EXPECT_EQ(resources.size(), 1UL); for (auto it : resources) { EXPECT_EQ(it.second, generate_subfolder_path("prefix2")); EXPECT_EQ(it.first, "bar"); } } TEST(AmentIndexCpp, get_empty_resource) { std::string content; EXPECT_THROW(ament_index_cpp::get_resource("", "", content), std::runtime_error); } TEST(AmentIndexCpp, get_unknown_resource) { std::list subfolders; subfolders.push_back("prefix1"); set_ament_prefix_path(subfolders); std::string content; bool success = ament_index_cpp::get_resource("resource_type4", "bar", content); EXPECT_FALSE(success); } TEST(AmentIndexCpp, get_resource) { std::list subfolders; subfolders.push_back("prefix1"); set_ament_prefix_path(subfolders); std::string content; bool success = ament_index_cpp::get_resource("resource_type4", "foo", content); EXPECT_TRUE(success); EXPECT_EQ(content, "foo"); } TEST(AmentIndexCpp, get_resource_underlay) { // Ensure that a resource can be found in the underlay if it doesn't exist in the overlay std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); std::string content; // This resource is only found in the underlay bool success = ament_index_cpp::get_resource("resource_type2", "bar", content); EXPECT_TRUE(success); EXPECT_EQ(content, ""); } TEST(AmentIndexCpp, get_resource_overlay) { // Ensure that the resource in the overlay is found before the one in the underlay std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); std::string content; // This resource is in both the overlay and the underlay bool success = ament_index_cpp::get_resource("resource_type5", "foo", content); EXPECT_TRUE(success); EXPECT_EQ(content, "foo1"); } TEST(AmentIndexCpp, get_resource_overlay_base_path) { // Ensure that a resource found in the overlay returns the correct path std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); std::string content; std::string base_path; // This resource is only found in the overlay bool success = ament_index_cpp::get_resource("resource_type2", "foo", content, &base_path); EXPECT_TRUE(success); EXPECT_EQ(base_path, generate_subfolder_path("prefix1")); } TEST(AmentIndexCpp, get_resource_underlay_base_path) { // Ensure that a resource found in the underlay returns the correct path std::list subfolders; subfolders.push_back("prefix1"); subfolders.push_back("prefix2"); set_ament_prefix_path(subfolders); std::string content; std::string base_path; // This resource is only found in the underlay bool success = ament_index_cpp::get_resource("resource_type2", "bar", content, &base_path); EXPECT_TRUE(success); EXPECT_EQ(base_path, generate_subfolder_path("prefix2")); } TEST(AmentIndexCpp, get_package_prefix) { // Ensure that a known to exist package is found and that a known to not exist package is not. std::list subfolders; subfolders.push_back("prefix1"); // only contains foo and bar packages subfolders.push_back("prefix2"); // only contains bar and baz packages set_ament_prefix_path(subfolders); // foo is found in prefix 1 EXPECT_EQ(generate_subfolder_path("prefix1"), ament_index_cpp::get_package_prefix("foo")); // bar is in both, but prefix 1 takes precedence EXPECT_EQ(generate_subfolder_path("prefix1"), ament_index_cpp::get_package_prefix("bar")); // baz is found in prefix 2 only EXPECT_EQ(generate_subfolder_path("prefix2"), ament_index_cpp::get_package_prefix("baz")); // exception when package is not found EXPECT_THROW( ament_index_cpp::get_package_prefix("does_not_exist"), ament_index_cpp::PackageNotFoundError); // exception when the package name is empty EXPECT_THROW( ament_index_cpp::get_package_prefix(""), std::runtime_error); } TEST(AmentIndexCpp, get_package_share_directory) { // Ensure that a known to exist package is found and the share directory is correct. std::list subfolders; subfolders.push_back("prefix1"); // only contains foo and bar packages subfolders.push_back("prefix2"); // only contains bar and baz packages set_ament_prefix_path(subfolders); // bar is in both, but prefix 1 takes precedence EXPECT_EQ( generate_subfolder_path("prefix1") + "/share/bar", ament_index_cpp::get_package_share_directory("bar")); } TEST(AmentIndexCpp, get_packages_with_prefixes) { // Ensure the list of packages and prefixes matches resource layout. std::list subfolders; subfolders.push_back("prefix1"); // only contains foo and bar packages subfolders.push_back("prefix2"); // only contains bar and baz packages set_ament_prefix_path(subfolders); std::map packages_with_prefixes = ament_index_cpp::get_packages_with_prefixes(); // should be exactly three elements EXPECT_EQ(3UL, packages_with_prefixes.size()); // foo is found in prefix 1 EXPECT_EQ(generate_subfolder_path("prefix1"), packages_with_prefixes["foo"]); // bar is in both, but prefix 1 takes precedence EXPECT_EQ(generate_subfolder_path("prefix1"), packages_with_prefixes["bar"]); // baz is found in prefix 2 only EXPECT_EQ(generate_subfolder_path("prefix2"), packages_with_prefixes["baz"]); } TEST(AmentIndexCpp, has_empty_name) { EXPECT_THROW( ament_index_cpp::has_resource("type", ""), std::runtime_error); } TEST(AmentIndexCpp, has_empty_type) { EXPECT_THROW( ament_index_cpp::has_resource("", "name"), std::runtime_error); } TEST(AmentIndexCpp, has_unknown_resource) { bool success = ament_index_cpp::has_resource("resource_type4", "bar21"); EXPECT_FALSE(success); } TEST(AmentIndexCpp, has_resource) { std::string result_path; EXPECT_TRUE(ament_index_cpp::has_resource("resource_type1", "foo", &result_path)); EXPECT_EQ(result_path, generate_subfolder_path("prefix1")); EXPECT_TRUE(ament_index_cpp::has_resource("resource_type3", "bar")); EXPECT_TRUE(ament_index_cpp::has_resource("packages", "baz", &result_path)); EXPECT_EQ(result_path, generate_subfolder_path("prefix2")); EXPECT_FALSE(ament_index_cpp::has_resource("resource_type1", "resource", &result_path)); } #include #include #include #include #include #include "Model.h" const char *deviceName="fake_room_climatics";//имя устройства const Uuid deviceId("5a059a0216934e71bf753e4afe26e6f6");//идентификатор устройства const char *interfaceStr= "" "" "" "" "" "" "" "" "" "" "" ""; const char *sensorsDef="" "" "" "" "" "" ""; class SrvReadyCb :public ISrvReadyCallback { public: explicit SrvReadyCb(Device *d) { dev=d; } virtual void processSrvReadyMsg(const Uuid &serverId,const char *serverName,in_addr addr)override { if(!dev->sock().isConnected()&&dev->sock().connectToAddr(addr)) { char idStr[Uuid::idStringLen]; serverId.toString(idStr); printf("connected to server: %i.%i.%i.%i; %s:%s\n",(addr.s_addr%(1<<8)),(addr.s_addr%(1<<16))/(1<<8), (addr.s_addr%(1<<24))/(1<<16),addr.s_addr/(1<<24),idStr,serverName); } } private: Device *dev; }; int main(int argc,char **argv) { Device dev(300,&deviceId,deviceName); SrvReadyCb srvRdyCb(&dev); SrvReady rdy(120,&srvRdyCb); Model mdl(&dev); int counter=0; dev.disp().setControls(interfaceStr); dev.disp().setSensors(sensorsDef); dev.disp().setDevEventsHandler(&mdl); int tmrFd=timerfd_create(CLOCK_REALTIME,0); if(tmrFd==-1)return 1; itimerspec s; s.it_value.tv_sec=1; s.it_value.tv_nsec=0; s.it_interval.tv_sec=1; s.it_interval.tv_nsec=0; timerfd_settime(tmrFd,0,&s,0); uint64_t r; while(read(tmrFd,&r,sizeof(r))>0) { rdy.checkForMessages(); dev.sock().checkForNewData(); ++counter; if(counter==10) { counter=0; mdl.updateTempHum(); } } } pac85/RayTracedGL1 // Copyright (c) 2021 // // 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 "SwapchainPass.h" RTGL1::SwapchainPass::SwapchainPass( VkDevice _device, VkPipelineLayout _pipelineLayout, VkFormat _surfaceFormat, const std::shared_ptr &_shaderManager, const RgInstanceCreateInfo &_instanceInfo) : device(_device), swapchainRenderPass(VK_NULL_HANDLE), swapchainWidth(0), swapchainHeight(0) { CreateSwapchainRenderPass(_surfaceFormat); swapchainPipelines = std::make_shared(device, _pipelineLayout, swapchainRenderPass, _instanceInfo.rasterizedVertexColorGamma); swapchainPipelines->SetShaders(_shaderManager.get(), "VertRasterizer", "FragRasterizer"); } RTGL1::SwapchainPass::~SwapchainPass() { vkDestroyRenderPass(device, swapchainRenderPass, nullptr); DestroyFramebuffers(); } void RTGL1::SwapchainPass::CreateFramebuffers(uint32_t newSwapchainWidth, uint32_t newSwapchainHeight, const VkImageView *pSwapchainAttchs, uint32_t swapchainAttchCount) { // prepare framebuffers for drawing right into swapchain images swapchainFramebuffers.resize(swapchainAttchCount, VK_NULL_HANDLE); for (uint32_t i = 0; i < swapchainAttchCount; i++) { assert(swapchainFramebuffers[i] == VK_NULL_HANDLE); VkFramebufferCreateInfo fbInfo = {}; fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; fbInfo.renderPass = swapchainRenderPass; fbInfo.attachmentCount = 1; fbInfo.pAttachments = &pSwapchainAttchs[i]; fbInfo.width = newSwapchainWidth; fbInfo.height = newSwapchainHeight; fbInfo.layers = 1; VkResult r = vkCreateFramebuffer(device, &fbInfo, nullptr, &swapchainFramebuffers[i]); VK_CHECKERROR(r); SET_DEBUG_NAME(device, swapchainFramebuffers[i], VK_OBJECT_TYPE_FRAMEBUFFER, "Rasterizer swapchain framebuffer"); } this->swapchainWidth = newSwapchainWidth; this->swapchainHeight = newSwapchainHeight; } void RTGL1::SwapchainPass::DestroyFramebuffers() { for (VkFramebuffer &fb : swapchainFramebuffers) { if (fb != VK_NULL_HANDLE) { vkDestroyFramebuffer(device, fb, nullptr); fb = VK_NULL_HANDLE; } } } void RTGL1::SwapchainPass::OnShaderReload(const ShaderManager *shaderManager) { swapchainPipelines->Clear(); swapchainPipelines->SetShaders(shaderManager, "VertRasterizer", "FragRasterizer"); } VkRenderPass RTGL1::SwapchainPass::GetSwapchainRenderPass() const { return swapchainRenderPass; } const std::shared_ptr &RTGL1::SwapchainPass::GetSwapchainPipelines() const { return swapchainPipelines; } uint32_t RTGL1::SwapchainPass::GetSwapchainWidth() const { return swapchainWidth; } uint32_t RTGL1::SwapchainPass::GetSwapchainHeight() const { return swapchainHeight; } VkFramebuffer RTGL1::SwapchainPass::GetSwapchainFramebuffer(uint32_t swapchainImageIndex) const { if (swapchainImageIndex >= swapchainFramebuffers.size()) { VK_NULL_HANDLE; } return swapchainFramebuffers[swapchainImageIndex]; } void RTGL1::SwapchainPass::CreateSwapchainRenderPass(VkFormat surfaceFormat) { VkAttachmentDescription colorAttch = {}; colorAttch.format = surfaceFormat; colorAttch.samples = VK_SAMPLE_COUNT_1_BIT; colorAttch.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; colorAttch.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttch.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttch.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttch.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; colorAttch.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorRef = {}; colorRef.attachment = 0; colorRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorRef; subpass.pDepthStencilAttachment = nullptr; VkSubpassDependency dependency = {}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo passInfo = {}; passInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; passInfo.attachmentCount = 1; passInfo.pAttachments = &colorAttch; passInfo.subpassCount = 1; passInfo.pSubpasses = &subpass; passInfo.dependencyCount = 1; passInfo.pDependencies = &dependency; VkResult r = vkCreateRenderPass(device, &passInfo, nullptr, &swapchainRenderPass); VK_CHECKERROR(r); SET_DEBUG_NAME(device, swapchainRenderPass, VK_OBJECT_TYPE_RENDER_PASS, "Rasterizer swapchain render pass"); } /*++ Copyright (c) 2001 Microsoft Corporation Module Name: chunkflt.cxx Abstract: Contains a filter for encoding and decoding chunked transfers. Contents: FILTER_LIST::Insert FILTER_LIST::RemoveAll FILTER_LIST::Decode ChunkFilter::Reset ChunkFilter::Decode ChunkFilter::Encode ChunkFilter::RegisterContext ChunkFilter::UnregisterContext Revision History: Created 13-Feb-2001 --*/ #include // Global lookup table to map 0x0 - 0x7f bytes for obtaining mapping to its // token value. All values above 0x7f are considered to be data. const BYTE g_bChunkTokenTable[] = { /* 0x00 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_LF, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_CR, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x10 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x20 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x30 */ CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_COLON, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x40 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x50 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x60 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DIGIT, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, /* 0x70 */ CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA, CHUNK_TOKEN_DATA }; // Look-up table to map a token in a given state to the next state const CHUNK_DECODE_STATE g_eMapChunkTokenToNextState[CHUNK_DECODE_STATE_LAST+1][CHUNK_TOKEN_LAST+1] = { /* |---------DIGIT----------|-------------CR-------------|-------------LF------------|----------COLON----------|-----------DATA----------| */ // CHUNK_DECODE_STATE_START CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_SIZE, // CHUNK_DECODE_STATE_SIZE CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_SIZE_CRLF,CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_EXT, CHUNK_DECODE_STATE_EXT, // CHUNK_DECODE_STATE_SIZE_CRLF CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_SIZE_CRLF,CHUNK_DECODE_STATE_DATA, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, // CHUNK_DECODE_STATE_EXT CHUNK_DECODE_STATE_EXT, CHUNK_DECODE_STATE_SIZE_CRLF,CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_EXT, CHUNK_DECODE_STATE_EXT, // CHUNK_DECODE_STATE_DATA CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_DATA_CRLF,CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_DATA, CHUNK_DECODE_STATE_ERROR, // CHUNK_DECODE_STATE_DATA_CRLF CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_DATA_CRLF,CHUNK_DECODE_STATE_SIZE, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, // CHUNK_DECODE_STATE_FOOTER_NAME CHUNK_DECODE_STATE_FOOTER_NAME, CHUNK_DECODE_STATE_FINAL_CRLF, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_FOOTER_VALUE, CHUNK_DECODE_STATE_FOOTER_NAME, // CHUNK_DECODE_STATE_FOOTER_VALUE CHUNK_DECODE_STATE_FOOTER_VALUE, CHUNK_DECODE_STATE_FINAL_CRLF, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_FOOTER_VALUE, // CHUNK_DECODE_STATE_FINAL_CRLF CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_FINAL_CRLF, CHUNK_DECODE_STATE_FINISHED, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, // CHUNK_DECODE_STATE_ERROR CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, // CHUNK_DECODE_STATE_FINISHED -- force client to reset before reuse CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR, CHUNK_DECODE_STATE_ERROR }; // Helper macros // Where to next? #define MAP_CHUNK_TOKEN_TO_NEXT_STATE(eCurState, chToken) \ (g_eMapChunkTokenToNextState[(eCurState)][(chToken)]) // Given a byte, what does it represent w/regards to chunked responses #define GET_CHUNK_TOKEN(ch) ((ch) & 0x80 ? CHUNK_TOKEN_DATA : g_bChunkTokenTable[ch]) // Should only be used with digit tokens. // Expects byte in range 0x30-0x39 (digits), 0x41-0x46 (uppercase hex), // or 0x61-0x66 (lowercase hex) #define GET_VALUE_FROM_ASCII_HEX(ch) ((ch) - ((ch) & 0xf0) + (((ch) & 0x40) ? 9 : 0)) HRESULT ChunkFilter::Reset(DWORD_PTR dwContext) { DEBUG_ENTER((DBG_HTTP, Dword, "ChunkFilter::Reset", "%#x", dwContext )); if (dwContext) (reinterpret_cast(dwContext))->Reset(); DEBUG_LEAVE(TRUE); return S_OK; } HRESULT ChunkFilter::Decode( DWORD_PTR dwContext, IN OUT LPBYTE pInBuffer, IN DWORD dwInBufSize, IN OUT LPBYTE *ppOutBuffer, IN OUT LPDWORD pdwOutBufSize, OUT LPDWORD pdwBytesRead, OUT LPDWORD pdwBytesWritten ) /*++ Routine Description: Decode downloaded chunked data based on the inputted context and its current state Arguments: dwContext - registered encode/decode context for this filter pInBuffer - input data buffer to be processed dwInBufSize - byte count of pInBuffer ppOutBuffer - allocated buffer containing encoded/decoded data if not done in place with pInBuffer. pdwOutBufSize - size of allocated output buffer, or 0 if pInBuffer holds the processed data pdwBytesRead - Number of input buffer bytes used pdwBytesWritten - Number of output buffer bytes written Return Value: HRESULT Success - S_OK Failure - E_FAIL --*/ { HRESULT hResult = S_OK; LPBYTE pCurrentLoc = pInBuffer; LPBYTE pStartOfChunk = pInBuffer; ChunkDecodeContext * pCtx = reinterpret_cast(dwContext); CHUNK_DECODE_STATE ePreviousState; BYTE chToken; DEBUG_ENTER((DBG_HTTP, Dword, "ChunkFilter::Decode", "%x, [%x, %.10q], %u, %x, %u, %x, %x", dwContext, pInBuffer, *pInBuffer, dwInBufSize, ppOutBuffer, pdwOutBufSize, pdwBytesRead, pdwBytesWritten )); if (!dwContext) { hResult = E_INVALIDARG; goto quit; } else if (!pdwBytesRead || !pdwBytesWritten || !pInBuffer || (ppOutBuffer && !pdwOutBufSize)) { hResult = E_POINTER; goto quit; } *pdwBytesRead = 0; *pdwBytesWritten = 0; while (*pdwBytesRead < dwInBufSize && pCtx->GetState() != CHUNK_DECODE_STATE_ERROR) { chToken = GET_CHUNK_TOKEN(*pCurrentLoc); ePreviousState = pCtx->GetState(); DEBUG_PRINT(HTTP, INFO, ("ChunkFilter::Decode: %q, %q, %u/%u\n", InternetMapChunkState(ePreviousState), InternetMapChunkToken((CHUNK_TOKEN_VALUE)chToken), *pdwBytesRead, dwInBufSize )); INET_ASSERT(pCurrentLoc < pInBuffer + dwInBufSize); switch (pCtx->GetState()) { case CHUNK_DECODE_STATE_START: pCtx->Reset(); pCtx->SetState(CHUNK_DECODE_STATE_SIZE); // fall through case CHUNK_DECODE_STATE_SIZE: { if (chToken == CHUNK_TOKEN_DIGIT) { if (pCtx->m_dwParsedSize & 0xF0000000) { // Don't allow overflow if by some chance // the server is trying to send a chunk over // 4 gigs worth in size. pCtx->SetState(CHUNK_DECODE_STATE_ERROR); break; } pCtx->m_dwParsedSize <<= 4; pCtx->m_dwParsedSize += GET_VALUE_FROM_ASCII_HEX(*pCurrentLoc); } else { pCtx->SetState(MAP_CHUNK_TOKEN_TO_NEXT_STATE( CHUNK_DECODE_STATE_SIZE, chToken)); } break; } case CHUNK_DECODE_STATE_SIZE_CRLF: // Handle the zero case which can take us to the footer or final CRLF // If it's the final CRLF, then this should be the end of the data. if (pCtx->m_dwParsedSize == 0 && chToken == CHUNK_TOKEN_LF) { pCtx->SetState(CHUNK_DECODE_STATE_FOOTER_NAME); } else { pCtx->SetState(MAP_CHUNK_TOKEN_TO_NEXT_STATE( CHUNK_DECODE_STATE_SIZE_CRLF, chToken)); } break; case CHUNK_DECODE_STATE_DATA: { INET_ASSERT(pCtx->m_dwParsedSize); // account for EOB if (pCurrentLoc + pCtx->m_dwParsedSize < pInBuffer + dwInBufSize) { const DWORD dwParsedSize = pCtx->m_dwParsedSize; // Move or skip the parsed size and crlf, if needed. // The start of the chunk could be equal this time if // spread across multiple decode calls. if (pStartOfChunk != pCurrentLoc) { MoveMemory(pStartOfChunk, pCurrentLoc, dwParsedSize); } // -1 so we can look at the first byte after the data // in the next pass. pCurrentLoc += dwParsedSize - 1; *pdwBytesRead += dwParsedSize - 1; *pdwBytesWritten += dwParsedSize; pStartOfChunk += dwParsedSize; pCtx->m_dwParsedSize = 0; // Should be CRLF terminated pCtx->SetState(CHUNK_DECODE_STATE_DATA_CRLF); } else { const DWORD dwSlice = dwInBufSize - (DWORD)(pCurrentLoc - pInBuffer); // We're reaching the end of the buffer before // the end of the chunk. Update the parsed // size remaining, so it will be carried over // to the next call. if (pStartOfChunk != pCurrentLoc) { // Skip over preceding size info. MoveMemory(pStartOfChunk, pCurrentLoc, dwSlice); } // -1 so we can look at the first byte after the data // in the next pass. Offset should never be bigger than DWORD since // since that's the biggest chunk we can handle. *pdwBytesWritten += dwSlice; pCtx->m_dwParsedSize -= dwSlice; *pdwBytesRead += dwSlice - 1; pCurrentLoc = pInBuffer + dwInBufSize - 1; } break; } // All remaining states simply parse over the value and // change state, depending on the token. default: { pCtx->SetState(MAP_CHUNK_TOKEN_TO_NEXT_STATE( ePreviousState, chToken)); break; } } (*pdwBytesRead)++; pCurrentLoc++; } if (pCtx->GetState() == CHUNK_DECODE_STATE_ERROR) { DEBUG_PRINT(HTTP, INFO, ("ChunkFilter::Decode entered error state\n" )); hResult = E_FAIL; } quit: DEBUG_LEAVE(hResult == S_OK ? TRUE : FALSE); return hResult; } HRESULT ChunkFilter::Encode( DWORD_PTR dwContext, IN OUT LPBYTE pInBuffer, IN DWORD dwInBufSize, IN OUT LPBYTE *ppOutBuffer, IN OUT LPDWORD pdwOutBufSize, OUT LPDWORD pdwBytesRead, OUT LPDWORD pdwBytesWritten ) /*++ Routine Description: Chunk data for uploading based on the inputted context and current state Arguments: dwContext - registered encode/decode context for this filter pInBuffer - input data buffer to be processed dwInBufSize - byte count of pInBuffer ppOutBuffer - allocated buffer containing encoded/decoded data if not done in place with pInBuffer. pdwOutBufSize - size of allocated output buffer, or 0 if pInBuffer holds the processed data pdwBytesRead - Number of input buffer bytes used pdwBytesWritten - Number of output buffer bytes written Return Value: HRESULT E_NOTIMPL - currently no chunked upload support --*/ { // We don't support chunked uploads...yet return E_NOTIMPL; } HRESULT ChunkFilter::RegisterContext(OUT DWORD_PTR *pdwContext) { DEBUG_ENTER((DBG_HTTP, Dword, "ChunkFilter::RegisterContext", "%#x", pdwContext )); HRESULT hr = S_OK; if (!pdwContext || IsBadWritePtr(pdwContext, sizeof(DWORD_PTR))) { hr = E_POINTER; goto quit; } *pdwContext = (DWORD_PTR) New ChunkDecodeContext; if (!*pdwContext) { hr = E_OUTOFMEMORY; } quit: DEBUG_LEAVE(hr == S_OK ? TRUE : FALSE); return hr; } HRESULT ChunkFilter::UnregisterContext(IN DWORD_PTR dwContext) { DEBUG_ENTER((DBG_HTTP, Dword, "ChunkFilter::UnregisterContext", "%#x", dwContext )); HRESULT hr = S_OK; if (!dwContext) { hr = E_INVALIDARG; goto quit; } delete reinterpret_cast(dwContext); quit: DEBUG_LEAVE(hr == S_OK ? TRUE : FALSE); return hr; } // Always inserts as the beginning of the list BOOL FILTER_LIST::Insert(IN BaseFilter *pFilter, IN DWORD_PTR dwContext) { LPFILTER_LIST_ENTRY pNewEntry; pNewEntry = New FILTER_LIST_ENTRY; if (pNewEntry != NULL) { pNewEntry->pFilter = pFilter; pNewEntry->dwContext = dwContext; pNewEntry->pNext = _pFilterEntry; _pFilterEntry = pNewEntry; _uFilterCount++; return TRUE; } else { return FALSE; } } VOID FILTER_LIST::ClearList() { LPFILTER_LIST_ENTRY pEntry = _pFilterEntry; while (pEntry) { pEntry->pFilter->UnregisterContext(pEntry->dwContext); pEntry = pEntry->pNext; delete _pFilterEntry; _pFilterEntry = pEntry; } _uFilterCount = 0; } DWORD FILTER_LIST::Decode( IN OUT LPBYTE pInBuffer, IN DWORD dwInBufSize, IN OUT LPBYTE *ppOutBuffer, IN OUT LPDWORD pdwOutBufSize, OUT LPDWORD pdwBytesRead, OUT LPDWORD pdwBytesWritten ) { LPFILTER_LIST_ENTRY pEntry = _pFilterEntry; HRESULT hr = S_OK; DWORD dwBytesRead = 0; DWORD dwBytesWritten = 0; LPBYTE pLocalInBuffer = pInBuffer; DWORD dwLocalInBufSize = dwInBufSize; *pdwBytesRead = 0; *pdwBytesWritten = 0; // Loop through filters which should be in the proper order while (pEntry) { dwBytesRead = 0; dwBytesWritten = 0; // At a minimum, we're guaranteed the decode method parses // the input buffer until one of the following is met: // // - Input buffer is fully parsed and processed // - Output buffer is filled up // - Decoder reaches a finished state // - Error occurs while processing input data // // Currently, only 1, 3, and 4 are possible since chunked // transfers are decoded in place. We also don't need // to loop since chunked decoding is always fully done // in the first pass. do { pLocalInBuffer = pLocalInBuffer + dwBytesRead; dwLocalInBufSize = dwLocalInBufSize - dwBytesRead; dwBytesWritten = 0; dwBytesRead = 0; hr = pEntry->pFilter->Decode(pEntry->dwContext, pLocalInBuffer, dwLocalInBufSize, ppOutBuffer, pdwOutBufSize, &dwBytesRead, &dwBytesWritten ); *pdwBytesWritten += dwBytesWritten; *pdwBytesRead += dwBytesRead; if (hr == S_OK && dwBytesRead < dwLocalInBufSize) { // Given the current requirements we shouldn't be here // if there's still input buffer data to process. RIP(FALSE); hr = E_FAIL; goto quit; } } while (hr == S_OK && dwLocalInBufSize > 0 && dwBytesRead < dwLocalInBufSize); pEntry = pEntry->pNext; } INET_ASSERT(hr != S_OK || dwBytesRead == dwLocalInBufSize); quit: switch (hr) { case S_OK: return ERROR_SUCCESS; case E_OUTOFMEMORY: return ERROR_NOT_ENOUGH_MEMORY; default: return ERROR_WINHTTP_INTERNAL_ERROR; } } // // Created by gelldur on 14.06.19. // #include #include #include #include #include #include #include namespace { struct SimpleEvent { std::int64_t value = 0; }; Dexode::AsyncEventBus bus; } // namespace void checkFor(benchmark::State& state) { if(state.thread_index == 0) { Dexode::TokenHolder listener {&bus}; std::uint64_t consumed = 0; listener.listen( [&consumed](const auto& event) { benchmark::DoNotOptimize(consumed += 1); }); for(auto _ : state) { //if(bus.wait()) { bus.consume(); } } state.counters["consumed"] = consumed; } else { for(auto _ : state) { bus.schedule(SimpleEvent {std::chrono::steady_clock::now().time_since_epoch().count()}); } } } BENCHMARK(checkFor)->Threads(2)->MinTime(1)->MeasureProcessCPUTime(); BENCHMARK(checkFor)->Threads(5)->MinTime(1)->MeasureProcessCPUTime(); BENCHMARK(checkFor)->Threads(10)->MinTime(1)->MeasureProcessCPUTime(); #include "bitmatrix.hpp" #include "doctest/doctest.h" TEST_CASE("get column") { BitMatrix<3, 5> bm; bm.setBit(0, 0, false); bm.setBit(1, 0, true); bm.setBit(2, 0, true); bm.setBit(0, 1, true); bm.setBit(1, 1, false); bm.setBit(2, 1, false); bm.setBit(0, 2, true); bm.setBit(1, 2, true); bm.setBit(2, 2, true); bm.setBit(0, 3, false); bm.setBit(1, 3, false); bm.setBit(2, 3, false); bm.setBit(0, 4, false); bm.setBit(1, 4, true); bm.setBit(2, 4, false); CHECK(bm.getColumn(0) == 12); CHECK(bm.getColumn(1) == 21); CHECK(bm.getColumn(2) == 20); } #include "LevelsMap.h" lMap::lMap( sf::RenderWindow *window ) : wMap() { assignScreen(window); //this method is in initiator.h levelcount = 0; pButtonMade = false; if(!tSelectLevel.loadFromFile("assets/levelsMap/selectLevel.png")) { std::cerr << "Unable to load \'assets/levelsMap/selectLevel.png\' texture.\n"; } else { selectLevelSprite.setTexture( tSelectLevel ); } sf::Texture * t = TextureManager::loadTexture("assets/levelsMap/lock.png"); lTextures.push_back( t ); t = TextureManager::loadTexture( "assets/levelsMap/1.png" ); lTextures.push_back( t ); m_levelTracker = 1; areaPushed = false; texturesPushed = false; } lMap::~lMap() { for( unsigned i = 0; i < lTextures.size(); i++ ) { if( lTextures[i] ) { delete lTextures[i]; lTextures[i] = NULL; } } } void lMap::chooseLevels( int& m_levelCount, int levelTracker ) { m_levelTracker = levelTracker; if( !texturesPushed )loadTextures(); renderlTags(); m_levelCount = select(); } void lMap::loadTextures() { if ( m_levelTracker > 1 && m_levelTracker < 8) //we have only eight level tags { //creates path for the textures and pushes them in the lTextures data member for(int i = 2; i <= m_levelTracker; i++) { std::string path = "assets/levelsMap/"; std::stringstream tName; tName << path << i << ".png"; sf::Texture * t = TextureManager::loadTexture( tName.str().c_str() ); lTextures.push_back( t ); } texturesPushed = true; } } int lMap::select() { if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { int MouseX = sf::Mouse::getPosition(*m_window).x; int MouseY = sf::Mouse::getPosition(*m_window).y; for(unsigned i = 0; i < lAreas.size(); i++) { if(lAreas[i].contains(MouseX, MouseY)) { //counting in array starts from zero //std::cerr << "value= " << i+1 << std::endl; return ( i+1 ); } } } return 0; } void lMap::renderlTags() { selectLevelSprite.setPosition(340.f, 50.f); m_window->draw(selectLevelSprite); lSprite.setTexture(*(lTextures[1])); lSprite.setPosition( 200.f, 150.f ); sf::IntRect rect1 = lSprite.getTextureRect(); rect1.left = 200.f; rect1.top = 150.f; m_window->draw(lSprite); if( m_levelTracker > 1 ) lSprite.setTexture( *(lTextures[2]) ); else lSprite.setTexture( *(lTextures[0]) ); lSprite.setPosition( 400.f, 150.f ); sf::IntRect rect2 = lSprite.getTextureRect(); rect2.left = 400.f; rect2.top = 150.f; m_window->draw(lSprite); if( m_levelTracker > 2) lSprite.setTexture(*(lTextures[3])); else lSprite.setTexture(*(lTextures[0])); lSprite.setPosition( 600.f, 150.f ); sf::IntRect rect3 = lSprite.getTextureRect(); rect3.left = 600.f; rect3.top = 150.f; m_window->draw(lSprite); if( m_levelTracker > 3) lSprite.setTexture(*(lTextures[4])); else lSprite.setTexture(*(lTextures[0])); lSprite.setPosition( 800.f, 150.f ); sf::IntRect rect4 = lSprite.getTextureRect(); rect4.left = 800.f; rect4.top = 150.f; m_window->draw(lSprite); if( m_levelTracker > 4) lSprite.setTexture(*(lTextures[5])); else lSprite.setTexture(*(lTextures[0])); lSprite.setPosition( 200.f, 250.f ); sf::IntRect rect5 = lSprite.getTextureRect(); rect5.left = 200.f; rect5.top = 250.f; m_window->draw(lSprite); if( m_levelTracker > 5) lSprite.setTexture(*(lTextures[6])); else lSprite.setTexture(*(lTextures[0])); lSprite.setPosition( 400.f, 250.f ); sf::IntRect rect6 = lSprite.getTextureRect(); rect6.left = 400.f; rect6.top = 250.f; m_window->draw(lSprite); if( !areaPushed ) { lAreas.push_back( rect1 ); if( m_levelTracker > 1) lAreas.push_back( rect2 ); if( m_levelTracker > 2) lAreas.push_back( rect3 ); if( m_levelTracker > 3) lAreas.push_back( rect4 ); if( m_levelTracker > 4) lAreas.push_back( rect5 ); if( m_levelTracker > 5) lAreas.push_back( rect6 ); areaPushed = true; } } spjuanjoc/brainfuck_compiler_cpp // // Created by juan.castellanos on 17/09/20. // //输出2的乘方直到我所输入的数字限制他。 #include int main(void) { int num1; int num2; printf("请输入一个整数:"); scanf_s("%d", &num1); while (num1 <= num2){ printf("%d",num1); num1 = num1 * 2; /* 这个也可以表示为num1 *= 2; */ } printf("\n"); /* 若不是那个则换行*/ return 0; }#include #include using namespace System::IO; BufferStream::BufferStream(u32 limit) : length(0), limit(limit) { indexesCapacity = 4; indexes = Memory::Allocate(indexesCapacity); bufferCapacity = 512; buffer = Memory::Allocate(bufferCapacity); for (u32 i = 0; i < indexesCapacity; i++) indexes[i] = buffer + i * BUFFERSTREAM_BLOCK; } uint32 BufferStream::Read(void* buffer, uint32 count) { uint8* data = (uint8*)buffer; // TODO: Wait if no data available for (uint32 i = 0; i < count; i++) data[i] = queue.Dequeue(); return count; } void BufferStream::Write(void* buffer, u32 count) { byte* data = (byte*)buffer; u32 beginning = Maths::Min(count, BUFFERSTREAM_BLOCK - position); Memory::Copy() } #include "cleMaximumYProjectionKernel.h" namespace cle { void MaximumYProjectionKernel::SetInput(Buffer& x) { this->AddObject(x, "src"); } void MaximumYProjectionKernel::SetOutput(Buffer& x) { this->AddObject(x, "dst_max"); } void MaximumYProjectionKernel::Execute() { this->BuildProgramKernel(); this->SetArguments(); this->EnqueueKernel(); } } // namespace cle /*-------------------------main.cpp------------------------------------------ Main project is "luckyBackup" a backup and sync tool project version : 0.4.7 =============================================================================================================================== =============================================================================================================================== This file is part of "luckyBackup" project Copyright, luckyBackup is distributed under the terms of the GNU General Public License luckyBackup is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luckyBackup 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 luckyBackup. If not, see . developer : luckyb last modified : 11 Sep 2013 =============================================================================================================================== =============================================================================================================================== */ // Perform various initial checks // include the qt libraries needed & the main window header file // show the main window or execute in command line mode #include #include #include "luckybackupwindow.h" #include "commandline.cpp" int main(int argc, char *argv[]) { //arguments test if (!argumentsTest(argc,argv)) return 1; // error code1: something wrong with the command arguments - app fail to start (or just --help or --version given as args) //profile validity check for console mode or gui-no profile specified (will use default) if ( (runImmediately) && (!loadCurrentProfile()) ) return 2; // profile is not valid or does not exist // task list validity check if ( (runImmediately) && (!check_list()) ) return 3; // task list is not ok // declared directories check if ( (runImmediately) && (!check_dirs()) ) return 4; // declared dirs are not ok // declare the rsync & ssh commands for use either at console or gui mode declareRsyncCommand(); if (!console) //execute gui { QApplication app(argc, argv); //translation QString locale = QLocale::system().name(); transDir.setPath(relativeTransDir); if (transDir.exists()) appTranslator.load(QString("luckybackup_") + locale, relativeTransDir); else appTranslator.load(QString("luckybackup_") + locale, systemTransDir); app.installTranslator(&appTranslator); // windows related stuff appPath = app.applicationDirPath(); // This is used for windows app path. It's also causing a ... //"QCoreApplication::applicationDirPath: Please instantiate the QApplication object first" WARNING message rsyncDefaultWinCommand = appPath+"/rsync.exe"; // Holds the default rsync command for windows sshDefaultWinCommand = appPath+"/ssh.exe"; // Holds the default ssh command for windows mapdrive="w"; vshadowDir= appPath; vshadowDefaultDir= appPath; dosdevCommand= appPath+"/dosdev.exe"; dosdevDefaultCommand= appPath+"/dosdev.exe"; cygpathCommand= appPath+"/cygpath.exe"; cygpathDefaultCommand= appPath+"/cygpath.exe"; // end of windows stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ luckyBackupWindow luckybackup; if (!silentMode) luckybackup.show(); return app.exec(); } else //execute luckybackup in console mode { commandline commandLine; return commandLine.result(); //then execute anything necessary } return 1; } // end of main.cpp--------------------------------------------------------- /* “ButterflyPACK” Copyright (c) 2018, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved. If you have questions about your rights to use or distribute this software, please contact Berkeley Lab's Intellectual Property Office at . NOTICE. This Software was developed under funding from the U.S. Department of Energy and the U.S. Government consequently retains certain rights. As such, the U.S. Government has been granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable worldwide license in the Software to reproduce, distribute copies to the public, prepare derivative works, and perform publicly and display publicly, and to permit other to do so. Developers: (Lawrence Berkeley National Lab, Computational Research Division). */ //------------------------------------------------------------------------------ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dC_BPACK_wrapper.h" //------------------------------------------------------------------------------ using namespace std; extern "C" { /////////////////////////////////////////////// ////// BLACS ////////////////////////////////// /////////////////////////////////////////////// void Cblacs_exit(int); } // 2-norm distance inline double dist2(double *x, double *y, int d) { double k = 0.; for (int i = 0; i < d; i++) k += pow(x[i] - y[i], 2.); return k; } // dot product of two real vectors inline double dot_product(double* v, double* u, int d) { double result = 0.0; for (int i = 0; i < d; i++) result += v[i]*u[i]; return result; } // Gauss Kernel inline double Gauss_kernel(double *x, double *y, int d, double h) { double dists; dists = dist2(x, y, d); if(dists> -log(1e-30)*2.0*pow(h,2.0)){ return 0; }else{ return exp(-dists / (2. * h * h)); } } //R^4 kernel inline double K07_kernel(double *x, double *y, int d) { double dists; dists = dist2(x, y, d); return pow(dists,4); } // sqrt(R^2+h) kernel inline double K08_kernel(double *x, double *y, int d, double h) { double dists; dists = dist2(x, y, d); return sqrt(pow(dists,2)+h); } // 1/sqrt(R^2+h) kernel inline double K09_kernel(double *x, double *y, int d, double h) { double dists; dists = dist2(x, y, d); return 1.0/sqrt(pow(dists,2)+h); } // Polynomial kernel (X^tY+h)^2 inline double K10_kernel(double *x, double *y, int d, double h) { double dotp; dotp = dot_product(x, y, d); return pow(dotp+h,2); } // // LR Product of two random matrices // inline double LR_random(int *m, int *n) { // double dotp; // dotp = dot_product(x, y, d); // return pow(dotp+h,2); // } // The object handling kernel parameters and sampling function class C_QuantApp { public: vector _data; int _d = 0; int _n = 0; double _h = 0.; double _l = 0.; int _ker=1; // int _rank_rand; int _n_rand; std::vector _MatU; std::vector _MatV; std::vector _MatFull; std::vector _Hperm; std::vector _iHperm; int _nloc = 0; F2Cptr* bmat; //hierarchical matrix returned by Fortran code F2Cptr* bf; //BF returned by Fortran code F2Cptr* stats; //statistics structure returned by Fortran code F2Cptr* msh; //mesh structure returned by Fortran code F2Cptr* ptree; //process tree returned by Fortran code F2Cptr* option; //option structure returned by Fortran code C_QuantApp() = default; C_QuantApp(vector data, int d, double h, double l, int ker) : _data(move(data)), _d(d), _n(_data.size() / _d), _h(h), _l(l),_ker(ker){ assert(size_t(_n * _d) == _data.size()); } C_QuantApp(int n_rand, int rank_rand, int ker, vector MatU, vector MatV) : _n_rand(n_rand), _rank_rand(rank_rand), _ker(ker), _MatU(move(MatU)), _MatV(move(MatV)){ // cout<<_n_rand<<_rank_rand<<_MatU.size()< MatFull, vector perm) : _n(n), _ker(ker), _MatFull(move(MatFull)), _Hperm(move(perm)){ // cout<<_n_rand<<_rank_rand<<_MatU.size()<Sample(*m-1,*n-1,val); } // The sampling function wrapper required by the Fortran HODLR code inline void C_FuncBZmn(int *m, int *n, double *val, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; // here positve inidex means row, negative index means column int m1, n1; if(*m>0){ m1=*m; n1=-*n; }else{ m1=*n; n1=-*m; } Q->Sample(m1-1,n1-1,val); } // The distance function wrapper required by the Fortran HODLR code inline void C_FuncDistmn(int *m, int *n, double *val, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; } // The compressibility function wrapper required by the Fortran HODLR code inline void C_FuncNearFar(int *m, int *n, int *val, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; } // The extraction sampling function wrapper required by the Fortran HODLR code inline void C_FuncZmnBlock(int* Ninter, int* Nallrows, int* Nallcols, int* Nalldat_loc, int* allrows, int* allcols, double* alldat_loc, int* rowidx,int* colidx, int* pgidx, int* Npmap, int* pmaps, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; d_c_bpack_extractelement(Q->bmat,Q->option,Q->msh,Q->stats,Q->ptree,Ninter,Nallrows, Nallcols, Nalldat_loc, allrows,allcols,alldat_loc,rowidx,colidx,pgidx,Npmap,pmaps); } // The extraction sampling function wrapper required by the Fortran HODLR code inline void C_FuncBZmnBlock(int* Ninter, int* Nallrows, int* Nallcols, int* Nalldat_loc, int* allrows, int* allcols, double* alldat_loc, int* rowidx,int* colidx, int* pgidx, int* Npmap, int* pmaps, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; d_c_bf_extractelement(Q->bf,Q->option,Q->msh,Q->stats,Q->ptree,Ninter,Nallrows, Nallcols, Nalldat_loc, allrows,allcols,alldat_loc,rowidx,colidx,pgidx,Npmap,pmaps); // // for(int ii=0;ii<*Nallrows;ii++)cout<bmat,Q->option,Q->msh,Q->stats,Q->ptree,Ninter,Nallrows, Nallcols, Nalldat_loc, allrows,allcols,alldat_loc,rowidx,colidx,pgidx,Npmap,pmaps); } // The matvec sampling function wrapper required by the Fortran HODLR code inline void C_FuncHMatVec(char const *trans, int *nin, int *nout, int *nvec, double const *xin, double *xout, C2Fptr quant) { C_QuantApp* Q = (C_QuantApp*) quant; d_c_bpack_mult(trans, xin, xout, nin, nout, nvec, Q->bmat,Q->option,Q->stats,Q->ptree); } // The matvec sampling function wrapper required by the Fortran HODLR code inline void C_FuncBMatVec(char const *trans, int *nin, int *nout, int *nvec, double const *xin, double *xout, C2Fptr quant, double *a, double *b) { C_QuantApp* Q = (C_QuantApp*) quant; int cnt = (*nvec)*(*nout); double* xout1 = new double[cnt]; d_c_bpack_mult(trans, xin, xout1, nin, nout, nvec, Q->bmat,Q->option,Q->stats,Q->ptree); for (int ii=0; ii vector write_from_file(string filename) { vector data; ifstream f(filename); string l; while (getline(f, l)) { istringstream sl(l); string s; while (getline(sl, s, ',')) data.push_back(stod(s)); } return data; } // The command line parser for the example related parameters void set_option_from_command_line(int argc, const char* const* cargv,F2Cptr option0) { double opt_d; int opt_i; std::vector> argv_data(argc); std::vector argv(argc); for (int i=0; i> opt_i; d_c_bpack_set_I_option(&option0, "Nmin_leaf", opt_i); } break; case 2: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "tol_comp", opt_d); d_c_bpack_set_D_option(&option0, "tol_rand", opt_d); d_c_bpack_set_D_option(&option0, "tol_Rdetect", opt_d*0.1); } break; case 3: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "tol_rand", opt_d); } break; case 4: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "tol_Rdetect", opt_d); } break; case 5: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "tol_itersol", opt_d); } break; case 6: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "n_iter", opt_i); } break; case 7: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "level_check", opt_i); } break; case 8: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "precon", opt_i); } break; case 9: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "xyzsort", opt_i); } break; case 10: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "LRlevel", opt_i); } break; case 11: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "ErrFillFull", opt_i); } break; case 12: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "BACA_Batch", opt_i); } break; case 13: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "RecLR_leaf", opt_i); } break; case 14: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "nogeo", opt_i); } break; case 15: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "less_adapt", opt_i); } break; case 16: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "ErrSol", opt_i); } break; case 17: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "LR_BLK_NUM", opt_i); } break; case 18: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "rank0", opt_i); } break; case 19: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "rankrate", opt_i); } break; case 20: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "itermax", opt_i); } break; case 21: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "powiter", opt_i); } break; case 22: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "ILU", opt_i); } break; case 23: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "Nbundle", opt_i); } break; case 24: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "near_para", opt_d); } break; case 25: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "format", opt_i); } break; case 26: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "verbosity", opt_i); } break; case 27: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "rmax", opt_i); } break; case 28: { std::istringstream iss(optarg); iss >> opt_d; d_c_bpack_set_D_option(&option0, "sample_para", opt_d); } break; case 29: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "pat_comp", opt_i); } break; case 30: { std::istringstream iss(optarg); iss >> opt_i; d_c_bpack_set_I_option(&option0, "knn", opt_i); } break; default: break; } } } //////////////////////////////////////////////////////////////////////////////// // --------------------------- Main Code Starts Here ------------------------ // int main(int argc, char* argv[]) { int myrank, size; // Store values of processor rank and total no of procs requestedss int master_rank = 0; MPI_Init(&argc, &argv); // Initialize MPI, called only once MPI_Comm_size(MPI_COMM_WORLD, &size); // Get no of procs MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // Get no of procs MPI_Op op; double h=0.1; //kernel parameter double lambda=10.0 ; //kernel parameter int ker=1 ; // kernel choice int Npo=5000; // matrix size int Ndim=1; //data dimension int rank_rand=100; //rank of the random LR product double starttime, endtime; double* dat_ptr; int* nns_ptr; int nogeo; // 1: no geometrical information passed to hodlr, dat_ptr and Ndim are dummy int Nmin=200; //finest leafsize double tol=1e-4; //compression tolerance double sample_para=2.0; //oversampling factor in entry evaluation int com_opt=5; //1:SVD 2:RRQR 3:ACA 4:BACA 5:BACA_improved 6:Pseudo-skeleton int sort_opt=1; //0:natural order 1:kd-tree 2:cobble-like ordering 3:gram distance-based cobble-like ordering int checkerr = 0; //1: check compression quality int batch = 100; //batch size for BACA int bnum = 1; //sqrt of #of subblocks in H-BACA int knn=0; //k nearest neighbours stored per point C_QuantApp *quant_ptr; int v_major,v_minor,v_bugfix; //version numbers int tst = 1; int lrlevel=0; int nlevel = 0; // 0: tree level, nonzero if a tree is provided int* tree = new int[(int)pow(2,nlevel)]; //user provided array containing size of each leaf node, not used if nlevel=0 string trainfile("../EXAMPLE/KRR_DATA/susy_10Kn"); string fullmatfile("../EXAMPLE/FULLMAT_DATA/FHODLR_colmajor_real_double_40000x40000.dat"); string leaffile("../EXAMPLE/FULLMAT_DATA/leafs_40000_noheader.dat"); tree[0] = Npo; //getting the example configurations from command line std::vector> argv_data(argc); std::vector argv1(argc); for (int i=0; i> tst; } break; case 2: { std::istringstream iss(optarg); iss >> Npo; } break; case 3: { std::istringstream iss(optarg); iss >> Ndim; } break; case 4: { std::istringstream iss(optarg); iss >> ker; } break; case 5: { std::istringstream iss(optarg); iss >> h; } break; case 6: { std::istringstream iss(optarg); iss >> lambda; } break; case 7: { std::istringstream iss(optarg); iss >> rank_rand; } break; case 8: { std::istringstream iss(optarg); iss >> trainfile; } break; case 9: { std::istringstream iss(optarg); iss >> nlevel; } break; case 10: { std::istringstream iss(optarg); iss >> leaffile; } break; case 11: { std::istringstream iss(optarg); iss >> fullmatfile; } break; case 'h': { std::cout<<" tst=1: testing data sets with csv formats with ker 1:5 \n tst=2: testing randomly generated data sets with ker 1:5 \n tst=3: testing a LR product of two random matrices with ker=6 \n tst=4: testing full matrix and leaves stored in file with ker=7 "< data_train = write_from_file(trainfile + "_train.csv"); assert(Npo == data_train.size() / Ndim); quant_ptr=new C_QuantApp(data_train, Ndim, h, lambda,ker); dat_ptr = new double[data_train.size()]; for(int ii=0;ii data_train(Npo*Ndim); for (int i=0; i matU(Npo*rank_rand); for (int i=0; i matV(Npo*rank_rand); for (int i=0; i t1((int)pow(2,nlevel)); vector matFull(Npo*Npo); vector perm(Npo); if(myrank==master_rank){ // vector matFull1(Npo*Npo); ifstream f(fullmatfile, ios::binary); f.read((char*)matFull.data(), sizeof(double)*Npo*Npo); // perm = write_from_file("../EXAMPLE/FULLMAT_DATA/sorder_40000.dat"); // vector perm1=perm; // for(int ii=0;ii(leaffile); // std::cout<bmat=&bmat; quant_ptr1->msh=&msh; quant_ptr1->ptree=&ptree; quant_ptr1->stats=&stats; quant_ptr1->option=&option; d_c_bpack_createptree(&size, groups, &Fcomm, &ptree1); d_c_bpack_copyoption(&option,&option1); d_c_bpack_createstats(&stats1); d_c_bpack_set_I_option(&option1, "nogeo", 1); // no geometrical information d_c_bpack_set_I_option(&option1, "xyzsort", 0);// natural ordering d_c_bpack_set_I_option(&option1, "format", 1);// HODLR format int Npo1 = Npo; int myseg1=0; // local number of unknowns int* perms1 = new int[Npo1]; //permutation vector returned by HODLR //tree1 and nlevel1 should be provided by the caller, otherwise natural ordering is used int nlevel1 = 0; // 0: tree level, nonzero if a tree is provided int* tree1 = new int[(int)pow(2,nlevel1)]; //user provided array containing size of each leaf node, not used if nlevel=0 tree1[0] = Npo1; int Ndim1=0; //data dimension double* dat_ptr1; d_c_bpack_construct_init(&Npo1, &Ndim1, dat_ptr1, nns_ptr,&nlevel1, tree1, perms1, &myseg1, &bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1, &C_FuncDistmn, &C_FuncNearFar, quant_ptr); d_c_bpack_construct_matvec_compute(&bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1, &C_FuncHMatVec, quant_ptr1); if(myrank==master_rank)std::cout<<"Printing stats of the second HODLR: "<bmat=&bmat; quant_ptr1->msh=&msh; quant_ptr1->ptree=&ptree; quant_ptr1->stats=&stats; quant_ptr1->option=&option; d_c_bpack_createptree(&size, groups, &Fcomm, &ptree1); d_c_bpack_copyoption(&option,&option1); d_c_bpack_createstats(&stats1); d_c_bpack_set_I_option(&option1, "nogeo", 1); // no geometrical information d_c_bpack_set_I_option(&option1, "xyzsort", 0);// natural ordering d_c_bpack_set_I_option(&option1, "format", 1);// HODLR format d_c_bpack_set_I_option(&option1, "elem_extract", 1);// use element extraction perms1 = new int[Npo1]; //permutation vector returned by HODLR //tree1 and nlevel1 should be provided by the caller, otherwise natural ordering is used nlevel1 = 0; // 0: tree level, nonzero if a tree is provided tree1 = new int[(int)pow(2,nlevel1)]; //user provided array containing size of each leaf node, not used if nlevel=0 tree1[0] = Npo1; // d_c_bpack_construct_matvec_init(&Npo1, &nlevel1, tree1, perms1, &myseg1, &bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1); // d_c_bpack_construct_matvec_compute(&bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1, &C_FuncHMatVec, quant_ptr1); d_c_bpack_construct_init(&Npo1, &Ndim, dat_ptr, nns_ptr,&nlevel1, tree1, perms1, &myseg1, &bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1, &C_FuncDistmn, &C_FuncNearFar, quant_ptr); d_c_bpack_construct_element_compute(&bmat1, &option1, &stats1, &msh1, &kerquant1, &ptree1, &C_FuncZmn, &C_FuncZmnBlock, quant_ptr1); if(myrank==master_rank)std::cout<<"Printing stats of the third HODLR: "<bmat=&bmat; quant_ptr2->msh=&msh; quant_ptr2->ptree=&ptree; quant_ptr2->stats=&stats; quant_ptr2->option=&option; d_c_bpack_createptree(&size, groups, &Fcomm, &ptree2); d_c_bpack_copyoption(&option,&option2); d_c_bpack_createstats(&stats2); d_c_bpack_set_I_option(&option2, "nogeo", 1); // no geometrical information d_c_bpack_set_I_option(&option2, "xyzsort", 0);// natural ordering int M = Npo; int N = Npo; int myrow=0; // local number of rows int mycol=0; // local number of columns d_c_bf_construct_init(&M, &N, &myrow, &mycol, nns_ptr, nns_ptr, &msh, &msh, &bf, &option2, &stats2, &msh1, &kerquant2, &ptree2,&C_FuncDistmn, &C_FuncNearFar, quant_ptr2); d_c_bf_construct_matvec_compute(&bf, &option2, &stats2, &msh1, &kerquant2, &ptree2, &C_FuncBMatVec, quant_ptr2); if(myrank==master_rank)std::cout<<"Printing stats of the fourth BF: "<bf=&bf; quant_ptr2->msh=&msh1; quant_ptr2->ptree=&ptree; quant_ptr2->stats=&stats; quant_ptr2->option=&option; quant_ptr2->_n=Npo; d_c_bpack_createptree(&size, groups, &Fcomm, &ptree2); d_c_bpack_copyoption(&option,&option2); d_c_bpack_createstats(&stats2); d_c_bpack_set_I_option(&option2, "nogeo", 1); // no geometrical information d_c_bpack_set_I_option(&option2, "xyzsort", 0);// natural ordering d_c_bpack_set_I_option(&option2, "elem_extract", 1);// use block-wise element extraction d_c_bf_construct_init(&M, &N, &myrow, &mycol, nns_ptr, nns_ptr, &msh, &msh, &bf2, &option2, &stats2, &msh2, &kerquant2, &ptree2,&C_FuncDistmn, &C_FuncNearFar, quant_ptr2); d_c_bf_construct_element_compute(&bf2, &option2, &stats2, &msh2, &kerquant2, &ptree2, &C_FuncBZmn, &C_FuncBZmnBlock, quant_ptr2); // C_FuncBZmn is not referenced since elem_extract=1 if(myrank==master_rank)std::cout<<"Printing stats of the fifth BF: "< #include #include #include "net/third_party/uri_template/uri_template.h" #include "third_party/abseil-cpp/absl/container/flat_hash_map.h" #include "third_party/abseil-cpp/absl/container/flat_hash_set.h" #include "third_party/abseil-cpp/absl/strings/str_cat.h" #include "third_party/abseil-cpp/absl/strings/str_replace.h" #include "third_party/abseil-cpp/absl/strings/string_view.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/url_canon.h" #include "url/url_util.h" namespace quiche { bool ExpandURITemplateImpl( const std::string& uri_template, const absl::flat_hash_map& parameters, std::string* target, absl::flat_hash_set* vars_found) { std::unordered_map std_parameters; for (const auto& pair : parameters) { std_parameters[pair.first] = pair.second; } std::set std_vars_found; const bool result = uri_template::Expand(uri_template, std_parameters, target, vars_found != nullptr ? &std_vars_found : nullptr); if (vars_found != nullptr) { for (const std::string& var_found : std_vars_found) { vars_found->insert(var_found); } } return result; } absl::optional AsciiUrlDecodeImpl(absl::string_view input) { std::string input_encoded = std::string(input); url::RawCanonOutputW<1024> canon_output; url::DecodeURLEscapeSequences(input_encoded.c_str(), input_encoded.length(), url::DecodeURLMode::kUTF8, &canon_output); std::string output; output.reserve(canon_output.length()); for (int i = 0; i < canon_output.length(); i++) { const uint16_t c = reinterpret_cast(canon_output.data())[i]; if (c > std::numeric_limits::max()) { return absl::nullopt; } output += static_cast(c); } return output; } } // namespace quiche /* * This is a part of the BugTrap package. * Copyright (c) 2005-2007 IntelleSoft. * All rights reserved. * * Description: Wait dialog. * Author: . * * This source code is only intended as a supplement to the * BugTrap package reference and related electronic documentation * provided with the product. See these sources for detailed * information regarding the BugTrap package. */ #include "StdAfx.h" #include "resource.h" #include "WaitDlg.h" #include "BugTrapUtils.h" #include "ResManager.h" #include "Globals.h" #ifdef _DEBUG #define new DEBUG_NEW #endif /** * @addtogroup BugTrapUI BugTrap Graphical User Interface * @{ */ /** * @param hwndParent - parent window handle. */ CWaitDialog::CWaitDialog(HWND hwndParent) { InitVars(); BeginWait(hwndParent); } /** * @param hwndParent - parent window handle. */ void CWaitDialog::BeginWait(HWND hwndParent) { _ASSERTE(m_hwndWait == NULL && m_hOldCursor == NULL); m_hOldCursor = SetCursor(g_pResManager->m_hWaitCursor); m_hwndWait = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_WAIT_DLG), hwndParent, NULL); if (m_hwndWait) { CenterWindow(m_hwndWait, hwndParent); ShowWindow(m_hwndWait, SW_SHOW); UpdateWindow(m_hwndWait); } } void CWaitDialog::EndWait(void) { if (m_hwndWait) { DestroyWindow(m_hwndWait); m_hwndWait = NULL; } if (m_hOldCursor) { SetCursor(m_hOldCursor); m_hOldCursor = NULL; } } /** @} */ // Copyright (c) 2015-2021 // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include #include namespace hpx { namespace util { namespace functional { /////////////////////////////////////////////////////////////////////////// struct segmented_iterator_segment { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::segment_iterator; template type operator()(Iter iter) const { return traits::segmented_iterator_traits::segment( iter); } }; }; struct segmented_iterator_local { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::local_iterator; template type operator()(Iter iter) const { return traits::segmented_iterator_traits::local(iter); } }; }; struct segmented_iterator_begin { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::local_iterator; template type operator()(SegIter iter) const { return traits::segmented_iterator_traits::begin(iter); } }; }; struct segmented_iterator_end { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::local_iterator; template type operator()(SegIter iter) const { return traits::segmented_iterator_traits::end(iter); } }; }; struct segmented_iterator_local_begin { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::local_raw_iterator; template type operator()(LocalSegIter iter) const { return traits::segmented_iterator_traits::begin(iter); } }; }; struct segmented_iterator_local_end { template struct apply { using type = typename traits::segmented_iterator_traits< Iterator>::local_raw_iterator; template type operator()(LocalSegIter iter) const { return traits::segmented_iterator_traits::end(iter); } }; }; }}} // namespace hpx::util::functional dzeromsk/goma // Copyright 2015 The Goma 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 "http.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "callback.h" #include "compiler_proxy_info.h" #include "compiler_specific.h" #include "file_helper.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "lockhelper.h" #include "mock_socket_factory.h" #include "mypath.h" #include "path.h" #include "scoped_tmp_file.h" #include "socket_factory.h" #include "worker_thread.h" namespace devtools_goma { TEST(NetworkErrorStatusTest, Basic) { HttpClient::NetworkErrorStatus status(absl::Seconds(30)); EXPECT_FALSE(status.NetworkErrorStartedTime().has_value()); EXPECT_TRUE(status.OnNetworkErrorDetected(absl::FromTimeT(100))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(100, absl::ToTimeT(*status.NetworkErrorStartedTime())); // Don't recover for 30 seconds. EXPECT_FALSE(status.OnNetworkRecovered(absl::FromTimeT(110))); EXPECT_EQ(100, absl::ToTimeT(*status.NetworkErrorStartedTime())); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_FALSE(status.OnNetworkRecovered(absl::FromTimeT(120))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(100, absl::ToTimeT(*status.NetworkErrorStartedTime())); EXPECT_FALSE(status.OnNetworkRecovered(absl::FromTimeT(129))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(100, absl::ToTimeT(*status.NetworkErrorStartedTime())); // Now recovered. EXPECT_TRUE(status.OnNetworkRecovered(absl::FromTimeT(131))); EXPECT_FALSE(status.NetworkErrorStartedTime().has_value()); // Another network issue. (time=200) EXPECT_TRUE(status.OnNetworkErrorDetected(absl::FromTimeT(200))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(200, absl::ToTimeT(*status.NetworkErrorStartedTime())); EXPECT_FALSE(status.OnNetworkRecovered(absl::FromTimeT(210))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(200, absl::ToTimeT(*status.NetworkErrorStartedTime())); // Network error on time=220, so postpone to recover until time=250. EXPECT_FALSE(status.OnNetworkErrorDetected(absl::FromTimeT(220))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(200, absl::ToTimeT(*status.NetworkErrorStartedTime())); EXPECT_FALSE(status.OnNetworkRecovered(absl::FromTimeT(249))); EXPECT_TRUE(status.NetworkErrorStartedTime().has_value()); EXPECT_EQ(200, absl::ToTimeT(*status.NetworkErrorStartedTime())); // Now we consider the network is recovered. EXPECT_TRUE(status.OnNetworkRecovered(absl::FromTimeT(251))); EXPECT_FALSE(status.NetworkErrorStartedTime().has_value()); } TEST(HttpClientOptions, InitFromURLChromeInfraAuth) { HttpClient::Options options; EXPECT_TRUE(options.InitFromURL( "https://chrome-infra-auth.appspot.com/auth/api/v1/server/oauth_config")); EXPECT_EQ("chrome-infra-auth.appspot.com", options.dest_host_name); EXPECT_EQ(443, options.dest_port); EXPECT_TRUE(options.use_ssl); EXPECT_EQ("/auth/api/v1/server/oauth_config", options.url_path_prefix); } TEST(HttpClientOptions, InitFromURLGCEMetadata) { HttpClient::Options options; EXPECT_TRUE(options.InitFromURL( "http://metadata/computeMetadata/v1/instance/service-accounts/")); EXPECT_EQ("metadata", options.dest_host_name); EXPECT_EQ(80, options.dest_port); EXPECT_FALSE(options.use_ssl); EXPECT_EQ("/computeMetadata/v1/instance/service-accounts/", options.url_path_prefix); } TEST(HttpClientOptions, InitFromURLGoogleOAuth2TokenURI) { HttpClient::Options options; EXPECT_TRUE(options.InitFromURL("https://oauth2.googleapis.com/token")); EXPECT_EQ("oauth2.googleapis.com", options.dest_host_name); EXPECT_EQ(443, options.dest_port); EXPECT_TRUE(options.use_ssl); EXPECT_EQ("/token", options.url_path_prefix); } TEST(HttpClientOptions, InitFromURLWithExplicitPort) { HttpClient::Options options; EXPECT_TRUE(options.InitFromURL( "http://example.com:8080/foo/bar")); EXPECT_EQ("example.com", options.dest_host_name); EXPECT_EQ(8080, options.dest_port); EXPECT_FALSE(options.use_ssl); EXPECT_EQ("/foo/bar", options.url_path_prefix); } TEST(HttpClientOptions, ProxyOptionsWitHTTP) { HttpClient::Options options; options.proxy_host_name = "proxy-example.com"; options.proxy_port = 1234; EXPECT_TRUE(options.InitFromURL("http://example.com")); EXPECT_EQ("proxy-example.com", options.SocketHost()); EXPECT_EQ(1234, options.SocketPort()); EXPECT_EQ("example.com", options.Host()); EXPECT_EQ("http://example.com:80/foo", options.RequestURL("foo")); } TEST(HttpClientOptions, ProxyOptionsWitHTTPS) { HttpClient::Options options; options.proxy_host_name = "proxy-example.com"; options.proxy_port = 1234; EXPECT_TRUE(options.InitFromURL("https://example.com")); EXPECT_EQ("proxy-example.com", options.SocketHost()); EXPECT_EQ(1234, options.SocketPort()); EXPECT_EQ("example.com", options.Host()); EXPECT_EQ("/foo", options.RequestURL("foo")); } class HttpClientTest : public ::testing::Test { protected: class TestContext { public: enum class State { INIT, CALL, DONE }; TestContext(HttpClient* client, HttpClient::Request* req, HttpClient::Response* resp, OneshotClosure* callback) : client_(client), req_(req), resp_(resp), callback_(callback) { } HttpClient* client_; HttpClient::Request* req_; HttpClient::Response* resp_; OneshotClosure* callback_; HttpClient::Status status_; State state_ = State::INIT; }; void SetUp() override { wm_ = absl::make_unique(); wm_->Start(1); pool_ = wm_->StartPool(1, "test"); mock_server_ = absl::make_unique(wm_.get()); ASSERT_EQ(0, OpenSocketPairForTest(socks_)); } void TearDown() override { mock_server_.reset(); wm_->Finish(); wm_.reset(); pool_ = -1; } void ServerReceive(absl::string_view req, string* req_buf) { req_buf->resize(req.size()); mock_server_->ServerRead(socks_[0], req_buf); } void ServerResponse(absl::string_view resp) { mock_server_->ServerWrite(socks_[0], string(resp)); } void ServerClose() { mock_server_->ServerClose(socks_[0]); } void ServerWait(absl::Duration duration) { mock_server_->ServerWait(duration); } std::string ExpectedRequest( absl::string_view method, absl::string_view host) { return absl::StrCat(method, " / HTTP/1.1\r\n", "Host: ", host, "\r\n", "User-Agent: ", kUserAgentString, "\r\n", "Content-Type: text/plain\r\n", "Content-Length: 0\r\n", "Connection: close\r\n", "\r\n"); } std::string ExpectedRequestWithBody(absl::string_view method, absl::string_view host, absl::string_view body) { return absl::StrCat(method, " / HTTP/1.1\r\n", "Host: ", host, "\r\n", "User-Agent: ", kUserAgentString, "\r\n", "Content-Type: text/plain\r\n", "Content-Length: ", body.size(), "\r\n", "Connection: close\r\n", "\r\n", body); } std::unique_ptr NewHttpClient(absl::string_view host, int port) { std::unique_ptr socket_factory( absl::make_unique(socks_[1], &socket_status_)); socket_factory->set_dest(absl::StrCat(host, ":", port)); socket_factory->set_host_name(string(host)); socket_factory->set_port(port); HttpClient::Options options; options.InitFromURL(absl::StrCat("http://", host, "/")); options.socket_read_timeout = absl::Milliseconds(200); return absl::make_unique( std::move(socket_factory), nullptr, options, wm_.get()); } void RunTest(TestContext* tc) { wm_->RunClosureInPool( FROM_HERE, pool_, NewCallback( this, &HttpClientTest::DoTest, tc), WorkerThread::PRIORITY_LOW); } void DoTest(TestContext* tc) { tc->client_->DoAsync(tc->req_, tc->resp_, &tc->status_, tc->callback_); AutoLock lock(&mu_); tc->state_ = TestContext::State::CALL; cond_.Signal(); } void Wait(TestContext* tc) { wm_->RunClosureInPool( FROM_HERE, pool_, NewCallback( this, &HttpClientTest::DoWait, tc), WorkerThread::PRIORITY_LOW); } void DoWait(TestContext* tc) { tc->client_->Wait(&tc->status_); AutoLock lock(&mu_); tc->state_ = TestContext::State::DONE; cond_.Signal(); } OneshotClosure* NewDoneCallback(bool* done) { { AutoLock lock(&mu_); *done = false; } return NewCallback( this, &HttpClientTest::DoneCallback, done); } void DoneCallback(bool* done) { AutoLock lock(&mu_); *done = true; cond_.Signal(); } void ExpectSocketClosed(bool expect_closed) { if (expect_closed) { EXPECT_FALSE(socket_status_.is_owned()); EXPECT_TRUE(socket_status_.is_closed()); EXPECT_FALSE(socket_status_.is_released()); } else { EXPECT_TRUE(socket_status_.is_owned()); EXPECT_FALSE(socket_status_.is_closed()); EXPECT_TRUE(socket_status_.is_released()); } } std::unique_ptr wm_; int pool_ = -1; std::unique_ptr mock_server_; MockSocketFactory::SocketStatus socket_status_; int socks_[2]; mutable Lock mu_; ConditionVariable cond_; }; TEST_F(HttpClientTest, GetNoContentLengthConnectionClose) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "ok"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("ok", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetNoContentLengthConnectionCloseSlowBody) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); ServerResponse( "ok"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("ok", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetNoContentLengthConnectionCloseEmptyBody) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetEmptyBody) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 0\r\n\r\n"); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(false); } TEST_F(HttpClientTest, GetResponse) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 8\r\n\r\n" "response"); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("response", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(false); } TEST_F(HttpClientTest, GetConnectionClose) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 8\r\n\r\n" "re"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_NE(OK, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RECEIVING_RESPONSE, tc.status_.state); EXPECT_EQ(200, tc.status_.http_return_code); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetTimedOut) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); tc.status_.timeouts.push_back(absl::Milliseconds(100)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } LOG(INFO) << "request sent"; ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 8\r\n\r\n" "re"); ServerWait(absl::Milliseconds(1500)); ServerResponse( "sponse"); LOG(INFO) << "waiting response"; Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(ERR_TIMEOUT, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RECEIVING_RESPONSE, tc.status_.state); EXPECT_EQ(0, tc.status_.http_return_code); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, Get204) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 204 No Content\r\n" "\r\n"); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(OK, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(204, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, Get302) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 302 Found\r\n" "Content-Type: text/plain\r\n" "Location: http://example.com/dos_attack\r\n" "Connection: close\r\n" "\r\n" "redirect to http://example.com/dos_attack\r\n"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(FAIL, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(302, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, Get401) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 401 Unauthorized\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n" "\r\n" "unauthorized request\r\n"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(FAIL, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(401, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, Get502) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 502 Bad Gateway\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n" "\r\n" "server error\r\n"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(FAIL, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(HttpClient::Status::RESPONSE_RECEIVED, tc.status_.state); EXPECT_EQ(502, tc.status_.http_return_code); EXPECT_EQ("", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetFileDownload) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); ScopedTmpDir tmpdir("http_unittest_get_filedownload"); EXPECT_TRUE(tmpdir.valid()); string resp_file = file::JoinPath(tmpdir.dirname(), "resp"); LOG(INFO) << "download to " << resp_file; HttpFileDownloadResponse resp(resp_file, 0644); TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "ok"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(0, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(200, tc.status_.http_return_code); string resp_data; EXPECT_TRUE(ReadFileToString(resp_file, &resp_data)); EXPECT_EQ("ok", resp_data); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, GetFileDownloadFail) { const string req_expected = ExpectedRequest("GET", "example.com"); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "GET", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); ScopedTmpDir tmpdir("http_unittest_get_filedownload"); EXPECT_TRUE(tmpdir.valid()); string resp_file = file::JoinPath(tmpdir.dirname(), "resp"); LOG(INFO) << "download to " << resp_file; HttpFileDownloadResponse resp(resp_file, 0644); TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "no such file exists"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(FAIL, tc.status_.err); EXPECT_NE("", tc.status_.err_message); EXPECT_EQ(404, tc.status_.http_return_code); string resp_data; EXPECT_FALSE(ReadFileToString(resp_file, &resp_data)); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, Post) { constexpr absl::string_view kBody = "request body data"; const string req_expected = ExpectedRequestWithBody("POST", "example.com", kBody); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; HttpRequest req; client->InitHttpRequest(&req, "POST", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); req.SetBody(string(kBody)); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "ok"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(0, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("ok", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, PostUpload) { constexpr absl::string_view kBody = "request body data"; const string req_expected = ExpectedRequestWithBody("POST", "example.com", kBody); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; ScopedTmpDir tmpdir("http_unittest_post_upload"); EXPECT_TRUE(tmpdir.valid()); string req_file = file::JoinPath(tmpdir.dirname(), "req"); ASSERT_TRUE(WriteStringToFile(kBody, req_file)); LOG(INFO) << "upload from " << req_file; HttpFileUploadRequest req; client->InitHttpRequest(&req, "POST", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); req.SetBodyFile(req_file, kBody.size()); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); EXPECT_FALSE(tc.status_.finished); } ServerResponse( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "ok"); ServerClose(); Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_EQ(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_EQ(0, tc.status_.err); EXPECT_EQ("", tc.status_.err_message); EXPECT_EQ(200, tc.status_.http_return_code); EXPECT_EQ("ok", resp.parsed_body()); } client->WaitNoActive(); ExpectSocketClosed(true); } TEST_F(HttpClientTest, PostUploadFailFileNotFound) { constexpr absl::string_view kBody = "request body data"; const string req_expected = ExpectedRequestWithBody("POST", "example.com", kBody); string req_buf; ServerReceive(req_expected, &req_buf); std::unique_ptr client(NewHttpClient("example.com", 80)); bool done = false; ScopedTmpDir tmpdir("http_unittest_post_upload"); EXPECT_TRUE(tmpdir.valid()); string req_file = file::JoinPath(tmpdir.dirname(), "req"); LOG(INFO) << "upload from " << req_file; HttpFileUploadRequest req; client->InitHttpRequest(&req, "POST", ""); req.SetContentType("text/plain"); req.AddHeader("Connection", "close"); req.SetBodyFile(req_file, kBody.size()); HttpResponse resp; TestContext tc(client.get(), &req, &resp, NewDoneCallback(&done)); RunTest(&tc); { AutoLock lock(&mu_); while (tc.state_ != TestContext::State::CALL) { cond_.Wait(&mu_); } EXPECT_TRUE(tc.status_.connect_success); // might be finished because it failed to create request stream // or not yet. } Wait(&tc); { AutoLock lock(&mu_); while (!done) { cond_.Wait(&mu_); } while (tc.state_ != TestContext::State::DONE) { cond_.Wait(&mu_); } EXPECT_NE(req_expected, req_buf); EXPECT_TRUE(tc.status_.connect_success); EXPECT_TRUE(tc.status_.finished); EXPECT_NE(0, tc.status_.err); EXPECT_NE("", tc.status_.err_message); } client->WaitNoActive(); ExpectSocketClosed(true); } bool HandleResponseBody(HttpClient::Response::Body* body, absl::string_view response) { bool need_more = true; while (need_more) { char* ptr; int size; body->Next(&ptr, &size); if (response.size() <= size) { size = response.size(); } memcpy(ptr, response.data(), size); response.remove_prefix(size); bool should_end = (size == 0 && response.empty()); switch (body->Process(size)) { case HttpClient::Response::Body::State::Error: return false; case HttpClient::Response::Body::State::Ok: if (!response.empty()) { return false; } need_more = false; break; case HttpClient::Response::Body::State::Incomplete: if (should_end) { return false; } continue; } } return true; } std::string ReadAllFromZeroCopyInputStream( google::protobuf::io::ZeroCopyInputStream* input) { std::string data; const void* buffer; int size; while (input->Next(&buffer, &size)) { data += std::string(static_cast(buffer), size); } return data; } class HttpResponseBodyTest : public testing::Test { protected: bool ParsedBody( size_t content_length, bool is_chunked, EncodingType encoding_type, absl::string_view response, std::string* parsed_body) { std::unique_ptr body = absl::make_unique( content_length, is_chunked, encoding_type); if (body == nullptr) { return false; } parsed_body->clear(); if (!HandleResponseBody(body.get(), response)) { return false; } std::unique_ptr input = body->ParsedStream(); if (input == nullptr) { return false; } *parsed_body = ReadAllFromZeroCopyInputStream(input.get()); return true; } }; TEST_F(HttpResponseBodyTest, NoContentLength) { static constexpr absl::string_view kBody = "response body"; std::string parsed_body; EXPECT_TRUE(ParsedBody(string::npos, false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ(kBody, parsed_body); } TEST_F(HttpResponseBodyTest, ContentLength) { static constexpr absl::string_view kBody = "response body"; std::string parsed_body; EXPECT_FALSE(ParsedBody(kBody.size()-1, false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_TRUE(ParsedBody(kBody.size(), false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ(kBody, parsed_body); } TEST_F(HttpResponseBodyTest, Chunked) { static constexpr absl::string_view kBody = "3\r\nabc\r\n" "0d\r\ndefghijklmnop\r\n" "a\r\nqrstuvwxyz\r\n" "0\r\n\r\n"; std::string parsed_body; EXPECT_FALSE(ParsedBody(string::npos, true, EncodingType::NO_ENCODING, kBody.substr(0, kBody.size()-1), &parsed_body)); EXPECT_TRUE(ParsedBody(string::npos, true, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", parsed_body); } // TODO: test for ENCODING_DEFLATE, ENCODING_LZMA2 class HttpFileDownloadBodyTest : public testing::Test { protected: bool ParsedBody( size_t content_length, bool is_chunked, EncodingType encoding_type, absl::string_view response, std::string* parsed_body) { ScopedTmpDir tmpdir("http_http_file_download_body_test"); if (!tmpdir.valid()) { LOG(ERROR) << "failed to create tmpdir"; return false; } string tempfile = file::JoinPath(tmpdir.dirname(), "out"); ScopedFd fd(ScopedFd::Create(tempfile, 0644)); auto body = absl::make_unique( std::move(fd), content_length, is_chunked, encoding_type); if (body == nullptr) { return false; } parsed_body->clear(); if (!HandleResponseBody(body.get(), response)) { return false; } body.reset(); if (!ReadFileToString(tempfile, parsed_body)) { LOG(ERROR) << "failed to read tempfile:" << tempfile; return false; } return true; } }; TEST_F(HttpFileDownloadBodyTest, NoContentLength) { static constexpr absl::string_view kBody = "response body"; std::string parsed_body; EXPECT_TRUE(ParsedBody(string::npos, false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ(kBody, parsed_body); } TEST_F(HttpFileDownloadBodyTest, ContentLength) { static constexpr absl::string_view kBody = "response body"; std::string parsed_body; EXPECT_FALSE(ParsedBody(kBody.size()-1, false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_TRUE(ParsedBody(kBody.size(), false, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ(kBody, parsed_body); } TEST_F(HttpFileDownloadBodyTest, BinaryFile) { std::string my_pathname = GetMyPathname(); std::string binary_file; ASSERT_TRUE(ReadFileToString(my_pathname, &binary_file)) << my_pathname; std::string parsed_body; EXPECT_TRUE(ParsedBody(binary_file.size(), false, EncodingType::NO_ENCODING, binary_file, &parsed_body)); EXPECT_EQ(binary_file, parsed_body); } TEST_F(HttpFileDownloadBodyTest, Chunked) { static constexpr absl::string_view kBody = "3\r\nabc\r\n" "0d\r\ndefghijklmnop\r\n" "a\r\nqrstuvwxyz\r\n" "0\r\n\r\n"; std::string parsed_body; EXPECT_FALSE(ParsedBody(string::npos, true, EncodingType::NO_ENCODING, kBody.substr(0, kBody.size()-1), &parsed_body)); EXPECT_TRUE(ParsedBody(string::npos, true, EncodingType::NO_ENCODING, kBody, &parsed_body)); EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", parsed_body); } // TODO: test for ENCODING_DEFLATE, ENCODING_LZMA2 } // namespace devtools_goma bernardocarvalho/esp32-bme680 /** * @file main.cp * @brief ESP32 software to mesure Air quality * @author / IPFN * @date 29/01/2022 * * @copyright Copyright 2016 - 2021 IPFN-Instituto Superior Tecnico, Portugal * Licensed under the EUPL, Version 1.2 only (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence, available in 23 official languages of * the European Union, at: * https://joinup.ec.europa.eu/community/eupl/og_page/eupl-text-11-12 * * @warning Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * @details * */ // Include the correct display library #include #include #include "SSD1306Wire.h" // #include #include "bsec.h" //#include #include "CRC8.h" //#define BME_PRESENT 0 // WiFi credentials. char const * WIFI_SSID = "Cabovisao-E30F"; char const * WIFI_PASS = ""; const uint8_t bsec_config_iaq[] = { #include "config/generic_33v_3s_4d/bsec_iaq.txt" }; #define STATE_SAVE_PERIOD UINT32_C(360 * 60 * 1000) // 360 minutes - 4 times a day #define SAVE_PERIOD UINT32_C( 1000) // in millis #define BME680_I2C_ADDR 0x77 /*** Global vars ***/ Bsec iaqSensor; uint8_t bsecState[BSEC_MAX_STATE_BLOB_SIZE] = {0}; uint16_t stateUpdateCounter = 0; String output; // Initialize the OLED display using Arduino Wire: SSD1306Wire display(0x3c, OLED_SDA, OLED_SCL); // ADDRESS, SDA and SCL usually populate automatically based on your board's pins_arduino.h e.g. https://github.com/esp8266/Arduino/blob/master/variants/nodemcu/pins_arduino.h float iaq, rawTemperature, pressure, rawHumidity, gasResistance, stabStatus, runInStatus, temperature, humidity, staticIaq, co2Equivalent, breathVocEquivalent, compGasValue, gasPercentage; uint8_t iaqAccuracy; CRC8 crc; void wifi_connect(void) { // Connect to Wifi. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WIFI_SSID); // Set WiFi to station mode and disconnect from an AP if it was previously connected // WiFi.mode(WIFI_STA); // WiFi.disconnect(); delay(100); WiFi.begin(WIFI_SSID, WIFI_PASS); Serial.println("Connecting..."); for (int i=10; i-- >10;) { //while (WiFi.status() != WL_CONNECTED) { // Check to see if connecting failed. // This is due to incorrect credentials if (WiFi.status() == WL_CONNECT_FAILED) { Serial.println("Failed to connect to WIFI. Please verify credentials: "); Serial.println(); Serial.print("SSID: "); Serial.println(WIFI_SSID); Serial.print("Password: "); Serial.println(WIFI_PASS); Serial.println(); } delay(1000); if (WiFi.status() == WL_CONNECTED){ //Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); Serial.println("Hello World, I'm connected to the internets!!"); break; } } } /** Configure the BSEC library with information about the sensor 18v/33v = Voltage at Vdd. 1.8V or 3.3V 3s/300s = BSEC operating mode, BSEC_SAMPLE_RATE_LP or BSEC_SAMPLE_RATE_ULP 4d/28d = Operating age of the sensor in days generic_18v_3s_4d generic_18v_3s_28d generic_18v_300s_4d generic_18v_300s_28d generic_33v_3s_4d generic_33v_3s_28d generic_33v_300s_4d generic_33v_300s_28d */ // Helper functions declarations void checkIaqSensorStatus(void); void errLeds(void); void loadState(void); // Helper functions declarations void checkIaqSensorStatus(void); void errLeds(void); void loadState(void); void updateState(void); void print_bme680(unsigned long time); void scan_I2C() { byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for(address = 1; address < 127; address++ ) { Wire.beginTransmission(address); error = Wire.endTransmission(); // Wire1.beginTransmission(address); // error = Wire1.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address<16) Serial.print("0"); Serial.print(address,HEX); Serial.println(" !"); nDevices++; } else if (error==4) { Serial.print("Unknown error at address 0x"); if (address<16) Serial.print("0"); Serial.println(address,HEX); } } if (nDevices == 0) Serial.println("No I2C devices found\n"); else Serial.println("done\n"); } void bme680_setup() { EEPROM.begin(BSEC_MAX_STATE_BLOB_SIZE + 1); // 1st address for the length //Serial.println(F("0, BME680 test Init")); iaqSensor.begin(BME680_I2C_ADDR, Wire); output = "0, BSEC library version " + String(iaqSensor.version.major) + "." + String(iaqSensor.version.minor) + "." + String(iaqSensor.version.major_bugfix) + "." + String(iaqSensor.version.minor_bugfix); Serial.println(output); checkIaqSensorStatus(); iaqSensor.setConfig(bsec_config_iaq); checkIaqSensorStatus(); loadState(); Serial.println("0, BME680 0x77 OK"); bsec_virtual_sensor_t sensorList[10] = { BSEC_OUTPUT_RAW_TEMPERATURE, BSEC_OUTPUT_RAW_PRESSURE, BSEC_OUTPUT_RAW_HUMIDITY, BSEC_OUTPUT_RAW_GAS, BSEC_OUTPUT_IAQ, BSEC_OUTPUT_STATIC_IAQ, BSEC_OUTPUT_CO2_EQUIVALENT, BSEC_OUTPUT_BREATH_VOC_EQUIVALENT, BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE, BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY, }; } void print_bme680(unsigned long time){ /* Message format all floats, except pressure, iaq (uint_8) time, temperature, pressure, humidity, co2Equivalent, iaq, iaqAccuracy, staticIaq, rawTemperature rawHumidity, rawHumidity */ output = "1 " + String(time,DEC); output += ", " + String(iaqSensor.temperature, 1); output += ", " + String(iaqSensor.pressure,0); output += ", " + String(iaqSensor.humidity,1); output += ", " + String(iaqSensor.co2Equivalent,1); output += ", " + String(iaqSensor.breathVocEquivalent,1); output += ", " + String(iaqSensor.iaq, DEC); output += ", " + String(iaqSensor.iaqAccuracy,1); output += ", " + String(iaqSensor.staticIaq,1); output += ", " + String(iaqSensor.rawTemperature,1); output += ", " + String(iaqSensor.rawHumidity, 1); output += ", " + String(iaqSensor.rawHumidity, 1); Serial.println(output); } void print_bme680_mockup(unsigned long time){ uint16_t length; char c; output = "1, " + String(time, DEC); output += ", " + String(temperature, 1); output += ", " + String(pressure, 0); output += ", " + String(humidity, 1); output += ", " + String(co2Equivalent, 1); output += ", " + String(breathVocEquivalent, 1); output += ", " + String(iaq,1); output += ", " + String(iaqAccuracy, DEC); /* output += ", " + String(iaqSensor.staticIaq); output += ", " + String(iaqSensor.rawTemperature); output += ", " + String(iaqSensor.rawHumidity); output += ", " + String(iaqSensor.gasResistance); */ length = output.length(); output += ", " + String(length); Serial.print(output); crc.restart(); for(int i =0; i < length; i++){ c = output[i]; crc.add(c); } Serial.print(", "); //crc.add(output); //Serial.println(crc8((uint8_t *)str, length)); Serial.print(crc.getCRC(), HEX); Serial.print(", "); Serial.println(crc.getCRC()); //Serial.println(crc8((uint8_t *)str, length), HEX); } void draw_oled_mockup(unsigned long time){ display.setFont(ArialMT_Plain_10); // The coordinates define the left starting point of the text display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(0, 10, "Left aligned (0,10)"); display.drawString(20, 22, String(temperature) ); display.drawString(60, 22, String(pressure/1e2) ); display.drawString(100, 22, String(humidity) ); display.drawString(20, 44, String(breathVocEquivalent) ); display.drawString(60, 44, String(iaq) ); display.drawString(100, 44, String(iaqAccuracy) ); } void draw_oled(unsigned long time){ display.setFont(ArialMT_Plain_10); // The coordinates define the left starting point of the text display.setTextAlignment(TEXT_ALIGN_LEFT); display.drawString(0, 10, "Left aligned (0,10)"); // The coordinates define the center of the text display.setTextAlignment(TEXT_ALIGN_CENTER); display.drawString(64, 22, "Center aligned (64,22)"); // The coordinates define the right end of the text display.setTextAlignment(TEXT_ALIGN_RIGHT); display.drawString(128, 33, "Right aligned (128,33)"); display.drawString(20, 22, String(iaqSensor.temperature) ); display.drawString(60, 22, String(iaqSensor.pressure/1e2) ); display.drawString(100, 22, String(iaqSensor.humidity) ); display.drawString(20, 44, String(iaqSensor.breathVocEquivalent) ); display.drawString(60, 44, String(iaqSensor.iaq) ); display.drawString(100, 44, String(iaqSensor.iaqAccuracy) ); } /* // Heltec.display->clear(); Heltec.display->setColor(BLACK); Heltec.display->fillRect(10, 22, 140, 10); //Heltec.display->fillRect(60, 22, 40, 10); Heltec.display->fillRect(10, 44, 140, 10); //Heltec.display->drawString(20, 22, " "); Heltec.display->setColor(WHITE); Heltec.display->setTextAlignment(TEXT_ALIGN_CENTER); //Heltec.display->drawString(20, 22, " "); Heltec.display->drawString(20, 22, String(iaqSensor.temperature) ); Heltec.display->drawString(60, 22, String(iaqSensor.pressure/1e2) ); Heltec.display->drawString(100, 22, String(iaqSensor.humidity) ); Heltec.display->drawString(20, 44, String(iaqSensor.breathVocEquivalent) ); Heltec.display->drawString(60, 44, String(iaqSensor.iaq) ); Heltec.display->drawString(100, 44, String(iaqSensor.iaqAccuracy) ); Heltec.display->display(); //errLeds(); } */ // Helper function definitions void checkIaqSensorStatus(void) { if (iaqSensor.status != BSEC_OK) { if (iaqSensor.status < BSEC_OK) { output = "0, BSEC error code : " + String(iaqSensor.status); Serial.println(output); for (;;) errLeds(); /* Halt in case of failure */ } else { output = "0, BSEC warning code : " + String(iaqSensor.status); Serial.println(output); } } if (iaqSensor.bme680Status != BME680_OK) { if (iaqSensor.bme680Status < BME680_OK) { output = "0, BME680 error code : " + String(iaqSensor.bme680Status); Serial.println(output); for (;;) errLeds(); /* Halt in case of failure */ } else { output = "0, BME680 warning code : " + String(iaqSensor.bme680Status); Serial.println(output); } } } void errLeds(void) { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); delay(100); } void loadState(void) { if (EEPROM.read(0) == BSEC_MAX_STATE_BLOB_SIZE) { // Existing state in EEPROM Serial.println("0, Reading state from EEPROM"); for (uint8_t i = 0; i < BSEC_MAX_STATE_BLOB_SIZE; i++) { bsecState[i] = EEPROM.read(i + 1); //Serial.println(bsecState[i], HEX); } iaqSensor.setState(bsecState); checkIaqSensorStatus(); } else { // Erase the EEPROM with zeroes Serial.println("0, Erasing EEPROM"); for (uint8_t i = 0; i < BSEC_MAX_STATE_BLOB_SIZE + 1; i++) EEPROM.write(i, 0); EEPROM.commit(); } } void updateState(void) { bool update = false; /* Set a trigger to save the state. Here, the state is saved every STATE_SAVE_PERIOD with the first state being saved once the algorithm achieves full calibration, i.e. iaqAccuracy = 3 */ if (stateUpdateCounter == 0) { if (iaqSensor.iaqAccuracy >= 3) { update = true; stateUpdateCounter++; } } else { /* Update every STATE_SAVE_PERIOD milliseconds */ if ((stateUpdateCounter * STATE_SAVE_PERIOD) < millis()) { update = true; stateUpdateCounter++; } } if (update) { iaqSensor.getState(bsecState); checkIaqSensorStatus(); Serial.println("0, Writing state to EEPROM"); for (uint8_t i = 0; i < BSEC_MAX_STATE_BLOB_SIZE ; i++) { EEPROM.write(i + 1, bsecState[i]); //Serial.println(bsecState[i], HEX); } EEPROM.write(0, BSEC_MAX_STATE_BLOB_SIZE); EEPROM.commit(); } } void setup() { // initialize LED digital pin as an output. pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); Serial.println(__FILE__); //Serial.println(); //Serial.println(); wifi_connect(); #ifdef BME_PRESENT bme680_setup(); #endif // Initialising the UI will init the display too. display.init(); display.flipScreenVertically(); display.setFont(ArialMT_Plain_10); } void loop() { static unsigned long nextTime = 0; unsigned long now = millis(); static bool led_state = LOW; #ifdef BME_PRESENT if (iaqSensor.run()) { // If new data is available now = millis(); print_bme680(now); updateState(); led_state = !led_state; digitalWrite(LED_BUILTIN, led_state); } else { checkIaqSensorStatus(); } #else if ( now > nextTime ) { nextTime = now + SAVE_PERIOD; led_state = !led_state; digitalWrite(LED_BUILTIN, led_state); temperature = random(0,500)/10.0; pressure = random(980,1020)*100.0; humidity = random(500,1000)/10.0; co2Equivalent = random(0,9000)/1.0; breathVocEquivalent = random(0,2000)/10.0; iaq = random(0,500)/1.0; iaqAccuracy = random(0,3); print_bme680_mockup(now); } #endif } #include #include using namespace std; unsigned short readNumberFromFile(const char *filename); void writeNumberToFile(const char *filename, int number); ////////////////////////////////////////////////////////////// /// Solution for "LIO Olimps" Problem Nr 1: Reizinasana ar 2 ////////////////////////////////////////////////////////////// int main() { unsigned short n = readNumberFromFile("reiz.in"); writeNumberToFile("reiz.out", n * 2); return 0; } void writeNumberToFile(const char *filename, int number) { ofstream outputFile; outputFile.open(filename); outputFile << number; outputFile.close(); } unsigned short readNumberFromFile(const char *filename) { ifstream inputFile; inputFile.open(filename); unsigned n = 0; inputFile >> n; inputFile.close(); return n; } whisperlib/net/util/test/ip2location_test.cc // Copyright (c) 2009, Whispersoft s.r.l. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Whispersoft s.r.l. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: // // Simple test for looking up ips // #include "common/base/types.h" #include "common/base/log.h" #include "common/base/system.h" #include "common/base/gflags.h" #include "net/base/address.h" #include "net/util/ip2location.h" ////////////////////////////////////////////////////////////////////// DEFINE_string(ip2loc_file, "", "IP location database"); DEFINE_string(ip, "", "IP to lookup"); ////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { common::Init(argc, argv); CHECK(!FLAGS_ip.empty()) << "Please specify an IP"; CHECK(!FLAGS_ip2loc_file.empty()) << "Please specify the IP2Location DB"; net::Ip2Location ip2loc(FLAGS_ip2loc_file.c_str()); LOG_INFO << "LookupCountry: " << ip2loc.LookupCountry(FLAGS_ip.c_str()); LOG_INFO << "LookupCountryLong: " << ip2loc.LookupCountryLong(FLAGS_ip.c_str()); LOG_INFO << "LookupRegion: " << ip2loc.LookupRegion(FLAGS_ip.c_str()); LOG_INFO << "LookupCity: " << ip2loc.LookupCity(FLAGS_ip.c_str()); LOG_INFO << "LookupIsp: " << ip2loc.LookupIsp(FLAGS_ip.c_str()); } npocmaka/Windows-Server-2003 class CWinNTUserAcctStats; class CWinNTUserAcctStats : INHERIT_TRACKING, public IADsFSUserAccountStatistics { friend class CWinNTUser; public: /* IUnknown methods */ STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID FAR* ppvObj) ; DECLARE_STD_REFCOUNTING DECLARE_IDispatch_METHODS DECLARE_IADsFSUserAccountStatistics_METHODS CWinNTUserAcctStats::CWinNTUserAcctStats(); CWinNTUserAcctStats::~CWinNTUserAcctStats(); static HRESULT Create( CCoreADsObject FAR * pCoreADsObject, CWinNTUserAcctStats FAR * FAR * ppUserAS ); protected: CCoreADsObject * _pCoreADsObject; CAggregatorDispMgr *_pDispMgr; }; // #define _WINSOCKAPI_ #include #include #include // Create the module class. class MyHttpModule : public CHttpModule { public: // Process an RQ_BEGIN_REQUEST event. REQUEST_NOTIFICATION_STATUS OnBeginRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER( pHttpContext ); UNREFERENCED_PARAMETER( pProvider ); WriteEventViewerLog("OnBeginRequest"); return RQ_NOTIFICATION_CONTINUE; } // Process an RQ_BEGIN_REQUEST post-event. REQUEST_NOTIFICATION_STATUS OnPostBeginRequest( IN IHttpContext * pHttpContext, IN IHttpEventProvider * pProvider ) { UNREFERENCED_PARAMETER( pHttpContext ); UNREFERENCED_PARAMETER( pProvider ); WriteEventViewerLog("OnPostBeginRequest"); return RQ_NOTIFICATION_CONTINUE; } MyHttpModule() { // Open a handle to the Event Viewer. m_hEventLog = RegisterEventSource( NULL,"IISADMIN" ); } ~MyHttpModule() { // Test whether the handle for the Event Viewer is open. if (NULL != m_hEventLog) { // Close the handle to the Event Viewer. DeregisterEventSource( m_hEventLog ); m_hEventLog = NULL; } } private: // Create a handle for the event viewer. HANDLE m_hEventLog; // Define a method that writes to the Event Viewer. BOOL WriteEventViewerLog(LPCSTR szNotification) { // Test whether the handle for the Event Viewer is open. if (NULL != m_hEventLog) { // Write any strings to the Event Viewer and return. return ReportEvent( m_hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, &szNotification, NULL ); } return FALSE; } }; // Create the module's class factory. class MyHttpModuleFactory : public IHttpModuleFactory { public: HRESULT GetHttpModule( OUT CHttpModule ** ppModule, IN IModuleAllocator * pAllocator ) { UNREFERENCED_PARAMETER( pAllocator ); // Create a new instance. MyHttpModule * pModule = new MyHttpModule; // Test for an error. if (!pModule) { // Return an error if the factory cannot create the instance. return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } else { // Return a pointer to the module. *ppModule = pModule; pModule = NULL; // Return a success status. return S_OK; } } void Terminate() { // Remove the class from memory. delete this; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Set the request notifications and exit. return pModuleInfo->SetRequestNotifications( // Specify the class factory. new MyHttpModuleFactory, // Specify the event notifications. RQ_BEGIN_REQUEST, // Specify the post-event notifications. RQ_BEGIN_REQUEST ); } // minium2/Box2D /* * Copyright (c) 2006-2011 http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_WORLD_HPP #define B2_WORLD_HPP #include #include #include #include #include #include namespace b2 { struct AABB; struct BodyDef; struct Color; struct JointDef; class Body; class Draw; class Fixture; class Joint; /// The world class manages all physics entities, dynamic simulation, /// and asynchronous queries. The world also contains efficient memory /// management facilities. class World { public: /// Construct a world object. /// @param gravity the world gravity vector. World(const Vec2& gravity); /// Destruct the world. All physics entities are destroyed and all heap memory is released. ~World(); /// Register a destruction listener. The listener is owned by you and must /// remain in scope. void SetDestructionListener(DestructionListener* listener); /// Register a contact filter to provide specific control over collision. /// Otherwise the default filter is used (defaultFilter). The listener is /// owned by you and must remain in scope. void SetContactFilter(ContactFilter* filter); /// Register a contact event listener. The listener is owned by you and must /// remain in scope. void SetContactListener(ContactListener* listener); /// Register a routine for debug drawing. The debug draw functions are called /// inside with b2::World::DrawDebugData method. The debug draw object is owned /// by you and must remain in scope. void SetDebugDraw(Draw* debugDraw); /// Create a rigid body given a definition. No reference to the definition /// is retained. /// @warning This function is locked during callbacks. Body* CreateBody(const BodyDef* def); /// Destroy a rigid body given a definition. No reference to the definition /// is retained. This function is locked during callbacks. /// @warning This automatically deletes all associated shapes and joints. /// @warning This function is locked during callbacks. void DestroyBody(Body* body); /// Create a joint to constrain bodies together. No reference to the definition /// is retained. This may cause the connected bodies to cease colliding. /// @warning This function is locked during callbacks. Joint* CreateJoint(const JointDef* def); /// Destroy a joint. This may cause the connected bodies to begin colliding. /// @warning This function is locked during callbacks. void DestroyJoint(Joint* joint); /// Take a time step. This performs collision detection, integration, /// and constraint solution. /// @param timeStep the amount of time to simulate, this should not vary. /// @param velocityIterations for the velocity constraint solver. /// @param positionIterations for the position constraint solver. void Step( float32 timeStep, int32 velocityIterations, int32 positionIterations); /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain /// a fixed sized time step under a variable frame-rate. /// When you perform sub-stepping you will disable auto clearing of forces and instead call /// ClearForces after all sub-steps are complete in one pass of your game loop. /// @see SetAutoClearForces void ClearForces(); /// Call this to draw shapes and other debug draw data. This is intentionally non-const. void DrawDebugData(); /// Query the world for all fixtures that potentially overlap the /// provided AABB. /// @param callback a user implemented callback class. /// @param aabb the query box. void QueryAABB(QueryCallback* callback, const AABB& aabb) const; /// Ray-cast the world for all fixtures in the path of the ray. Your callback /// controls whether you get the closest point, any point, or n-points. /// The ray-cast ignores shapes that contain the starting point. /// @param callback a user implemented callback class. /// @param point1 the ray starting point /// @param point2 the ray ending point void RayCast(RayCastCallback* callback, const Vec2& point1, const Vec2& point2) const; /// Get the world body list. With the returned body, use b2::Body::GetNext to get /// the next body in the world list. A NULL body indicates the end of the list. /// @return the head of the world body list. Body* GetBodyList(); const Body* GetBodyList() const; /// Get the world joint list. With the returned joint, use b2::Joint::GetNext to get /// the next joint in the world list. A NULL joint indicates the end of the list. /// @return the head of the world joint list. Joint* GetJointList(); const Joint* GetJointList() const; /// Get the world contact list. With the returned contact, use b2::Contact::GetNext to get /// the next contact in the world list. A NULL contact indicates the end of the list. /// @return the head of the world contact list. /// @warning contacts are created and destroyed in the middle of a time step. /// Use b2::ContactListener to avoid missing contacts. Contact* GetContactList(); const Contact* GetContactList() const; /// Enable/disable sleep. void SetAllowSleeping(bool flag); bool GetAllowSleeping() const { return m_allowSleep; } /// Enable/disable warm starting. For testing. void SetWarmStarting(bool flag) { m_warmStarting = flag; } bool GetWarmStarting() const { return m_warmStarting; } /// Enable/disable continuous physics. For testing. void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } bool GetContinuousPhysics() const { return m_continuousPhysics; } /// Enable/disable single stepped continuous physics. For testing. void SetSubStepping(bool flag) { m_subStepping = flag; } bool GetSubStepping() const { return m_subStepping; } /// Get the number of broad-phase proxies. int32 GetProxyCount() const; /// Get the number of bodies. int32 GetBodyCount() const; /// Get the number of joints. int32 GetJointCount() const; /// Get the number of contacts (each may have 0 or more contact points). int32 GetContactCount() const; /// Get the height of the dynamic tree. int32 GetTreeHeight() const; /// Get the balance of the dynamic tree. int32 GetTreeBalance() const; /// Get the quality metric of the dynamic tree. The smaller the better. /// The minimum is 1. float32 GetTreeQuality() const; /// Change the global gravity vector. void SetGravity(const Vec2& gravity); /// Get the global gravity vector. Vec2 GetGravity() const; /// Is the world locked (in the middle of a time step). bool IsLocked() const; /// Set flag to control automatic clearing of forces after each time step. void SetAutoClearForces(bool flag); /// Get the flag that controls automatic clearing of forces after each time step. bool GetAutoClearForces() const; /// Shift the world origin. Useful for large worlds. /// The body shift formula is: position -= newOrigin /// @param newOrigin the new origin with respect to the old origin void ShiftOrigin(const Vec2& newOrigin); /// Get the contact manager for testing. const ContactManager& GetContactManager() const; /// Get the current profile. const Profile& GetProfile() const; /// Dump the world into the log file. /// @warning this should be called outside of a time step. void Dump(); private: // m_flags enum { e_newFixture = 0x0001, e_locked = 0x0002, e_clearForces = 0x0004 }; friend class Body; friend class Fixture; friend class ContactManager; friend class Controller; void Solve(const TimeStep& step); void SolveTOI(const TimeStep& step); void DrawJoint(Joint* joint); void DrawShape(Fixture* shape, const Transform& xf, const Color& color); BlockAllocator m_blockAllocator; StackAllocator m_stackAllocator; int32 m_flags; ContactManager m_contactManager; Body* m_bodyList; Joint* m_jointList; int32 m_bodyCount; int32 m_jointCount; Vec2 m_gravity; bool m_allowSleep; DestructionListener* m_destructionListener; Draw* g_debugDraw; // This is used to compute the time step ratio to // support a variable time step. float32 m_inv_dt0; // These are for debugging the solver. bool m_warmStarting; bool m_continuousPhysics; bool m_subStepping; bool m_stepComplete; Profile m_profile; }; inline Body* World::GetBodyList() { return m_bodyList; } inline const Body* World::GetBodyList() const { return m_bodyList; } inline Joint* World::GetJointList() { return m_jointList; } inline const Joint* World::GetJointList() const { return m_jointList; } inline Contact* World::GetContactList() { return m_contactManager.m_contactList; } inline const Contact* World::GetContactList() const { return m_contactManager.m_contactList; } inline int32 World::GetBodyCount() const { return m_bodyCount; } inline int32 World::GetJointCount() const { return m_jointCount; } inline int32 World::GetContactCount() const { return m_contactManager.m_contactCount; } inline void World::SetGravity(const Vec2& gravity) { m_gravity = gravity; } inline Vec2 World::GetGravity() const { return m_gravity; } inline bool World::IsLocked() const { return (m_flags & e_locked) == e_locked; } inline void World::SetAutoClearForces(bool flag) { if (flag) { m_flags |= e_clearForces; } else { m_flags &= ~e_clearForces; } } /// Get the flag that controls automatic clearing of forces after each time step. inline bool World::GetAutoClearForces() const { return (m_flags & e_clearForces) == e_clearForces; } inline const ContactManager& World::GetContactManager() const { return m_contactManager; } inline const Profile& World::GetProfile() const { return m_profile; } } // namespace b2 #endif // B2_WORLD_HPP colinw7/CQDemosCQGLWaterSurface/src/CQGLWaterSurface.cpp1-10 #include #include #include #include #include #include #include int main(int argc, char **argv) { QApplication app(argc, argv); CQGLWaterSurface *surface = new CQGLWaterSurface; surface->init(); surface->show(); return app.exec(); } //------ CQGLWaterSurface:: CQGLWaterSurface() : CQMainWindow("CQGLWaterSurface") { surface_ = new CWaterSurface; initWaterSurface(); } QWidget * CQGLWaterSurface:: createCentralWidget() { QWidget *frame = new QWidget; QVBoxLayout *layout = new QVBoxLayout(frame); canvas_ = new CQGLWaterSurfaceCanvas(this); control_ = new CQGLControl(canvas_); toolbar_ = control_->createToolBar(); connect(control_, SIGNAL(stateChanged()), this, SLOT(controlSlot())); layout->addWidget(toolbar_); layout->addWidget(canvas_); timer_ = new QTimer; connect(timer_, SIGNAL(timeout()), this, SLOT(stepWaterSurface())); timer_->start(10); return frame; } void CQGLWaterSurface:: createWorkspace() { } void CQGLWaterSurface:: createMenus() { fileMenu_ = new CQMenu(this, "&File"); CQMenuItem *quitItem = new CQMenuItem(fileMenu_, "&Quit"); quitItem->setShortcut("Ctrl+Q"); quitItem->setStatusTip("Quit the application"); connect(quitItem->getAction(), SIGNAL(triggered()), this, SLOT(close())); //---- helpMenu_ = new CQMenu(this, "&Help"); //---- CQMenuItem *aboutItem = new CQMenuItem(helpMenu_, "&About"); aboutItem->setStatusTip("Show the application's About box"); //connect(aboutItem->getAction(), SIGNAL(triggered()), this, SLOT(aboutSlot())); } void CQGLWaterSurface:: createToolBars() { } void CQGLWaterSurface:: createStatusBar() { } void CQGLWaterSurface:: createDockWindows() { } void CQGLWaterSurface:: controlSlot() { canvas_->update(); } void CQGLWaterSurface:: initWaterSurface() { int n = surface_->getSize(); for (int y = 1; y < n - 1; y++) { for (int x = 1; x < n - 1; x++) { //double xx = surface_->getX(x, y); //double yy = surface_->getY(x, y); //if ((xx*xx + yy*yy) <= 10) surface_->setDampening(x, y, 0); surface_->setDampening(x, y, 1.0); surface_->setZ(x, y, 0.0); } } surface_->setZ((int) ( n/4.0), (int) ( n/4.0), 4.0); surface_->setZ((int) (3.0*n/4.0), (int) (3.0*n/4.0), 4.0); } void CQGLWaterSurface:: stepWaterSurface() { surface_->step(0.001); canvas_->update(); } //------ CQGLWaterSurfaceCanvas:: CQGLWaterSurfaceCanvas(CQGLWaterSurface *surface) : QGLWidget(surface), surface_(surface) { setFocusPolicy(Qt::StrongFocus); } void CQGLWaterSurfaceCanvas:: paintGL() { static GLfloat blue[4] = {0.2, 0.2, 0.5, 1.0}; //static GLfloat mat_specular [] = { 1.0, 1.0, 1.0, 1.0 }; //static GLfloat mat_shininess [] = { 50.0 }; static GLfloat light_position[] = { 5.0, 5.0, -5.0, 0.0 }; //glEnable(GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL); //glColor3d(blue[0], blue[1], blue[2]); //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CQGLControl *control = surface_->getControl(); control->getDepthTest () ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); control->getCullFace () ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); control->getLighting () ? glEnable(GL_LIGHTING) : glDisable(GL_LIGHTING); control->getOutline () ? glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) : glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); control->getFrontFace () ? glFrontFace(GL_CW) : glFrontFace(GL_CCW); control->getSmoothShade() ? glShadeModel(GL_SMOOTH) : glShadeModel(GL_FLAT); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, light_position); static GLfloat ambient[4] = {0.1, 0.1, 0.1, 1.0}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, blue); //glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR , mat_specular ); //glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); CWaterSurface *surface = surface_->getWaterSurface(); int n = surface->getSize(); for (int y = 1; y < n; ++y) { double y1 = surface->getY(0, y - 1); double y2 = surface->getY(0, y ); for (int x = 1; x < n; ++x) { double x1 = surface->getX(x - 1, 0); double x2 = surface->getX(x , 0); double z1 = surface->getZ(x - 1, y - 1); double z2 = surface->getZ(x - 1, y ); double z3 = surface->getZ(x , y ); double z4 = surface->getZ(x , y - 1); //CVector3D n1 = surface->getNormal(x - 1, y - 1).normalized(); //CVector3D n2 = surface->getNormal(x - 1, y ).normalized(); //CVector3D n3 = surface->getNormal(x , y ).normalized(); //CVector3D n4 = surface->getNormal(x , y - 1).normalized(); //CVector3D n = (n1 + n2 + n3 + n4)/4; //n.normalize(); double z; CVector3D normal; surface->interpolate(x - 0.5, y - 0.5, z, normal); glColor3d(blue[0], blue[1], blue[2]); glBegin(GL_POLYGON); glNormal3f(normal.getX(), normal.getY(), normal.getZ()); //glNormal3f(n1.getX(), n1.getY(), n1.getZ()); glVertex3d(x1, y1, z1); //glNormal3f(n2.getX(), n2.getY(), n2.getZ()); glVertex3d(x1, y2, z2); //glNormal3f(n3.getX(), n3.getY(), n3.getZ()); glVertex3d(x2, y2, z3); //glNormal3f(n4.getX(), n4.getY(), n4.getZ()); glVertex3d(x2, y1, z4); glEnd(); } } } void CQGLWaterSurfaceCanvas:: resizeGL(int width, int height) { CQGLControl *control = surface_->getControl(); control->handleResize(width, height); } void CQGLWaterSurfaceCanvas:: mousePressEvent(QMouseEvent *e) { CQGLControl *control = surface_->getControl(); control->handleMousePress(e); update(); } void CQGLWaterSurfaceCanvas:: mouseReleaseEvent(QMouseEvent *e) { CQGLControl *control = surface_->getControl(); control->handleMouseRelease(e); update(); } void CQGLWaterSurfaceCanvas:: mouseMoveEvent(QMouseEvent *e) { CQGLControl *control = surface_->getControl(); control->handleMouseMotion(e); update(); } void CQGLWaterSurfaceCanvas:: keyPressEvent(QKeyEvent *) { } /* * Copyright (c) 2014 loujiayu * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include #include #include #include #include #include #include #include #include "http.h" namespace by { HttpException::HttpException(int curl_code, int http_code, const char *err_buf) : runtime_error(Format(curl_code, http_code, err_buf)) { } std::string HttpException::Format(int curl_code, int http_code, const char *err_buf) { std::ostringstream ss; ss << "CURL code = " << curl_code << " HTTP code = " << http_code << " (" << err_buf << ")"; return ss.str(); } std::size_t WriteCallback(char *data, size_t size, size_t nmemb, std::string *resp) { assert(resp != 0); assert(data != 0); std::size_t count = size * nmemb; resp->append(data, count); return count; } size_t ReadCallback( void *ptr, std::size_t size, std::size_t nmemb, std::string *data ) { assert( ptr != 0 ) ; assert( data != 0 ) ; std::size_t count = std::min( size * nmemb, data->size() ) ; if ( count > 0 ) { std::memcpy( ptr, &(*data)[0], count ) ; data->erase( 0, count ) ; } return count ; } std::size_t Callback(char *data, size_t size, size_t nmemb, std::ofstream *file) { assert(data != 0); std::size_t count = size * nmemb; return file->rdbuf()->sputn( data, count ) ;; } CURL* InitCurl(const std::string& url, std::string *resp, const Headers& hdr) { CURL *curl = curl_easy_init(); if (curl == 0) throw std::bad_alloc(); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); struct curl_slist *curl_hdr = 0; for (Headers::const_iterator i = hdr.begin(); i != hdr.end(); ++i) curl_hdr = curl_slist_append(curl_hdr, i->c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_hdr); return curl; } void DoCurl(CURL *curl) { char error_buf[CURL_ERROR_SIZE] = {}; curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buf); CURLcode curl_code = curl_easy_perform(curl); int http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (curl_code != CURLE_OK) { throw HttpException(curl_code, http_code, error_buf); } else if (http_code >= 400) { std::cout << "http error " << http_code << std::endl; throw HttpException(curl_code, http_code, error_buf); } } std::string HttpPostData( const std::string& url, const std::string& data, const Headers& hdr) { std::string resp; CURL *curl = InitCurl(url, &resp, hdr); std::string post_data = data; curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &post_data[0]); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, post_data.size()); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1 ) ; DoCurl(curl); return resp; } std::string HttpGet( const std::string& url, const Headers& hdr) { std::string resp; CURL *curl = InitCurl(url, &resp, hdr); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_perform(curl); return resp; } void HttpGetFile( const std::string& url, std::ofstream *mfile, const Headers& hdr) { CURL *curl = InitCurl(url, 0, hdr); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, mfile); curl_easy_perform(curl); } std::string Put(const std::string& url,const std::string& data,const Headers& hdr) { std::string resp ; CURL *curl = InitCurl( url, &resp, hdr ) ; std::string put_data = data ; curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L ) ; curl_easy_setopt(curl, CURLOPT_READFUNCTION, &ReadCallback ) ; curl_easy_setopt(curl, CURLOPT_READDATA , &put_data ) ; curl_easy_setopt(curl, CURLOPT_INFILESIZE, put_data.size() ) ; curl_easy_setopt(curl, CURLOPT_VERBOSE, 0 ) ; curl_easy_perform(curl); return resp; } std::string Customizing( const std::string& url, const std::string& data, const Headers& hdr) { std::string resp; CURL *curl = InitCurl(url, &resp, hdr); std::string post_data = data; curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1 ) ; DoCurl(curl); return resp; } } // namespace by #include "r_gc_unmark_callback.h" #include "r_callback.h" #include "GcUnmarkCallback.hpp" using instrumentr::GcUnmarkCallback; SEXP r_gc_unmark_callback_create_from_r_function(SEXP r_function) { return r_callback_create_from_r_function(r_function); } SEXP r_gc_unmark_callback_create_from_c_function(SEXP r_c_function) { return r_callback_create_from_c_function(r_c_function); } class Solution { public: int largestRectangleArea(vector& heights) { heights.push_back(0); stack s; int i=0; int ans=0; while (i=heights[s.top()]){ s.push(i); i++; } else { int h=s.top(); s.pop(); ans=max(ans,heights[h]*(s.empty()?i:i-s.top()-1)); } } return ans; } }; // Copyright 2020 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 // // 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 "aistreams/gstreamer/gstreamer_video_exporter.h" #include #include "absl/strings/match.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "aistreams/base/util/packet_utils.h" #include "aistreams/gstreamer/gstreamer_raw_image_yielder.h" #include "aistreams/gstreamer/gstreamer_runner.h" #include "aistreams/gstreamer/gstreamer_video_writer.h" #include "aistreams/gstreamer/type_utils.h" #include "aistreams/port/canonical_errors.h" #include "aistreams/port/logging.h" #include "aistreams/port/status.h" #include "aistreams/port/status_macros.h" #include "aistreams/util/file_path.h" #include "aistreams/util/random_string.h" #include "google/cloud/storage/client.h" #include "google/cloud/storage/parallel_upload.h" namespace aistreams { namespace { constexpr int kDefaultRandomStringLength = 5; constexpr char kDefaultWorkerName[] = "Worker"; constexpr char kGcsUploaderName[] = "GcsUploader"; constexpr char kLocalVideoSaverName[] = "LocalVideoSaver"; constexpr char kStreamServerSourceName[] = "StreamServerSource"; constexpr char kGstreamerInputSourceName[] = "GstreamerInputSource"; // -------------------------------------------------------------------- // Basic worker-channel implementation (i.e. a tiny dataflow system). // // Workers run business logic and communicate values to the other workers // through Channels. A Channel is a pcqueue for one Worker to send values // to another. It also allows either worker to know whether each other have // completed their processing. // // The typical workflow is to create a set of Workers, some Channels, and use // the free function Attach to connect them together. See // GstreamerVideoExporter::Run() later on for an example. // A Channel carries values of type T. template class Channel { public: // Create a channel of size `size`. // // CHECK-fails for non-positive sizes. explicit Channel(int size); // Set `worker` to be the value source/destination of this channel. template void SetSrc(const U& worker); template void SetDst(const U& worker); // Returns true if the channel has a value source/destination. // // CHECK-fails if you have not set a source/destination. bool HasSrc() const; bool HasDst() const; // Returns true if the source/destination worker has completed. // // CHECK-fails if you have not set a source/destination. bool IsSrcCompleted() const; bool IsDstCompleted() const; // Returns a reference to the pcqueue. // // Use this and the ProducerConsumerQueue API to send/receive values. std::shared_ptr> pcqueue() { return pcqueue_; } ~Channel() = default; Channel(const Channel&) = delete; Channel& operator=(const Channel&) = delete; private: std::shared_ptr src_completion_signal_ = nullptr; std::shared_ptr dst_completion_signal_ = nullptr; std::shared_ptr> pcqueue_ = nullptr; }; template Channel::Channel(int size) { CHECK(size > 0); pcqueue_ = std::make_shared>(size); } template template void Channel::SetSrc(const U& worker) { src_completion_signal_ = worker.GetCompletionSignal(); } template template void Channel::SetDst(const U& worker) { dst_completion_signal_ = worker.GetCompletionSignal(); } template bool Channel::HasSrc() const { return src_completion_signal_ != nullptr; } template bool Channel::HasDst() const { return dst_completion_signal_ != nullptr; } template bool Channel::IsSrcCompleted() const { CHECK(src_completion_signal_ != nullptr); return src_completion_signal_->IsCompleted(); } template bool Channel::IsDstCompleted() const { CHECK(dst_completion_signal_ != nullptr); return dst_completion_signal_->IsCompleted(); } // CRTP base class for Workers. // // A Worker consumes any number of inputs and produces any number of outputs. // These input/output values all flow through Channels of the given type. // // For example, to create a new Worker that accepts int values from a Channel // and produces double values to another Channel, do the following: // // class MySpecialWorker : Worker, // std::tuple> { // // your implementation goes here. // }; // // See StreamServerSource or LocalVideoSaver for more examples. template class Worker; template class Worker, std::tuple> { public: // Async call to start working in the background. void Work(); // Wait for the worker to complete up to a `timeout`. // // If the worker has completed, reclaim the background thread and return true. // Otherwise, let the worker keep working and return false. bool Join(absl::Duration timeout); // Get/Set the name of this worker. void SetName(const std::string& name); std::string GetName(); // Get the return Status of the specific logic executed by this Worker. // // Call this after you have successfully Join()'d. Status GetStatus(); ~Worker(); Worker() = default; Worker(const Worker&) = delete; Worker& operator=(const Worker&) = delete; std::shared_ptr GetCompletionSignal() const { return completion_signal_; } template std::shared_ptr< Channel>::type>>& GetInputChannel() { return std::get(in_channels_); } template std::shared_ptr< Channel>::type>>& GetOutputChannel() { return std::get(out_channels_); } private: T* derived() { return static_cast(this); } std::string name_ = kDefaultWorkerName; std::thread worker_thread_; std::shared_ptr completion_signal_ = std::make_shared(); protected: std::tuple>...> in_channels_; std::tuple>...> out_channels_; }; template void Worker, std::tuple>::Work() { completion_signal_->Start(); worker_thread_ = std::thread([this]() { auto status = derived()->WorkImpl(); completion_signal_->SetStatus(status); completion_signal_->End(); return; }); return; } template bool Worker, std::tuple>::Join( absl::Duration timeout) { if (!completion_signal_->WaitUntilCompleted(timeout)) { return false; } if (worker_thread_.joinable()) { worker_thread_.join(); } return true; } template void Worker, std::tuple>::SetName( const std::string& name) { name_ = name; } template std::string Worker, std::tuple>::GetName() { return name_; } template Status Worker, std::tuple>::GetStatus() { return completion_signal_->GetStatus(); } template Worker, std::tuple>::~Worker() { if (worker_thread_.joinable()) { worker_thread_.detach(); } } // Attach `channel` from the `M`th output of `src_worker` to the `N`th // input of the `dst_worker`. template Status Attach(std::shared_ptr> channel, std::shared_ptr src_worker, std::shared_ptr dst_worker) { if (channel == nullptr) { return InvalidArgumentError("Given a nullptr to the Channel."); } if (src_worker == nullptr) { return InvalidArgumentError("Given a nullptr to the source Worker."); } if (dst_worker == nullptr) { return InvalidArgumentError("Given a nullptr to the destination Worker."); } channel->SetSrc(*src_worker); channel->SetDst(*dst_worker); src_worker->template GetOutputChannel() = channel; dst_worker->template GetInputChannel() = channel; return OkStatus(); } // -------------------------------------------------------------------- // GstreamerInputSource implementation. // // TODO: Can the StreamServerSource not just be GstreamerInputSource with an // aissrc in the beginning? Probably yes, but more features will be needed to // control the gstreamer pipeline (most likely by adding features to // GstreamerRunner). class GstreamerInputSource : public Worker, std::tuple>> { public: struct Options { std::string gstreamer_input_pipeline; }; explicit GstreamerInputSource(const Options& options) : options_(options) {} Status WorkImpl() { AIS_RETURN_IF_ERROR(ValidatePreconditions()); // Create and run the gstreamer input pipeline. GstreamerRunner::Options gstreamer_runner_options; gstreamer_runner_options.appsink_sync = true; gstreamer_runner_options.processing_pipeline_string = DecideProcessingPipeline(); gstreamer_runner_options.receiver_callback = [this](GstreamerBuffer buffer) -> Status { auto raw_image_statusor = ToRawImage(std::move(buffer)); if (!raw_image_statusor.ok()) { return raw_image_statusor.status(); } if (out_channel()->IsDstCompleted()) { return CancelledError(absl::StrFormat( "%s: The downstream worker has completed.", GetName())); } if (!out_channel()->pcqueue()->TryEmplace( std::move(raw_image_statusor))) { LOG(ERROR) << "The working raw image buffer is full; dropping frame. Consider " "increasing the working buffer size if you believe this is " "transient. Otherwise, your input source's frame rate may be " "too high; please contact us to let us know your use case."; } return OkStatus(); }; auto gstreamer_runner_statusor = GstreamerRunner::Create(gstreamer_runner_options); if (!gstreamer_runner_statusor.ok()) { return gstreamer_runner_statusor.status(); } auto gstreamer_runner = std::move(gstreamer_runner_statusor).ValueOrDie(); // Wait for the runner to complete. // // TODO: Add support to get GstreamerRunner's status on completion. while (!gstreamer_runner->WaitUntilCompleted(absl::Seconds(5))) ; // Cleanup. if (!out_channel()->pcqueue()->TryEmplace(NotFoundError("Reached EOS."))) { LOG(WARNING) << absl::StrFormat( "%s: Failed to deliver EOS to dependent workers.", GetName()); } return OkStatus(); } private: Options options_; std::shared_ptr>> out_channel() { return std::get<0>(out_channels_); } Status ValidatePreconditions() { if (options_.gstreamer_input_pipeline.empty()) { return InvalidArgumentError(absl::StrFormat( "%s: You must specify a non-empty gstreamer input pipeline.", GetName())); } if (out_channel() == nullptr) { return FailedPreconditionError(absl::StrFormat( "%s: No output channel found; please Attach() one.", GetName())); } if (!out_channel()->HasDst()) { return InternalError(absl::StrFormat( "%s: The output channel has no destination.", GetName())); } return OkStatus(); } std::string DecideProcessingPipeline() { return absl::StrFormat("%s ! videoconvert ! video/x-raw,format=RGB", options_.gstreamer_input_pipeline); } }; // -------------------------------------------------------------------- // StreamServerSource implementation. class StreamServerSource : public Worker, std::tuple>> { public: struct Options { ReceiverOptions receiver_options; absl::Duration receiver_timeout = absl::Seconds(10); }; explicit StreamServerSource(const Options& options) : options_(options) {} Status WorkImpl() { AIS_RETURN_IF_ERROR(ValidatePreconditions()); // TODO: May need to be in a retry loop to re-establish connections in the // future for the poor connectivity use cases. AIS_RETURN_IF_ERROR(ConnectAndWarmup()); // Main fetch/decode loop. Status return_status = OkStatus(); while (!out_channel()->IsDstCompleted()) { // Get a packet and check for EOS. bool is_eos = false; StatusOr packet_statusor = ReceivePacket(&is_eos); if (!packet_statusor.ok()) { return_status = UnknownError( absl::StrFormat("Failed to receive a packet from upstream: %s", packet_statusor.status().message())); break; } if (is_eos) { break; } // Feed the Packet for decoding. auto gstreamer_buffer_statusor = ToGstreamerBuffer(std::move(packet_statusor).ValueOrDie()); if (!gstreamer_buffer_statusor.ok()) { return_status = UnknownError(absl::StrFormat( "Failed to convert a packet to a gstreamer buffer: %s", gstreamer_buffer_statusor.status().message())); break; } auto status = raw_image_yielder_->Feed( std::move(gstreamer_buffer_statusor).ValueOrDie()); if (!status.ok()) { return_status = UnknownError(absl::StrFormat( "Failed to Feed the data for raw image conversion: %s", status.message())); break; } } raw_image_yielder_->SignalEOS(); return return_status; } ~StreamServerSource() = default; private: StatusOr ReceivePacket(bool* is_eos) { Packet p; if (!packet_receiver_queue_->TryPop(p, options_.receiver_timeout)) { return DeadlineExceededError(absl::StrFormat( "Failed to receive a packet within the specified timeout (%s).", FormatDuration(options_.receiver_timeout))); } *is_eos = IsEos(p); return p; } Status ValidatePreconditions() { if (out_channel() == nullptr) { return FailedPreconditionError(absl::StrFormat( "%s: No output channel found; please Attach() one.", GetName())); } if (!out_channel()->HasDst()) { return InternalError(absl::StrFormat( "%s: The output channel has no destination.", GetName())); } return OkStatus(); } Status ConnectAndWarmup() { // Create the packet reciever queue. packet_receiver_queue_ = std::make_unique>(); auto status = MakePacketReceiverQueue(options_.receiver_options, packet_receiver_queue_.get()); if (!status.ok()) { return InvalidArgumentError(absl::StrFormat( "Failed to create a packet receiver queue: %s", status.message())); } // Receive the first packet and convert it to a gstreamer buffer. bool is_eos = false; StatusOr packet_statusor = ReceivePacket(&is_eos); if (!packet_statusor.ok()) { return UnknownError( absl::StrFormat("Failed to receive a packet from upstream: %s", packet_statusor.status().message())); } if (is_eos) { return NotFoundError("Got EOS. The stream has already ended."); } auto gstreamer_buffer_statusor = ToGstreamerBuffer(std::move(packet_statusor).ValueOrDie()); if (!gstreamer_buffer_statusor.ok()) { return UnknownError(absl::StrFormat( "Failed to convert the first packet to a gstreamer buffer: %s", gstreamer_buffer_statusor.status().message())); } auto gstreamer_buffer = std::move(gstreamer_buffer_statusor).ValueOrDie(); // Create the raw image yielder. GstreamerRawImageYielder::Options raw_image_yielder_options; raw_image_yielder_options.caps_string = gstreamer_buffer.get_caps(); raw_image_yielder_options.callback = [this](StatusOr raw_image_statusor) -> Status { if (!out_channel()->pcqueue()->TryEmplace( std::move(raw_image_statusor))) { LOG(ERROR) << "The working raw image buffer is full; dropping frame. Consider " "increasing the working buffer size if you believe this is " "transient. Otherwise, your input source's frame rate may be " "too high; please contact us to let us know your use case."; } return OkStatus(); }; auto raw_image_yielder_statusor = GstreamerRawImageYielder::Create(raw_image_yielder_options); if (!raw_image_yielder_statusor.ok()) { return raw_image_yielder_statusor.status(); } raw_image_yielder_ = std::move(raw_image_yielder_statusor).ValueOrDie(); // Feed the first buffer. status = raw_image_yielder_->Feed(gstreamer_buffer); if (!status.ok()) { return UnknownError(absl::StrFormat( "Failed to Feed the first buffer into the raw image yielder: %s", status.message())); } return OkStatus(); } Options options_; std::shared_ptr>> out_channel() { return std::get<0>(out_channels_); } std::unique_ptr> packet_receiver_queue_ = nullptr; // TODO: Consider pushing the decoder into the local video saver. std::unique_ptr raw_image_yielder_ = nullptr; }; // -------------------------------------------------------------------- // LocalVideoSaver implementation. class LocalVideoSaver : public Worker>, std::tuple>> { public: struct Options { std::string file_prefix; std::string output_dir; int max_frames_per_file; // TODO: Consider refactoring to have two Workers, one having no output // stream and another having one so that we can avoid this conditional // behavior that muddies the interface semantics. bool forward_file_paths; }; explicit LocalVideoSaver(const Options& options) : options_(options) {} Status WorkImpl() { AIS_RETURN_IF_ERROR(ValidatePreconditions()); Status return_status = OkStatus(); for (bool start_new_file = true; start_new_file;) { std::unique_ptr video_writer = nullptr; std::string output_video_file_path; for (int image_index = 0; image_index < options_.max_frames_per_file; ++image_index) { // Get a new raw image from the decoder. StatusOr raw_image_statusor; while (!in_channel()->pcqueue()->TryPop(raw_image_statusor, absl::Seconds(5))) { if (in_channel()->IsSrcCompleted()) { raw_image_statusor = NotFoundError( "The image source completed without delivering an EOS."); break; } } if (raw_image_statusor.status().code() == StatusCode::kNotFound) { start_new_file = false; break; } // Get the raw image and write it into the current video file. auto raw_image_gstreamer_buffer_statusor = ToGstreamerBuffer(std::move(raw_image_statusor).ValueOrDie()); if (!raw_image_gstreamer_buffer_statusor.ok()) { return_status = UnknownError(absl::StrFormat( "Could not convert a raw image into a gstreamer buffer: %s", raw_image_gstreamer_buffer_statusor.status().message())); break; } auto raw_image_gstreamer_buffer = std::move(raw_image_gstreamer_buffer_statusor).ValueOrDie(); if (video_writer == nullptr) { output_video_file_path = GenerateVideoFilePath(); GstreamerVideoWriter::Options video_writer_options; video_writer_options.file_path = output_video_file_path; video_writer_options.caps_string = raw_image_gstreamer_buffer.get_caps(); auto video_writer_statusor = GstreamerVideoWriter::Create(video_writer_options); if (!video_writer_statusor.ok()) { return_status = InternalError( absl::StrFormat("Failed to create a new video writer: %s", video_writer_statusor.status().message())); break; } video_writer = std::move(video_writer_statusor).ValueOrDie(); } auto status = video_writer->Put(raw_image_gstreamer_buffer); if (!status.ok()) { return_status = UnknownError(absl::StrFormat( "Failed to write a raw image: %s", status.message())); break; } } // Explicitly flush the video file. video_writer.reset(nullptr); if (!return_status.ok()) { if (std::remove(output_video_file_path.c_str()) != 0) { LOG(WARNING) << absl::StrFormat("%s: Failed to remove %s.", GetName(), output_video_file_path); } start_new_file = false; continue; } LOG(INFO) << absl::StrFormat("%s: Successfully wrote local file %s.", GetName(), output_video_file_path); if (options_.forward_file_paths) { // Forward the video path if downstream is still running. // Stop processing otherwise. if (!out_channel()->IsDstCompleted()) { if (!out_channel()->pcqueue()->TryEmplace(output_video_file_path)) { LOG(WARNING) << absl::StrFormat( "%s: The file path buffer is full. Omitting %s from " "downstream processing.", GetName(), output_video_file_path); } } else { start_new_file = false; continue; } } } // Cleanup. if (options_.forward_file_paths) { if (!out_channel()->pcqueue()->TryEmplace( NotFoundError("Reached EOS."))) { LOG(WARNING) << absl::StrFormat( "%s: Failed to deliver EOS to dependent workers.", GetName()); } } return return_status; } private: Options options_; std::shared_ptr>> in_channel() { return std::get<0>(in_channels_); } std::shared_ptr>> out_channel() { return std::get<0>(out_channels_); } Status ValidatePreconditions() { if (options_.max_frames_per_file <= 0) { return InvalidArgumentError( absl::StrFormat("%s: A positive value for the maximum frame count is " "expected (given %d)", GetName(), options_.max_frames_per_file)); } if (in_channel() == nullptr) { return FailedPreconditionError(absl::StrFormat( "%s: No input channel found; please Attach() one.", GetName())); } if (!in_channel()->HasSrc()) { return InternalError( absl::StrFormat("%s: The input channel has no source.", GetName())); } if (options_.forward_file_paths) { if (out_channel() == nullptr) { return FailedPreconditionError(absl::StrFormat( "%s: No output channel found; please Attach() one.", GetName())); } if (!out_channel()->HasDst()) { return InternalError(absl::StrFormat( "%s: The output channel has no destination.", GetName())); } } return OkStatus(); } std::string GenerateVideoFilePath() { // TODO: Name the files according to server conventions. // // Currently, we use the following: // [-]-.mp4 // // The is in absl's default human readable format (RFC3339). // and uses the local time. // // It is better to use the packet timestamp for the stream server // source and the gstreamer buffer time for the gstreamer input source // (although one should investigate whether the buffer's timestamp // corresponds to the event's local time; for on-device sources, this is // close to absl::Now(), but not necessarily for network sources). static const std::string session_string = RandomString(kDefaultRandomStringLength); std::string time_string = absl::FormatTime(absl::Now()); std::vector file_name_components; if (!options_.file_prefix.empty()) { file_name_components.push_back(options_.file_prefix); } file_name_components.push_back(session_string); file_name_components.push_back(time_string); std::string file_name = absl::StrJoin(file_name_components, "-"); file_name += ".mp4"; // Decide the output file path. std::string file_path = file_name; if (!options_.output_dir.empty()) { file_path = absl::StrFormat("%s/%s", options_.output_dir, file_name); } return file_path; } }; // -------------------------------------------------------------------- // GcsUploader implementation. class GcsUploader : public Worker>, std::tuple<>> { public: struct Options { bool do_work; std::string gcs_bucket_name; std::string gcs_object_dir; bool keep_local; }; explicit GcsUploader(const Options& options) : options_(options) {} Status WorkImpl() { if (!options_.do_work) { return OkStatus(); } AIS_RETURN_IF_ERROR(ValidatePreconditions()); for (bool start_new_connection = true; start_new_connection;) { google::cloud::StatusOr client_statusor = google::cloud::storage::Client::CreateDefaultClient(); if (!client_statusor.ok()) { return UnknownError( absl::StrFormat("%s: Failed to create a GCS Client: %s", GetName(), client_statusor.status().message())); } auto gcs_client = std::move(client_statusor).value(); while (true) { // Get the path to a local video file. StatusOr file_path_statusor; while (!in_channel()->pcqueue()->TryPop(file_path_statusor, absl::Seconds(5))) { if (in_channel()->IsSrcCompleted()) { file_path_statusor = NotFoundError( absl::StrFormat("%s: The file path source completed but the " "EOS was not delivered.", GetName())); break; } } if (file_path_statusor.status().code() == StatusCode::kNotFound) { start_new_connection = false; break; } // Upload the file. auto file_path = std::move(file_path_statusor).ValueOrDie(); auto object_name = GenerateGcsObjectName(file_path); google::cloud::StatusOr metadata = gcs_client.UploadFile( file_path, options_.gcs_bucket_name, object_name); // TODO: Currently we force all errors to recover by trying to get a new // GCS connection. Clearly, this can be improved, but it works as a big // hammer to take care of poor connectivity cases. if (!metadata.ok()) { LOG(WARNING) << absl::StrFormat("%s: Failed to upload %s to GCS: %s", GetName(), file_path, metadata.status().message()); break; } LOG(INFO) << absl::StrFormat( "%s: Successfully uploaded %s to gs://%s/%s.", GetName(), file_path, (*metadata).bucket(), (*metadata).name()); // Remove the local file. if (!options_.keep_local) { if (std::remove(file_path.c_str()) != 0) { LOG(WARNING) << absl::StrFormat("%s: Failed to remove %s.", GetName(), file_path); } } } } return OkStatus(); } private: Options options_; Status ValidatePreconditions() { if (options_.gcs_bucket_name.empty()) { return InvalidArgumentError(absl::StrFormat( "%s: You must supply a non-empty GCS bucket name.", GetName())); } if (in_channel() == nullptr) { return FailedPreconditionError(absl::StrFormat( "%s: No input channel found; please Attach() one.", GetName())); } if (!in_channel()->HasSrc()) { return InternalError( absl::StrFormat("%s: The input channel has no source.", GetName())); } return OkStatus(); } std::shared_ptr>> in_channel() { return std::get<0>(in_channels_); } std::string GenerateGcsObjectName(const std::string& file_path) { std::string file_name(file::Basename(file_path)); if (options_.gcs_object_dir.empty()) { return file_name; } if (!absl::EndsWith(options_.gcs_object_dir, "/")) { return absl::StrFormat("%s/%s", options_.gcs_object_dir, file_name); } else { return absl::StrFormat("%s%s", options_.gcs_object_dir, file_name); } } }; } // namespace // -------------------------------------------------------------------- // GstreamerVideoExporter implementation. GstreamerVideoExporter::GstreamerVideoExporter(const Options& options) : options_(options) {} StatusOr> GstreamerVideoExporter::Create(const Options& options) { if (options.working_buffer_size <= 0) { return InvalidArgumentError( "You must supply a positive value for the working buffer size"); } auto video_exporter = std::make_unique(options); return video_exporter; } Status GstreamerVideoExporter::Run() { if (has_been_run_) { return FailedPreconditionError( "This video exporter has already been Run. Please Create a new " "instance and try again."); } has_been_run_ = true; // Create the workers and connect them up with channels. GcsUploader::Options gcs_uploader_options; gcs_uploader_options.do_work = options_.upload_to_gcs; gcs_uploader_options.gcs_bucket_name = options_.gcs_bucket_name; gcs_uploader_options.gcs_object_dir = options_.gcs_object_dir; gcs_uploader_options.keep_local = options_.keep_local; auto gcs_uploader = std::make_shared(gcs_uploader_options); gcs_uploader->SetName(kGcsUploaderName); LocalVideoSaver::Options local_video_saver_options; local_video_saver_options.output_dir = options_.output_dir; local_video_saver_options.file_prefix = options_.file_prefix; local_video_saver_options.max_frames_per_file = options_.max_frames_per_file; local_video_saver_options.forward_file_paths = options_.upload_to_gcs; auto local_video_saver = std::make_shared(local_video_saver_options); local_video_saver->SetName(kLocalVideoSaverName); StreamServerSource::Options stream_server_source_options; stream_server_source_options.receiver_options = options_.receiver_options; auto stream_server_source = std::make_shared(stream_server_source_options); stream_server_source->SetName(kStreamServerSourceName); GstreamerInputSource::Options gstreamer_input_source_options; gstreamer_input_source_options.gstreamer_input_pipeline = options_.gstreamer_input_pipeline; auto gstreamer_input_source = std::make_shared(gstreamer_input_source_options); gstreamer_input_source->SetName(kGstreamerInputSourceName); auto file_path_channel = std::make_shared>>( options_.working_buffer_size); auto status = Attach<0, 0>(file_path_channel, local_video_saver, gcs_uploader); if (!status.ok()) { LOG(ERROR) << status; return UnknownError( absl::StrFormat("Failed to Attach workers \"%s\" and \"%s\".", local_video_saver->GetName(), gcs_uploader->GetName())); } auto raw_image_channel = std::make_shared>>( options_.working_buffer_size); if (options_.use_gstreamer_input_source) { status = Attach<0, 0>(raw_image_channel, gstreamer_input_source, local_video_saver); if (!status.ok()) { LOG(ERROR) << status; return UnknownError(absl::StrFormat( "Failed to Attach workers \"%s\" and \"%s\".", gstreamer_input_source->GetName(), local_video_saver->GetName())); } } else { status = Attach<0, 0>(raw_image_channel, stream_server_source, local_video_saver); if (!status.ok()) { LOG(ERROR) << status; return UnknownError(absl::StrFormat( "Failed to Attach workers \"%s\" and \"%s\".", stream_server_source->GetName(), local_video_saver->GetName())); } } // Start the workers. gcs_uploader->Work(); local_video_saver->Work(); // Wait for the video source to complete. Status video_source_status = OkStatus(); if (options_.use_gstreamer_input_source) { gstreamer_input_source->Work(); while (!gstreamer_input_source->Join(absl::Seconds(5))) ; video_source_status = gstreamer_input_source->GetStatus(); } else { stream_server_source->Work(); while (!stream_server_source->Join(absl::Seconds(5))) ; video_source_status = stream_server_source->GetStatus(); } // Join the other workers. std::string deadline_exceeded_message = "\"%s\" did not finalize its work in time. It will be detached."; Status local_video_saver_status = OkStatus(); if (!local_video_saver->Join(options_.finalization_deadline)) { local_video_saver_status = DeadlineExceededError( absl::StrFormat(absl::string_view(deadline_exceeded_message), local_video_saver->GetName())); } else { local_video_saver_status = local_video_saver->GetStatus(); } Status gcs_uploader_status = OkStatus(); if (!gcs_uploader->Join(options_.finalization_deadline)) { gcs_uploader_status = DeadlineExceededError(absl::StrFormat( absl::string_view(deadline_exceeded_message), gcs_uploader->GetName())); } else { gcs_uploader_status = gcs_uploader->GetStatus(); } // Report errors. Status return_status = OkStatus(); Status error_status = UnknownError("The Run() did not complete successfully."); if (!video_source_status.ok()) { LOG(ERROR) << video_source_status; return_status = error_status; } if (!local_video_saver_status.ok()) { LOG(ERROR) << local_video_saver_status; return_status = error_status; } if (!gcs_uploader_status.ok()) { LOG(ERROR) << gcs_uploader_status; return_status = error_status; } return return_status; } GstreamerVideoExporter::~GstreamerVideoExporter() {} } // namespace aistreams #include "game_options.hpp" #include "input.hpp" #include #include #include namespace bulls_and_cows { // Affichage des options du jeu // utilisation d'objets output stream void display_game_options(std::ostream& output_stream, const GameOptions& game_options) { output_stream << "Voici les options du jeu: " << std::endl; output_stream << "Le nombre maximal de tentatives est: " << game_options.max_number_of_attempts << std::endl; output_stream << "Le nombre maximal de caracteres est: " << game_options.number_of_characters_per_code << std::endl; output_stream << "Eventail des caracteres autorises: entre " << game_options.minimum_allowed_character << " et " << game_options.maximum_allowed_character << std::endl; } // Affichage du menu des options du jeu // utilisation d'objets output stream void display_game_options_menu(std::ostream& output_stream) { output_stream << "Configuration des options:" << std::endl; output_stream << "0 - Retour au menu principal" << std::endl; output_stream << "1 - Modifier le nombre maximal de tentative par jeu" << std::endl; output_stream << "2 - Modifier le nombre de caracteres du code" << std::endl; output_stream << "3 - Modifier l'eventail de caracteres autorises (borne inferieure)" << std::endl; output_stream << "4 - Modifier l'eventail de caractères autorises (borne superieure)" << std::endl; output_stream << "5 - Sauver les options" << std::endl; output_stream << "6 - Charger les options" << std::endl; output_stream << "Quel est votre choix ?" << std::endl; } //fonction demandant au joueur son choix dans le menu des options //on utilisera une syntaxe switch GameOptionsMenuChoice ask_game_options_menu_choice(std::istream& input_stream) { const int choix = ask_int_or_default(input_stream, -1); switch (choix) { case 0: return GameOptionsMenuChoice::BackToMain; case 1: return GameOptionsMenuChoice::ModifyMaximumNumberOfAttempts; case 2: return GameOptionsMenuChoice::ModifyNumberOfCharactersPerCode; case 3: return GameOptionsMenuChoice::ModifyMinimumAllowedCharacter; case 4: return GameOptionsMenuChoice::ModifyMaximumAllowedCharacter; case 5: return GameOptionsMenuChoice::SaveOptions; case 6: return GameOptionsMenuChoice::LoadOptions; } return GameOptionsMenuChoice::Error; } // Sauvegarde des options du jeu // on changera les valeurs dans le .txt lié aux options du jeu (avec des objets output_file_stream pour l'écriture) bool save_game_options(std::ostream& output_file_stream, const GameOptions& game_options) { if (output_file_stream) { output_file_stream << game_options.max_number_of_attempts << "\n" << game_options.number_of_characters_per_code << "\n" << game_options.minimum_allowed_character << "\n" << game_options.maximum_allowed_character << std::endl; return true; } return false; } // Chargement des options du jeu // on ira cherecher dans le .txt les options, puis on les affichera // on utilisera des objects input file stream pour la lecture bool load_game_options(std::istream& input_file_stream, GameOptions& game_options) { if (input_file_stream) { std::string ligne{}; std::getline(input_file_stream, ligne); unsigned int nb_attempt = std::stoi(ligne); game_options.max_number_of_attempts = nb_attempt; std::getline(input_file_stream, ligne); unsigned int nb_attempt1 = std::stoi(ligne); game_options.number_of_characters_per_code = nb_attempt1; std::getline(input_file_stream, ligne); char min_character = ligne[0]; game_options.minimum_allowed_character = min_character; std::getline(input_file_stream, ligne); char max_character = ligne[0]; game_options.maximum_allowed_character = max_character; return true; } return false; } } // namespace bulls_and_cows #include "erm/loaders/collada/ColladaSceneLoader.h" #include "erm/loaders/collada/ColladaLoaderUtils.h" #include "erm/rendering/data_structs/Bone.h" #include "erm/rendering/data_structs/Skin.h" #include "erm/utils/Utils.h" #include using namespace tinyxml2; namespace erm { void ProcessNode( XMLElement& node, std::unique_ptr& root, BonesTree* tree, math::mat4 parentBind, const std::map& skinsData); void ProcessScene( std::mutex& mutex, const char* path, tinyxml2::XMLDocument& document, Skins& skins, const std::map& skinsData) { XMLElement* libraryVisualScene = document.RootElement()->FirstChildElement("library_visual_scenes"); if (!libraryVisualScene) return; XMLElement* visualScene = libraryVisualScene->FirstChildElement("visual_scene"); std::unique_ptr tree = nullptr; while (visualScene) { XMLElement* node = visualScene->FirstChildElement("node"); while (node) { ProcessNode(*node, tree, tree.get(), glm::identity(), skinsData); node = node->NextSiblingElement("node"); } visualScene = visualScene->NextSiblingElement("visual_scene"); } if (tree) { mutex.lock(); skins.emplace_back(std::make_unique(path, path, std::move(tree))); mutex.unlock(); } } void ProcessNode( XMLElement& node, std::unique_ptr& root, BonesTree* tree, math::mat4 parentBind, const std::map& skinsData) { bool found = false; if (const char* boneName = node.Attribute("sid")) { for (const auto& entry : skinsData) { const ColladaSkinData& skinData = entry.second; for (unsigned int i = 0; i < skinData.mBoneNames.size(); ++i) { if (skinData.mBoneNames[i] == boneName) { std::vector values = Utils::SplitString(node.FirstChildElement("matrix")->GetText(), ' '); math::mat4 bindMatrix; ParseMatrix(values, 0, bindMatrix); parentBind *= bindMatrix; const math::mat4 parentInverseBind = glm::inverse(parentBind); if (!root) { root = std::make_unique(i, std::make_unique(bindMatrix, parentInverseBind, boneName)); tree = root.get(); } else { tree = &tree->AddChild(i, std::make_unique(bindMatrix, parentInverseBind, boneName)); } found = true; break; } } } } if (!found && std::strcmp(node.Attribute("id"), "Armature") == 0) { math::mat4 bindMatrix = glm::identity(); if (XMLElement* matrixElement = node.FirstChildElement("matrix")) { std::vector values = Utils::SplitString(node.FirstChildElement("matrix")->GetText(), ' '); ParseMatrix(values, 0, bindMatrix); } parentBind *= bindMatrix; } XMLElement* childNode = node.FirstChildElement("node"); while (childNode) { ProcessNode(*childNode, root, tree, parentBind, skinsData); childNode = childNode->NextSiblingElement("node"); } } } // namespace erm src/akDB/aMSSQLWrapper.cpp /* * File: aMSSQLWrapper.cpp * Package: akDB * * Created on: July 07, 2021 * Author: * Copyright (c) 2020 * This file is part of the uiCore component. * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. */ #include #include #include #include ak::aMSSQLWrapper::aMSSQLWrapper() : m_environmentHandle(nullptr), m_connectionHandle(nullptr), m_lastQueryHandle(nullptr), m_isConnected(false) {} ak::aMSSQLWrapper::aMSSQLWrapper( const std::string & _ipAddress, const std::string & _port, const std::string & _userName, const std::string & _password ) : m_environmentHandle(nullptr), m_connectionHandle(nullptr), m_lastQueryHandle(nullptr), m_isConnected(false) { if (!connect(_ipAddress, _port, _userName, _password)) { assert(0); throw std::exception("Failed to initialize connection to Database"); } } ak::aMSSQLWrapper::~aMSSQLWrapper() { disconnect(); } // ################################################################################################################ // Connection bool ak::aMSSQLWrapper::connect( const std::string & _ipAddress, const std::string & _port, const std::string & _userName, const std::string & _password ) { return connect(convertString(_ipAddress), convertString(_port), convertString(_userName), convertString(_password)); } bool ak::aMSSQLWrapper::connect( const std::wstring & _ipAddress, const std::wstring & _port, const std::wstring & _userName, const std::wstring & _password ) { std::wstring logInInfo{ L"DRIVER={SQL Server};SERVER=" }; logInInfo.append(_ipAddress); logInInfo.append(L", "); logInInfo.append(_port); logInInfo.append(L"; UID="); logInInfo.append(_userName); logInInfo.append(L"; PWD="); logInInfo.append(_password); logInInfo.append(L";"); return connect(logInInfo); } bool ak::aMSSQLWrapper::connect( const std::string & _connectionString ) { return connect(convertString(_connectionString)); } bool ak::aMSSQLWrapper::connect( const std::wstring & _connectionString ) { if (m_isConnected) { assert(0); return true; } //define handles and variables SQLHANDLE sqlStmtHandle; SQLWCHAR retconstring[1024]; //initializations sqlStmtHandle = NULL; //allocations if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_environmentHandle)) { return false; } if (SQL_SUCCESS != SQLSetEnvAttr(m_environmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) { return false; } if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, m_environmentHandle, &m_connectionHandle)) { return false; } // Try to connect switch (SQLDriverConnect(m_connectionHandle, NULL, (SQLWCHAR*)_connectionString.c_str(), SQL_NTS, retconstring, 1024, NULL, SQL_DRIVER_NOPROMPT)) { case SQL_SUCCESS: break; case SQL_SUCCESS_WITH_INFO: break; case SQL_INVALID_HANDLE: throw std::exception("Invalid handle"); case SQL_ERROR: throw aMSSQLConnectionException(); default: assert(0); // That should not happen throw std::exception("Unknown error"); break; } m_isConnected = true; return true; } void ak::aMSSQLWrapper::disconnect(void) { deallocateHandles(); m_isConnected = false; } SQLHANDLE ak::aMSSQLWrapper::executeQuery(const std::wstring & _query) { freeLastQueryHandle(); // Allocates the statement if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, m_connectionHandle, &m_lastQueryHandle)) { throw aMSSQLConnectionException("An error occured while allocating the statement handle"); } // Executes a preparable statement auto result = SQLExecDirectW(m_lastQueryHandle, (SQLWCHAR*)_query.c_str(), SQL_NTS); if (SQL_SUCCESS != result) { throw aMSSQLQueryException("Failed to execute query"); } else { return m_lastQueryHandle; } } // ################################################################################################################################### // Getter bool ak::aMSSQLWrapper::tableExists(const std::wstring & _table) { std::wstring query{ L"SELECT name FROM SYSOBJECTS WHERE xtype = 'U' AND name = '" }; query.append(_table).append(L"'"); auto handle = executeQuery(query); if (handle != NULL) { return SQLFetch(handle) == SQL_SUCCESS; } return false; } // #################################################################################################################################### // Helper functions std::wstring ak::aMSSQLWrapper::getSQLConnectionError(bool _includeState) { return getSQLError(SQL_HANDLE_DBC, m_connectionHandle, _includeState); } std::wstring ak::aMSSQLWrapper::getSQLEnvironmentError(bool _includeState) { return getSQLError(SQL_HANDLE_ENV, m_environmentHandle, _includeState); } std::wstring ak::aMSSQLWrapper::getSQLQueryError(bool _includeState) { return getSQLError(SQL_HANDLE_STMT, m_lastQueryHandle, _includeState); } std::wstring ak::aMSSQLWrapper::getSQLError(unsigned int _handleType, const SQLHANDLE & _handle, bool _includeState) { SQLWCHAR SQLState[1024]; SQLWCHAR message[1024]; if (SQL_SUCCESS == SQLGetDiagRec(_handleType, _handle, 1, SQLState, NULL, message, 1024, NULL)) { // Returns the current values of multiple fields of a diagnostic record that contains error, warning, and status information std::wstringstream ss; if (_includeState) { ss << L"SQL state: " << SQLState << L", SQL driver message: " << message << L"\n"; } else { ss << message; } return ss.str(); } else { return L"Unknown SQL error"; } } std::wstring ak::aMSSQLWrapper::convertString(const std::string & _str) { std::wstring_convert> myconv; return myconv.from_bytes(_str); } void ak::aMSSQLWrapper::freeLastQueryHandle(void) { freeHandle(m_lastQueryHandle, SQL_HANDLE_STMT); } void ak::aMSSQLWrapper::freeHandle(SQLHANDLE & _handle, unsigned int _handleType) { if (_handle != nullptr) { SQLFreeHandle(_handleType, _handle); _handle = nullptr; } } // #################################################################################################################################### // Private functions void ak::aMSSQLWrapper::deallocateHandles(void) { freeLastQueryHandle(); if (m_connectionHandle != NULL) { // Free the resources and disconnect SQLDisconnect(m_connectionHandle); freeHandle(m_connectionHandle, SQL_HANDLE_DBC); freeHandle(m_environmentHandle, SQL_HANDLE_ENV); } m_isConnected = false; } // #################################################################################################################################### // #################################################################################################################################### // #################################################################################################################################### // Exceptions ak::aMSSQLConnectionException::aMSSQLConnectionException() : std::exception("MSSQL connection exception") {} ak::aMSSQLConnectionException::aMSSQLConnectionException(const char * _errorText) : std::exception(_errorText) {} ak::aMSSQLQueryException::aMSSQLQueryException() : std::exception("MSSQL query exception") {} ak::aMSSQLQueryException::aMSSQLQueryException(const char * _errorText) : std::exception(_errorText) {}txml/applications/fb2/include/Empty.hpp1-10 #ifndef EMPTY_HPP #define EMPTY_HPP #include #include #include #include namespace fb2 { Empty::Empty(std::string&& str) : base(std::move(str)) { } const char *Empty::name() const noexcept { return class_name(); } template void Empty::serialize_impl(std::ostream &out, Tracer tracer/* = Tracer()*/) const { out << "<" << Empty::class_name() << getValue() << " -->\n"; } template std::shared_ptr Empty::create_impl(/*std::string &name, */txml::TextReaderWrapper &reader, Tracer tracer) { std::shared_ptr ret; if (reader.has_value()) { const std::string& tmp_value = reader.get_value(); auto it = tmp_value.begin(); if (*it == '\r' or *it == '\n') { ++it; } ret.reset( new Empty(std::string(it, tmp_value.end()))); tracer.trace("Value: '", ret->getValue(), "'"); } return ret; } } // namespace fb2 #endif //EMPTY_HPP 1-10 #include using namespace std; typedef long long int lli; typedef long double ld; #define endn "\n" void test(void) { int n; cin >> n; int temp; bool flag = false; for (int i = 0; i < n; i++) { cin >> temp; if (temp < 0) { flag = true; } } if (flag) { cout << "NO" << endn; } else { cout << "YES" << endn; cout << 101 << endn; for (int i = 0; i <= 100; i++) { cout << i << " "; } cout << endn; } } int main(void) { int T; cin >> T; while(T--) test(); return 0; } // By // Date: Sunday, June 06, 2021 | 08:50:07 PM (+06) 0 #include "Level2.h" #define LEVEL2_WIDTH 14 #define LEVEL2_HEIGHT 8 #define L2ENEMY_COUNT 2 unsigned int level2_data[] = { 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 1, 1, 3, 1, 1, 17, 9, 9, 1, 3, 1, 1, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 9, 9, 9, 9, 9, }; void Level2::Initialize() { state.nextScene = -1; state.enemyCount = L2ENEMY_COUNT; GLuint mapTextureID = Util::LoadTexture("DarkTiles.png"); state.map = new Map(LEVEL2_WIDTH, LEVEL2_HEIGHT, level2_data, mapTextureID, 1.0f, 8, 4); // Move over all of the player and enemy code from initialization. state.player = new Entity(); state.player->entityType = PLAYER; state.player->position = glm::vec3(1, 0, 0); state.player->movement = glm::vec3(0); state.player->acceleration = glm::vec3(0, -9.8f, 0); state.player->speed = 1.5f; state.player->textureID = Util::LoadTexture("Warrior.png"); state.player->animIdle = new int[6]{ 0, 1, 2, 3, 4 ,5 }; state.player->animRight = new int[6]{ 6, 7, 8, 9,10, 11 }; state.player->animAttack = new int[6]{ 18,19,20,21,22,23 }; state.player->animIndices = state.player->animIdle; state.player->animFrames = 6; state.player->animIndex = 0; state.player->animTime = 0; state.player->animCols = 6; state.player->animRows = 17; state.player->height = 1.0f; state.player->width = 0.8f; state.player->jumpPower = 5.0f; state.enemies = new Entity[L2ENEMY_COUNT]; GLuint enemeyTextureID = Util::LoadTexture("Golem.png"); state.enemies[0].position = glm::vec3(5, -2, 0); state.enemies[0].AItype = WALKER; state.enemies[0].AIState = WALKING; state.enemies[1].position = glm::vec3(8, -3, 0); state.enemies[1].AItype = LURKER; state.enemies[1].AIState = LURK; for (int i = 0; i < L2ENEMY_COUNT; i++) { state.enemies[i].entityType = ENEMY; state.enemies[i].textureID = enemeyTextureID; state.enemies[i].acceleration = glm::vec3(0, -9.8f, 0); state.enemies[i].speed = 0.5; state.enemies[i].animIdle = new int[4]{ 0, 1, 2, 3 }; state.enemies[i].animAttack = new int[9]{ 20, 21, 22, 23,24, 25,26,27,28 }; state.enemies[i].height = 1.0; state.enemies[i].width = 0.8; state.enemies[i].animIndices = new int[1]{ 37 }; state.enemies[i].animFrames = 1; state.enemies[i].animIndex = 0; state.enemies[i].animTime = 0; state.enemies[i].animCols = 10; state.enemies[i].animRows = 10; } } void Level2::Update(float deltaTime) { state.player->Update(deltaTime, state.player, state.map, state.enemies, L2ENEMY_COUNT); for (int i = 0; i < L2ENEMY_COUNT; i++) { state.enemies[i].Update(deltaTime, state.player, state.map, state.enemies, L2ENEMY_COUNT); } if (state.player->position.x > 12) { state.nextScene = 3; } } void Level2::Render(ShaderProgram* program) { state.map->Render(program); state.player->Render(program); for (int i = 0; i < L2ENEMY_COUNT; i++) { state.enemies[i].Render(program); }; }Danish-Belal/CodeCollection //strassens matrix multiplication: #include #include void display(int n, int arr[50][50]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%d\t", arr[i][j]); } printf("\n"); } } void addmatrices(int n, int a[50][50], int b[50][50], int c[50][50]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = a[i][j] + b[i][j]; } } } void submatrices(int n, int a[50][50], int b[50][50], int c[50][50]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = a[i][j] - b[i][j]; } } } void strassen(int n, int a[50][50], int b[50][50], int c[50][50]) { // printf("inside strassen function for n value %d\n",n); if (n == 2) { // printf("recursive call starts\n"); c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]; c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]; c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]; c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]; // printf("recursive call ends\n"); } else { int a00[50][50]; int a01[50][50]; int a10[50][50]; int a11[50][50]; int b00[50][50]; int b01[50][50]; int b10[50][50]; int b11[50][50]; int c00[50][50]; int c01[50][50]; int c10[50][50]; int c11[50][50]; //partitioning starts // printf("partitioning starts\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i < n / 2 && j < n / 2) { a00[i][j] = a[i][j]; b00[i][j] = b[i][j]; c00[i][j] = c[i][j]; } if (i < n / 2 && j >= n / 2) { a01[i][j - n / 2] = a[i][j]; b01[i][j - n / 2] = b[i][j]; c01[i][j - n / 2] = c[i][j]; } if (i >= n / 2 && j < n / 2) { a10[i - n / 2][j] = a[i][j]; b10[i - n / 2][j] = b[i][j]; c10[i - n / 2][j] = c[i][j]; } if (i >= n / 2 && j >= n / 2) { a11[i - n / 2][j - n / 2] = a[i][j]; b11[i - n / 2][j - n / 2] = b[i][j]; c11[i - n / 2][j - n / 2] = c[i][j]; } } } // printf("partitioning ends \n"); //partitioning ends // printf("after partitioning array a:\n");display(n/2,a00);display(n/2,a01);display(n/2,a10);display(n/2,a11); int p[50][50]; int q[50][50]; int r[50][50]; int s[50][50]; int t[50][50]; int u[50][50]; int v[50][50]; int p1[50][50]; int p2[50][50]; int q1[50][50]; int r1[50][50]; int s1[50][50]; int t1[50][50]; int u1[50][50]; int u2[50][50]; int v1[50][50]; int v2[50][50]; addmatrices(n / 2, a00, a11, p1); addmatrices(n / 2, b00, b11, p2); addmatrices(n / 2, a10, a11, q1); submatrices(n / 2, b01, b11, r1); submatrices(n / 2, b10, b00, s1); addmatrices(n / 2, a00, a01, t1); submatrices(n / 2, a10, a00, u1); addmatrices(n / 2, b00, b01, u2); submatrices(n / 2, a01, a11, v1); addmatrices(n / 2, b10, b11, v2); // printf("recursive call starts\n"); // printf("strassen p\n"); strassen(n / 2, p1, p2, p); // printf("strassen q\n"); strassen(n / 2, q1, b00, q); // printf("strassen r\n"); strassen(n / 2, a00, r1, r); // printf("strassen s\n"); strassen(n / 2, a11, s1, s); // printf("strassen t\n"); strassen(n / 2, t1, b11, t); // printf("strassen u\n"); strassen(n / 2, u1, u2, u); // printf("strassen v\n"); strassen(n / 2, v1, v2, v); // printf("recursive call ends\n"); addmatrices(n / 2, p, s, c00); submatrices(n / 2, c00, t, c00); addmatrices(n / 2, c00, v, c00); addmatrices(n / 2, r, t, c01); addmatrices(n / 2, q, s, c10); addmatrices(n / 2, p, r, c11); submatrices(n / 2, c11, q, c11); addmatrices(n / 2, c11, u, c11); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i < n / 2 && j < n / 2) { c[i][j] = c00[i][j]; } if (i < n / 2 && j >= n / 2) { c[i][j] = c01[i][j - n / 2]; } if (i >= n / 2 && j < n / 2) { c[i][j] = c10[i - n / 2][j]; } if (i >= n / 2 && j >= n / 2) { c[i][j] = c11[i - n / 2][j - n / 2]; } } } } } int main() { int a[50][50]; int b[50][50]; int c[50][50]; printf("Enter number of elements\n"); int n; // n=4; scanf("%d", &n); printf("Enter elements of matrix a\n"); for (int i = 0; i < n; i++) { printf("Enter elements of row %d\n", i); for (int j = 0; j < n; j++) // a[i][j]=j+1; scanf("%d", &a[i][j]); } printf("Enter elements of matrix b\n"); for (int i = 0; i < n; i++) { printf("Enter elements of row %d\n", i); for (int j = 0; j < n; j++) // b[i][j]=j+1; scanf("%d", &b[i][j]); } // printf("calling function\n"); double time_spent = 0.0; clock_t begin = clock(); strassen(n, a, b, c); // printf("function called successfully\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf("%d\t", c[i][j]); printf("\n"); } clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf("\nThe elapsed time is %f seconds", time_spent); return 1; } /* $Id: sparse_aln.cpp 378862 2012-10-24 19:58:27Z rafanovi $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: * * File Description: * */ #include #include #include #include #include #include #include #define NCBI_USE_ERRCODE_X Objtools_Aln_Sparse BEGIN_NCBI_SCOPE USING_SCOPE(ncbi::objects); CSparseAln::CSparseAln(const CAnchoredAln& anchored_aln, objects::CScope& scope) : m_Scope(&scope), m_GapChar('-'), m_NaCoding(CSeq_data::e_not_set), m_AaCoding(CSeq_data::e_not_set), m_AnchorDirect(true) { x_Build(anchored_aln); } CSparseAln::~CSparseAln() { } CSparseAln::TDim CSparseAln::GetDim() const { return m_Aln->GetDim(); } struct SGapRange { TSignedSeqPos from; // original position of the gap on the anchor TSignedSeqPos second_from; // position on the sequence TSignedSeqPos len; // length of the gap bool direct; int row; // Row, containing the gap. size_t idx; // Index of the gap in the original vector. // This gap's 'from' must be shifted by 'shift'. // Segments at or after 'from' position must be offset by 'shift + len'. TSignedSeqPos shift; bool operator<(const SGapRange& rg) const { if (from != rg.from) return from < rg.from; // sort by pos return row < rg.row; // lower rows go first. // Don't check the length. Stable sort will preserve the order // of consecutive gaps on the same row. } }; typedef vector TGapRanges; void CSparseAln::x_Build(const CAnchoredAln& src_align) { const TDim& dim = src_align.GetDim(); m_BioseqHandles.clear(); m_BioseqHandles.resize(dim); m_SeqVectors.clear(); m_SeqVectors.resize(dim); // Collect all gaps on all rows. They need to be inserted into the // new anchor as normal segments. TGapRanges gaps; for (TDim row = 0; row < dim; ++row) { const CPairwiseAln& pw = *src_align.GetPairwiseAlns()[row]; const CPairwiseAln::TAlignRangeVector& ins_vec = pw.GetInsertions(); gaps.reserve(gaps.size() + ins_vec.size()); for (size_t i = 0; i < ins_vec.size(); i++) { SGapRange gap; gap.from = ins_vec[i].GetFirstFrom(); gap.second_from = ins_vec[i].GetSecondFrom(); gap.len = ins_vec[i].GetLength(); gap.direct = ins_vec[i].IsDirect(); gap.row = row; gap.shift = 0; gap.idx = i; gaps.push_back(gap); } } // We need to preserve the order of consecutive gaps at the same // position on the same row. Use stable_sort. stable_sort(gaps.begin(), gaps.end()); // Set shift for all gaps. TSignedSeqPos shift = 0; NON_CONST_ITERATE(TGapRanges, gap_it, gaps) { gap_it->shift = shift; shift += gap_it->len; } m_Aln.Reset(new CAnchoredAln()); m_Aln->SetDim(dim); m_Aln->SetAnchorRow(src_align.GetAnchorRow()); m_Aln->SetScore(src_align.GetScore()); // Now for each row convert insertions to normal segments and change // the old anchor coordinates to alignment coordinates. for (TDim row = 0; row < dim; ++row) { const CPairwiseAln& pw = *src_align.GetPairwiseAlns()[row]; CPairwiseAln::const_iterator seg_it = pw.begin(); TGapRanges::const_iterator gap = gaps.begin(); TSignedSeqPos shift = 0; CRef dst(new CPairwiseAln( pw.GetFirstId(), pw.GetSecondId(), pw.GetFlags())); TSeqPos last_to = 0; bool first_direct = true; bool second_direct = true; while (seg_it != pw.end()) { CPairwiseAln::TAlignRange rg = *seg_it; first_direct = rg.IsFirstDirect(); second_direct = rg.IsDirect(); ++seg_it; // Check if there are gaps before the new segment's end. while (gap != gaps.end() && gap->from < rg.GetFirstToOpen()) { if (gap->row == row) { // Insertion in this row - align to the anchor. CPairwiseAln::TAlignRange ins(gap->from + shift, gap->second_from, gap->len, gap->direct); // Reset flags to match row orientation. ins.SetFirstDirect(first_direct); ins.SetDirect(second_direct); dst->push_back(ins); } else if (gap->from > rg.GetFirstFrom()) { // Split the range if there are insertions in other rows. CPairwiseAln::TAlignRange sub = rg; sub.SetLength(gap->from - rg.GetFirstFrom()); sub.SetFirstFrom(sub.GetFirstFrom() + shift); if (rg.IsDirect()) { rg.SetSecondFrom(rg.GetSecondFrom() + sub.GetLength()); } else { sub.SetSecondFrom(rg.GetSecondToOpen() - sub.GetLength()); } rg.SetFirstFrom(rg.GetFirstFrom() + sub.GetLength()); rg.SetLength(rg.GetLength() - sub.GetLength()); dst->push_back(sub); } shift = gap->shift + gap->len; ++gap; } rg.SetFirstFrom(rg.GetFirstFrom() + shift); dst->push_back(rg); last_to = rg.GetSecondToOpen(); } // Still have gaps in some rows? while (gap != gaps.end()) { if (gap->row == row) { CPairwiseAln::TAlignRange ins(gap->from + shift, last_to, gap->len, gap->direct); ins.SetFirstDirect(first_direct); ins.SetDirect(second_direct); dst->push_back(ins); } shift = gap->shift + gap->len; ++gap; } m_Aln->SetPairwiseAlns()[row] = dst; } // Now the new anchored alignment should contain all segments and gaps // aligned to the new anchor coordinates. m_SecondRanges.resize(dim); for (TDim row = 0; row < dim; ++row) { /// Check collections flags _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(TAlnRngColl::fInvalid) ); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(TAlnRngColl::fUnsorted) ); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(TAlnRngColl::fOverlap) ); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(TAlnRngColl::fMixedDir) ); /// Determine m_FirstRange if (row == 0) { m_FirstRange = m_Aln->GetPairwiseAlns()[row]->GetFirstRange(); } else { m_FirstRange.CombineWith(m_Aln->GetPairwiseAlns()[row]->GetFirstRange()); } /// Determine m_SecondRanges CAlignRangeCollExtender ext(*m_Aln->GetPairwiseAlns()[row]); ext.UpdateIndex(); m_SecondRanges[row] = ext.GetSecondRange(); } const CPairwiseAln& anch_pw = *m_Aln->GetPairwiseAlns()[m_Aln->GetAnchorRow()]; m_AnchorDirect = anch_pw.empty() || anch_pw.begin()->IsFirstDirect(); } CSparseAln::TRng CSparseAln::GetAlnRange() const { return m_FirstRange; } void CSparseAln::SetGapChar(TResidue gap_char) { m_GapChar = gap_char; } CRef CSparseAln::GetScope() const { return m_Scope; } const CSparseAln::TAlnRngColl& CSparseAln::GetAlignCollection(TNumrow row) { _ASSERT(row >= 0 && row < GetDim()); return *m_Aln->GetPairwiseAlns()[row]; } const CSeq_id& CSparseAln::GetSeqId(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return m_Aln->GetPairwiseAlns()[row]->GetSecondId()->GetSeqId(); } TSignedSeqPos CSparseAln::GetSeqAlnStart(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return m_Aln->GetPairwiseAlns()[row]->GetFirstFrom(); } TSignedSeqPos CSparseAln::GetSeqAlnStop(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return m_Aln->GetPairwiseAlns()[row]->GetFirstTo(); } CSparseAln::TSignedRange CSparseAln::GetSeqAlnRange(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return TSignedRange(GetSeqAlnStart(row), GetSeqAlnStop(row)); } TSeqPos CSparseAln::GetSeqStart(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return m_SecondRanges[row].GetFrom(); } TSeqPos CSparseAln::GetSeqStop(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return m_SecondRanges[row].GetTo(); } CSparseAln::TRange CSparseAln::GetSeqRange(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); return TRange(GetSeqStart(row), GetSeqStop(row)); } bool CSparseAln::IsPositiveStrand(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(CPairwiseAln::fMixedDir) ); return m_Aln->GetPairwiseAlns()[row]->IsSet(CPairwiseAln::fDirect) == m_AnchorDirect; } bool CSparseAln::IsNegativeStrand(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->IsSet(CPairwiseAln::fMixedDir) ); return m_Aln->GetPairwiseAlns()[row]->IsSet(CPairwiseAln::fReversed) == m_AnchorDirect; } bool CSparseAln::IsTranslated() const { /// TODO Does BaseWidth of 1 always mean nucleotide? Should we /// have an enum (with an invalid (unasigned) value? const int k_unasigned_base_width = 0; int base_width = k_unasigned_base_width; for (TDim row = 0; row < GetDim(); ++row) { if (base_width == k_unasigned_base_width) { base_width = m_Aln->GetPairwiseAlns()[row]->GetFirstBaseWidth(); } if (base_width != m_Aln->GetPairwiseAlns()[row]->GetFirstBaseWidth() || base_width != m_Aln->GetPairwiseAlns()[row]->GetSecondBaseWidth()) { return true; //< there *at least one* base diff base width } /// TODO or should this check be stronger: if (base_width != 1) { return true; } } return false; } inline CSparseAln::TAlnRngColl::ESearchDirection GetCollectionSearchDirection(CSparseAln::ESearchDirection dir) { typedef CSparseAln::TAlnRngColl T; switch(dir) { case CSparseAln::eNone: return T::eNone; case CSparseAln::eLeft: return T::eLeft; case CSparseAln::eRight: return T::eRight; case CSparseAln::eForward: return T::eForward; case CSparseAln::eBackwards: return T::eBackwards; } _ASSERT(false); // invalid return T::eNone; } TSignedSeqPos CSparseAln::GetAlnPosFromSeqPos(TNumrow row, TSeqPos seq_pos, ESearchDirection dir, bool try_reverse_dir) const { _ASSERT(row >= 0 && row < GetDim()); TAlnRngColl::ESearchDirection c_dir = GetCollectionSearchDirection(dir); return m_Aln->GetPairwiseAlns()[row]->GetFirstPosBySecondPos(seq_pos, c_dir); } TSignedSeqPos CSparseAln::GetSeqPosFromAlnPos(TNumrow row, TSeqPos aln_pos, ESearchDirection dir, bool try_reverse_dir) const { _ASSERT(row >= 0 && row < GetDim()); TAlnRngColl::ESearchDirection c_dir = GetCollectionSearchDirection(dir); return m_Aln->GetPairwiseAlns()[row]->GetSecondPosByFirstPos(aln_pos, c_dir); } const CBioseq_Handle& CSparseAln::GetBioseqHandle(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); if ( !m_BioseqHandles[row] ) { if ( !(m_BioseqHandles[row] = m_Scope->GetBioseqHandle(GetSeqId(row))) ) { string errstr = "Invalid bioseq handle. Seq id \"" + GetSeqId(row).AsFastaString() + "\" not in scope?"; NCBI_THROW(CAlnException, eInvalidRequest, errstr); } } return m_BioseqHandles[row]; } CSeqVector& CSparseAln::x_GetSeqVector(TNumrow row) const { _ASSERT(row >= 0 && row < GetDim()); if ( !m_SeqVectors[row] ) { CSeqVector vec = GetBioseqHandle(row).GetSeqVector (CBioseq_Handle::eCoding_Iupac, IsPositiveStrand(row) ? CBioseq_Handle::eStrand_Plus : CBioseq_Handle::eStrand_Minus); m_SeqVectors[row].Reset(new CSeqVector(vec)); } CSeqVector& seq_vec = *m_SeqVectors[row]; if ( seq_vec.IsNucleotide() ) { if (m_NaCoding != CSeq_data::e_not_set) { seq_vec.SetCoding(m_NaCoding); } else { seq_vec.SetIupacCoding(); } } else if ( seq_vec.IsProtein() ) { if (m_AaCoding != CSeq_data::e_not_set) { seq_vec.SetCoding(m_AaCoding); } else { seq_vec.SetIupacCoding(); } } return seq_vec; } void CSparseAln::TranslateNAToAA(const string& na, string& aa, int gencode) { const CTrans_table& tbl = CGen_code_table::GetTransTable(gencode); size_t na_remainder = na.size() % 3; size_t na_size = na.size() - na_remainder; if (&aa != &na) { aa.resize(na_size / 3 + (na_remainder ? 1 : 0)); } if ( na.empty() ) return; size_t aa_i = 0; int state = 0; for (size_t na_i = 0; na_i < na_size; ) { for (size_t i = 0; i < 3; ++i, ++na_i) { state = tbl.NextCodonState(state, na[na_i]); } aa[aa_i++] = tbl.GetCodonResidue(state); } if (na_remainder) { aa[aa_i++] = '\\'; } if (&aa == &na) { aa.resize(aa_i); } } string& CSparseAln::GetSeqString(TNumrow row, string &buffer, TSeqPos seq_from, TSeqPos seq_to, bool force_translation) const { _ASSERT(row >= 0 && row < GetDim()); buffer.erase(); int width = m_Aln->GetPairwiseAlns()[row]->GetSecondBaseWidth(); if (width > 1) { seq_from /= 3; seq_to /= 3; force_translation = false; // do not translate AAs. } if (seq_to >= seq_from) { CSeqVector& seq_vector = x_GetSeqVector(row); size_t size = seq_to - seq_from + 1; buffer.resize(size, m_GapChar); if (IsPositiveStrand(row)) { seq_vector.GetSeqData(seq_from, seq_to + 1, buffer); } else { TSeqPos vec_size = seq_vector.size(); seq_vector.GetSeqData(vec_size - seq_to - 1, vec_size - seq_from, buffer); } if ( force_translation ) { TranslateNAToAA(buffer, buffer); } } return buffer; } string& CSparseAln::GetSeqString(TNumrow row, string &buffer, const TRange &rq_seq_range, bool force_translation) const { _ASSERT(row >= 0 && row < GetDim()); TRange seq_range = rq_seq_range; if ( seq_range.IsWhole() ) { seq_range = GetSeqRange(row); } return GetSeqString(row, buffer, seq_range.GetFrom(), seq_range.GetTo(), force_translation); } string& CSparseAln::GetAlnSeqString(TNumrow row, string &buffer, const TSignedRange &rq_aln_range, bool force_translation) const { _ASSERT(row >= 0 && row < GetDim()); TSignedRange aln_range(rq_aln_range); if ( aln_range.IsWhole() ) { aln_range = GetSeqAlnRange(row); } buffer.erase(); if (aln_range.GetLength() <= 0) { return buffer; } const CPairwiseAln& pairwise_aln = *m_Aln->GetPairwiseAlns()[row]; if (pairwise_aln.empty()) { string errstr = "Invalid (empty) row (" + NStr::IntToString(row) + "). Seq id \"" + GetSeqId(row).AsFastaString() + "\"."; NCBI_THROW(CAlnException, eInvalidRequest, errstr); } CSeqVector& seq_vector = x_GetSeqVector(row); TSeqPos vec_size = seq_vector.size(); const int base_width = pairwise_aln.GetSecondBaseWidth(); bool translate = force_translation || pairwise_aln.GetSecondId()->IsProtein(); // buffer holds sequence for "aln_range", 0 index corresonds to aln_range.GetFrom() size_t size = aln_range.GetLength(); if (translate) { size /= 3; } buffer.resize(size, m_GapChar); string s; // current segment sequence CSparse_CI it(*this, row, IAlnSegmentIterator::eSkipInserts, aln_range); while ( it ) { const IAlnSegment::TSignedRange& aln_r = it->GetAlnRange(); // in alignment const IAlnSegment::TSignedRange& row_r = it->GetRange(); // on sequence if ( row_r.Empty() ) { ++it; continue; } size_t off; if (base_width == 1) { // TODO performance issue - waiting for better API if (IsPositiveStrand(row)) { seq_vector.GetSeqData(row_r.GetFrom(), row_r.GetToOpen(), s); } else { seq_vector.GetSeqData(vec_size - row_r.GetToOpen(), vec_size - row_r.GetFrom(), s); } if (translate) { TranslateNAToAA(s, s); } off = aln_r.GetFrom() - aln_range.GetFrom(); if (translate) { off /= 3; } } else { _ASSERT(base_width == 3); IAlnSegment::TSignedRange prot_r = row_r; if (prot_r.GetLength() > 0) { prot_r.SetFrom(row_r.GetFrom() / 3); prot_r.SetLength(row_r.GetLength() < 3 ? 1 : row_r.GetLength() / 3); if (IsPositiveStrand(row)) { seq_vector.GetSeqData(prot_r.GetFrom(), prot_r.GetToOpen(), s); } else { seq_vector.GetSeqData(vec_size - prot_r.GetToOpen(), vec_size - prot_r.GetFrom(), s); } } off = (aln_r.GetFrom() - aln_range.GetFrom()) / 3; } size_t len = min(size - off, s.size()); _ASSERT(off + len <= size); if ( m_AnchorDirect ) { buffer.replace(off, len, s, 0, len); } else { buffer.replace(size - off - len, len, s, 0, len); } ++it; } return buffer; } IAlnSegmentIterator* CSparseAln::CreateSegmentIterator(TNumrow row, const TSignedRange& range, IAlnSegmentIterator::EFlags flag) const { _ASSERT(row >= 0 && row < GetDim()); _ASSERT( !m_Aln->GetPairwiseAlns()[row]->empty() ); if (m_Aln->GetPairwiseAlns()[row]->empty()) { string errstr = "Invalid (empty) row (" + NStr::IntToString(row) + "). Seq id \"" + GetSeqId(row).AsFastaString() + "\"."; NCBI_THROW(CAlnException, eInvalidRequest, errstr); } return new CSparse_CI(*this, row, flag, range); } END_NCBI_SCOPE /* * Copyright (c) 2006, (www.ondrej-danek.net) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ondrej Danek nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Projekt: The Mouse 3 Popis: Kontrola pohybu */ #include "mouse3.h" /* ================================================== Konec urovne - kdyz se dotkne bloku vychodu ================================================== */ static void KONTR_LevelEnd (int x, int y) { int pos; if (m3Man[0].X % 20 > 3) return; M3_M_SETFLAG (0, M3_F_NEXT); // Presunuti bloku z pozadi do popredi pos = 2 * (m3Lev.Sir * (y - 1) + x + 2); m3Data.lev[pos + 1] = m3Data.lev[pos]; m3Data.lev[pos + 3] = m3Data.lev[pos + 2]; pos += 2 * m3Lev.Sir; m3Data.lev[pos + 1] = m3Data.lev[pos]; m3Data.lev[pos + 3] = m3Data.lev[pos + 2]; // Odpochodovani do vychodu m3Man[0].Push = 53; } /* ================================================== Otevreni dveri ================================================== */ static void KONTR_OpenDoor (int x, int y, int &b, int pos) { int cK = b - (DVERE + (b - DVERE) / 2 * 2), cD = (b - DVERE) / 2; if (!m3Game.key[cD]) return; if (cK) { pos -= 2 * m3Lev.Sir; y--; } m3Data.lev[pos] = 0; m3Data.lev[pos + 2 * m3Lev.Sir] = 0; m3Door[cD].A = 1; m3Door[cD].X = x * 20; m3Door[cD].Y = y * 20; m3Door[cD].C = cD; b = 0; } /* ================================================== ================================================== */ static void KONTR_CheckBlock (int x, int y, int &b, int pos, int kontr) { int *znak = m3Data.znak, i; // Zkontroluj bloky ktere zabiji zespodu if ((znak[b] == 3) && (kontr == 1)) { m3Man[0].MS = m3Mon[0].MaxS; return; } // Zkontroluj bloky ktere zabiji if ((znak[b] == 4) && (kontr != 3)) { m3Man[0].MS = m3Mon[0].MaxS; return; } // Zkontroluj zda nevesel do vychodu z urovne if (znak[b] == 6 && !m3Man[0].S) { KONTR_LevelEnd (x, y); return; } // Zkontroluj zda nestoji na lede if ((znak[b] == 21) && (kontr == 3)) { M3_M_ADDFLAG(0, M3_F_ONICE); return; } // Zkontroluj zda se nedotkl dveri a pripadne je otevri if (znak[b] == 22) { KONTR_OpenDoor (x, y, b, pos); return; } // Pokud se nejedna o bonus nebo klic tak skonci if (znak[b] != 5) return; for (i = 1; i < 7; i++) SOUND_Add (400 + i * 100, 5); // Odstran bonus m3Data.lev[pos] = 0; if ((b - KLICE >= 0) && (b - KLICE < 8)) m3Game.key[(b - KLICE) / 2] = true; if (b == BULLETS) m3Game.bullets += 3; if (b == POINTS1) m3Game.points += 100; if (b == POINTS2) m3Game.points += 200; if (b == POINTS5) m3Game.points += 500; if (b == POINTS10) m3Game.points += 1000; if (b == POINTS20) m3Game.points += 2000; if (b == POINTS50) m3Game.points += 5000; if (b == EXTRALIFE || m3Game.points >= m3Game.exp) { for (i = 1; i < 21; i++) SOUND_Add (600 + (i / 2) * 100, 5); if (m3Game.life < 5) m3Game.life++; if (m3Game.points >= m3Game.exp) m3Game.exp += 50000; } } /* ================================================== Vraci atribut bloku na dane pozici Pokud je ch_p = true provadi i pripadne sbirani bonusu ================================================== */ int KONTR_Attr (int x, int y, int kontr, bool ch_p) { int b, pos; if (x < 0 || x >= m3Lev.Sir || y >= m3Lev.Vys) return 1; if (y < 0) return 0; pos = (m3Lev.Sir * y + x) << 1; b = m3Data.lev[pos]; if (!m3Data.znak[b]) b = m3Data.lev[++pos]; if (ch_p && !M3_M_ISFLAG(0, M3_F_NEXT)) KONTR_CheckBlock (x, y, b, pos, kontr); if (m3Data.znak[b] > 19) return 1; else b = m3Data.znak[b]; if ((b == 3) && ((kontr == 2) || (kontr == 3))) return 2; return b; } //*************************************************************************** static int rX, rY, rS, rV, kt; /* ================================================== Kontrola pri vyskoku ================================================== */ static void KONTR_Kontr1 (void) { int obX, obY, obC, olMS = m3Man[kt].MS; obY = rY / 20; for (obC = 0; obC <= (rS - 1) / 20; obC++) { obX = (rX + obC * 20) / 20; if (KONTR_Attr (obX, obY, 1, !kt) == 1) { m3Man[kt].S = 2; m3Man[kt].MS = olMS; m3Man[kt].Y += m3Man[kt].Ad; return; } } obX = (rX + rS - 1) / 20; if (KONTR_Attr (obX, obY, 1, !kt) == 1) { m3Man[kt].S = 2; m3Man[kt].MS = olMS; m3Man[kt].Y += m3Man[kt].Ad; } } /* ================================================== Kontrola pri padu ================================================== */ static void KONTR_Kontr2 (void) { int obX, obY, obC, obA, obP, olMS = m3Man[kt].MS; obY = (rY + rV - 1) / 20; obP = (rY + rV - m3Man[kt].Ad); obP = obP - (obP / 20) * 20; for (obC = 0; obC <= (rS - 1) / 20; obC++) { obX = (rX + obC * 20) / 20; obA = KONTR_Attr (obX, obY, 2, !kt); if ((obA == 1) || ((obA == 2) && (obP == 0))) { m3Man[kt].MS = olMS; m3Man[kt].S = 0; m3Man[kt].Y -= m3Man[kt].Ad; return; } } obX = (rX + rS - 1) / 20; obA = KONTR_Attr (obX, obY, 2, !kt); if ((obA == 1) || ((obA == 2) && (obP == 0))) { m3Man[kt].MS = olMS; m3Man[kt].S = 0; m3Man[kt].Y -= m3Man[kt].Ad; } } /* ================================================== Kontrola zda stoji na pevnem ================================================== */ static void KONTR_Kontr3 (void) { int obX, obY, obC, obA, obP; bool pra = true, npra = false; obY = (rY + rV) / 20; obP = (rY + rV); obP = obP - (obP / 20) * 20; for (obC = 0; obC <= (rS - 1) / 20; obC++) { obX = (rX + obC * 20) / 20; obA = KONTR_Attr (obX, obY, 3, !kt); if ((obA == 1) || ((obA == 2) && (obP == 0))) pra = false; else npra = true; } obX = (rX + rS - 1) / 20; obA = KONTR_Attr (obX, obY, 3, !kt); if ((obA == 1) || ((obA == 2) && (obP == 0))) pra = false; else npra = true; if (pra) m3Man[kt].S = 2; if (npra) M3_M_ADDFLAG (kt, M3_F_NPRA); } /* ================================================== Kontrola pri pohybu do stran ================================================== */ static void KONTR_Kontr4 (void) { int obX1, obX2, obY, obC; obX1 = rX / 20; obX2 = (rX + rS - 1) / 20; for (obC = 0; obC <= (rV - 1) / 20; obC++) { obY = (rY + obC * 20) / 20; if (rX < 0 || KONTR_Attr (obX1, obY, 4, !kt) == 1) { m3Man[kt].X += m3Man[kt].Ad; return; } if (KONTR_Attr (obX2, obY, 4, !kt) == 1) { m3Man[kt].X -= m3Man[kt].Ad; return; } } obY = (rY + rV - 1) / 20; if (KONTR_Attr (obX1, obY, 4, !kt) == 1) { m3Man[kt].X += m3Man[kt].Ad; return; } if (KONTR_Attr (obX2, obY, 4, !kt) == 1) { m3Man[kt].X -= m3Man[kt].Ad; return; } } /* ================================================== Kontroly - vstupni bod ================================================== */ void KONTR_Kontrola (int cis, int koho) { rX = m3Man[koho].X; rY = m3Man[koho].Y; rS = m3Mon[m3Man[koho].Bt].Sir; rV = m3Mon[m3Man[koho].Bt].Vys; kt = koho; if (cis == 1) KONTR_Kontr1 (); else if (cis == 2) KONTR_Kontr2 (); else if (cis == 3) KONTR_Kontr3 (); else if (cis == 4) KONTR_Kontr4 (); } 1-10 // // $Id: mscat.cpp 5009 2013-09-27 22:26:56Z pcbrefugee $ // // // Original author: <> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "pwiz/data/msdata/MSDataFile.hpp" #include "pwiz_tools/common/FullReaderList.hpp" #include "pwiz/utility/misc/Std.hpp" using namespace pwiz::cv; using namespace pwiz::msdata; /* This example program iterates through the spectra and chromatograms in a data file, writing out the m/z-intensity and time-intensity pairs in a text column format. # scanNumber msLevel m/z intensity 1 ms1 204.7591 0.00 1 ms1 204.7593 0.00 1 ms1 204.7596 1422.17 1 ms1 204.7598 3215.49 1 ms1 204.7601 3887.36 1 ms1 204.7604 2843.17 1 ms1 204.7606 582.91 1 ms1 204.7609 0.00 1 ms1 204.7611 0.00 # index id time intensity 0 TIC 30.9310 37.21 0 TIC 30.9392 95.23 0 TIC 30.9477 37.20 0 TIC 30.9558 99.50 1 SRM SIC 484.944,500.319 30.9310 34.29 1 SRM SIC 484.944,500.319 30.9477 33.29 1 SRM SIC 484.944,500.319 30.9643 29.88 1 SRM SIC 484.944,500.319 30.9809 24.00 [...] */ void cat(const char* filename) { // open the data file FullReaderList readers; // for vendor Reader support MSDataFile msd(filename, &readers); // verify that we have a SpectrumList if (!msd.run.spectrumListPtr.get() || !msd.run.spectrumListPtr->size()) { if (!msd.run.chromatogramListPtr.get() || !msd.run.chromatogramListPtr->size()) throw runtime_error("[mscat] No spectra or chromatograms found."); } else { SpectrumList& spectrumList = *msd.run.spectrumListPtr; // write header const size_t columnWidth = 14; cout << "#" << setw(columnWidth) << "scanNumber" << setw(columnWidth) << "msLevel" << setw(columnWidth) << "m/z" << setw(columnWidth) << "intensity" << endl; // iterate through the spectra in the SpectrumList for (size_t i=0, size=spectrumList.size(); i!=size; i++) { // retrieve the spectrum, with binary data const bool getBinaryData = true; SpectrumPtr spectrum = spectrumList.spectrum(i, getBinaryData); // fill in MZIntensityPair vector for convenient access to binary data vector pairs; spectrum->getMZIntensityPairs(pairs); // iterate through the m/z-intensity pairs for (vector::const_iterator it=pairs.begin(), end=pairs.end(); it!=end; ++it) { cout << " " << setw(columnWidth) << id::value(spectrum->id, "scan") << setw(columnWidth) << "ms" + spectrum->cvParam(MS_ms_level).value << setw(columnWidth) << fixed << setprecision(4) << it->mz << setw(columnWidth) << fixed << setprecision(2) << it->intensity << endl; } } } if (msd.run.chromatogramListPtr.get() && msd.run.chromatogramListPtr->size()) { ChromatogramList& chromatogramList = *msd.run.chromatogramListPtr; // write header const size_t columnWidth = 14; cout << "#" << setw(columnWidth/2) << "index" << setw(columnWidth*2) << "id" << setw(columnWidth) << "time" << setw(columnWidth) << "intensity" << endl; // iterate through the spectra in the chromatogramList for (size_t i=0, size=chromatogramList.size(); i!=size; i++) { // retrieve the chromatogram, with binary data const bool getBinaryData = true; ChromatogramPtr chromatogram = chromatogramList.chromatogram(i, getBinaryData); // fill in TimeIntensityPair vector for convenient access to binary data vector pairs; chromatogram->getTimeIntensityPairs(pairs); // iterate through the m/z-intensity pairs for (vector::const_iterator it=pairs.begin(), end=pairs.end(); it!=end; ++it) { cout << " " << setw(columnWidth/2) << chromatogram->index << setw(columnWidth*2) << chromatogram->id << setw(columnWidth) << fixed << setprecision(4) << it->time << setw(columnWidth) << fixed << setprecision(2) << it->intensity << endl; } } } } int main(int argc, char* argv[]) { try { if (argc != 2) { cout << "Usage: mscat filename\n" << "Write spectrum and chromatogram data as text to console.\n\n" << "http://proteowizard.sourceforge.net\n" << "\n"; return 1; } const char* filename = argv[1]; cat(filename); return 0; } catch (exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "Caught unknown exception.\n"; } return 1; } 1-10 /* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by - * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include #include "slavestodarkness/ChaosMarauderHorsemen.h" #include "SlavesToDarknessPrivate.h" namespace SlavesToDarkness { static const int g_basesize = 65; static const int g_wounds = 2; static const int g_minUnitSize = 10; static const int g_maxUnitSize = 30; static const int g_pointsPerBlock = 110; static const int g_pointsMaxUnitSize = g_pointsPerBlock * 3; bool ChaosMarauderHorsemen::s_registered = false; Unit *ChaosMarauderHorsemen::Create(const ParameterList ¶meters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto weapons = (WeaponOption) GetEnumParam("Weapons", parameters, Axe_And_Shield); bool iconBearer = GetBoolParam("Icon Bearer", parameters, false); bool hornblower = GetBoolParam("Hornblower", parameters, false); auto legion = (DamnedLegion) GetEnumParam("Damned Legion", parameters, g_damnedLegion[0]); auto mark = (MarkOfChaos) GetEnumParam("Mark of Chaos", parameters, g_markOfChaos[0]); return new ChaosMarauderHorsemen(legion, mark, numModels, weapons, iconBearer, hornblower, ComputePoints(parameters)); } void ChaosMarauderHorsemen::Init() { if (!s_registered) { static const std::array weapons = {Axe_And_Shield, Javelin_And_Shield, Flail}; static FactoryMethod factoryMethod = { Create, ValueToString, EnumStringToInt, ComputePoints, { IntegerParameter("Models", g_minUnitSize, g_minUnitSize, g_maxUnitSize, g_minUnitSize), EnumParameter("Weapons", Axe_And_Shield, weapons), BoolParameter("Icon Bearer"), BoolParameter("Hornblower"), EnumParameter("Damned Legion", g_damnedLegion[0], g_damnedLegion), EnumParameter("Mark of Chaos", g_markOfChaos[0], g_markOfChaos), }, CHAOS, {SLAVES_TO_DARKNESS, KHORNE, TZEENTCH, SLAANESH, NURGLE} }; s_registered = UnitFactory::Register("Chaos Marauders", factoryMethod); } } ChaosMarauderHorsemen::ChaosMarauderHorsemen(DamnedLegion legion, MarkOfChaos mark, int numModels, WeaponOption weapons, bool iconBearer, bool hornblower, int points) : SlavesToDarknessBase(legion, "Chaos Marauder Horsemen", 12, g_wounds, 5, 6, false, points) { m_keywords = {CHAOS, MORTAL, SLAVES_TO_DARKNESS, MARK_OF_CHAOS, CHAOS_MARAUDER_HORSEMEN}; m_weapons = {&m_javelinMissile, &m_axe, &m_flail, &m_javelin, &m_axeMaster, &m_flailMaster, &m_javelinMaster, &m_hooves}; m_hasMount = true; m_hooves.setMount(true); s_globalBraveryMod.connect(this, &ChaosMarauderHorsemen::iconBearer, &m_connection); setMarkOfChaos(mark); // Feigned Flight m_retreatAndCharge = true; m_retreatAndShoot = true; m_weaponOption = weapons; auto leader = new Model(g_basesize, wounds()); if (weapons == Axe_And_Shield) { leader->addMeleeWeapon(&m_axeMaster); } else if (weapons == Flail) { leader->addMeleeWeapon(&m_flailMaster); } else if (weapons == Javelin_And_Shield) { leader->addMeleeWeapon(&m_javelinMaster); leader->addMissileWeapon(&m_javelinMissile); } leader->addMeleeWeapon(&m_hooves); leader->setName(""); addModel(leader); if (iconBearer) { auto model = new Model(g_basesize, wounds()); model->setName(Model::IconBearer); if (weapons == Axe_And_Shield) model->addMeleeWeapon(&m_axe); else if (weapons == Flail) model->addMeleeWeapon(&m_flail); else if (weapons == Javelin_And_Shield) { model->addMissileWeapon(&m_javelinMissile); model->addMeleeWeapon(&m_javelin); } model->addMeleeWeapon(&m_hooves); addModel(model); } if (hornblower) { auto model = new Model(g_basesize, wounds()); model->setName(Model::Hornblower); if (weapons == Axe_And_Shield) model->addMeleeWeapon(&m_axe); else if (weapons == Flail) model->addMeleeWeapon(&m_flail); else if (weapons == Javelin_And_Shield) { model->addMissileWeapon(&m_javelinMissile); model->addMeleeWeapon(&m_javelin); } model->addMeleeWeapon(&m_hooves); addModel(model); } for (auto i = (int) m_models.size(); i < numModels; i++) { auto model = new Model(g_basesize, wounds()); if (weapons == Axe_And_Shield) model->addMeleeWeapon(&m_axe); else if (weapons == Flail) model->addMeleeWeapon(&m_flail); else if (weapons == Javelin_And_Shield) { model->addMissileWeapon(&m_javelinMissile); model->addMeleeWeapon(&m_javelin); } model->addMeleeWeapon(&m_hooves); addModel(model); } // Darkwood Shields if (m_weaponOption == Axe_And_Shield || m_weaponOption == Javelin_And_Shield) { m_save = 5; } } ChaosMarauderHorsemen::~ChaosMarauderHorsemen() { m_connection.disconnect(); } std::string ChaosMarauderHorsemen::ValueToString(const Parameter ¶meter) { if (std::string(parameter.name) == "Weapons") { if (parameter.intValue == Axe_And_Shield) { return "Barbarian Axe and Darkwood Shield"; } else if (parameter.intValue == Flail) { return "Barbarian Flail"; } else if (parameter.intValue == Javelin_And_Shield) { return "Marauder Javelin and Darkwood Shield"; } } return SlavesToDarknessBase::ValueToString(parameter); } int ChaosMarauderHorsemen::EnumStringToInt(const std::string &enumString) { if (enumString == "Barbarian Axe and Darkwood Shield") { return Axe_And_Shield; } else if (enumString == "Barbarian Flail") { return Flail; } else if (enumString == "Marauder Javelin and Darkwood Shield") { return Javelin_And_Shield; } return SlavesToDarknessBase::EnumStringToInt(enumString); } int ChaosMarauderHorsemen::runModifier() const { auto modifier = SlavesToDarknessBase::runModifier(); if (isNamedModelAlive(Model::Hornblower)) modifier += 1; return modifier; } int ChaosMarauderHorsemen::chargeModifier() const { auto modifier = SlavesToDarknessBase::chargeModifier(); if (isNamedModelAlive(Model::Hornblower)) modifier += 1; return modifier; } int ChaosMarauderHorsemen::toHitModifier(const Weapon *weapon, const Unit *target) const { // auto modifier = SlavesToDarknessBase::toHitModifier(weapon, target); if (remainingModels() >= 10) modifier++; return modifier; } int ChaosMarauderHorsemen::weaponRend(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // auto rend = SlavesToDarknessBase::weaponRend(attackingModel, weapon, target, hitRoll, woundRoll); if (remainingModels() >= 10) rend--; return rend; } int ChaosMarauderHorsemen::ComputePoints(const ParameterList& parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto points = numModels / g_minUnitSize * g_pointsPerBlock; if (numModels == g_maxUnitSize) { points = g_pointsMaxUnitSize; } return points; } int ChaosMarauderHorsemen::iconBearer(const Unit *unit) { // Icon Bearer if (isNamedModelAlive(Model::IconBearer) && (unit->owningPlayer() != owningPlayer()) && (distanceTo(unit) <= 6.0)) { return -1; } return 0; } } //SlavesToDarknessMishaVernik/LeetCode0 /* Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) Example 1: Input: [1,1,4,2,1,3] Output: 3 Explanation: Students with heights 4, 3 and the last 1 are not standing in the right positions. Note: 1 <= heights.length <= 100 1 <= heights[i] <= 100 */ class Solution { public: int heightChecker(vector& h) { vector t = h; sort(t.begin(), t.end()); int cnt = 0; for (int i = 0; i < t.size(); i++){ if (t[i] != h[i]) cnt++; } if (cnt - 1 < 0) return 0; return cnt; } };EEnginE/engine /*! * \file rFrameCounter.cpp */ /* * Copyright (C) 2015 EEnginE project * * 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 "rFrameCounter.hpp" #include "uLog.hpp" namespace e_engine { rFrameCounter::~rFrameCounter() { disableFrameCounter(true); } rFrameCounter::rFrameCounter(rWorld *_rWorld, bool _enable) : vWorld(_rWorld), vRenderedFrames(_rWorld->getRenderedFramesPtr()) { if (_enable) enableFrameCounter(); if (!vWorld) eLOG("Wrold is NULL"); } /*! * \brief The loop that outputs the frames per second in the interval defined through vSleepDelay */ void rFrameCounter::frameCounterLoop() { LOG.nameThread(L"fps"); while (vFrameCounterEnabled) { iLOG("FPS: ", *vRenderedFrames / vHelper); // Change this to output the // resulting fps in a proper way (and // as a double) *vRenderedFrames = 0; B_SLEEP(milliseconds, vSleepDelay); } } /*! * \brief Enables the frame counter */ void rFrameCounter::enableFrameCounter() { *vRenderedFrames = 0; vFrameCounterEnabled = true; frameCounterThread = std::thread(&rFrameCounter::frameCounterLoop, this); iLOG("Frame counter enabled"); } /*! * \brief Disables the frame counter * \param _join Make the current thread join the frameloopthread until it is finished */ void rFrameCounter::disableFrameCounter(bool _join) { vFrameCounterEnabled = false; if (_join) if (frameCounterThread.joinable()) frameCounterThread.join(); iLOG("Frame counter disabled"); } } // namespace e_engine // kate: indent-mode cstyle; indent-width 2; replace-tabs on; line-numbers on; #ifndef A35F0D22_56E4_4F86_82CF_11D129B9BAFE #define A35F0D22_56E4_4F86_82CF_11D129B9BAFE #include namespace scp::graphics { enum class API { OpenGL, Vulkan, Direct3D, Direct3D_12, Metal }; } #endif /* A35F0D22_56E4_4F86_82CF_11D129B9BAFE */ Synergy/src/Synergy/Renderer/Texture.cpp // Created by on 20-04-2020. // Copyright © 2020 . All rights reserved. #include #include "Synergy/Renderer/Texture.h" #include "Synergy/Application.h" #include "Synergy/Renderer/RendererAPI.h" #include "Synergy/Renderer/API/OpenGL.h" #include "Synergy/Renderer/API/OpenGL/Texture.h" namespace Synergy { Synergy::Ref Texture::Create(uint32_t width, uint32_t height, Synergy::Texture::Parameters parameters) { switch (Synergy::Renderer::RendererAPI::Get()) { case Synergy::Renderer::RendererAPI::API::OpenGL: struct RefEnabler: public Synergy::Renderer::OpenGL::Texture { explicit RefEnabler(uint32_t width, uint32_t height, Synergy::Texture::Parameters parameters): Synergy::Renderer::OpenGL::Texture(width, height, parameters) { } }; return Synergy::CreateRef(width, height, parameters); default: break; } SYNERGY_ASSERT(false, "Textures aren't supported in the currently selected RendererAPI."); return nullptr; } Synergy::Ref Texture::Load(const char* path, Synergy::Texture::Parameters parameters) { int width, height, channels; stbi_set_flip_vertically_on_load(1); stbi_uc* data = stbi_load(path, &width, &height, &channels, 0); SYNERGY_ASSERT(data, stbi_failure_reason()); parameters.format = channels == 4 ? Synergy::Texture::Format::RGBA : Synergy::Texture::Format::RGB; Synergy::Ref texture = Synergy::Texture::Create(width, height, parameters); texture->SetData(data, width * height * channels); stbi_image_free(data); return texture; } Texture::Texture(uint32_t width, uint32_t height, Texture::Parameters parameters) : width(width), height(height), parameters(parameters) { } uint32_t Texture::GetWidth() const { return width; } uint32_t Texture::GetHeight() const { return height; } const glm::vec2* Texture::GetUVs() const { static constexpr glm::vec2 uvs[] = { { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; return uvs; } } #include "HLCReadyAggregator.hpp" /** * \file HLCReadyAggregator.cpp * \ingroup lcc */ //The reader callback is initialized in the init list of the constructor; store all IDs in a map together with the current time in nanoseconds HLCReadyAggregator::HLCReadyAggregator() : async_hlc_reader( [&](std::vector& samples){ //Lock the mutex for thread-safe access std::lock_guard lock(hlc_list_mutex); //Store new IDs / update receive time //Checks for on-/offline NUCs are performed in get_hlc_ids_string, which is called regularly by the UI for (auto& data : samples) { auto id_string = data.source_id(); //Convert ID to uint8_t try { int id_int = std::stoi(id_string); if (id_int < 0 || id_int > 255) { throw std::runtime_error("HLC ID is too small / too large"); } uint8_t id_uint8 = static_cast(id_int); hlc_map[id_uint8] = cpm::get_time_ns(); //Store whether the programs on the HLC are currently running (with a small risk that the order of msgs is not correct) hlc_script_running[id_uint8] = data.script_running(); hlc_middleware_running[id_uint8] = data.middleware_running(); } catch (const std::runtime_error& err) { cpm::Logging::Instance().write(2, "Error on converting HLC ID %s: %s", id_string.c_str(), err.what()); } catch (...) { cpm::Logging::Instance().write(2, "Error: Could not convert HLC ID %s to int in HLCReadyAggregator", id_string.c_str()); } } }, "hlc_hello", true) { } std::vector HLCReadyAggregator::get_hlc_ids_string() { auto ids_uint = get_hlc_ids_uint8_t(); std::vector valid_hlc_ids; for (auto entry : ids_uint) { //Convert ID to string (convert to int first, or uint8_t is interpreted as symbol) valid_hlc_ids.push_back(std::to_string(static_cast(entry))); } return valid_hlc_ids; } std::vector HLCReadyAggregator::get_hlc_ids_uint8_t() { //Lock the mutex for thread-safe access std::lock_guard lock(hlc_list_mutex); //Only use IDs that are still up-to-date uint64_t current_time_ns = cpm::get_time_ns(); std::vector valid_hlc_ids; for (auto iterator = hlc_map.begin(); iterator != hlc_map.end();) { if (current_time_ns - iterator->second < time_to_live_ns) { valid_hlc_ids.push_back(iterator->first); ++iterator; } else { cpm::Logging::Instance().write(1, "HLC / NUC crashed / now offline / missed online message: %s", std::to_string(static_cast(iterator->first)).c_str()); iterator = hlc_map.erase(iterator); } } return valid_hlc_ids; } bool HLCReadyAggregator::script_running_on(uint8_t hlc_id) { std::lock_guard lock(hlc_list_mutex); //Considered not running if no HLC msg has been received auto iterator = hlc_map.find(hlc_id); if (iterator == hlc_map.end()) { return false; } //Considered not running if data is not up to date if (cpm::get_time_ns() - iterator->second >= time_to_live_ns) { return false; } //Else, obtain the actual value - which must exist if an entry in hlc_map exists return hlc_script_running.at(hlc_id); } bool HLCReadyAggregator::middleware_running_on(uint8_t hlc_id) { std::lock_guard lock(hlc_list_mutex); //Considered not running if no HLC msg has been received auto iterator = hlc_map.find(hlc_id); if (iterator == hlc_map.end()) return false; //Considered not running if data is not up to date if (cpm::get_time_ns() - iterator->second >= time_to_live_ns) { return false; } //Else, obtain the actual value - which must exist if an entry in hlc_map exists return hlc_middleware_running.at(hlc_id); } /*************************************************************************** * * Perceptron.hpp * * * * This is a Perceptron Class header * * *************************************************************************** * Copyright 2018 whuang022. * * 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 PERCEPTRON_H_ /* Include guard */ #define PERCEPTRON_H_ #include "Matrix.hpp" using namespace std; class Perceptron{ public : Perceptron(MatrixFuction *activation,MatrixFuction *activationDiv,int inputDim,double learningRate); void trainStepSGD(Matrix &X, Matrix &D); void train(Matrix &X, Matrix &D); private: MatrixFuction *activation; MatrixFuction *activationDiv; Matrix *WIO;//weight Input-Output double learningRate=0.5; }; #endif // HELLO_H_/* https://www.hackerrank.com/challenges/mandragora/problem The evil forest is guarded by vicious mandragoras. Garnet and her pet must make a journey through. She starts with health point () and experience points. As she encouters each mandragora, her choices are: Garnet's pet eats mandragora . This increments by and defeats mandragora . Garnet's pet battles mandragora . This increases by experience points and defeats mandragora . Once she defeats a mandragora, it is out of play. Given a list of mandragoras with various health levels, determine the maximum number of experience points she can collect on her journey. For example, as always, she starts out with health point and experience points. Mandragoras have the following health values: . For each of the beings, she has two choices, at or attle. We have the following permutations of choices and outcomes: Action s p _______ _ __ e, e, e 4 0 e, e, b 3 15 e, b, b 2 14 b, b, b 1 10 b, b, e 2 10 b, e, e 3 9 b, e, b 2 16 e, b, e 3 6 Working through a couple of rows, first, her pet can eat all three and she does not gain any experience points. In the second row, her pet eats the first two to have health points, then battles the beast with heatlth points to gain experience points. We see that the best option is to eat the beast with points and battle the others to achieve experience points. Function Description Complete the mandragora function in the editor below. It must return an integer that denotes the maximum number of experience points that Garnet can earn. mandragora has the following parameter(s): H: an array of integers that represents the health values of mandragoras Input Format The first line contains an integer, , denoting the number of test cases. Each test case is described over two lines: The first line contains a single integer , the number of mandragoras in the forest. The second line contains space-separated integers describing the respective health points for the mandragoras . Constraints , where The sum of all s in a single test case is Output Format For each test case, print a single line with an integer denoting the maximum number of experience points that Garnet can earn. Sample Input 1 3 3 2 2 Sample Output 10 Explanation There are mandragoras having the following health points: . Initially, and . The following is an optimal sequence of actions for achieving the maximum number of experience points possible: Eat the second mandragora ( ). is increased from to , and is still . Battle the first mandragora ( ). remains the same, but increases by experience points. Battle the third mandragora ( ). remains the same, but increases by experience points. Garnet earns experience points. */ #include //#define DEBUG 1 #undef DEBUG #include #include using namespace std; const bool continue_on_failure = false; long mandragora2(vector H, long s, long p, size_t start_index) { if (start_index == H.size()) return p; return max(mandragora2(H, s + 1, p, start_index+1), mandragora2(H, s, p + s * H[start_index], start_index+1)); } long mandragora2(vector &H) { sort(H.begin(), H.end()); return mandragora2(H, 1, 0, 0); } long mandragora(vector &H) { sort(H.begin(), H.end()); long hsum = 0, p = 0, s = 1; for (auto h : H) hsum += h; for (auto h : H) { if ((s * hsum) > (s+1) * (hsum - h)) p += s * h; else s += 1; hsum -= h; } return p; } long mandragora_bf(vector H, vector S, long s = 1, long p = 0) { // printf("%s(%s, %s, s(%ld), p(%ld))\n", // __func__, array2str(H).c_str(), array2str(S).c_str(), s, p); if ((H.size() == 0) and (S.size() == 0)) return p; /* e or beat or skip the next in H or eat or beat or skip the next in skip */ int h = -1; long p_eatS = 0, p_beatS = 0, p_skipS = 0, p_eatH = 0, p_beatH = 0, p_skipH = 0; if (H.size()) { h = H.back(); H.pop_back(); p_eatH = mandragora_bf(H, S, s + 1, p); p_beatH = mandragora_bf(H, S, s, p + s * h); S.emplace_back(h); p_skipH = mandragora_bf(H, S, s, p); S.pop_back(); H.emplace_back(h); } if (S.size()) { h = S.back(); S.pop_back(); p_eatS = mandragora_bf(H, S, s + 1, p); p_beatS = mandragora_bf(H, S, s, p + s * h); // if (H.size()) // { // S.emplace(S.begin(), h); // p_skipS = mandragora(H, S, s, p); // } } return max(max(max(max(max(p_eatH, p_beatH), p_skipH), p_eatS), p_beatS), p_skipS); } long mandragora_bf(vector &H) { vector S; S.reserve(H.size()); return mandragora_bf(H, S); } int run_test_case(void *_s, TestCase *tc) { UNUSED(_s); vector x = tc->test_case[JSON_TEST_CASE_IN_FIELDNAME]; long expected = tc->test_case[JSON_TEST_CASE_EXPECTED_FIELDNAME]; long result = mandragora(x); if (result == expected) return 0; printf("mandragora(%s) returned %ld but expected %ld\n", array2str(x).c_str(), result, expected); assert(continue_on_failure); return 1; } int main(int argc, char **argv) { int tests_ran = 0; const char *tc_id = NULL; if (argc < 2 || argc > 3) { cerr << "Usage: " << argv[0] << " [test case index or name]" << endl; cerr << "Where: [test case index or name] specifies which test to run (all by default)" << endl; return -1; } UnitTests uts(NULL, &run_test_case, argv[1]); if (argc == 3) tc_id = argv[2]; int errors_count = uts.run_test_cases(tc_id, tests_ran); if (errors_count == 0) cout << "All " << tests_ran << " test(s) succeeded!!!" << endl; else cout << errors_count << " test(s) failed over a total of " << tests_ran << endl; return errors_count; } mcoughli/platform-system-core /* * Copyright (C) 2008 The Android Open Source Project * * 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 #include #include #include #define LOG_TAG "Property" #include #include "Property.h" Property::Property(const char *name, bool readOnly, int type, int numElements) : mName(name), mReadOnly(readOnly), mType(type), mNumElements(numElements) { if (index(name, '.')) { LOGW("Property name %s violates namespace rules", name); } } StringProperty::StringProperty(const char *name, bool ro, int elements) : Property(name, ro, Property::Type_STRING, elements) { } int StringProperty::set(int idx, int value) { LOGE("Integer 'set' called on string property!"); errno = EINVAL; return -1; } int StringProperty::set(int idx, struct in_addr *value) { LOGE("IpAddr 'set' called on string property!"); errno = EINVAL; return -1; } int StringProperty::get(int idx, int *buffer) { LOGE("Integer 'get' called on string property!"); errno = EINVAL; return -1; } int StringProperty::get(int idx, struct in_addr *buffer) { LOGE("IpAddr 'get' called on string property!"); errno = EINVAL; return -1; } StringPropertyHelper::StringPropertyHelper(const char *name, bool ro, char *buffer, size_t max) : StringProperty(name, ro, 1) { mBuffer = buffer; mMax = max; } int StringPropertyHelper::set(int idx, const char *value) { if (idx != 0) { LOGW("Attempt to use array index on StringPropertyHelper::set"); errno = EINVAL; return -1; } strncpy(mBuffer, value, mMax); return 0; } int StringPropertyHelper::get(int idx, char *buffer, size_t max) { if (idx != 0) { LOGW("Attempt to use array index on StringPropertyHelper::get"); errno = EINVAL; return -1; } strncpy(buffer, mBuffer, max); return 0; } IntegerProperty::IntegerProperty(const char *name, bool ro, int elements) : Property(name, ro, Property::Type_INTEGER, elements) { } int IntegerProperty::set(int idx, const char *value) { LOGE("String 'set' called on integer property!"); errno = EINVAL; return -1; } int IntegerProperty::set(int idx, struct in_addr *value) { LOGE("IpAddr 'set' called on integer property!"); errno = EINVAL; return -1; } int IntegerProperty::get(int idx, char *buffer, size_t max) { LOGE("String 'get' called on integer property!"); errno = EINVAL; return -1; } int IntegerProperty::get(int idx, struct in_addr *buffer) { LOGE("IpAddr 'get' called on integer property!"); errno = EINVAL; return -1; } IntegerPropertyHelper::IntegerPropertyHelper(const char *name, bool ro, int *buffer) : IntegerProperty(name, ro, 1) { mBuffer = buffer; } int IntegerPropertyHelper::set(int idx, int value) { if (idx != 0) { LOGW("Attempt to use array index on IntegerPropertyHelper::set"); errno = EINVAL; return -1; } *mBuffer = value; return 0; } int IntegerPropertyHelper::get(int idx, int *buffer) { if (idx != 0) { LOGW("Attempt to use array index on IntegerPropertyHelper::get"); errno = EINVAL; return -1; } *buffer = *mBuffer; return 0; } IPV4AddressProperty::IPV4AddressProperty(const char *name, bool ro, int elements) : Property(name, ro, Property::Type_IPV4, elements) { } int IPV4AddressProperty::set(int idx, const char *value) { LOGE("String 'set' called on ipv4 property!"); errno = EINVAL; return -1; } int IPV4AddressProperty::set(int idx, int value) { LOGE("Integer 'set' called on ipv4 property!"); errno = EINVAL; return -1; } int IPV4AddressProperty::get(int idx, char *buffer, size_t max) { LOGE("String 'get' called on ipv4 property!"); errno = EINVAL; return -1; } int IPV4AddressProperty::get(int idx, int *buffer) { LOGE("Integer 'get' called on ipv4 property!"); errno = EINVAL; return -1; } IPV4AddressPropertyHelper::IPV4AddressPropertyHelper(const char *name, bool ro, struct in_addr *buffer) : IPV4AddressProperty(name, ro, 1) { mBuffer = buffer; } int IPV4AddressPropertyHelper::set(int idx, struct in_addr *value) { if (idx != 0) { LOGW("Attempt to use array index on IPV4AddressPropertyHelper::set"); errno = EINVAL; return -1; } memcpy(mBuffer, value, sizeof(struct in_addr)); return 0; } int IPV4AddressPropertyHelper::get(int idx, struct in_addr *buffer) { if (idx != 0) { LOGW("Attempt to use array index on IPV4AddressPropertyHelper::get"); errno = EINVAL; return -1; } memcpy(buffer, mBuffer, sizeof(struct in_addr)); return 0; } PropertyNamespace::PropertyNamespace(const char *name) { mName = strdup(name); mProperties = new PropertyCollection(); } PropertyNamespace::~PropertyNamespace() { PropertyCollection::iterator it; for (it = mProperties->begin(); it != mProperties->end();) { delete (*it); it = mProperties->erase(it); } delete mProperties; free(mName); } #include #include #include "Vector.h" #include "Matrix.h" /* Matrices in input files are formatted: rows columns elem_0_0 elem_0_1 ... elem_0_n elem_1_n ... elem_m_n */ Matrix::Matrix(double **Ptr, int Rows, int Cols) { (*this).rows = Rows; (*this).cols = Cols; (*this).ptr = new double*[(*this).rows]; for (int i = 0; i < (*this).rows; i++) ptr[i] = new double[(*this).cols]; for (int i = 0; i < (*this).rows; i++) for (int j = 0; j < (*this).cols; j++) (*this).ptr[i][j] = Ptr[i][j]; } Matrix::Matrix() { (*this).rows = 0; (*this).cols = 0; ptr = NULL; } Matrix::Matrix(const Matrix& obj) { (*this).rows = obj.rows; (*this).cols = obj.cols; (*this).ptr = new double*[(*this).rows]; for (int i = 0; i < (*this).rows; i++) ptr[i] = new double[(*this).cols]; for (int i = 0; i < (*this).rows; i++) for (int j = 0; j < (*this).cols; j++) (*this).ptr[i][j] = obj.ptr[i][j]; } Matrix::~Matrix() { for (int i = 0; i < (*this).rows; i++) delete [] ptr[i]; delete [] ptr; } void Matrix::setPtr(double **Ptr, int PtrRows, int PtrCols) { // Check if matrix size matches before setting pointer if ((*this).rows == PtrRows && (*this).cols == PtrCols) (*this).ptr = Ptr; } void Matrix::setRows(int Rows) { // Delete entire matrix for (int i = 0; i < (*this).rows; i++) delete [] ptr[i]; delete [] ptr; (*this).rows = Rows; // Allocate memory for new row sizes (*this).ptr = new double*[(*this).rows]; for (int i = 0; i < (*this).rows; i++) (*this).ptr[i] = NULL; } void Matrix::setCols(int Cols) { // Delete columns set before if ((*this).ptr == NULL) { for (int i = 0; i < (*this).rows; i++) { delete [] (*this).getPtr()[i]; } } (*this).cols = Cols; // Allocate memory for new column sizes for (int i = 0; i < (*this).rows; i++) ptr[i] = new double[(*this).cols]; } double** Matrix::getPtr() const { return (*this).ptr; } int Matrix::getRows() const { return (*this).rows; } int Matrix::getCols() const { return (*this).cols; } std::istream& operator>>(std::istream& in, Matrix& obj) { int rows, cols; in >> rows >> cols; obj.setRows(rows); obj.setCols(cols); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) in >> obj.ptr[i][j]; return in; } std::ostream& operator<<(std::ostream& out, const Matrix& obj) { out << "Rows: " << obj.rows << std::endl << "Columns: " << obj.cols << std::endl; for(int i = 0; i < obj.rows; i++) for(int j = 0; j < obj.cols; j++) out << obj.ptr[i][j] << std::endl; return out; } // Overloaded multiplication operator to work with Matrix x Vector Vector Matrix::operator*(Vector& vector) { // Check if column number of matrix is equal to vector size // Considering vector to always be a column vector of the form size x 1 if ((*this).cols == vector.getSize()) { double *resultVector = new double[(*this).getRows()]; for (int i = 0; i < (*this).getRows(); i++) { resultVector[i] = 0; for (int j = 0; j < (*this).getCols(); j++) { resultVector[i] += (*this).getPtr()[i][j] * vector.getPtr()[j]; } } return Vector(resultVector, (*this).getRows()); } else { std::cout << "Conditions for multiplication aren't satisfied!\n"; return Vector(); } return Vector(); }/** * Copyright (C) 2016-2017 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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 "scheduler.h" #include "xrt/config.h" #include "xrt/device/device.h" #include #ifdef _WIN32 # pragma warning( disable : 4996 ) #endif namespace { static bool is_windows() { #ifdef _WIN32 return true; #else return false; #endif } static bool emulation_mode() { static bool val = (std::getenv("XCL_EMULATION_MODE") != nullptr); return val; } static bool is_sw_emulation() { // TODO check for only sw_emu. Some github examples are using "true", Remove this check once all github examples are updated static auto xem = std::getenv("XCL_EMULATION_MODE"); static bool swem = xem ? (std::strcmp(xem,"sw_emu")==0) : false; return swem; } inline bool kds_enabled(bool forceoff=false) { static bool enabled = !is_sw_emulation() && xrt::config::get_kds() && !xrt::config::get_feature_toggle("Runtime.sws") && !is_windows(); if (forceoff) enabled = false; return enabled; } // Force disabling of kds if emulation and 5.0 DSA static void emu_50_disable_kds(const xrt::device* device) { static bool done = false; if (!done) { done = true; if (!kds_enabled()) return; if (!emulation_mode()) return; if (device->getName().find("_5_0")==std::string::npos) return; // stop kds thread xrt::scheduler::stop(); // force kds off kds_enabled(true/*forceoff*/); // restart scheduler thread xrt::scheduler::start(); } } } namespace xrt { namespace scheduler { void start() { if (kds_enabled()) kds::start(); else sws::start(); } void stop() { if (kds_enabled()) kds::stop(); else sws::stop(); purge_command_freelist(); } /** * Schedule a command for execution on either sws or kds */ void schedule(const command_type& cmd) { if (kds_enabled()) kds::schedule(cmd); else sws::schedule(cmd); } void init(xrt::device* device, const axlf* top) { emu_50_disable_kds(device); if (kds_enabled()) kds::init(device,top); else sws::init(device,top); } }} // scheduler,xrt /***************************************************************************** * Project: RooFit * * * * This code was autogenerated by RooClassFactory * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // BEGIN_HTML // The Burr distribution is often used to describe insurance claims distributions or household imcome. // This implementation follows wikipedia: // https://en.wikipedia.org/wiki/Burr_distribution // END_HTML // #include "Riostream.h" #include #include "RooAbsReal.h" #include "TMath.h" ClassImp(RooBurr) RooBurr::RooBurr(const char *name, const char *title, RooAbsReal& _x, RooAbsReal& _c, RooAbsReal& _k, RooAbsReal& _lambda) : RooAbsPdf(name,title), x("x","x",this,_x), c("c","c",this,_c), k("k","k",this,_k), lambda("lambda","lambda",this,_lambda) { } RooBurr::RooBurr(const RooBurr& other, const char* name) : RooAbsPdf(other,name), x("x",this,other.x), c("c",this,other.c), k("k",this,other.k), lambda("lambda",this,other.lambda) { } Double_t RooBurr::evaluate() const { // ENTER EXPRESSION IN TERMS OF VARIABLE ARGUMENTS HERE return (c*k/lambda)*TMath::Power(x/lambda, c-1)*TMath::Power(1+TMath::Power(x/lambda, c), -k-1) ; } Int_t RooBurr::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const { // LIST HERE OVER WHICH VARIABLES ANALYTICAL INTEGRATION IS SUPPORTED, // ASSIGN A NUMERIC CODE FOR EACH SUPPORTED (SET OF) PARAMETERS // THE EXAMPLE BELOW ASSIGNS CODE 1 TO INTEGRATION OVER VARIABLE X // YOU CAN ALSO IMPLEMENT MORE THAN ONE ANALYTICAL INTEGRAL BY REPEATING THE matchArgs // EXPRESSION MULTIPLE TIMES if (matchArgs(allVars,analVars,x)) return 1 ; return 0 ; } Double_t RooBurr::analyticalIntegral(Int_t code, const char* rangeName) const { // RETURN ANALYTICAL INTEGRAL DEFINED BY RETURN CODE ASSIGNED BY getAnalyticalIntegral // THE MEMBER FUNCTION x.min(rangeName) AND x.max(rangeName) WILL RETURN THE INTEGRATION // BOUNDARIES FOR EACH OBSERVABLE x if (code==1) { return TMath::Power(1+TMath::Power(x.min(rangeName)/lambda, c), -k) - TMath::Power(1+TMath::Power(x.max(rangeName)/lambda, c), -k); } return 0 ; } #include "shape_solve.h" Shape_solve::Shape_solve() { s_max_x=0; s_min_x=INT_MAX; s_max_y=0; s_min_y = INT_MAX; dotsize = 8; } void Shape_solve::output_message(string c) { } bool Shape_solve::Inside_Last_Shape(QPoint f,QPoint start,QPoint end,int size) { return ((f.x()>s_min_x-2*size)&&(f.x()s_min_y+2*size)&&(f.y()start.x()-size)&&(f.x()start.y()-size)&&(f.y()setPen(pen); int type = current->init_type; if(type != s_Line && type != s_Pen) // 多边形完成 { vectormy_curve = current->my_curve; int curve_size = (type == s_Polygon)?(my_curve.size()-1):4; for(int i= 0;i < curve_size;i++) { if(my_curve[i].x() > s_max_x) { s_max_x = my_curve[i].x(); } if(my_curve[i].x() < s_min_x) { s_min_x = my_curve[i].x(); } if(my_curve[i].y() > s_max_y) { s_max_y = my_curve[i].y(); } if(my_curve[i].y()startpoint,end = current->endpoint; s_max_x = end.x(); s_min_x = start.x(); s_max_y = end.y(); s_min_y = start.y(); if(end.x() < start.x()) { s_max_x = start.x(); s_min_x = end.x(); } if(end.y() < start.y()) { s_max_y = start.y(); s_min_y = end.y(); } } else if(type == s_Pen) // 画笔 { for(int i = 0;i < current->my_pen.size();i++) { if(current->my_pen[i].x() > s_max_x) { s_max_x = current->my_pen[i].x(); } if(current->my_pen[i].x() < s_min_x) { s_min_x = current->my_pen[i].x(); } if(current->my_pen[i].y() > s_max_y) { s_max_y = current->my_pen[i].y(); } if(current->my_pen[i].y()my_pen[i].y(); } } } painter->drawRect(s_min_x-size,s_min_y-size,s_max_x-s_min_x+3*size,s_max_y-s_min_y+3*size); int r = 1; pen.setWidth(dotsize); painter->setPen(pen); QPointF pointf; pointf.setX(s_min_x); pointf.setY(s_min_y); painter->drawEllipse(pointf,r,r); pointf.setX(s_min_x); pointf.setY(s_max_y); painter->drawEllipse(pointf,r,r); pointf.setX(s_max_x); pointf.setY(s_min_y); painter->drawEllipse(pointf,r,r); pointf.setX(s_max_x); pointf.setY(s_max_y); painter->drawEllipse(pointf,r,r); } Problems/searchindexpostion.cpp #include #include using namespace std; class Solution { public: int searchInsert(vector& nums, int target) { int f = -1; for(int i=0;itarget){ f = i; break; } } if(f == -1){ return nums.size(); } return f; } };// Copyright 2002. // 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) #ifndef SC_WORKAROUND_DWA2002126_HPP # define SC_WORKAROUND_DWA2002126_HPP // Compiler/library version workaround macro // // Usage: // // #if SC_BOOST_WORKAROUND(SC_BOOST_MSVC, <= 1200) // ... // workaround code here // #endif // // When SC_BOOST_STRICT_CONFIG is defined, expands to 0. Otherwise, the // first argument must be undefined or expand to a numeric // value. The above expands to: // // (SC_BOOST_MSVC) != 0 && (SC_BOOST_MSVC) <= 1200 // // When used for workarounds that apply to the latest known version // and all earlier versions of a compiler, the following convention // should be observed: // // #if SC_BOOST_WORKAROUND(SC_BOOST_MSVC, SC_BOOST_TESTED_AT(1301)) // // The version number in this case corresponds to the last version in // which the workaround was known to have been required. When // SC_BOOST_DETECT_OUTDATED_WORKAROUNDS is not the defined, the macro // SC_BOOST_TESTED_AT(x) expands to "!= 0", which effectively activates // the workaround for any version of the compiler. When // SC_BOOST_DETECT_OUTDATED_WORKAROUNDS is defined, a compiler warning or // error will be issued if the compiler version exceeds the argument // to SC_BOOST_TESTED_AT(). This can be used to locate workarounds which // may be obsoleted by newer versions. # ifndef SC_BOOST_STRICT_CONFIG # define SC_BOOST_WORKAROUND(symbol, test) \ ((symbol != 0) && (1 % (( (symbol test) ) + 1))) // ^ ^ ^ ^ // The extra level of parenthesis nesting above, along with the // SC_BOOST_OPEN_PAREN indirection below, is required to satisfy the // broken preprocessor in MWCW 8.3 and earlier. // // The basic mechanism works as follows: // (symbol test) + 1 => if (symbol test) then 2 else 1 // 1 % ((symbol test) + 1) => if (symbol test) then 1 else 0 // // The complication with % is for cooperation with SC_BOOST_TESTED_AT(). // When "test" is SC_BOOST_TESTED_AT(x) and // SC_BOOST_DETECT_OUTDATED_WORKAROUNDS is #defined, // // symbol test => if (symbol <= x) then 1 else -1 // (symbol test) + 1 => if (symbol <= x) then 2 else 0 // 1 % ((symbol test) + 1) => if (symbol <= x) then 1 else divide-by-zero // # ifdef SC_BOOST_DETECT_OUTDATED_WORKAROUNDS # define SC_BOOST_OPEN_PAREN ( # define SC_BOOST_TESTED_AT(value) > value) ?(-1): SC_BOOST_OPEN_PAREN 1 # else # define SC_BOOST_TESTED_AT(value) != ((value)-(value)) # endif # else # define SC_BOOST_WORKAROUND(symbol, test) 0 # endif #endif // SC_WORKAROUND_DWA2002126_HPP 0 #include "Arduino.h" #include "oregon.hpp" #define SEND_HIGH() digitalWrite(OregonTxPin, HIGH) #define SEND_LOW() digitalWrite(OregonTxPin, LOW) #define RF_BIT_TIME 512 #define RF_2BIT_TIME 2*RF_BIT_TIME Oregon::Oregon(void) { } void Oregon::begin(byte tx_pin) { OregonTxPin = tx_pin; pinMode(OregonTxPin, OUTPUT); digitalWrite(OregonTxPin, LOW); } void Oregon::end() { pinMode(OregonTxPin, INPUT); digitalWrite(OregonTxPin, LOW); } void Oregon::send_temperature(uint8_t ch, uint8_t id, float temperature, byte battery) { DEBUG_OREGON_PRINTLN(F("- Sending temperature")); OregonMessageSize = 8; // Set type OregonMessage[0] = 0xEA; OregonMessage[1] = 0x4C; // Channel OregonMessage[2] = ch; // Id OregonMessage[3] = id; // Battery info if (!battery) OregonMessage[4] = 0x0C; else OregonMessage[4] = 0x00; setTemperature(temperature); calculateAndSetChecksum(); sendMessage(); } void Oregon::send_temperature_from_ds18(uint8_t ch, uint8_t id, int temperature, byte battery) { DEBUG_OREGON_PRINTLN(F("- Sending temperature from DS18 raw")); OregonMessageSize = 8; // Set type OregonMessage[0] = 0xEA; OregonMessage[1] = 0x4C; // Channel OregonMessage[2] = ch; // Id OregonMessage[3] = id; // Battery info if (!battery) OregonMessage[4] = 0x0C; else OregonMessage[4] = 0x00; setTemperature_ds18(temperature); calculateAndSetChecksum(); sendMessage(); } void Oregon::send_temperature_hum(uint8_t ch, uint8_t id, float temperature, byte hum, byte battery) { DEBUG_OREGON_PRINTLN(F("- Sending temperature & hum")); OregonMessageSize = 9; OregonMessage[0] = 0x1A; OregonMessage[1] = 0x2D; // Channel OregonMessage[2] = ch; // Id OregonMessage[3] = id; // Battery info if (!battery) OregonMessage[4] = 0x0C; else OregonMessage[4] = 0x00; setTemperature(temperature); setHumidity(hum); calculateAndSetChecksum(); sendMessage(); } void Oregon::sendMessage() { DEBUG_OREGON_PRINTLN(F("- Oregon Message:")); for (byte i = 0; i < OregonMessageSize; ++i) { DEBUG_OREGON_PRINT(OregonMessage[i] >> 4, HEX); DEBUG_OREGON_PRINT(OregonMessage[i] & 0x0F, HEX); } DEBUG_OREGON_PRINTLN(); DEBUG_OREGON_PRINTLN(F("- Oregon Message (reverse):")); for (byte i = 0; i < OregonMessageSize; ++i) { DEBUG_OREGON_PRINT(OregonMessage[OregonMessageSize - i - 1] >> 4, HEX); DEBUG_OREGON_PRINT(OregonMessage[OregonMessageSize - i - 1] & 0x0F, HEX); } DEBUG_OREGON_PRINTLN(); // Send the Message over RF sendOregon(); // Send a "pause" SEND_LOW(); delayMicroseconds(RF_2BIT_TIME * 8); // Send a copie of the first message. The v2.1 protocol send the // message two RF_BIT_TIME sendOregon(); } /** \brief Set the sensor temperature \param temp the temperature */ void Oregon::setTemperature(float temp) { // Set temperature sign if (temp < 0) { OregonMessage[6] = 0x08; temp *= -1; } else { OregonMessage[6] = 0x00; } // Determine decimal and float part int tempInt = (int)temp; int td = (int)(tempInt / 10); int tf = (int)round((float)((float)tempInt / 10 - (float)td) * 10); int tempFloat = (int)round((float)(temp - (float)tempInt) * 10); // Set temperature decimal part OregonMessage[5] = (td << 4); OregonMessage[5] |= tf; // Set temperature float part OregonMessage[4] |= (tempFloat << 4); } /* * * * uint8_t bcd2dec2(uint8_t n) { return n - 6 * (n/16); } */ uint8_t Oregon::dec2bcd2(uint8_t n) { uint16_t a = n; byte b = (a*103) >> 10; // this equals: b = a/10; return n + b*6; } /** \brief Set the sensor temperature \param temp the temperature in 1/128°C raw value from DS18B20 */ void Oregon::setTemperature_ds18(int16_t raw_temperature) { // raw temperature input is in 1/128°C int td; if (raw_temperature < 0) { OregonMessage[6] = 0x08; raw_temperature *= -1; } else { OregonMessage[6] = 0x00; } // Convert temperature in 1/10 of °C ( *10/128 ) raw_temperature = (10*raw_temperature)>>7; td = raw_temperature /10; OregonMessage[5] = dec2bcd2(td); OregonMessage[4] |= dec2bcd2(raw_temperature-(10*td))<<4; } /** \brief Set the sensor humidity \param hum the humidity */ void Oregon::setHumidity(byte hum) { OregonMessage[7] = (hum / 10); OregonMessage[6] |= (hum - OregonMessage[7] * 10) << 4; } /** \brief Set the sensor temperature \param temp the temperature */ void Oregon::setPressure(float pres) { if ((pres > 850) && (pres < 1100)) { OregonMessage[8] = (int)round(pres) - 856; OregonMessage[9] = 0xC0; } } /** \brief Sum data for checksum \param count number of bit to sum */ int Oregon::Sum(byte count) { int s = 0; for (byte i = 0; i < count; i++) { s += (OregonMessage[i] & 0xF0) >> 4; s += (OregonMessage[i] & 0xF); } if (int(count) != count) s += (OregonMessage[count] & 0xF0) >> 4; return s; } /** \brief Calculate checksum */ void Oregon::calculateAndSetChecksum() { if (OregonMessageSize == 8) { int s = ((Sum(6) + (OregonMessage[6] & 0xF) - 0xa) & 0xff); OregonMessage[6] |= (s & 0x0F) << 4; OregonMessage[7] = (s & 0xF0) >> 4; } else if (OregonMessageSize == 9) { OregonMessage[8] = ((Sum(8) - 0xa) & 0xFF); } else if (OregonMessageSize == 11) { OregonMessage[10] = ((Sum(10) - 0xa) & 0xFF); } } /** \brief Send logical "0" over RF \details azero bit be represented by an off-to-on transition \ of the RF signal at the middle of a clock period. \ Remenber, the Oregon v2.1 protocol add an inverted bit first */ void Oregon::sendZero(void) { SEND_HIGH(); delayMicroseconds(RF_BIT_TIME); SEND_LOW(); delayMicroseconds(RF_2BIT_TIME); SEND_HIGH(); delayMicroseconds(RF_BIT_TIME); } /** \brief Send logical "1" over RF \details a one bit be represented by an on-to-off transition \ of the RF signal at the middle of a clock period. \ Remenber, the Oregon v2.1 protocol add an inverted bit first */ void Oregon::sendOne(void) { SEND_LOW(); delayMicroseconds(RF_BIT_TIME); SEND_HIGH(); delayMicroseconds(RF_2BIT_TIME); SEND_LOW(); delayMicroseconds(RF_BIT_TIME); } /** Send a bits quarter (4 bits = MSB from 8 bits value) over RF @param data Source data to process and sent */ /** \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF \param data Data to send */ void Oregon::sendQuarterMSB(const byte data) { (bitRead(data, 4)) ? sendOne() : sendZero(); (bitRead(data, 5)) ? sendOne() : sendZero(); (bitRead(data, 6)) ? sendOne() : sendZero(); (bitRead(data, 7)) ? sendOne() : sendZero(); } /** \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF \param data Data to send */ void Oregon::sendQuarterLSB(const byte data) { (bitRead(data, 0)) ? sendOne() : sendZero(); (bitRead(data, 1)) ? sendOne() : sendZero(); (bitRead(data, 2)) ? sendOne() : sendZero(); (bitRead(data, 3)) ? sendOne() : sendZero(); } /** \brief Send an Oregon message \param data The Oregon message */ void Oregon::sendOregon(void) { //sendPreamble(); sendQuarterLSB(0xFF); sendQuarterMSB(0xFF); sendQuarterLSB(0xFF); sendQuarterMSB(0xFF); for (byte i = 0; i < OregonMessageSize; ++i) { sendQuarterLSB(OregonMessage[i]); sendQuarterMSB(OregonMessage[i]); } //sendPostamble(); if (OregonMessageSize == 8) { sendQuarterLSB(0x00); } else { sendQuarterLSB(0x00); sendQuarterMSB(0x00); } } /* Exemple de trames: OSV2 EA4C106F7011D0D30300 OSV3 FA28A428202290834B46 OSV2 EA4C106F7011D0D30300 OSV2 EA4C106F7011D0D30300 OSV3 FA28A428202290834B46 OSV2 EA4C106F7011D0D30300 OSV2 EA4C106F7011D0D30300 OSV3 FA28A428202290834B46 OSV3 FA28A428202290834B46 OSV2 EA4C106F6011C0A30600 OSV2 EA4C106F6011C0A30600 OSV2 EA4C106F6011C0A30600 OSV3 FA28A428202290834B46 OSV2 EA4C106F6011C0A30600 OSV3 FA28A428202290834B46 OSV2 EA4C106F6011C0A30600 OSV2 EA4C106F6011C0A30600 Bit 0 is sent first, then bit 1, 2, 3, 4, 5, 6, and then bit 7 of a byte The sample packet above is from a THGR122NX on channel 1 with rolling code EC . It's returning a temperature of +27.3°C, and humidity 65%: 1A 2D 10 EC 32 27 50 06 44 25 - 0-3: Device ID. The ID for THGN132N sensors is 1A2D . - 4: Channel. This corresponds to the channel slider on the back of the sensor ( 1, 2, or 4 for channel 1, 2 or 3). - 5: Battery? All of my readings have 0 for this nibble. I'm half-expecting it to become non-zero on low battery. - 6-7: Rolling code. This is a unique identifier for the sensor. It resets when the battery is replaced. - 8: The tenths digit of the temperature. - 10: The tens digit of the temperature. - 11: The unit digit of the temperature. - 12: The unit digit of the humidity. - 13: The sign for the temperature. This nibble will be 0 for a +ve temp, and non-zero for -ve. During my testing with the sensor in the freezer, I've only seen this return 0 or 8. - 15: The tens digit of the humidity. -------------------------------------------------------- | Sensor Name | Code | Type | -------------------------------------------------------- | Oregon-THR128 | | | | Oregon-THR138 | 0x0A4D | Inside Temperature | | Oregon-THC138 | | | -------------------------------------------------------- | Oregon-THC238 | | | | Oregon-THC268 | | | | Oregon-THN132N | | | | Oregon-THWR288A | 0xEA4C | Outside/Water Temp | | Oregon-THRN122N | | | | Oregon-THN122N | | | | Oregon-AW129 | | | | Oregon-AW131 | | | -------------------------------------------------------- | Oregon-THWR800 | 0xCA48 | Water Temp | -------------------------------------------------------- | Oregon-THGN122N | | | | Oregon-THGN123N | | | | Oregon-THGR122NX | 0x1A2D | Inside Temp-Hygro | | Oregon-THGR228N | | | | Oregon-THGR238 | | | | Oregon-THGR268 | | | -------------------------------------------------------- | Oregon-THGR810 | 0xFA28 | Inside Temp-Hygro | | Oregon-RTGR328N | 0x*ACC | Outside Temp-Hygro | | Oregon-THGR328N | 0xCA2C | Outside Temp-Hygro | | Oregon-WTGR800 | 0xFAB8 | Outside Temp-Hygro | -------------------------------------------------------- | Oregon-THGR918 | | | | Oregon-THGRN228NX | 0x1A3D | Outside Temp-Hygro | | Oregon-THGN500 | | | -------------------------------------------------------- | Huger - BTHR918 | 0x5A5D | Inside Temp-Hygro-Baro | -------------------------------------------------------- | Oregon-BTHR918N | | | | Oregon-BTHR968 | 0x5A6D | Inside Temp-Hygro-Baro | -------------------------------------------------------- | Oregon-RGR126 | | | | Oregon-RGR682 | 0x2A1D | Rain Gauge | | Oregon-RGR918 | | | -------------------------------------------------------- | Oregon-PCR800 | 0x2A19 | Rain Gauge | | Oregon-WTGR800 | 0x1A99 | Anemometer | | Oregon-WGR800 | 0x1A89 | Anemometer | -------------------------------------------------------- | Huger-STR918 | | | | Oregon-WGR918 | 0x3A0D | Anemometer | -------------------------------------------------------- | Oregon-UVN128 | | | | Oregon-UV138 | 0xEA7C | UV sensor | -------------------------------------------------------- | Oregon-UVN800 | 0xDA78 | UV sensor | | Oregon-RTGR328N | 0x*AEC | Date & RF_BIT_TIME | -------------------------------------------------------- | cent-a-meter | | | | OWL CM113 | 0xEAC0 | Ampere meter | | Electrisave | | | -------------------------------------------------------- | OWL CM119 | 0x1A* | | | 0x2A* | Power meter | | | 0x3A** | | -------------------------------------------------------- */ #include "Profiler.h" #include static volatile uint16_t profileIpBuf[256]; static volatile uint8_t profileIdx = 0; static bool addedTask = false; Task profilingTask(300, sendProfilingData); void sendProfilingData() { disableProfiling(); uint16_t ipBuf[256]; m_memcpy(ipBuf, (void *)profileIpBuf, sizeof(ipBuf)); m_memclr((void *)profileIpBuf, sizeof(profileIpBuf)); profileIdx = 0; MidiUart.putc(0xF0); MidiUart.putc(0x01); for (int i = 0; i < 256; i++) { MidiUart.putc((ipBuf[i] >> 14) & 0x7F); MidiUart.putc((ipBuf[i] >> 7) & 0x7F); MidiUart.putc((ipBuf[i] >> 0) & 0x7F); } MidiUart.putc(0xF7); enableProfiling(); } void enableProfiling() { SET_BIT(TIMSK, TOIE0); if (!addedTask) { GUI.addTask(&profilingTask); addedTask = true; } } void disableProfiling() { CLEAR_BIT(TIMSK, TOIE0); } static uint8_t profileCnt0 = 255; ISR(TIMER0_OVF_vect) { uint16_t fp = (uint16_t)__builtin_frame_address(0); uint8_t a, b; fp += 12; a = (*((uint8_t *)fp)); b = *((uint8_t *)(fp + 1)); // a <<= 1; // b <<= 1; uint16_t address = ((a << 8) | b) << 1; // uint16_t address = (((a << 1) & 0xFF) << 8 | ((b << 1) & 0xFF)); // uint16_t address = (a << 8) | b; profileIpBuf[(profileIdx++)] = address; // avoid aliasing profileCnt0--; if (profileCnt0 < 128) { profileCnt0 = 255; } TCNT0 = profileCnt0; } // // // Multithreading example using custom MT API // - TBB with C++98 requires writing functor classes/structs // which are must more tedious to implement than C++11 versions // using lambdas // // #include #include #include #include #include #include "../Common.hh" #include #include #include #include using namespace mad; //============================================================================// class ComputePi { public: typedef tbb::blocked_range range_t; typedef range_t::const_iterator const_iterator; public: // primary constructor ComputePi(double_type step) : m_step(step), m_sum(0.0) { } // split copy constructor required by tbb::parallel_reduce ComputePi(ComputePi& rhs, splitter) : m_step(rhs.m_step), m_sum(0.0) { } // for computing integral _inline_ double_type x(ulong_type i) const { return (i-0.5)*m_step; } _inline_ void operator()(const range_t& range) { for(const_iterator itr = range.begin(); itr != range.end(); ++itr) { //double _x = x(itr); m_sum += 4.0/(1.0 + x(itr)*x(itr)); } } // called at end of tbb::parallel_reduce _inline_ void join(ComputePi& rhs) { m_sum += rhs.m_sum; } // access sum double_type& sum() { return m_sum; } const double_type& sum() const { return m_sum; } private: double_type m_step; double_type m_sum; }; //============================================================================// int main(int, char** argv) { typedef ComputePi::range_t range_t; ulong_type num_steps = GetEnvNumSteps(500000000UL); double_type step = 1.0/static_cast(num_steps); ulong_type num_threads = thread_manager::GetEnvNumThreads(1); tbb::task_scheduler_init init(num_threads); //========================================================================// timer::timer t; ComputePi pi_body(step); tbb::parallel_reduce(range_t(0, num_steps), pi_body, tbb::auto_partitioner()); report(num_steps, step*pi_body.sum(), t.stop_and_return(), argv[0]); //========================================================================// double_type pi = step * pi_body.sum(); return (fabs(pi - M_PI) > PI_EPSILON); } rockandsalt/conan-center-index #include #include #include int main() { bliss::Graph graph(4); graph.change_color(1, 1); graph.add_edge(0, 1); graph.add_edge(3, 0); graph.add_edge(1, 2); graph.add_edge(1, 3); graph.add_edge(2, 3); graph.write_dot("dot_output.txt"); std::ifstream ifs("dot_output.txt", std::ios::binary); std::cout << ifs.rdbuf() << std::endl; return 0; } #include "xmlExporter.h" bool XmlExporter::beginDocument(QString fileName) { file = new QFile(fileName); if (!file->open(QFile::WriteOnly | QFile::Text)) { file->close(); return false; } xmlWriter = new QXmlStreamWriter(file); xmlWriter->setAutoFormatting(true); xmlWriter->writeStartDocument(); return true; } void XmlExporter::endDocument() { xmlWriter->writeEndDocument(); delete xmlWriter; xmlWriter = NULL; file->close(); delete file; } void XmlExporter::beginElement(QString type) { xmlWriter->writeStartElement(type); } void XmlExporter::endElement() { xmlWriter->writeEndElement(); } void XmlExporter::addAttribute(QString name, QString value) { xmlWriter->writeAttribute(name, value); } 0 #include "TextureMgr.h" TextureMgr::TextureMgr() { } TextureMgr::~TextureMgr() { } std::shared_ptr TextureMgr::getTexture(int threadId, const std::string &keyName) { assert(threadId < _texMap.size()); if (_texMap[threadId].find(keyName) != _texMap[threadId].end()) return _texMap[threadId][keyName]; else return nullptr; } std::vector > TextureMgr::getTextures(int threadId, const std::vector &keyNames) { assert(threadId < _texMap.size()); std::vector > ta; for (int i=0;i tex) { _configMutex.lock(); if (threadId >= _texMap.size()) { for(int i=_texMap.size(); i < threadId + 1; i++) { std::map > threadMap; _texMap.push_back(threadMap); } } _configMutex.unlock(); _texMap[threadId].insert(std::pair >(keyName, tex)); } void TextureMgr::removeTextureEntry(int threadId, const std::string &keyName) { assert(threadId < _texMap.size()); _texMap[threadId].erase(keyName); } std::string TextureMgr::lookupTextureKeyName(int threadId, std::shared_ptr tex) { assert(threadId < _texMap.size()); for(auto it = _texMap[threadId].begin(); it != _texMap[threadId].end(); ++it) { if (it->second == tex) { return it->first; } } return std::string(""); } std::vector TextureMgr::getAllTextureKeys(int threadId) { assert(threadId < _texMap.size()); std::vector keys; for(auto it = _texMap[threadId].begin(); it != _texMap[threadId].end(); ++it) { keys.push_back(it->first); } return keys; } void TextureMgr::loadTexturesFromConfigVal(int threadId, const std::string &configName) { _configMutex.lock(); if (threadId >= _texMap.size()) { for(int i=_texMap.size(); i < threadId + 1; i++) { std::map > threadMap; _texMap.push_back(threadMap); } } std::string in = MinVR::ConfigVal(configName,""); while (in.size()) { std::string filename; std::string keyname; std::string token; GLenum wrapMode = GL_REPEAT; GLenum minInterpMode = GL_LINEAR_MIPMAP_LINEAR; GLenum magInterpMode = GL_LINEAR; int semicolonpos = in.find(";"); BOOST_ASSERT_MSG(semicolonpos >= 0, "Expected a ; to signal the end of each texture in the LoadTextures ConfigVal."); int commapos = in.find(","); //bool hasalpha = ((commapos >= 0) && (commapos <= semicolonpos)); if (!MinVR::popNextToken(in, filename, true)) BOOST_ASSERT_MSG(false, "Expected filename while loading texture from ConfigVal"); /* if (hasalpha) { // remove the , separating the filename from the alphafilename in = in.substr(1); if (!MinVR::popNextToken(in, alphafilename, true)) alwaysAssertM(false, "TexMgr expected filename for alpha channel while loading texture from ConfigVal"); // assume format of RGBA8 if alpha is specified, AUTO doesn't seem to work by default. format = std::string("RGBA8"); } */ if (!MinVR::popNextToken(in, keyname, true)) { BOOST_ASSERT_MSG(false, "TexMgr expected keyname while loading texture from ConfigVal"); } else { // Optional wrap mode if (MinVR::popNextToken(in, token, true)) { if (token == "GL_CLAMP_TO_EDGE") { wrapMode = GL_CLAMP_TO_EDGE; } else if (token == "GL_CLAMP_TO_BORDER") { wrapMode = GL_CLAMP_TO_BORDER; } else if (token == "GL_REPEAT") { wrapMode = GL_REPEAT; } else if (token == "GL_MIRRORED_REPEAT") { wrapMode = GL_MIRRORED_REPEAT; } else { BOOST_ASSERT_MSG(false, "Unsupported wrap mode"); } } // optional interpolation mode if (MinVR::popNextToken(in, token, true)) { if (token == "GL_NEAREST") { minInterpMode = GL_NEAREST; } else if (token == "GL_LINEAR") { minInterpMode = GL_LINEAR; } else if (token == "GL_LINEAR_MIPMAP_LINEAR") { minInterpMode = GL_LINEAR_MIPMAP_LINEAR; } else { BOOST_ASSERT_MSG(false, "Unsupported min interpolation mode"); } } // optional interpolation mode if (MinVR::popNextToken(in, token, true)) { if (token == "GL_NEAREST") { magInterpMode = GL_NEAREST; } else if (token == "GL_LINEAR") { magInterpMode = GL_LINEAR; } else { BOOST_ASSERT_MSG(false, "Unsupported mag interpolation mode"); } } // Remove the semicolon in = in.substr(1); } filename = MinVR::decygifyPath(MinVR::replaceEnvVars(filename)); if (filename.find("*") != std::string::npos) { // cubemap std::string filenames[6]; generateCubeMapFilenames(filename, filenames); for(int i=0; i < 6; i++) { if (!boost::filesystem::exists(filenames[i])) { BOOST_ASSERT_MSG(false, ("Texture file does not exist: " + filenames[i]).c_str()); } } std::string msg; msg = "Loading cubemap texture " + filename + " with keyname " + keyname; std::cout << msg << std::endl; std::shared_ptr tex = Texture::createCubeMapFromFiles(filenames, true, 4); tex->setTexParameteri(GL_TEXTURE_WRAP_S, wrapMode); tex->setTexParameteri(GL_TEXTURE_WRAP_T, wrapMode); tex->setTexParameteri(GL_TEXTURE_WRAP_R, wrapMode); tex->setTexParameteri(GL_TEXTURE_MIN_FILTER, minInterpMode); tex->setTexParameteri(GL_TEXTURE_MAG_FILTER, magInterpMode); tex->setFileName(filename); _texMap[threadId].insert(std::pair >(keyname, tex)); } else { //alphafilename = MinVR::decygifyPath(MinVR::replaceEnvVars(alphafilename)); if (!boost::filesystem::exists(filename)) { BOOST_ASSERT_MSG(false, ("Texture file does not exist: " + filename).c_str()); } //if ((hasalpha) && (!FileSystem::exists(alphafilename))) // alwaysAssertM(false, "Texture file does not exist: " + alphafilename); std::string msg; //if (hasalpha) { // msg = "Loading texture " + filename + " with alpha texture " + alphafilename + " and keyname " + keyname; //} //else { msg = "Loading texture " + filename + " with keyname " + keyname; //} std::cout << msg << std::endl; std::shared_ptr tex = Texture::create2DTextureFromFile(filename, true, 4); tex->setTexParameteri(GL_TEXTURE_WRAP_S, wrapMode); tex->setTexParameteri(GL_TEXTURE_WRAP_T, wrapMode); tex->setTexParameteri(GL_TEXTURE_WRAP_R, wrapMode); tex->setTexParameteri(GL_TEXTURE_MIN_FILTER, minInterpMode); tex->setTexParameteri(GL_TEXTURE_MAG_FILTER, magInterpMode); tex->setTexParameterf(GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0); tex->setFileName(filename); _texMap[threadId].insert(std::pair >(keyname, tex)); } } _configMutex.unlock(); } void TextureMgr::generateCubeMapFilenames(const std::string& src, std::string realFilename[6]) { std::string filenameBase, filenameExt; const std::string splitter = "*"; size_t i = src.rfind(splitter); if (i != std::string::npos) { filenameBase = src.substr(0, i); filenameExt = src.substr(i + 1, src.size() - i - splitter.length()); } std::string face[6] = {"+x", "-x", "+y", "-y", "+z", "-z"}; for (int f = 0; f < 6; ++f) { realFilename[f] = filenameBase + face[f] + filenameExt; } }src_main/gameui/BonusMapsDialog.cpp // Copyright © 1996-2018, Valve Corporation, All rights reserved. #include "BonusMapsDialog.h" #include "EngineInterface.h" #include "FileSystem.h" #include "MouseMessageForwardingPanel.h" #include "TGAImagePanel.h" #include "basepanel.h" #include "vgui/ILocalize.h" #include "vgui/ISurface.h" #include "vgui/ISystem.h" #include "vgui/IVGui.h" #include "vgui_controls/BitmapImagePanel.h" #include "vgui_controls/Button.h" #include "vgui_controls/ComboBox.h" #include "vgui_controls/FileOpenDialog.h" #include "vgui_controls/ImagePanel.h" #include "vgui_controls/PanelListPanel.h" #include "vgui_controls/QueryBox.h" #include "tier0/include/memdbgon.h" using namespace vgui; #define MAX_LISTED_BONUS_MAPS 128 extern const char *COM_GetModDirectory(void); static bool ConstructFullImagePath(const char *pCurrentPath, const char *pchImageName, char *pchImageFileName, size_t image_file_name_size) { char *ext = Q_strstr(pchImageName, ".tga"); if (ext) { // Use the specified image if (pchImageName[0] != '.') Q_snprintf(pchImageFileName, image_file_name_size, "%s", pchImageName); else Q_snprintf(pchImageFileName, image_file_name_size, "%s/%s", pCurrentPath, pchImageName); return true; } Q_strcpy(pchImageFileName, image_file_name_size, pchImageName); return false; } //----------------------------------------------------------------------------- // Purpose: Describes the layout of a same game pic //----------------------------------------------------------------------------- class CBonusMapPanel : public vgui::EditablePanel { DECLARE_CLASS_SIMPLE(CBonusMapPanel, vgui::EditablePanel); public: CBonusMapPanel(PanelListPanel *parent, const char *name, int bonusMapListItemID) : BaseClass(parent, name) { m_iBonusMapListItemID = bonusMapListItemID; m_pParent = parent; m_pBonusMapTGAImage = new CTGAImagePanel(this, "BonusMapTGAImage"); m_pBonusMapImage = SETUP_PANEL(new ImagePanel(this, "BonusMapImage")); m_pBonusMapScreenshotBackground = SETUP_PANEL(new ImagePanel(this, "BonusMapScreenshotBackground")); m_pMapNameLabel = new Label(this, "MapNameLabel", ""); m_pLockIcon = new ImagePanel(this, "LockIcon"); m_pCompleteIcon = new ImagePanel(this, "CompleteIcon"); CMouseMessageForwardingPanel *panel = new CMouseMessageForwardingPanel(this, NULL); panel->SetZPos(2); SetSize(200, 140); LoadControlSettings("resource/BonusMapPanel.res"); m_FillColor = m_pBonusMapScreenshotBackground->GetFillColor(); } void SetBonusMapInfo(const char *pCurrentPath, BonusMapDescription_t &map) { // set the image to display char szImageFileName[SOURCE_MAX_PATH]; bool bIsTGA = false; if (map.bIsFolder) { if (map.szImageName[0] == '\0') { // use associate bonus folder icon Q_snprintf(szImageFileName, sizeof(szImageFileName), "%s/foldericon.tga", map.szFileName); bIsTGA = true; // use default folder icon if (!g_pFullFileSystem->FileExists(szImageFileName, "MOD")) { Q_strcpy(szImageFileName, "bonusmaps/icon_bonus_map_folder"); bIsTGA = false; } } else { // Use the specified image bIsTGA = ConstructFullImagePath(pCurrentPath, map.szImageName, szImageFileName, SOURCE_ARRAYSIZE(szImageFileName)); } } else { if (map.szImageName[0] == '\0') { // Didn't specify an image name, so pair it with the name of this file char szImpliedTgaName[SOURCE_MAX_PATH]; Q_snprintf(szImpliedTgaName, sizeof(szImpliedTgaName), "%s.tga", map.szMapFileName); bIsTGA = ConstructFullImagePath(pCurrentPath, szImpliedTgaName, szImageFileName, SOURCE_ARRAYSIZE(szImageFileName)); // if it doesn't exist use default bonus map icon if (!g_pFullFileSystem->FileExists(szImageFileName, "MOD")) { Q_strcpy(szImageFileName, "bonusmaps/icon_bonus_map_default"); bIsTGA = false; } } else { // Use the specified image bIsTGA = ConstructFullImagePath(pCurrentPath, map.szImageName, szImageFileName, SOURCE_ARRAYSIZE(szImageFileName)); } } if (bIsTGA) { m_pBonusMapTGAImage->SetTGANonMod(szImageFileName); m_pBonusMapTGAImage->SetSize(180, 100); m_pBonusMapTGAImage->SetVisible(true); m_pBonusMapImage->SetVisible(false); } else { m_pBonusMapImage->SetImage(szImageFileName); m_pBonusMapImage->SetSize(180, 100); m_pBonusMapImage->SetVisible(true); m_pBonusMapTGAImage->SetVisible(false); } m_pLockIcon->SetVisible(map.bLocked); m_pCompleteIcon->SetVisible(map.bComplete); // set the title text m_pMapNameLabel->SetText(map.szMapName); } MESSAGE_FUNC_INT(OnPanelSelected, "PanelSelected", state) { if (state) { // set the text color to be orange, and the pic border to be orange m_pBonusMapScreenshotBackground->SetFillColor(m_SelectedColor); m_pMapNameLabel->SetFgColor(Color(0, 0, 0, 255)); } else { m_pBonusMapScreenshotBackground->SetFillColor(m_FillColor); m_pMapNameLabel->SetFgColor(m_TextColor); } PostMessage(m_pParent->GetVParent(), new KeyValues("PanelSelected")); } virtual void OnMousePressed(vgui::MouseCode code) { m_pParent->SetSelectedPanel(this); } virtual void ApplySchemeSettings(IScheme *pScheme) { m_TextColor = pScheme->GetColor("NewGame.TextColor", Color(255, 255, 255, 255)); m_SelectedColor = pScheme->GetColor("NewGame.SelectionColor", Color(255, 255, 255, 255)); BaseClass::ApplySchemeSettings(pScheme); } virtual void OnMouseDoublePressed(vgui::MouseCode code) { // call the panel OnMousePressed(code); PostMessage(m_pParent->GetParent(), new KeyValues("Command", "command", "loadbonusmap")); } int GetBonusMapListItemID() { return m_iBonusMapListItemID; } private: vgui::PanelListPanel *m_pParent; vgui::Label *m_pMapNameLabel; ImagePanel *m_pBonusMapImage; CTGAImagePanel *m_pBonusMapTGAImage; ImagePanel *m_pLockIcon; ImagePanel *m_pCompleteIcon; // things to change color when the selection changes ImagePanel *m_pBonusMapScreenshotBackground; Color m_TextColor, m_FillColor, m_SelectedColor; int m_iBonusMapListItemID; }; CBonusMapsDialog *g_pBonusMapsDialog = NULL; //----------------------------------------------------------------------------- // Purpose:Constructor //----------------------------------------------------------------------------- CBonusMapsDialog::CBonusMapsDialog(vgui::Panel *parent) : BaseClass(parent, "BonusMapsDialog") { g_pBonusMapsDialog = this; m_hImportBonusMapsDialog = NULL; BonusMapsDatabase()->RootPath(); CreateBonusMapsList(); BuildMapsList(); new vgui::Button(this, "loadbonusmap", ""); SetControlEnabled("loadbonusmap", false); SetDeleteSelfOnClose(true); // SetBounds(0, 0, 512, 384); // SetMinimumSize( 256, 300 ); SetSizeable(false); SetTitle("#GameUI_BonusMaps", true); vgui::Button *cancel = new vgui::Button(this, "Cancel", "#GameUI_Cancel"); cancel->SetCommand("Close"); m_pPercentageBarBackground = SETUP_PANEL(new ImagePanel(this, "PercentageBarBackground")); m_pPercentageBar = SETUP_PANEL(new ImagePanel(this, "PercentageBar")); LoadControlSettings("resource/BonusMapsDialog.res"); // Stop blinking the bonus maps menu item CBasePanel *pBasePanel = BasePanel(); if (pBasePanel) pBasePanel->SetMenuItemBlinkingState("OpenBonusMapsDialog", false); BonusMapsDatabase()->SetBlink(false); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CBonusMapsDialog::~CBonusMapsDialog() { BonusMapsDatabase() ->WriteSaveData(); // Closing this dialog is a good time to save g_pBonusMapsDialog = NULL; } bool CBonusMapsDialog::ImportZippedBonusMaps(const char *pchZippedFileName) { // Get the zip file's name with dir info char *pchShortFileName = Q_strrchr(pchZippedFileName, '\\'); if (!pchShortFileName) return false; // It's going to go in the maps folder char szOutFilename[512]; Q_snprintf(szOutFilename, sizeof(szOutFilename), "maps%s", pchShortFileName); Q_StripExtension(szOutFilename, szOutFilename, sizeof(szOutFilename)); // If there's already a folder by the same name we're going to tack a number // onto the end int iOutFilenameLength = Q_strlen(szOutFilename); int iSameFolderCount = 1; while (g_pFullFileSystem->FileExists(szOutFilename, "MOD")) { ++iSameFolderCount; if (iSameFolderCount > 99) { return false; } szOutFilename[iOutFilenameLength] = '\0'; Q_snprintf(szOutFilename, sizeof(szOutFilename), "%s%02i", szOutFilename, iSameFolderCount); } // Pull the files out of the zip if (g_pFullFileSystem->UnzipFile(pchZippedFileName, "MOD", szOutFilename)) { // New maps have been imported, so refresh the list BuildMapsList(); } return false; } //----------------------------------------------------------------------------- // Purpose: builds bonus map list from directory //----------------------------------------------------------------------------- void CBonusMapsDialog::BuildMapsList(void) { // clear the current list m_pGameList->DeleteAllItems(); BonusMapsDatabase()->ClearBonusMapsList(); BonusMapsDatabase()->ScanBonusMaps(); // Enable back button if we're in a sub folder bool bIsRoot = (Q_strcmp(BonusMapsDatabase()->GetPath(), ".") == 0); SetControlEnabled("Back", !bIsRoot); SetControlVisible("Back", !bIsRoot); SetControlEnabled("ImportBonusMaps", bIsRoot); SetControlVisible("ImportBonusMaps", bIsRoot); char szDisplayPath[SOURCE_MAX_PATH]; Q_snprintf(szDisplayPath, SOURCE_MAX_PATH, "%s/", BonusMapsDatabase()->GetPath()); SetControlString("FileName", szDisplayPath); SetControlString("CommentLabel", ""); int iMapCount = BonusMapsDatabase()->BonusCount(); // add to the list for (int iMapIndex = 0; iMapIndex < iMapCount && iMapIndex < MAX_LISTED_BONUS_MAPS; ++iMapIndex) { CBonusMapPanel *bonusMapPanel = new CBonusMapPanel(m_pGameList, "BonusMapPanel", iMapIndex); bonusMapPanel->SetBonusMapInfo( BonusMapsDatabase()->GetPath(), *(BonusMapsDatabase()->GetBonusData(iMapIndex))); m_pGameList->AddItem(NULL, bonusMapPanel); } // display a message if there are no save games if (iMapCount <= 0) { vgui::Label *pNoSavesLabel = SETUP_PANEL(new Label( m_pGameList, "NoBonusMapsLabel", "#GameUI_NoBonusMapsToDisplay")); pNoSavesLabel->SetTextColorState(vgui::Label::CS_DULL); m_pGameList->AddItem(NULL, pNoSavesLabel); m_pGameList->SetNumColumns(1); } else { m_pGameList->SetNumColumns(3); } RefreshCompletionPercentage(); // Disable load button SetControlEnabled("loadbonusmap", false); // Make challenge selection invisible m_pChallengeSelection->SetEnabled(false); m_pChallengeSelection->SetVisible(false); } //----------------------------------------------------------------------------- // Purpose: Creates the load game display list //----------------------------------------------------------------------------- void CBonusMapsDialog::CreateBonusMapsList() { m_pGameList = new vgui::PanelListPanel(this, "listpanel_bonusmaps"); m_pGameList->SetFirstColumnWidth(0); new Label(this, "FileName", "./"); new Label(this, "CommentLabel", ""); m_pChallengeSelection = new vgui::ComboBox(this, "ChallengeSelection", 0, false); } //----------------------------------------------------------------------------- // Purpose: returns the save file name of the selected item //----------------------------------------------------------------------------- int CBonusMapsDialog::GetSelectedItemBonusMapIndex() { CBonusMapPanel *panel = dynamic_cast(m_pGameList->GetSelectedPanel()); if (panel && panel->GetBonusMapListItemID() < BonusMapsDatabase()->BonusCount()) return panel->GetBonusMapListItemID(); return BonusMapsDatabase()->InvalidIndex(); } void CBonusMapsDialog::SetSelectedBooleanStatus(const char *pchName, bool bValue) { CBonusMapPanel *pSelectedBonusMapPanel = (CBonusMapPanel *)m_pGameList->GetSelectedPanel(); if (!pSelectedBonusMapPanel) return; BonusMapsDatabase()->SetBooleanStatus( pchName, pSelectedBonusMapPanel->GetBonusMapListItemID(), bValue); // Change the status in the dialog BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( pSelectedBonusMapPanel->GetBonusMapListItemID()); pSelectedBonusMapPanel->SetBonusMapInfo(BonusMapsDatabase()->GetPath(), *pMap); RefreshCompletionPercentage(); RefreshDialog(pMap); } void CBonusMapsDialog::RefreshData(void) { for (int iMap = 0; iMap < m_pGameList->GetItemCount(); ++iMap) { CBonusMapPanel *pBonusMapPanel = (CBonusMapPanel *)m_pGameList->GetItemPanel(iMap); if (pBonusMapPanel) pBonusMapPanel->SetBonusMapInfo( BonusMapsDatabase()->GetPath(), *(BonusMapsDatabase()->GetBonusData( pBonusMapPanel->GetBonusMapListItemID()))); } CBonusMapPanel *pSelectedBonusMapPanel = (CBonusMapPanel *)m_pGameList->GetSelectedPanel(); if (!pSelectedBonusMapPanel) return; BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( pSelectedBonusMapPanel->GetBonusMapListItemID()); RefreshCompletionPercentage(); RefreshDialog(pMap); } int CBonusMapsDialog::GetSelectedChallenge(void) { if (!m_pChallengeSelection->IsEnabled()) return -1; KeyValues *pUserDataKey = m_pChallengeSelection->GetActiveItemUserData(); return pUserDataKey->GetInt("challenge"); } void CBonusMapsDialog::RefreshDialog(BonusMapDescription_t *pMap) { if (!pMap || pMap->bLocked || (m_pChallengeSelection->IsEnabled() && GetSelectedChallenge() == -1)) { // It's locked or no challenge is selected, so disable the load button SetControlEnabled("loadbonusmap", false); } else { // Enable the load button SetControlEnabled("loadbonusmap", true); } RefreshMedalDisplay(pMap); if (pMap) SetControlString("CommentLabel", pMap->szComment); else SetControlString("CommentLabel", ""); } void CBonusMapsDialog::RefreshMedalDisplay(BonusMapDescription_t *pMap) { int iFirstChildIndex = FindChildIndexByName("ChallengeMedalOverview00"); for (int iMedal = 0; iMedal < 5; ++iMedal) { Panel *pMedalImage = GetChild(iFirstChildIndex + iMedal); pMedalImage->SetVisible(false); } if (!pMap || !pMap->m_pChallenges) { SetControlVisible("ChallengeCommentLabel", false); SetControlVisible("ChallengeEarnedMedal", false); SetControlVisible("ChallengeBestLabel", false); SetControlVisible("ChallengeNextMedal", false); SetControlVisible("ChallengeNextLabel", false); return; } char szBuff[512]; int iChallenge = GetSelectedChallenge(); if (iChallenge < 0) { SetControlVisible("ChallengeCommentLabel", false); SetControlVisible("ChallengeEarnedMedal", false); SetControlVisible("ChallengeBestLabel", false); SetControlVisible("ChallengeNextMedal", false); SetControlVisible("ChallengeNextLabel", false); iFirstChildIndex = FindChildIndexByName("ChallengeMedalOverview00"); for (int iChallengeIndex = 0; iChallengeIndex < m_pChallengeSelection->GetItemCount(); ++iChallengeIndex) { KeyValues *pUserDataKey = m_pChallengeSelection->GetItemUserData(iChallengeIndex); int iChallengeNum = pUserDataKey->GetInt("challenge"); if (iChallengeNum >= 0) { ChallengeDescription_t *pChallengeDescription = NULL; for (int i = 0; i < pMap->m_pChallenges->Count(); ++i) { int iType = ((*pMap->m_pChallenges)[i]).iType; if (iType == -1) { iType = i; } if (iType == iChallengeNum) pChallengeDescription = &((*pMap->m_pChallenges)[i]); } if (pChallengeDescription) { int iBest, iEarnedMedal, iNext, iNextMedal; GetChallengeMedals(pChallengeDescription, iBest, iEarnedMedal, iNext, iNextMedal); if (iChallengeNum < 10) Q_snprintf(szBuff, 256, "medals/medal_0%i_%s", iChallengeNum, g_pszMedalNames[iEarnedMedal]); else Q_snprintf(szBuff, 256, "medals/medal_%i_%s", iChallengeNum, g_pszMedalNames[iEarnedMedal]); } CBitmapImagePanel *pBitmap = dynamic_cast( GetChild(iFirstChildIndex + iChallengeNum)); pBitmap->SetVisible(true); pBitmap->setTexture(szBuff); } } return; } ChallengeDescription_t *pChallengeDescription = NULL; for (int i = 0; i < pMap->m_pChallenges->Count(); ++i) { int iType = ((*pMap->m_pChallenges)[i]).iType; if (iType == -1) { iType = i; } if (iType == iChallenge) pChallengeDescription = &((*pMap->m_pChallenges)[i]); } if (!pChallengeDescription) return; const char *pchChallengeComment = pChallengeDescription->szComment; int iBest, iEarnedMedal, iNext, iNextMedal; GetChallengeMedals(pChallengeDescription, iBest, iEarnedMedal, iNext, iNextMedal); // Set comment label SetControlString("ChallengeCommentLabel", pchChallengeComment); SetControlVisible("ChallengeCommentLabel", true); // Set earned medal if (iEarnedMedal > -1) { if (iChallenge < 10) Q_snprintf(szBuff, sizeof(szBuff), "medals/medal_0%i_%s", iChallenge, g_pszMedalNames[iEarnedMedal]); else Q_snprintf(szBuff, sizeof(szBuff), "medals/medal_%i_%s", iChallenge, g_pszMedalNames[iEarnedMedal]); CBitmapImagePanel *pBitmap = dynamic_cast( FindChildByName("ChallengeEarnedMedal")); pBitmap->SetVisible(true); pBitmap->setTexture(szBuff); } // Set next medal if (iNextMedal > 0) { if (iChallenge < 10) Q_snprintf(szBuff, sizeof(szBuff), "medals/medal_0%i_%s", iChallenge, g_pszMedalNames[iNextMedal]); else Q_snprintf(szBuff, sizeof(szBuff), "medals/medal_%i_%s", iChallenge, g_pszMedalNames[iNextMedal]); CBitmapImagePanel *pBitmap = dynamic_cast( FindChildByName("ChallengeNextMedal")); pBitmap->SetVisible(true); pBitmap->setTexture(szBuff); } else { SetControlVisible("ChallengeNextMedal", false); } wchar_t szWideBuff[64]; wchar_t szWideBuff2[64]; // Best label if (iBest != -1) { Q_snprintf(szBuff, sizeof(szBuff), "%i", iBest); g_pVGuiLocalize->ConvertANSIToUnicode(szBuff, szWideBuff2, sizeof(szWideBuff2)); g_pVGuiLocalize->ConstructString( szWideBuff, sizeof(szWideBuff), g_pVGuiLocalize->Find("#GameUI_BonusMapsBest"), 1, szWideBuff2); g_pVGuiLocalize->ConvertUnicodeToANSI(szWideBuff, szBuff, sizeof(szBuff)); SetControlString("ChallengeBestLabel", szBuff); SetControlVisible("ChallengeBestLabel", true); } else SetControlVisible("ChallengeBestLabel", false); // Next label if (iNext != -1) { Q_snprintf(szBuff, sizeof(szBuff), "%i", iNext); g_pVGuiLocalize->ConvertANSIToUnicode(szBuff, szWideBuff2, sizeof(szWideBuff2)); g_pVGuiLocalize->ConstructString( szWideBuff, sizeof(szWideBuff), g_pVGuiLocalize->Find("#GameUI_BonusMapsGoal"), 1, szWideBuff2); g_pVGuiLocalize->ConvertUnicodeToANSI(szWideBuff, szBuff, sizeof(szBuff)); SetControlString("ChallengeNextLabel", szBuff); SetControlVisible("ChallengeNextLabel", true); } else SetControlVisible("ChallengeNextLabel", false); } void CBonusMapsDialog::RefreshCompletionPercentage(void) { float fPercentage = BonusMapsDatabase()->GetCompletionPercentage(); if (fPercentage > 0.0f) { char szBuff[256]; if (fPercentage * 100.0f < 1.0f) Q_snprintf(szBuff, 256, "%.2f%%", fPercentage * 100.0f); // Show decimal places if less than 1% else Q_snprintf(szBuff, 256, "%.0f%%", fPercentage * 100.0f); SetControlString("PercentageText", szBuff); SetControlVisible("PercentageText", true); SetControlVisible("CompletionText", true); // Blend the color from backround color 0% to selected color 100% Color cProgressBar = Color(static_cast(m_PercentageBarBackgroundColor.r()) * (1.0f - fPercentage) + static_cast(m_PercentageBarColor.r()) * fPercentage, static_cast(m_PercentageBarBackgroundColor.g()) * (1.0f - fPercentage) + static_cast(m_PercentageBarColor.g()) * fPercentage, static_cast(m_PercentageBarBackgroundColor.b()) * (1.0f - fPercentage) + static_cast(m_PercentageBarColor.b()) * fPercentage, static_cast(m_PercentageBarBackgroundColor.a()) * (1.0f - fPercentage) + static_cast(m_PercentageBarColor.a()) * fPercentage); m_pPercentageBar->SetFillColor(cProgressBar); m_pPercentageBar->SetWide(m_pPercentageBarBackground->GetWide() * fPercentage); SetControlVisible("PercentageBarBackground", true); SetControlVisible("PercentageBar", true); } else { // 0% complete so don't display SetControlVisible("PercentageText", false); SetControlVisible("CompletionText", false); SetControlVisible("PercentageBarBackground", false); SetControlVisible("PercentageBar", false); } } void CBonusMapsDialog::ApplySchemeSettings(IScheme *pScheme) { m_PercentageBarBackgroundColor = Color(0, 0, 0, 64); m_PercentageBarColor = pScheme->GetColor("NewGame.SelectionColor", Color(255, 255, 255, 255)); BaseClass::ApplySchemeSettings(pScheme); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBonusMapsDialog::OnCommand(const char *command) { if (!_stricmp(command, "loadbonusmap")) { int mapIndex = GetSelectedItemBonusMapIndex(); if (BonusMapsDatabase()->IsValidIndex(mapIndex)) { BonusMapDescription_t *pBonusMap = BonusMapsDatabase()->GetBonusData(mapIndex); // Don't do anything with locked items if (pBonusMap->bLocked || (m_pChallengeSelection->IsEnabled() && GetSelectedChallenge() == -1)) return; const char *shortName = pBonusMap->szShortName; if (shortName && shortName[0]) { if (pBonusMap->bIsFolder) { BonusMapsDatabase()->AppendPath(shortName); // repopulate list with current directory BuildMapsList(); m_pGameList->MoveScrollBarToTop(); } else { // Load the game, return to top and switch to engine char sz[256]; // Set the challenge mode if one is selected int iChallenge = GetSelectedChallenge() + 1; if (iChallenge > 0) { Q_snprintf(sz, sizeof(sz), "sv_bonus_challenge %i\n", iChallenge); engine->ClientCmd_Unrestricted(sz); ChallengeDescription_t *pChallengeDescription = &((*pBonusMap->m_pChallenges)[iChallenge - 1]); // Set up medal goals BonusMapsDatabase()->SetCurrentChallengeObjectives( pChallengeDescription->iBronze, pChallengeDescription->iSilver, pChallengeDescription->iGold); BonusMapsDatabase()->SetCurrentChallengeNames( pBonusMap->szFileName, pBonusMap->szMapName, pChallengeDescription->szName); } if (pBonusMap->szMapFileName[0] != '.') { Q_snprintf(sz, sizeof(sz), "map %s\n", pBonusMap->szMapFileName); } else { const char *pchSubDir = Q_strnchr(BonusMapsDatabase()->GetPath(), '/', Q_strlen(BonusMapsDatabase()->GetPath())); if (pchSubDir) { pchSubDir = Q_strnchr(pchSubDir + 1, '/', Q_strlen(pchSubDir)); if (pchSubDir) { ++pchSubDir; const char *pchMapFileName = pBonusMap->szMapFileName + 2; Q_snprintf(sz, sizeof(sz), "map %s/%s\n", pchSubDir, pchMapFileName); } } } engine->ClientCmd_Unrestricted(sz); // Close this dialog // OnClose(); } } } } else if (!_stricmp(command, "back")) { BonusMapsDatabase()->BackPath(); // repopulate list with current directory BuildMapsList(); m_pChallengeSelection->RemoveAll(); m_pChallengeSelection->AddItem( "", new KeyValues("ChallengeSelection", "challenge", -1)); int iFoundSimilar = 0; for (iNumChallenges; iNumChallenges < pMap->m_pChallenges->Count(); ++iNumChallenges) { ChallengeDescription_t *pChallenge = &(*pMap->m_pChallenges)[iNumChallenges]; int iType = iNumChallenges; // If the challenge type was specified then use that instead of (legacy) // the order the challenges were listed if (pChallenge->iType != -1) iType = pChallenge->iType; m_pChallengeSelection->AddItem( pChallenge->szName, new KeyValues("ChallengeSelection", "challenge", iType)); if (iSelectedChallenge == iNumChallenges) iFoundSimilar = iNumChallenges + 1; } m_pChallengeSelection->ActivateItemByRow(iFoundSimilar); } if (iNumChallenges > 0) { m_pChallengeSelection->SetEnabled(true); m_pChallengeSelection->SetVisible(true); m_pChallengeSelection->SetNumberOfEditLines(iNumChallenges + 1); } else { m_pChallengeSelection->SetEnabled(false); m_pChallengeSelection->SetVisible(false); } RefreshDialog(pMap); } void CBonusMapsDialog::OnControlModified() { CBonusMapPanel *pSelectedBonusMapPanel = (CBonusMapPanel *)m_pGameList->GetSelectedPanel(); BonusMapDescription_t *pMap = BonusMapsDatabase()->GetBonusData( pSelectedBonusMapPanel->GetBonusMapListItemID()); RefreshDialog(pMap); } // file selected. This can only happen when someone selects an image to be // imported as a spray logo. void CBonusMapsDialog::OnFileSelected(const char *fullpath) { if (fullpath == NULL || fullpath[0] == '\0') return; // this can take a while, put up a waiting cursor surface()->SetCursor(dc_hourglass); ImportZippedBonusMaps(fullpath); // change the cursor back to normal surface()->SetCursor(dc_user); } iclue-summer-2020/nl-positivity-cc // Copyright (c) 2020 [Your Name]. All rights reserved. #define CATCH_CONFIG_MAIN #include #include #include #include #include TEST_CASE("product", "") { const nl_positivity::Set s = {1, 2, 3}; const auto ps = nl_positivity::product(s, 2); REQUIRE(ps.size() == 9); } TEST_CASE("disjoints", "") { const auto djs = nl_positivity::disjoints(3, 2); REQUIRE(djs.size() == 27); } TEST_CASE("tau", "") { const nl_positivity::Set s = {4, 6, 3, 9, 1}; const auto tt = nl_positivity::tau(s); const std::vector expected = {4, 2, 1, 1, 0}; REQUIRE(tt == expected); } TEST_CASE("grand n=2", "") { const auto x = nl_positivity::grand_ineqs(2, [](int64_t c) -> bool { return c > 0; }); REQUIRE(x.size() == 23); } TEST_CASE("grand n=3", "") { const auto x = nl_positivity::grand_ineqs(3, [](int64_t c) -> bool { return c == 1; }); REQUIRE(x.size() == 171); } // n = 4 ==> 1601 // n = 5 ==> 17911 for c > 0? TEST_CASE("flagger", "") { const auto flags = nl_positivity::flagger(3, 4); REQUIRE(flags.size() == 0); }#include #include //#include #include "Accel.h" #include "AccelPrint.h" const static Word m1("0x5555555555555555", 16); const static Word m2("0x3333333333333333", 16); const static Word m4("0x0f0f0f0f0f0f0f0f", 16); const static Word h01("0x0101010101010101", 16); // ----------------------------------------------------------------------- // Hardware-specific print helpers // ----------------------------------------------------------------------- template void print_ap_bits(const T& in, const unsigned W) { printf (" "); for (unsigned i = 0; i < W; ++i) printf ("%3d", in[i] ? -1 : 0); printf ("\n"); } template void print_params(T params[CONVOLVERS][K][K]) { for (unsigned m = 0; m < CONVOLVERS; ++m) { for (unsigned wr = 0; wr < K; ++wr) { for (unsigned wc = 0; wc < K; ++wc) { printf ("%3d", (params[m][wr][wc]==0) ? 0 : 1); } printf("\n"); } printf("--\n"); } } template void print_line_buffer_m(T lbuf[CONV_BANKS]) { for (unsigned wr = 0; wr < CONV_ROWS; ++wr) { for (unsigned bank = 0; bank < CONV_BANKS; ++bank) { for (unsigned wc = 0; wc < CONV_COLS; ++wc) { printf ("%3d", lbuf[bank][wr][wc].to_int()); } printf (" |"); } printf ("\n"); } } TwoBit encode_bit(const Bit& b) { #pragma HLS INLINE return (b == 0) ? TwoBit(1) : TwoBit(-1); } // ----------------------------------------------------------------------- // Conv // ----------------------------------------------------------------------- ConvOut conv3x3b( const TwoBit line_buffer_m[CONV_BANKS][CONV_ROWS][CONV_COLS], const Bit conv_params_m[K][K], const ap_uint<4> bank, const IdxType cc ) { #pragma HLS INLINE ConvOut sum = 0; for (ap_uint<2> kr = 0; kr < K; ++kr) { for (ap_uint<2> kc = 0; kc < K; ++kc) { TwoBit data = line_buffer_m[bank][kr][cc+kc]; const Bit& wt = conv_params_m[2-kr][2-kc]; data[1] = (wt & data[0]) ^ data[1]; sum += data; } } return sum; } // ----------------------------------------------------------------------- // Produce 32 elements of conv results // ----------------------------------------------------------------------- void conv_word( const TwoBit line_buffer_m[CONV_BANKS][CONV_ROWS][CONV_COLS], const Bit conv_params_m[K][K], ConvOut conv_out_buffer_m[WORD_SIZE] ) { #pragma HLS PIPELINE for (ap_uint<4> bank = 0; bank < CONV_BANKS; ++bank) { for (ap_uint<4> cc = 0; cc < BANK_WIDTH; ++cc) { conv_out_buffer_m[bank*BANK_WIDTH+cc] = conv3x3b( line_buffer_m, conv_params_m, bank, cc ); } } } // ----------------------------------------------------------------------- // Process each line in a word, we need to outline this loop to // avoid false control dependencies in Vivado HLS // ----------------------------------------------------------------------- void process_word( const TwoBit word_buffer_m[CONV_BANKS][CONV_COLS], const TwoBit old_word_buffer_m[CONV_BANKS][CONV_COLS], const bool lb[CONV_BANKS], const bool rb[CONV_BANKS], TwoBit line_buffer_m[CONV_BANKS][CONV_ROWS][CONV_COLS], const Bit conv_params_m[K][K], ConvOut conv_out_buffer_m[WORD_SIZE], const ap_uint<3> log_width, const ap_uint<6> words_per_image, const IdxType wrd ) { #pragma HLS INLINE // slices_per_line = width / BANK_WIDTH const ap_uint<5> slices_per_line = 1 << (log_width - LOG_BANK_WIDTH); const bool first_wrd = (wrd == 0); const bool last_wrd = (wrd == words_per_image); DB_PRINT(4, "process word %d, spl=%d\n", wrd.to_int(), slices_per_line.to_int()); // Prologue // Update bottom row, slices are shifted left. Some slices copied from previous word (middle row) for (ap_uint<4> bank = 0; bank < CONV_BANKS; ++bank) { ap_int<6> s_idx = bank + slices_per_line - CONV_BANKS; if (s_idx < 0) { // set to zero or copy from old word (middle row) for (ap_uint<4> cc = 1; cc < CONV_COLS-1; ++cc) { line_buffer_m[bank][CONV_ROWS-1][cc] = old_word_buffer_m[CONV_BANKS+s_idx][cc]; } line_buffer_m[bank][CONV_ROWS-1][0 ] = lb[bank] ? TwoBit(0) : old_word_buffer_m[CONV_BANKS+s_idx][0]; line_buffer_m[bank][CONV_ROWS-1][CONV_COLS-1] = rb[bank] ? TwoBit(0) : old_word_buffer_m[CONV_BANKS+s_idx][CONV_COLS-1]; } else { // fill from new word for (ap_uint<4> cc = 1; cc < CONV_COLS-1; ++cc) { line_buffer_m[bank][CONV_ROWS-1][cc] = (last_wrd) ? TwoBit(0) : word_buffer_m[s_idx][cc]; } line_buffer_m[bank][CONV_ROWS-1][0 ] = (last_wrd || lb[bank]) ? TwoBit(0) : word_buffer_m[s_idx][0]; line_buffer_m[bank][CONV_ROWS-1][CONV_COLS-1] = (last_wrd || rb[bank]) ? TwoBit(0) : word_buffer_m[s_idx][CONV_COLS-1]; } } DB(4, printf("Accel lbuf wrd%d before conv:\n", wrd.to_int()); print_line_buffer_m(line_buffer_m); ); // Convolution conv_word( line_buffer_m, conv_params_m, conv_out_buffer_m ); // Update // Fill line buffer with lines from the new word for (ap_uint<4> bank = 0; bank < CONV_BANKS; ++bank) { // -------------------------------------------------------------- // Top row, slices are shifted right by slices_per_line ap_int<6> s_idx0 = bank - slices_per_line; if (s_idx0 >= 0) { // slice from input word for (ap_uint<4> cc = 1; cc < CONV_COLS-1; ++cc) { line_buffer_m[bank][0][cc] = word_buffer_m[s_idx0][cc]; } line_buffer_m[bank][0][0 ] = lb[bank] ? TwoBit(0) : word_buffer_m[s_idx0][0]; line_buffer_m[bank][0][CONV_COLS-1] = rb[bank] ? TwoBit(0) : word_buffer_m[s_idx0][CONV_COLS-1]; } else { // set to zero or copy from old word (middle row) for (ap_uint<4> cc = 1; cc < CONV_COLS-1; ++cc) { line_buffer_m[bank][0][cc] = (first_wrd) ? TwoBit(0) : old_word_buffer_m[CONV_BANKS+s_idx0][cc]; } line_buffer_m[bank][0][0 ] = (first_wrd || lb[bank]) ? TwoBit(0) : old_word_buffer_m[CONV_BANKS+s_idx0][0]; line_buffer_m[bank][0][CONV_COLS-1] = (first_wrd || rb[bank]) ? TwoBit(0) : old_word_buffer_m[CONV_BANKS+s_idx0][CONV_COLS-1]; } // -------------------------------------------------------------- // Middle row, simply copy the word into the line buffer for (ap_uint<4> cc = 1; cc < CONV_COLS-1; ++cc) { line_buffer_m[bank][1][cc] = word_buffer_m[bank][cc]; } // Fill end buffer bits line_buffer_m[bank][1][0 ] = lb[bank] ? TwoBit(0) : word_buffer_m[bank][0]; line_buffer_m[bank][1][CONV_COLS-1] = rb[bank] ? TwoBit(0) : word_buffer_m[bank][CONV_COLS-1]; } DB(4, printf("Accel lbuf wrd%d after conv:\n", wrd.to_int()); print_line_buffer_m(line_buffer_m); ); } // ----------------------------------------------------------------------- // A single PE reads from all inputs and weights to generate a single // output feature map. // * Make sure this function gets inlined by VHLS, or cosim may fail! // ----------------------------------------------------------------------- void bin_conv( Word wt_mem[CONVOLVERS][C_WT_WORDS], NormComp nc, Word dmem[2][CONVOLVERS][C_DMEM_WORDS], ap_uint<1> d_i_idx, ap_uint<1> d_o_idx, const unsigned n_inputs, const Address o_index, const ap_uint<1> new_batch, const ap_uint<2> width_mode, // 0=8'b, 1=16'b, 2=32'b const ap_uint<2> norm_mode // 0='do nothing', 1='do norm', 2='do pool' ) { const ap_uint<3> log_width = width_mode + LOG_BANK_WIDTH; const ap_uint<5> words_per_image = 1 << (2*width_mode); const unsigned n_phases = n_inputs / CONVOLVERS; const unsigned images_per_phase = PIX_PER_PHASE >> (2*log_width); const unsigned WORDS_PER_PHASE = PIX_PER_PHASE / WORD_SIZE; assert(n_phases % images_per_phase == 0); assert(n_inputs % images_per_phase == 0); assert(images_per_phase*words_per_image == WORDS_PER_PHASE); // --------------------------------------------------------------------- // buffers // --------------------------------------------------------------------- TwoBit line_buffer[CONVOLVERS][CONV_BANKS][CONV_ROWS][CONV_COLS]; #pragma HLS ARRAY_PARTITION variable=line_buffer complete dim=0 Bit conv_params[CONVOLVERS][K][K]; #pragma HLS ARRAY_PARTITION variable=conv_params complete dim=0 ConvSum fixed_buffer[WORDS_PER_PHASE][WORD_SIZE]; #pragma HLS ARRAY_PARTITION variable=fixed_buffer complete dim=2 ConvSum fixed_temp[WORD_SIZE]; #pragma HLS ARRAY_PARTITION variable=fixed_temp complete dim=0 // per-convolver buffers TwoBit word_buffer[CONVOLVERS][CONV_BANKS][CONV_COLS]; #pragma HLS ARRAY_PARTITION variable=word_buffer complete dim=0 TwoBit old_word_buffer[CONVOLVERS][CONV_BANKS][CONV_COLS]; #pragma HLS ARRAY_PARTITION variable=old_word_buffer complete dim=0 ConvOut conv_out_buffer[CONVOLVERS][WORD_SIZE]; #pragma HLS ARRAY_PARTITION variable=conv_out_buffer complete dim=0 // edge padding flag bits bool lb[CONV_BANKS]; #pragma HLS ARRAY_PARTITION variable=lb complete dim=0 bool rb[CONV_BANKS]; #pragma HLS ARRAY_PARTITION variable=rb complete dim=0 static Address wt_addr = 0; // address of weight word static ap_uint<3> wt_offset = 0; // offset 0..6 of param if (new_batch != 0) { wt_addr = 0; wt_offset = 0; } // --------------------------------------------------------------------- // Calculate edge padding flag bits const ap_uint<4> log_slice = log_width - LOG_BANK_WIDTH; const ap_uint<4> w_div_8 = (1 << log_width) >> 3; assert (w_div_8 > 0); ap_uint<4> mask = ~ap_uint<4>(0); // set mask to all 1s mask = mask >> (4-log_slice); for (ap_uint<4> bank = 0; bank < CONV_BANKS; ++bank) { #pragma HLS unroll const ap_uint<4> x = bank & mask; lb[bank] = (x == 0); // (bank % w_div_8) == 0 rb[bank] = (x+1 == w_div_8); // (bank % w_div_8) == w_div_8-1 } // --------------------------------------------------------------------- // Reset conv buffer for (IdxType i = 0; i < WORDS_PER_PHASE; ++i) { for (IdxType j = 0; j < WORD_SIZE; ++j) { #pragma HLS UNROLL fixed_buffer[i][j] = 0; } } // --------------------------------------------------------------------- // Compute in phases // Each phase processes CONVOLVERS * WORDS_PER_PHASE input words // --------------------------------------------------------------------- LOOP_PHASES: for (ap_uint<10> p = 0; p < n_phases; p += images_per_phase) { #pragma HLS LOOP_TRIPCOUNT min=1 max=512 DB(3, printf ("=== PHASE %d ===\n", p.to_int()) ); // wrd = which word in the current image // wrd_phase = which wrd in the current phase ap_uint<8> wrd = 0; ap_uint<8> wrd_phase = 0; // Load a word each iteration, and then process it // We load WORDS_PER_PHASE words per phase, however we also need 1 extra "empty" // iteration per image in the phase to do the loop epilogue, so the loop bound // is WORDS_PER_PHASE + images_per_phase LOOP_WORDS_IN_PHASE: for (ap_uint<8> count = 0; count < WORDS_PER_PHASE+images_per_phase; ++count) { #pragma HLS DEPENDENCE variable=fixed_buffer inter false #pragma HLS LOOP_TRIPCOUNT min=17 max=32 #pragma HLS PIPELINE // First word of an image if (wrd == 0) { Word wt_word_buffer[CONVOLVERS]; #pragma HLS ARRAY_PARTITION variable=wt_word_buffer complete dim=0 // ------------------------------------------------------------------- // Load param word // Each word contains CONV_W_PER_WORD weight filters, after we use // them all we should load the next word // ------------------------------------------------------------------- LOOP_WT_WORDS: for (IdxType m = 0; m < CONVOLVERS; ++m) { /*if (wt_offset == 0) wt_word_buffer[m] = wt_mem[m][wt_addr]; else wt_word_buffer[m] = wt_word_buffer[m] >> WT_SIZE; */ wt_word_buffer[m] = wt_mem[m][wt_addr] >> ap_uint<6>(WT_SIZE*wt_offset); } if (wt_offset == CONV_W_PER_WORD-1) { ++wt_addr; wt_offset = 0; } else { ++wt_offset; } //print_wt_word(wt_word_buffer[0]); // ------------------------------------------------------------------- // Load params // Each word contains CONV_W_PER_WORD weight filters packed into the first // 63 bits, the last bit is unused. Wts are stored in output-major order. // ------------------------------------------------------------------- LOOP_LOAD_WTS: for (IdxType m = 0; m < CONVOLVERS; ++m) { for (ap_uint<2> kr = 0; kr < K; ++kr) { for (ap_uint<2> kc = 0; kc < K; ++kc) conv_params[m][kr][kc] = wt_word_buffer[m][kr*K+kc]; } } DB(3, print_params(conv_params) ); } // ------------------------------------------------------------------- // Every word in an image // ------------------------------------------------------------------- // Load word // (wrd_phase-wrd) is which wrd in the current phase, aligned to img boundary if (wrd != words_per_image) { LOOP_CONVOLVER_LOAD: for (IdxType m = 0; m < CONVOLVERS; ++m) { Word word = dmem[d_i_idx][m][p*words_per_image + wrd_phase]; for (IdxType bank = 0; bank < CONV_BANKS; ++bank) { for (IdxType cc = 0; cc < CONV_COLS-2; ++cc) { word_buffer[m][bank][cc+1] = encode_bit(word[ap_uint<6>(bank*BANK_WIDTH+cc)]); } word_buffer[m][bank][0 ] = (bank==0) ? TwoBit(0) : encode_bit(word[ap_uint<6>(bank*BANK_WIDTH-1)]); word_buffer[m][bank][CONV_COLS-1] = (bank==CONV_BANKS-1) ? TwoBit(0) : encode_bit(word[ap_uint<6>(bank*BANK_WIDTH+BANK_WIDTH)]); } } } // Compute LOOP_CONVOLVERS: for (IdxType m = 0; m < CONVOLVERS; ++m) { // Do the following for each word in an image process_word( word_buffer[m], old_word_buffer[m], lb, rb, line_buffer[m], conv_params[m], conv_out_buffer[m], log_width, words_per_image, wrd ); } // CONVOLVERS for (IdxType m = 0; m < CONVOLVERS; ++m) { for (IdxType bank = 0; bank < CONV_BANKS; ++bank) { for (IdxType cc = 0; cc < CONV_COLS; ++cc) { old_word_buffer[m][bank][cc] = word_buffer[m][bank][cc]; } } } // ------------------------------------------------------------------- // Sum results across convolvers // ------------------------------------------------------------------- for (IdxType i = 0; i < WORD_SIZE; ++i) { // Ignore conv results after processing the first word if (wrd > 0) { ConvSum s = 0; for (IdxType m = 0; m < CONVOLVERS; ++m) s += conv_out_buffer[m][i]; fixed_buffer[wrd_phase-1][i] += s; } } // ------------------------------------------------------------------- // Increment counters // ------------------------------------------------------------------- if (wrd != words_per_image) { wrd++; wrd_phase++; } else { wrd = 0; } } // wrd_phase = 0 .. WORDS_PER_PHASE } // n_phases LOOP_ACC_PHASES: for (ap_uint<5> w = 0; w < words_per_image; ++w) { #pragma HLS LOOP_TRIPCOUNT min=1 max=1 for (IdxType b = 0; b < WORD_SIZE; ++b) { #pragma HLS unroll fixed_temp[b] = fixed_buffer[w][b]; } LOOP_ACC_PHASES_I: for (ap_uint<8> i = words_per_image; i < WORDS_PER_PHASE; i += words_per_image) { #pragma HLS LOOP_TRIPCOUNT min=1 max=16 #pragma HLS PIPELINE for (IdxType b = 0; b < WORD_SIZE; ++b) { fixed_temp[b] += fixed_buffer[w+i][b]; } } for (IdxType b = 0; b < WORD_SIZE; ++b) { #pragma HLS unroll fixed_buffer[w][b] = fixed_temp[b]; } } const Address bank_idx = o_index % CONVOLVERS; const Address bank_off = o_index / CONVOLVERS; const ap_uint<5> pool_width = 1 << (log_width-1); DB(4, unsigned width = 1 << log_width; printf ("=== conv result ===\n"); print_mat(fixed_buffer[0], width, 8, width); ); DB_PRINT(2, " o_idx=%3d: nc=%6d\n", o_index.to_int(), nc.to_int()); static Word outword; Word poolword; LOOP_BATCH_NORM: for (ap_uint<6> w = 0; w < words_per_image; ++w) { #pragma HLS LOOP_TRIPCOUNT min=1 max=16 #pragma HLS PIPELINE Word binword; Address o_bank_idx = bank_idx; Address o_bank_offset = bank_off*words_per_image + w; const ap_uint<6> out_offset = (w % 4) << 4; for (ap_uint<7> i = 0; i < WORD_SIZE; ++i) { binword[i] = (fixed_buffer[w][i] >= nc) ? 0 : 1; } if (norm_mode == 1) { outword = binword; } else if (norm_mode == 2) { // horizontal pooling first ap_int poolword_h; for (ap_uint<6> i = 0; i < WORD_SIZE/2; ++i) { poolword_h[i] = binword[2*i] & binword[2*i+1]; } // vertical pooling for (ap_uint<6> i = 0; i < WORD_SIZE/4; ++i) { // source indices ap_uint<5> i0 = i >> (log_width-1); i0 = (i0 << log_width) + i(log_width-2,0); ap_uint<5> i1 = i0 + pool_width; // dest index ap_uint<6> d0 = out_offset + i; poolword[d0] = poolword_h[i0] & poolword_h[i1]; } // For log_width > 3 we can just assign the word, but log_width = 3 means width = 8, // which means pooled width = 4, which is only 16 bits, which is less than 1 Word. // So each time we get here we only have 16 bits, meaning we have to accumulate four // of these 16-bit batches before writing a word out. if (log_width != LOG_BANK_WIDTH) { o_bank_offset /= 4; outword = poolword; } else { outword = outword >> WORD_SIZE/4; outword(63,48) = poolword(15,0); o_bank_idx = (o_index/4)%CONVOLVERS; o_bank_offset = (o_index/4)/CONVOLVERS; } } dmem[d_o_idx][o_bank_idx][o_bank_offset] = outword; } } // ----------------------------------------------------------------------- // Module to do the first conv layer // ----------------------------------------------------------------------- void fp_conv( Word wt_mem[CONVOLVERS][C_WT_WORDS], Word kh_mem[KH_WORDS], Word dmem[2][CONVOLVERS][C_DMEM_WORDS], ap_uint<1> d_i_idx, ap_uint<1> d_o_idx, const Address kh_index, const Address o_index, const unsigned N ) { const unsigned M = 3; const unsigned S = 32; const unsigned OUTWORDS = 16; // words per output image C1InputType win[M][K][K]; #pragma HLS ARRAY_PARTITION variable=win complete dim=0 C1InputType lbuf[M][K-1][S]; #pragma HLS ARRAY_PARTITION variable=lbuf complete dim=0 Word outwords[OUTWORDS]; #pragma HLS ARRAY_PARTITION variable=outwords complete dim=0 WtType wtbuf[M]; #pragma HLS ARRAY_PARTITION variable=wtbuf complete dim=0 Address wt_offset = 0; ap_uint<3> wt_addr = 0; // Parallelized across m, better for HLS LOOP_FP_CONV_O: for (IdxType n = 0; n < N; ++n) { #pragma HLS LOOP_TRIPCOUNT min=1 max=32 // clear linebuffers for each new output map LOOP_RESET_LINEBUFFERS: for (IdxType m = 0; m < M; ++m) { #pragma HLS UNROLL region PROLOG_COLS: for (IdxType c = 0; c < S; ++c) { PROLOG_ROWS: for (IdxType r = 0; r < K/2; ++r) { for (IdxType lr = 0; lr < K-2; ++lr) { lbuf[m][lr][c] = lbuf[m][lr+1][c]; } lbuf[m][K-2][c] = 0; } } } // The weights for the 1st conv layer are just laid out // linearly across wt_mem, 3 weights per 64-bit word DB_PRINT(3, "n = %u\n", n.to_int()); Word wt_word = wt_mem[n % CONVOLVERS][n / CONVOLVERS]; LOOP_LOAD_WTS: for (ap_uint<2> m = 0; m < M; ++m) { #pragma HLS UNROLL wtbuf[m] = wt_word((m+1)*WT_SIZE-1, m*WT_SIZE); DB(3, print_wt(wtbuf[m])); DB(3, printf("--\n")); } // load batch norm params C1Comp nc; load_kh(nc, kh_mem, (kh_index+n)); //printf (" n=%3d, nc=%6.3f\n", n.to_int(), nc.to_float()); // begin convolution LOOP_CONV_ROWS: for (IdxType r = 0; r < S+1; ++r) { LOOP_CONV_COLS: for (IdxType c = 0; c < S+1; ++c) { #pragma HLS PIPELINE // load input word Word inword = 0; if (r < S && c < S) { const Address addr = r*S + c; inword = dmem[d_i_idx][addr/C_DMEM_WORDS][addr%C_DMEM_WORDS]; } for (ap_uint<2> m = 0; m < M; ++m) { // load data: the value of pix is either the pixel at [r,c] // 0 -> +1, -1 -> -1 // or -> 0 for padding around the boundaries C1InputType pix; const unsigned W = pix.length(); pix(W-1,0) = inword(W-1+m*W, m*W); // window: shift left, leaving rightmost col for new data for (IdxType wr = 0; wr < K; ++wr) { for (IdxType wc = 0; wc < K-1; ++wc) { win[m][wr][wc] = win[m][wr][wc+1]; } } // window: fill top K-1 pixels of rightmost column from lbuf for (IdxType wr = 0; wr < K-1; ++wr) { C1InputType val = (c != S) ? lbuf[m][wr][c] : C1InputType(0); win[m][wr][K-1] = val; } // window: fill bottom right with new input pixel win[m][K-1][K-1] = pix; // lbuf: shift up column c if (c != S) { for (IdxType lr = 0; lr < K-2; ++lr) { lbuf[m][lr][c] = lbuf[m][lr+1][c]; } lbuf[m][K-2][c] = pix; } } // m // only perform the conv and store if legal position if (r > 0 && c > 0) { C1ConvType res = 0; for (ap_uint<2> m = 0; m < M; ++m) { for (ap_uint<2> wr = 0; wr < K; ++wr) { for (ap_uint<2> wc = 0; wc < K; ++wc) { const C1InputType& pix = win[m][wr][wc]; const Bit& b = wtbuf[m][8-(wr*K+wc)]; res += (b==0) ? pix : (C1InputType)(-pix); } } } // perform normalization right here outwords[(r-1)/2][((r-1)%2)*S + (c-1)] = (res >= nc) ? Bit(0) : Bit(-1); } } // CONV_COLS } // CONV_ROWS // Here i is the word offset within the outwords buffer LOOP_OUTPUT: for (IdxType i = 0; i < OUTWORDS; ++i) { #pragma HLS PIPELINE Address img_idx = o_index+n; Address bank_idx = img_idx % CONVOLVERS; Address bank_off = img_idx / CONVOLVERS; dmem[d_o_idx][bank_idx][bank_off*OUTWORDS + i] = outwords[i]; } } // n } void bin_dense( const Word wt_mem[CONVOLVERS][C_WT_WORDS], const Word kh_mem[KH_WORDS], Word dmem[2][CONVOLVERS][C_DMEM_WORDS], ap_uint<2> layer_type, ap_uint<1> d_i_idx, ap_uint<1> d_o_idx, const Address o_index, const unsigned n_inputs, const unsigned n_outputs ) { //assert(n_outputs % WORD_SIZE == 0); assert(layer_type == LAYER_DENSE || n_outputs == 10); assert(n_inputs/WORD_SIZE % CONVOLVERS == 0); DenseSum sum_m[CONVOLVERS]; // for last layer DenseNorm best_out = -1024; ap_int<8> prediction = -1; // read words from dmem and the wt store, dot them // o is the output bit, i is the input bit LOOP_DENSE_O: for (Address o = 0; o < n_outputs; ++o) { #pragma HLS LOOP_TRIPCOUNT min=1 max=1 const Address o_addr = (o_index+o)/WORD_SIZE; const ap_uint<6> o_offset = (o_index+o) % WORD_SIZE; Word o_word = dmem[d_o_idx][o_addr%CONVOLVERS][o_addr/CONVOLVERS]; DenseSum sum = 0; LOOP_DENSE_I: for (Address i = 0; i < n_inputs; i+=CONVOLVERS*WORD_SIZE) { #pragma HLS LOOP_TRIPCOUNT min=1 max=64 #pragma HLS PIPELINE const Address wt_addr = (o*n_inputs+i) / WORD_SIZE; for (IdxType j = 0; j < CONVOLVERS; ++j) { // in_wrd addr = [(i/WORD_SIZE+j) % CONVOLVERS][(i/WORD_SIZE+j) / CONVOLVERS] // wt_wrd addr = [wt_addr % CONVOLVERS][wt_addr / CONVOLVERS] const Word in_wrd = dmem[d_i_idx][j][i/WORD_SIZE/CONVOLVERS]; const Word wt_wrd = wt_mem[j][wt_addr / CONVOLVERS]; Word x = wt_wrd ^ in_wrd; // count_set bit for 64 bits, returns 2*cnt x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; x += x >> 8; x += x >> 16; x += x >> 32; x = x & 0x7f; sum_m[j] = WORD_SIZE - (DenseSum)(x<<1); } for (IdxType j = 0; j < CONVOLVERS; ++j) sum += sum_m[j]; } // n_inputs // not last layer -> biniarize, // otherwise just store the value as a 64bit word if (layer_type == LAYER_DENSE) { Address kh_addr = o / KH_PER_WORD; Word kh_word = kh_mem[kh_addr]; NormComp nc; IdxType kh_off = o % KH_PER_WORD; if (kh_off == 0) nc(15,0) = kh_word(15, 0); else if (kh_off == 1) nc(15,0) = kh_word(31,16); else if (kh_off == 2) nc(15,0) = kh_word(47,32); else nc(15,0) = kh_word(63,48); o_word[o_offset] = (sum >= nc) ? 0 : 1; } else { Address kh_addr = o / (const unsigned)2; Word kh_word = kh_mem[kh_addr]; KType ki; HType hi; IdxType kh_off = o % 2; if (kh_off == 0) { ki(15,0) = kh_word(15, 0); hi(15,0) = kh_word(31,16); } else { ki(15,0) = kh_word(47,32); hi(15,0) = kh_word(63,48); } //printf (" >> %d * %f + %f\n", sum.to_int(), ki.to_float(), hi.to_float()); ap_fixed<20,10> out = ap_fixed<20,10>(sum)*ki + hi; if (o == 0 || out > best_out) { prediction = o; best_out = out; } } dmem[d_o_idx][o_addr%CONVOLVERS][o_addr/CONVOLVERS] = o_word; } // n_outputs // Here we are using o_index as a bit index, not a word index! if (layer_type == LAYER_LAST) { Word o_word; o_word(7,0) = prediction(7,0); o_word(WORD_SIZE-1, 8) = 0; dmem[d_o_idx][0][0] = o_word; } } // ----------------------------------------------------------------------- // Accelerator top module // ----------------------------------------------------------------------- void top( Word wt_i[WT_WORDS], Word kh_i[KH_WORDS], Word dmem_i[DMEM_WORDS], Word dmem_o[DMEM_O_WORDS], const Address n_inputs, const Address n_outputs, const Address input_words, const Address output_words, const ap_uint<3> layer_mode, // [0]='new layer', [2:1]='conv1,conv,dense,last' const ap_uint<1> dmem_mode, // 0 means dmem[0] is input const ap_uint<2> width_mode, // 0=8'b, 1=16'b, 2=32'b const ap_uint<2> norm_mode // 0='do nothing', 1='do norm', 2='do pool' ) { DB_PRINT(2, "==== Entering Accel ====\n"); const ap_uint<2> layer_type = layer_mode(2,1); const unsigned width = 8 << width_mode; DB_PRINT(1, " Inputs = %d\n", n_inputs.to_int()); DB_PRINT(1, " Outputs = %d\n", n_outputs.to_int()); DB_PRINT(1, " i_words = %d\n", input_words.to_int()); DB_PRINT(1, " o_words = %d\n", output_words.to_int()); DB_PRINT(1, " Width = %d\n", width); DB_PRINT(1, " layer_mode = %d %d\n", layer_mode[0]==0 ? 0 : 1, layer_type.to_int()); DB_PRINT(1, " dmem_mode = %d\n", dmem_mode.to_int()); assert(width <= MAX_WIDTH); assert(n_inputs != 0); if (layer_type <= LAYER_CONV) { assert(input_words % CONVOLVERS == 0); assert(n_inputs*width*width <= DMEM_WORDS*WORD_SIZE); assert(n_inputs*WT_SIZE <= WT_WORDS*WORD_SIZE); } static Word dmem[2][CONVOLVERS][C_DMEM_WORDS]; #pragma HLS ARRAY_PARTITION variable=dmem complete dim=1 #pragma HLS ARRAY_PARTITION variable=dmem complete dim=2 static Word kh_mem[KH_WORDS]; static Word wt_mem[CONVOLVERS][C_WT_WORDS]; #pragma HLS ARRAY_PARTITION variable=wt_mem complete dim=1 static Address kh_index = 0; static Address o_index = 0; if (layer_mode[0]) { kh_index = 0; o_index = 0; } else { kh_index = kh_index[0]; } ap_uint<1> d_i_idx = dmem_mode; ap_uint<1> d_o_idx = ~dmem_mode; // Data input const ap_uint<5> words_per_image = 1 << (2*width_mode); Address img_idx = 0; // i / words_per_image; IdxType img_off = 0; // i % words_per_image; LOOP_DMEM_I: for (Address i = 0; i < input_words; ++i) { #pragma HLS LOOP_TRIPCOUNT min=1 max=512 #pragma HLS PIPELINE if (layer_type == LAYER_CONV) { Address bank_idx = img_idx % CONVOLVERS; Address bank_off = img_idx / CONVOLVERS; dmem[d_i_idx][bank_idx][(bank_off<<(2*width_mode)) + img_off] = dmem_i[i]; } else if (layer_type == LAYER_CONV1) dmem[d_i_idx][i/C_DMEM_WORDS][i%C_DMEM_WORDS] = dmem_i[i]; else dmem[d_i_idx][i%CONVOLVERS][i/CONVOLVERS] = dmem_i[i]; if (++img_off == words_per_image) { img_off = 0; ++img_idx; } } // Weight input, we must copy every 64-bit Word from the interface // into the accelerator LOOP_WT_I: for (Address i = 0; i < C_WT_WORDS*CONVOLVERS; ++i) { #pragma HLS PIPELINE wt_mem[i%CONVOLVERS][i/CONVOLVERS] = wt_i[i]; } //printf ("\nAccel Weights:\n"); //print_params3d(wt_mem[0], 0, n_inputs*n_outputs); LOOP_KH_I: for (ap_uint<16> i = 0; i < KH_WORDS; ++i) #pragma HLS PIPELINE kh_mem[i] = kh_i[i]; if (layer_type == LAYER_CONV1) { assert(n_inputs == 3); fp_conv( wt_mem, kh_mem, dmem, d_i_idx, d_o_idx, kh_index, o_index, n_outputs ); kh_index += n_outputs; o_index += n_outputs; } else if (layer_type == LAYER_CONV) { assert(norm_mode != 2 || n_outputs % 4 == 0); // needed for pooling of 8x8 image assert(n_inputs % CONVOLVERS == 0); LOOP_IMG_BATCH: for (IdxType i = 0; i < n_outputs; ++i) { #pragma HLS LOOP_TRIPCOUNT min=1 max=1 // Load the batch-norm parameters for this output NormComp nc; load_kh(nc, kh_mem, kh_index); bin_conv( wt_mem, nc, dmem, d_i_idx, d_o_idx, n_inputs, o_index, i == 0 ? 1 : 0, // new_batch width_mode, norm_mode ); kh_index++; o_index++; } } else { bin_dense( wt_mem, kh_mem, dmem, layer_type, d_i_idx, d_o_idx, o_index, n_inputs, n_outputs ); o_index += n_outputs; } // layer_type // Data output ap_uint<5> words_per_out = words_per_image / ((norm_mode!=2) ? 1 : 4); img_idx = 0; img_off = 0; LOOP_DMEM_O: for (Address i = 0; i < output_words; ++i) { #pragma HLS LOOP_TRIPCOUNT min=1 max=1 #pragma HLS PIPELINE // exclude conv6 (width==8, norm_mode==2) here because it writes // the output fmaps linearly if (layer_type <= LAYER_CONV && !(width_mode == 0 && norm_mode == 2)) { Address bank_idx = img_idx % CONVOLVERS; Address bank_off = img_idx / CONVOLVERS; dmem_o[i] = dmem[d_o_idx][bank_idx][bank_off*words_per_out + img_off]; } else dmem_o[i] = dmem[d_o_idx][i%CONVOLVERS][i/CONVOLVERS]; if (++img_off == words_per_out) { img_off = 0; ++img_idx; } } } #include "cf_stub.h" void _p0_top_1_noasync(Word wt_i[4682], Word kh_i[64], Word dmem_i[2048], Word dmem_o[128], const Address n_inputs, const Address n_outputs, const Address input_words, const Address output_words, const ap_uint<3> layer_mode, const ap_uint<1> dmem_mode, const ap_uint<2> width_mode, const ap_uint<2> norm_mode); void _p0_top_1_noasync(Word wt_i[4682], Word kh_i[64], Word dmem_i[2048], Word dmem_o[128], const Address n_inputs, const Address n_outputs, const Address input_words, const Address output_words, const ap_uint<3> layer_mode, const ap_uint<1> dmem_mode, const ap_uint<2> width_mode, const ap_uint<2> norm_mode) { switch_to_next_partition(0); int start_seq[1]; start_seq[0] = 0; cf_request_handle_t _p0_swinst_top_1_cmd; cf_send_i(&(_p0_swinst_top_1.cmd_top), start_seq, 1 * sizeof(int), &_p0_swinst_top_1_cmd); cf_wait(_p0_swinst_top_1_cmd); #ifdef SDS_DEBUG if ((input_words) * 8 != 2048*8) printf("dmem_i of function top transfer size is different from declared size, system may hang!\n"); if ((output_words) * 8 != 128*8) printf("dmem_o of function top transfer size is different from declared size, system may hang!\n"); #endif cf_send_i(&(_p0_swinst_top_1.wt_i_V), wt_i, 37456, &_p0_request_0); cf_send_i(&(_p0_swinst_top_1.kh_i_V), kh_i, 512, &_p0_request_1); cf_send_i(&(_p0_swinst_top_1.dmem_i_V), dmem_i, (input_words) * 8, &_p0_request_2); cf_send_i(&(_p0_swinst_top_1.n_inputs_V), &n_inputs, 2, &_p0_request_4); cf_send_i(&(_p0_swinst_top_1.n_outputs_V), &n_outputs, 2, &_p0_request_5); cf_send_i(&(_p0_swinst_top_1.input_words_V), &input_words, 2, &_p0_request_6); cf_send_i(&(_p0_swinst_top_1.output_words_V), &output_words, 2, &_p0_request_7); cf_send_i(&(_p0_swinst_top_1.layer_mode_V), &layer_mode, 1, &_p0_request_8); cf_send_i(&(_p0_swinst_top_1.dmem_mode_V), &dmem_mode, 1, &_p0_request_9); cf_send_i(&(_p0_swinst_top_1.width_mode_V), &width_mode, 1, &_p0_request_10); cf_send_i(&(_p0_swinst_top_1.norm_mode_V), &norm_mode, 1, &_p0_request_11); cf_receive_i(&(_p0_swinst_top_1.dmem_o_V), dmem_o, (output_words) * 8, &_p0_top_1_noasync_num_dmem_o_V, &_p0_request_3); cf_wait(_p0_request_0); cf_wait(_p0_request_1); cf_wait(_p0_request_2); cf_wait(_p0_request_3); cf_wait(_p0_request_4); cf_wait(_p0_request_5); cf_wait(_p0_request_6); cf_wait(_p0_request_7); cf_wait(_p0_request_8); cf_wait(_p0_request_9); cf_wait(_p0_request_10); cf_wait(_p0_request_11); } silhavyj/Connect4-server-client-gameserver/src/Logger.cpp0 #include "Logger.h" Logger *Logger::instance = NULL; Logger *Logger::getInstance() { if (instance == NULL) instance = new Logger; return instance; } Logger::Logger() { logFileName = getCurrentDateTime(); // creates a folder 'log' where // all the log files will be stored mkdir(logDirectory.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } void Logger::log(int lineNumber, Type type, std::string msg) { // attaches the appropriate color to // the message given as a parameter by its type switch (type) { case ERROR: log(lineNumber, "ERROR_LOG", RED, msg); break; case INFO: log(lineNumber, "INFO_LOG", GREEN, msg); break; case COUNTDOWN: log(lineNumber, "COUNTDOWN_LOG", CYAN, msg); break; case BOOTING: log(lineNumber, "BOOTING_LOG", MAGENTA, msg); break; case WARNING: log(lineNumber, "WARNING_LOG", YELLOW, msg); break; case GAME: log(lineNumber, "GAME_LOG", WHITE, msg); break; case MSG: log(lineNumber, "MSG_LOG", BLUE, msg); break; } } void Logger::log(int lineNumber, std::string type, std::string color, std::string msg) { // prints out the message std::stringstream ss; ss << "[#" << lineNumber << "]"; ss << "[" << getCurrentDateTime() << "]"; ss << "[" << type << "]"; ss << " " << msg; std::cout << color << ss.str() << RESET << std::endl; // appends it to the end of the file addToLogFile(ss.str()); } std::string Logger::getCurrentDateTime() const { time_t current_time; struct tm *time_info; char buffer[80]; time(¤t_time); time_info = localtime(¤t_time); strftime(buffer, sizeof(buffer),"%d-%m-%Y_%H-%M-%S", time_info); return std::string(buffer); } void Logger::addToLogFile(std::string log) const { std::ofstream logFile; std::string file = logDirectory + "/" + logFileName + logFileType; logFile.open(file, std::ios::out | std::ios::app); if (logFile.fail()) throw std::ios_base::failure(std::strerror(errno)); logFile.exceptions(logFile.exceptions() | std::ios::failbit | std::ifstream::badbit); logFile << log << std::endl; logFile.close(); } void Logger::testAllTypes() { LOG_ERR("This is an error message"); LOG_INFO("This is an info message"); LOG_COUNTDOWN("This is a countdown message"); LOG_BOOTING("This is a booting message"); LOG_WARNING("This is a warning message"); LOG_GAME("This is a game message"); LOG_MSG("This is a received message"); }cms/src/model/ApplyTemplateResult.cc /* * Copyright 2009-2017 Alibaba Cloud 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 #include using namespace AlibabaCloud::Cms; using namespace AlibabaCloud::Cms::Model; ApplyTemplateResult::ApplyTemplateResult() : ServiceResult() {} ApplyTemplateResult::ApplyTemplateResult(const std::string &payload) : ServiceResult() { parse(payload); } ApplyTemplateResult::~ApplyTemplateResult() {} void ApplyTemplateResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto resourceNode = value["Resource"]; auto allCreateAlertResults = value["CreateAlertResults"]["AlertResult"]; for (auto value : allCreateAlertResults) { Resource::AlertResult alertResultObject; if(!value["Name"].isNull()) alertResultObject.name = value["Name"].asString(); if(!value["DisplayName"].isNull()) alertResultObject.displayName = value["DisplayName"].asString(); if(!value["MetricNamespace"].isNull()) alertResultObject.metricNamespace = value["MetricNamespace"].asString(); if(!value["MetricName"].isNull()) alertResultObject.metricName = value["MetricName"].asString(); if(!value["Message"].isNull()) alertResultObject.message = value["Message"].asString(); if(!value["Success"].isNull()) alertResultObject.success = value["Success"].asString(); resource_.createAlertResults.push_back(alertResultObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["ErrorCode"].isNull()) errorCode_ = std::stoi(value["ErrorCode"].asString()); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); } ApplyTemplateResult::Resource ApplyTemplateResult::getResource()const { return resource_; } int ApplyTemplateResult::getErrorCode()const { return errorCode_; } std::string ApplyTemplateResult::getErrorMessage()const { return errorMessage_; } bool ApplyTemplateResult::getSuccess()const { return success_; } hongmi/cpp-primer-4-exercises1-10 #include #include using namespace std; int main() { string last; int lastCnt = 0; string word; int maxCnt = 0; string maxStr; cin >> word; maxStr = word; maxCnt++; while (cin >> word) { if (word == last) { lastCnt++; } else { if (lastCnt > maxCnt) { maxStr = last; maxCnt = lastCnt; } last = word; lastCnt = 1; } } cout << maxStr << " times: " << maxCnt << endl; return 0; } /* ----------------------------------------------------------------------------- * Rule_clksrc_param_value.hpp * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Mon Jan 08 13:30:55 CET 2018 * * ----------------------------------------------------------------------------- */ #ifndef Rule_clksrc_param_value_hpp #define Rule_clksrc_param_value_hpp #include #include #include "Rule.hpp" namespace abnf { class Visitor; class ParserContext; class Rule_clksrc_param_value : public Rule { public: Rule_clksrc_param_value(const std::string& spelling, const std::vector& rules); Rule_clksrc_param_value(const Rule_clksrc_param_value& rule); Rule_clksrc_param_value& operator=(const Rule_clksrc_param_value& rule); virtual Rule* clone(void) const; static Rule_clksrc_param_value* parse(ParserContext& context); virtual void* accept(Visitor& visitor); }; } #endif /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */ 0 /*! \file */ //Copyright 2011-2018 ; All Rights Reserved #ifndef CHRONO_CLOCK_TIME_HPP_ #define CHRONO_CLOCK_TIME_HPP_ #include #include #include "../api/ChronoObject.hpp" namespace chrono { class MicroTime; /*! \brief Clock Time Class * \details The ClockTime class is a helper class for using * struct timespec times. This is a 64-bit time with a 32-bit * seconds element and a 32-bit nanoseconds element. * * */ class ClockTime : public api::ChronoInfoObject { public: /*! \details Constructs a MicroTime object using a u32 value. * * The default initial value is zero. * */ ClockTime(s32 seconds, s32 nanoseconds){ assign(seconds, nanoseconds); } /*! \details Constructs a clock time object based on the timespec. */ ClockTime(const struct timespec & nano_time){ m_value = nano_time; } /*! \details Contructs an object from a micro time object. */ ClockTime(const MicroTime & micro_time); /*! \details Constructs a zero value ClockTime object. */ ClockTime(){ reset(); } /*! \details Resets the value of the clock to zero. */ void reset(){ m_value.tv_sec = 0; m_value.tv_nsec = 0; } /*! \details Sets the value of the clock. * * @param seconds The seconds value * @param nanoseconds The nanosecond value * */ void set(s32 seconds, s32 nanoseconds){ m_value.tv_sec = seconds; m_value.tv_nsec = nanoseconds; } /*! \details Returns a pointer to the struct timespec. * * This allows the object to be passed directly to functions * that required a pointer to struct timespec (read-only) * */ operator const struct timespec * () const { return &m_value; } /*! \details Returns a pointer to the struct timespec. * * This allows the object to be passed directly to functions * that required a pointer to struct timespec (read-write) * */ operator struct timespec * (){ return &m_value; } /*! \details Returns true if the time is set to a valid value. * */ bool is_valid() const { return *this != invalid(); } /*! \details Returns a MicroTime object set to the invalid time. */ static ClockTime invalid(){ return ClockTime((u32)-1, (u32)-1); } /*! \details Returns true if this is greater than \a a. */ bool operator > (const ClockTime & a) const; /*! \details Returns true if this is less than \a a. */ bool operator < (const ClockTime & a) const; /*! \details Returns true if this is greater than or equal to \a a. */ bool operator >= (const ClockTime & a) const; /*! \details Returns true if this is less than or equal to \a a. */ bool operator <= (const ClockTime & a) const; /*! \details Returns true if this is equal to \a a. */ bool operator == (const ClockTime & a) const; /*! \details Returns true if this is not equal to \a a. */ bool operator != (const ClockTime & a) const; /*! \details Returns the sum of this object and \a a. */ ClockTime operator + (const ClockTime & a) const { return add(*this, a); } /*! \details Returns the difference of this object and \a a. */ ClockTime operator - (const ClockTime & a) const { return subtract(*this, a); } /*! \details Adds \a to this and assigned to this. */ ClockTime & operator += (const ClockTime & a){ *this = add(*this, a); return *this; } /*! \details Subracts \a from this and assigned to this. */ ClockTime & operator -= (const ClockTime & a){ //subtract nano time *this = subtract(*this, a); return *this; } /*! \details Returns the seconds component. */ s32 seconds() const { return m_value.tv_sec; } /*! \details Returns the nanoseconds component. */ s32 nanoseconds() const { return m_value.tv_nsec; } /*! \details Returns a pointer to a strut timespec. */ struct timespec * timespec(){ return &m_value; } /*! \details Returns a pointer to a strut timespec (read-only). */ const struct timespec * timespec() const { return &m_value; } private: void assign(s32 seconds, s32 nanoseconds); static ClockTime add(const ClockTime & a, const ClockTime & b); static ClockTime subtract(const ClockTime & a, const ClockTime & b); struct timespec m_value; }; } #endif /* CHRONO_NANO_TIME_HPP_ */ test/test_poll/src/main.cpp10-100 /* * Created by on 2018/3/2. * * 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 "corpc_mutex.h" #include "corpc_utils.h" #include "corpc_routine_env.h" #include #include #include using namespace corpc; static void *test_routine( void *arg ) { int fd = 13; struct stat _stat; struct pollfd fd_in; fd_in.fd = fd; fd_in.events = POLLIN; int ret = poll(&fd_in, 1, 4); LOG("poll return %d\n", ret); if (!fcntl(fd, F_GETFL)) { if (!fstat(fd, &_stat)) { if (_stat.st_nlink >= 1) { LOG("fd ok\n"); } else { LOG("fd not ok\n"); } } } else { LOG("fd errno: %d\n", errno); } return NULL; } int main(int argc, const char * argv[]) { co_start_hook(); corpc::RoutineEnvironment::startCoroutine(test_routine, NULL); RoutineEnvironment::runEventLoop(); return 0; } #include #include #include "./aft-vulkan/material-aft.hpp" using namespace lava::chamber; using namespace lava::magma; std::unordered_map Material::s_globalAttributes; Material::Material(Scene& scene, const std::string& hrid) : m_scene(scene) , m_hrid(hrid) { new (&aft()) MaterialAft(*this, m_scene); initFromMaterialInfo(hrid); } Material::~Material() { aft().~MaterialAft(); } // ----- Uniform setters void Material::set(const std::string& uniformName, bool value) { auto& attribute = findAttribute(uniformName); attribute.value.uintValue = (value) ? 1 : 0; auto offset = attribute.offset; m_ubo.data[offset][0] = (value) ? 1 : 0; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, uint32_t value) { auto& attribute = findAttribute(uniformName); attribute.value.uintValue = value; auto offset = attribute.offset; m_ubo.data[offset][0] = value; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, float value) { auto& attribute = findAttribute(uniformName); attribute.value.floatValue = value; auto offset = attribute.offset; reinterpret_cast(m_ubo.data[offset]) = value; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, const glm::vec2& value) { auto& attribute = findAttribute(uniformName); attribute.value.vec2Value = value; auto offset = attribute.offset; reinterpret_cast(m_ubo.data[offset]) = value; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, const glm::vec3& value) { auto& attribute = findAttribute(uniformName); attribute.value.vec3Value = value; auto offset = attribute.offset; reinterpret_cast(m_ubo.data[offset]) = value; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, const glm::vec4& value) { auto& attribute = findAttribute(uniformName); attribute.value.vec4Value = value; auto offset = attribute.offset; reinterpret_cast(m_ubo.data[offset]) = value; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, const TexturePtr& texture) { auto& attribute = findAttribute(uniformName); attribute.texture = texture; aft().foreUboChanged(); } void Material::set(const std::string& uniformName, const uint32_t* values, uint32_t size) { auto& attribute = findAttribute(uniformName); attribute.value = UniformFallback(values, size); auto offset = attribute.offset; for (auto i = 0u; i < size; i += 4u) { auto& data = m_ubo.data[offset + i / 4u]; data[0] = values[i]; if (i + 1 < size) data[1] = values[i + 1]; if (i + 2 < size) data[2] = values[i + 2]; if (i + 3 < size) data[3] = values[i + 3]; } aft().foreUboChanged(); } void Material::setGlobal(const std::string& uniformName, const TexturePtr& texture) { auto& attribute = findGlobalAttribute(uniformName); attribute.texture = texture; aft().foreGlobalUboChanged(); } // ----- Uniform getters float Material::get_float(const std::string& uniformName) const { auto& attribute = findAttribute(uniformName); return attribute.value.floatValue; } const glm::vec4& Material::get_vec4(const std::string& uniformName) const { auto& attribute = findAttribute(uniformName); return attribute.value.vec4Value; } // ----- Inits void Material::initFromMaterialInfo(const std::string& hrid) { const auto& materialInfo = m_scene.engine().materialInfo(hrid); m_ubo.header.id = materialInfo.id; initAttributes(m_attributes, materialInfo.uniformDefinitions); // Set up global attributes if needed. if (s_globalAttributes.find(m_hrid) == s_globalAttributes.end()) { initAttributes(s_globalAttributes[m_hrid], materialInfo.globalUniformDefinitions); aft().foreGlobalUboChanged(); } } void Material::initAttributes(Attributes& attributes, const UniformDefinitions& uniformDefinitions) { for (const auto& uniformDefinition : uniformDefinitions) { auto& attribute = attributes[uniformDefinition.name]; attribute.type = uniformDefinition.type; attribute.fallback = uniformDefinition.fallback; attribute.value = uniformDefinition.fallback; attribute.offset = uniformDefinition.offset; switch (attribute.type) { case UniformType::Bool: { set(uniformDefinition.name, uniformDefinition.fallback.uintValue); break; } case UniformType::Uint: { if (uniformDefinition.arraySize == 0u) { set(uniformDefinition.name, uniformDefinition.fallback.uintValue); } else { set(uniformDefinition.name, uniformDefinition.fallback.uintArrayValue, uniformDefinition.arraySize); } break; } case UniformType::Float: { set(uniformDefinition.name, uniformDefinition.fallback.floatValue); break; } case UniformType::Vec2: { set(uniformDefinition.name, uniformDefinition.fallback.vec2Value); break; } case UniformType::Vec3: { set(uniformDefinition.name, uniformDefinition.fallback.vec3Value); break; } case UniformType::Vec4: { set(uniformDefinition.name, uniformDefinition.fallback.vec4Value); break; } default: break; } } } // ----- Finders Material::Attribute& Material::findAttribute(const std::string& uniformName) { auto pAttribute = m_attributes.find(uniformName); if (pAttribute == m_attributes.end()) { logger.error("magma.material") << "Attribute '" << uniformName << "' has not been defined within material '" << m_hrid << "'." << std::endl; } return pAttribute->second; } const Material::Attribute& Material::findAttribute(const std::string& uniformName) const { auto pAttribute = m_attributes.find(uniformName); if (pAttribute == m_attributes.end()) { logger.error("magma.material") << "Attribute '" << uniformName << "' has not been defined within material '" << m_hrid << "'." << std::endl; } return pAttribute->second; } Material::Attribute& Material::findGlobalAttribute(const std::string& uniformName) { auto pAttribute = s_globalAttributes[m_hrid].find(uniformName); if (pAttribute == s_globalAttributes[m_hrid].end()) { logger.error("magma.material") << "Global attribute '" << uniformName << "' has not been defined within material '" << m_hrid << "'." << std::endl; } return pAttribute->second; } const Material::Attribute& Material::findGlobalAttribute(const std::string& uniformName) const { auto pAttribute = s_globalAttributes[m_hrid].find(uniformName); if (pAttribute == s_globalAttributes[m_hrid].end()) { logger.error("magma.material") << "Global attribute '" << uniformName << "' has not been defined within material '" << m_hrid << "'." << std::endl; } return pAttribute->second; } chainerx_cc/chainerx/scalar_test.cc #include "chainerx/scalar.h" #include namespace chainerx { namespace { TEST(ScalarTest, Dtype) { EXPECT_EQ(Scalar(true).dtype(), Dtype::kBool); EXPECT_EQ(Scalar(false).dtype(), Dtype::kBool); EXPECT_EQ(Scalar(int8_t(1)).dtype(), Dtype::kInt8); EXPECT_EQ(Scalar(int16_t(2)).dtype(), Dtype::kInt16); EXPECT_EQ(Scalar(int32_t(3)).dtype(), Dtype::kInt32); EXPECT_EQ(Scalar(int64_t(4)).dtype(), Dtype::kInt64); EXPECT_EQ(Scalar(uint8_t(5)).dtype(), Dtype::kUInt8); EXPECT_EQ(Scalar(6.7f).dtype(), Dtype::kFloat32); EXPECT_EQ(Scalar(8.9).dtype(), Dtype::kFloat64); } template void ExpectScalarEqual(T1 value1, T2 value2) { EXPECT_EQ(Scalar(value1), Scalar(value2)); EXPECT_EQ(Scalar(value2), Scalar(value1)); } TEST(ScalarTest, Equality) { // TODO(niboshi): Add cases for different types ExpectScalarEqual(int8_t{0}, int8_t{0}); ExpectScalarEqual(int16_t{0}, int16_t{0}); ExpectScalarEqual(int32_t{0}, int32_t{0}); ExpectScalarEqual(int64_t{0}, int64_t{0}); ExpectScalarEqual(uint8_t{0}, uint8_t{0}); ExpectScalarEqual(int8_t{1}, int8_t{1}); ExpectScalarEqual(int16_t{1}, int16_t{1}); ExpectScalarEqual(int32_t{1}, int32_t{1}); ExpectScalarEqual(int64_t{1}, int64_t{1}); ExpectScalarEqual(uint8_t{1}, uint8_t{1}); ExpectScalarEqual(1.5, 1.5); ExpectScalarEqual(1.5f, 1.5f); ExpectScalarEqual(-1.5, -1.5); ExpectScalarEqual(-1.5f, -1.5f); ExpectScalarEqual(true, true); ExpectScalarEqual(false, false); } template void ExpectScalarNotEqual(T1 value1, T2 value2) { EXPECT_NE(Scalar(value1), Scalar(value2)); EXPECT_NE(Scalar(value2), Scalar(value1)); } TEST(ScalarTest, Inequality) { ExpectScalarNotEqual(0, 1); ExpectScalarNotEqual(-1, 1); ExpectScalarNotEqual(-1.0001, -1.0); ExpectScalarNotEqual(-1.0001, -1); ExpectScalarNotEqual(true, false); ExpectScalarNotEqual(true, 1.1); ExpectScalarNotEqual(1.0001, 1.0002); ExpectScalarNotEqual(std::nan(""), std::nan("")); } TEST(ScalarTest, Cast) { EXPECT_TRUE(static_cast(Scalar(true))); EXPECT_TRUE(static_cast(Scalar(1))); EXPECT_TRUE(static_cast(Scalar(-3.2))); EXPECT_FALSE(static_cast(Scalar(false))); EXPECT_FALSE(static_cast(Scalar(0))); EXPECT_FALSE(static_cast(Scalar(0.0f))); EXPECT_EQ(static_cast(Scalar(1)), 1); EXPECT_EQ(static_cast(Scalar(-1.1f)), -1); EXPECT_EQ(static_cast(Scalar(1.1)), 1); EXPECT_EQ(static_cast(Scalar(-2)), -2); EXPECT_EQ(static_cast(Scalar(2.2f)), 2); EXPECT_EQ(static_cast(Scalar(2.2)), 2); EXPECT_EQ(static_cast(Scalar(3)), 3); EXPECT_EQ(static_cast(Scalar(3.3f)), 3); EXPECT_EQ(static_cast(Scalar(-3.3)), -3); EXPECT_EQ(static_cast(Scalar(4)), 4); EXPECT_EQ(static_cast(Scalar(4.4f)), 4); EXPECT_EQ(static_cast(Scalar(-4.4)), -4); EXPECT_EQ(static_cast(Scalar(5)), 5); EXPECT_EQ(static_cast(Scalar(5.5f)), 5); EXPECT_EQ(static_cast(Scalar(5.0)), 5); EXPECT_FLOAT_EQ(static_cast(Scalar(-6)), -6.0f); EXPECT_FLOAT_EQ(static_cast(Scalar(6.7f)), 6.7f); EXPECT_FLOAT_EQ(static_cast(Scalar(6.7)), 6.7f); EXPECT_DOUBLE_EQ(static_cast(Scalar(8)), 8.0); EXPECT_DOUBLE_EQ(static_cast(Scalar(-8.9f)), double{-8.9f}); EXPECT_DOUBLE_EQ(static_cast(Scalar(8.9)), 8.9); } TEST(DtypeTest, UnaryOps) { EXPECT_THROW(-Scalar(true), DtypeError); EXPECT_THROW(-Scalar(false), DtypeError); EXPECT_EQ(static_cast(-Scalar(1)), -1); EXPECT_EQ(static_cast(-Scalar(2)), -2); EXPECT_EQ(static_cast(-Scalar(3)), -3); EXPECT_EQ(static_cast(-Scalar(4)), -4); EXPECT_EQ(static_cast(-Scalar(5)), static_cast(-5)); EXPECT_FLOAT_EQ(static_cast(-Scalar(6)), -6.0f); EXPECT_FLOAT_EQ(static_cast(-Scalar(6.7)), -6.7f); EXPECT_DOUBLE_EQ(static_cast(-Scalar(8)), -8.0); EXPECT_DOUBLE_EQ(static_cast(-Scalar(8.9)), -8.9); EXPECT_EQ(static_cast(+Scalar(1)), 1); EXPECT_EQ(static_cast(+Scalar(2)), 2); EXPECT_EQ(static_cast(+Scalar(3)), 3); EXPECT_EQ(static_cast(+Scalar(4)), 4); EXPECT_EQ(static_cast(+Scalar(5)), 5); EXPECT_EQ(static_cast(+Scalar(5)), 5); EXPECT_FLOAT_EQ(static_cast(+Scalar(6)), 6.0f); EXPECT_FLOAT_EQ(static_cast(+Scalar(6.7)), 6.7f); EXPECT_DOUBLE_EQ(static_cast(+Scalar(8)), 8.0); EXPECT_DOUBLE_EQ(static_cast(+Scalar(8.9)), 8.9); } TEST(ScalarTest, ToString) { EXPECT_EQ(Scalar(true).ToString(), "True"); EXPECT_EQ(Scalar(false).ToString(), "False"); EXPECT_EQ(Scalar(int8_t{1}).ToString(), std::to_string(int8_t{1})); EXPECT_EQ(Scalar(int16_t{2}).ToString(), std::to_string(int16_t{2})); EXPECT_EQ(Scalar(int32_t{3}).ToString(), std::to_string(int32_t{3})); EXPECT_EQ(Scalar(int64_t{4}).ToString(), std::to_string(int64_t{4})); EXPECT_EQ(Scalar(uint8_t{5}).ToString(), std::to_string(uint8_t{5})); } } // namespace } // namespace chainerx NNet/NNetWindows/AnimationSequence.cpp0 // AnimationSequence.cpp // // NNetWindows #include "stdafx.h" #include "NNetModelWriterInterface.h" #include "win32_mainWindow.h" #include "SingleNobAnimation.h" #include "AnimationSequence.h" AnimationSequence::AnimationSequence(MainWindow & win) : m_win(win) {} void AnimationSequence::Do(NNetModelWriterInterface& nmwi) { m_uiPhase = 0; doPhase(); } void AnimationSequence::Undo(NNetModelWriterInterface& nmwi) { m_uiPhase = Cast2Int(m_phases.size()); undoPhase(); } void AnimationSequence::AddPhase(unique_ptr upCmd) { m_phases.push_back(move(upCmd)); } void AnimationSequence::BlockUI() { m_win.SendCommand2Application(IDM_BLOCK_UI, true); }; void AnimationSequence::UnblockUI() { m_win.SendCommand2Application(IDM_BLOCK_UI, false); }; void AnimationSequence::doPhase() // runs in UI thread { if (m_uiPhase == 0) BlockUI(); if (m_uiPhase < m_phases.size()) m_phases[m_uiPhase++]->Do([&](){ doPhase(); }); else UnblockUI(); m_win.Notify(false); } void AnimationSequence::undoPhase() // runs in UI thread { if (m_uiPhase >= m_phases.size()) BlockUI(); if (m_uiPhase > 0) m_phases[--m_uiPhase]->Undo([&](){ undoPhase(); }); else UnblockUI(); m_win.Notify(false); } #pragma once std::pair swiss_to_lat_lon(double north, double east){ east -= 600000.0; // Convert origin to "civil" system, where Bern has coordinates 0,0. north -= 200000.0; east /= 1E6; // Express distances in 1000km units. north /= 1E6; double lon = 2.6779094; // Calculate longitude in 10000" units. lon += 4.728982 * east; lon += 0.791484 * east * north; lon += 0.1306 * east * north * north; lon -= 0.0436 * east * east * east; double lat = 16.9023892; // Calculate latitude in 10000" units. lat += 3.238272 * north; lat -= 0.270978 * east * east; lat -= 0.002528 * north * north; lat -= 0.0447 * east * east * north; lat -= 0.0140 * north * north * north; lon *= 100.0 / 36.0; // Convert longitude and latitude back in degrees. lat *= 100.0 / 36.0; return std::make_pair(lat,lon); } std::pair lat_lon_to_swiss(double lat, double lon){ lat *= 3600; // Convert latitude and longitude in seconds. lon *= 3600; lat -= 169028.66; // Shift the origin in Bern. lon -= 26782.5; lat /= 10000; // Convert latitude and longitude in 10000" units. lon /= 10000; double east = 600072.37; // Calculate easting [m]. east += 211455.93 * lon; east -= 10938.51 * lon * lat; east -= 0.36 * lon * lat * lat; east -= 44.54 * lon * lon * lon; double north = 200147.07; // Calculate northing [m]. north += 308807.95 * lat; north += 3745.25 * lon * lon; north += 76.63 * lat * lat; north -= 194.56 * lon * lon * lat; north += 119.79 * lat * lat * lat; return std::make_pair(north,east); } sample/code/shm_common_SharedPCServer.cpp /** * @file shm_common_SharedPCServer.cpp * @brief Example of the referred class. * * @section LICENSE * * 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 AUTHOR/AUTHORS 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. * * @author uknown * @bug No known bugs. * @version 0.1.0.0 * */ #include // std::min, std::max #include #include #include #include #include // std::stringstream #include "../../commonobjects/shm_common/SharedPCServer.hpp" void main() { std::cout << "SharedPCServer" << std::endl; co::shm::SharedDataServer shared_data_server; const int width = 640; const int height = 480; const int num_skeletons = 10; const int num_points_skeletons = 18; // Set the shared data std::string name_shm = "MySharedMemory"; // which objects to allocate std::string cmd = "image," + std::to_string(width) + "," + std::to_string(height) + ",3|pcl,20," + std::to_string(width * height) + "|pose_kSize,12," + std::to_string(num_skeletons) + "," + std::to_string(num_points_skeletons); std::cout << "[shm::cmd]>>" << cmd << std::endl; // parse the command and allocate the memory int err = shared_data_server.parse(name_shm, cmd); if (err != co::shm::kSharedNoError) { std::cout << "shared_data error: " << err << std::endl; } while (true) { // share data if (true) { // set the maximum distance float max_distance_depth = 10.0f; float kRange = 10.0f; // set the shared data std::map data; // create a new data object for the point cloud int shared_object_id = shared_data_server.get_key_id("pcl"); data[shared_object_id] = (co::shm::ObservedObject() = { "serial", std::vector() }); // share the data shared_data_server.push_data(data); // create a new data object for the pose shared_object_id = shared_data_server.get_key_id("pose_kSize"); data[shared_object_id] = (co::shm::ObservedObject() = { "serial", std::vector() }); //std::cout << "###" << std::endl; for (int i = 0; i < num_points_skeletons * 2; ++i) { //std::cout << "> " << it << std::endl; data[shared_object_id].points_data.push_back((float)rand() / RAND_MAX); data[shared_object_id].points_data.push_back((float)rand() / RAND_MAX); data[shared_object_id].points_data.push_back((float)rand() / RAND_MAX); } data[shared_object_id].num_points = data[shared_object_id].points_data.size() / num_points_skeletons; // share the data shared_data_server.push_data(data); } } }// Copyright 2021 #include "../../../modules/task_1/shabunin_v_vector_max/vector_max.h" #include #include #include std::vector getRandomVector(int sz) { std::random_device dev; std::mt19937 gen(dev()); std::vector vec(sz); for (int i = 0; i < sz; i++) { vec[i] = gen() % 100; } return vec; } int getSequentialMax(std::vector vec) { const int sz = vec.size(); int reduction_elem = vec[0]; for (int i = 1; i < sz; i++) { reduction_elem = std::max(reduction_elem, vec[i]); } return reduction_elem; } int getParallelMax(std::vector global_vec, int count_size_vector) { int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int delta = count_size_vector / size; if (delta) { const int remnant = count_size_vector % size; if (rank == 0) { for (int proc = 1; proc < size; proc++) { MPI_Send(global_vec.data() + proc * delta + remnant, delta, MPI_INT, proc, 0, MPI_COMM_WORLD); } } std::vector local_vec(delta); if (rank == 0) { local_vec = std::vector(global_vec.begin(), global_vec.begin() + delta + remnant); } else { MPI_Status status; MPI_Recv(local_vec.data(), delta, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); } int global_max = 0; int local_max = getSequentialMax(local_vec); MPI_Reduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD); return global_max; } else { if (rank == 0) { return getSequentialMax(global_vec); } else { return 0; } } } 1pkg/dump #ifndef __GAME_ACT_CONTOURS_SEGMENT_HPP__ #define __GAME_ACT_CONTOURS_SEGMENT_HPP__ #include "Interfaces/INoncopyable.hpp" #include "Interfaces/IObserverable.hpp" #include "Interfaces/IObserver.hpp" #include namespace GameAct { namespace Colors { class Dye; } namespace Contours { class Kit; class Line; class KitExpert; class Segment : Interfaces::INoncopyable, public Interfaces::IObserverable, public Interfaces::IObserver { public: void nortify() const override; public: bool handle(const Interfaces::IObserverable * obsable) override; public: Segment(Kit * kit, Colors::Dye & dye); Kit * getParentKit() const; bool hasLine(Line * line) const; bool attachLine(std::unique_ptr & line); void blank(); cocos2d::Color4F getColor() const; friend Kit; friend KitExpert; private: Kit * _kit; Colors::Dye & _dye; bool _isBlanked; std::unique_ptr _current; std::vector> _lines; }; } } #endiforinem/google-cloud-cppgoogle/cloud/internal/filesystem.cc // Copyright 2018 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 // // 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 "google/cloud/internal/filesystem.h" #include "google/cloud/internal/throw_delegate.h" #include // The order of these two includes cannot be changed. #include #if _WIN32 #else #include #endif // _WIN32 namespace google { namespace cloud { inline namespace GOOGLE_CLOUD_CPP_NS { namespace internal { // NOLINTNEXTLINE(readability-identifier-naming) file_status status(std::string const& path) { std::error_code ec; auto s = status(path, ec); if (ec) { std::string msg = __func__; msg += ": getting status of file="; msg += path; ThrowSystemError(ec, msg); } return s; } #if _WIN32 using os_stat_type = struct ::_stat; #else using os_stat_type = struct stat; #endif // _WIN32 perms ExtractPermissions(os_stat_type const& s) { #if _WIN32 // On Windows only a few permissions are available. perms permissions = perms::none; if (s.st_mode & _S_IREAD) { permissions |= perms::owner_read; } if (s.st_mode & _S_IWRITE) { permissions |= perms::owner_write; } if (s.st_mode & _S_IEXEC) { permissions |= perms::owner_exec; } return permissions; #else // This depends on the fact that the permission bits in POSIX systems match // the definition of the `permissions` enum class. return static_cast(s.st_mode & static_cast(perms::mask)); #endif // _WIN32 } file_type ExtractFileType(os_stat_type const& s) { #if _WIN32 if (s.st_mode & _S_IFREG) { return file_type::regular; } if (s.st_mode & _S_IFDIR) { return file_type::directory; } if (s.st_mode & _S_IFCHR) { return file_type::character; } #else if (S_ISREG(s.st_mode)) { return file_type::regular; } if (S_ISDIR(s.st_mode)) { return file_type::directory; } if (S_ISBLK(s.st_mode)) { return file_type::block; } if (S_ISCHR(s.st_mode)) { return file_type::character; } if (S_ISFIFO(s.st_mode)) { return file_type::fifo; } if (S_ISSOCK(s.st_mode)) { return file_type::socket; } #endif // _WIN32 return file_type::unknown; } // NOLINTNEXTLINE(readability-identifier-naming) file_status status(std::string const& path, std::error_code& ec) noexcept { os_stat_type stat; ec.clear(); #if _WIN32 int r = ::_stat(path.c_str(), &stat); if (r == -1) { if (errno == ENOENT) { return file_status(file_type::not_found); } ec.assign(errno, std::generic_category()); return {}; } else if (r == EINVAL) { ec.assign(errno, std::generic_category()); return {}; } #else int r = ::stat(path.c_str(), &stat); if (r != 0) { if (errno == EACCES) { return file_status(file_type::unknown); } if (errno == ENOENT) { return file_status(file_type::not_found); } ec.assign(errno, std::generic_category()); return {}; } #endif // _WIN32 return file_status(ExtractFileType(stat), ExtractPermissions(stat)); } // NOLINTNEXTLINE(readability-identifier-naming) std::uintmax_t file_size(std::string const& path) { std::error_code ec; auto s = file_size(path, ec); if (ec) { std::string msg = __func__; msg += ": getting size of file="; msg += path; ThrowSystemError(ec, msg); } return s; } // NOLINTNEXTLINE(readability-identifier-naming) std::uintmax_t file_size(std::string const& path, std::error_code& ec) noexcept { os_stat_type stat; ec.clear(); #if _WIN32 int r = ::_stat(path.c_str(), &stat); if (r == -1) { ec.assign(errno, std::generic_category()); return static_cast(-1); } else if (r == EINVAL) { ec.assign(errno, std::generic_category()); return static_cast(-1); } #else int r = ::stat(path.c_str(), &stat); if (r != 0) { ec.assign(errno, std::generic_category()); return static_cast(-1); } #endif // _WIN32 return static_cast(stat.st_size); } } // namespace internal } // namespace GOOGLE_CLOUD_CPP_NS } // namespace cloud } // namespace google 695.MaxAreaofIsland.cpp class Solution { public: int island_size(vector> &grid, int i, int j) { int size = 1; grid[i][j] = -1; if(j-1 >= 0 && grid[i][j-1] == 1) size += island_size(grid, i, j-1); if(j+1 < grid[0].size() && grid[i][j+1] == 1) size += island_size(grid, i, j+1); if(i-1 >= 0 && grid[i-1][j] == 1) size += island_size(grid, i-1, j); if(i+1 < grid.size() && grid[i+1][j] == 1) size += island_size(grid, i+1, j); return size; } int maxAreaOfIsland(vector>& grid) { int max_size = 0; for(int i=0; i namespace xgboost { namespace common { TEST(CompressedIterator, Test) { ASSERT_TRUE(detail::SymbolBits(256) == 8); ASSERT_TRUE(detail::SymbolBits(150) == 8); std::vector test_cases = {1, 3, 426, 21, 64, 256, 100000, INT32_MAX}; int num_elements = 1000; int repetitions = 1000; srand(9); for (auto alphabet_size : test_cases) { for (int i = 0; i < repetitions; i++) { std::vector input(num_elements); std::generate(input.begin(), input.end(), [=]() { return rand() % alphabet_size; }); CompressedBufferWriter cbw(alphabet_size); // Test write entire array std::vector buffer( CompressedBufferWriter::CalculateBufferSize(input.size(), alphabet_size)); cbw.Write(buffer.data(), input.begin(), input.end()); CompressedIterator ci(buffer.data(), alphabet_size); std::vector output(input.size()); for (int i = 0; i < input.size(); i++) { output[i] = ci[i]; } ASSERT_TRUE(input == output); // Test write Symbol std::vector buffer2( CompressedBufferWriter::CalculateBufferSize(input.size(), alphabet_size)); for (int i = 0; i < input.size(); i++) { cbw.WriteSymbol(buffer2.data(), input[i], i); } CompressedIterator ci2(buffer.data(), alphabet_size); std::vector output2(input.size()); for (int i = 0; i < input.size(); i++) { output2[i] = ci2[i]; } ASSERT_TRUE(input == output2); } } } } // namespace common } // namespace xgboost /* -*- 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 #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/Maybe.h" #include "mozilla/Move.h" #include "mozilla/Types.h" #include "mozilla/TypeTraits.h" #include "mozilla/UniquePtr.h" using mozilla::IsSame; using mozilla::Maybe; using mozilla::Move; using mozilla::Nothing; using mozilla::Some; using mozilla::Swap; using mozilla::ToMaybe; using mozilla::UniquePtr; #if MOZ_IS_MSVC template struct Identity { typedef T type; }; # define DECLTYPE(EXPR) Identity::type #elif MOZ_IS_GCC // Work around a bug in GCC < 4.7 that prevents expressions of // the form |decltype(foo)::type| from working. See here: // http://stackoverflow.com/questions/14330768/c11-compiler-error-when-using-decltypevar-followed-by-internal-type-of-var # if MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) # define DECLTYPE(EXPR) decltype(EXPR) # else template struct Identity { typedef T type; }; # define DECLTYPE(EXPR) Identity::type # endif #else # define DECLTYPE(EXPR) decltype(EXPR) #endif #define RUN_TEST(t) \ do { \ bool cond = (t()); \ if (!cond) \ return 1; \ cond = AllDestructorsWereCalled(); \ MOZ_ASSERT(cond, "Failed to destroy all objects during test: " #t); \ if (!cond) \ return 1; \ } while (false) enum Status { eWasDefaultConstructed, eWasConstructed, eWasCopyConstructed, eWasMoveConstructed, eWasCopyAssigned, eWasMoveAssigned, eWasMovedFrom }; static size_t sUndestroyedObjects = 0; static bool AllDestructorsWereCalled() { return sUndestroyedObjects == 0; } struct BasicValue { BasicValue() : mStatus(eWasDefaultConstructed) , mTag(0) { ++sUndestroyedObjects; } explicit BasicValue(int aTag) : mStatus(eWasConstructed) , mTag(aTag) { ++sUndestroyedObjects; } BasicValue(const BasicValue& aOther) : mStatus(eWasCopyConstructed) , mTag(aOther.mTag) { ++sUndestroyedObjects; } BasicValue(BasicValue&& aOther) : mStatus(eWasMoveConstructed) , mTag(aOther.mTag) { ++sUndestroyedObjects; aOther.mStatus = eWasMovedFrom; aOther.mTag = 0; } ~BasicValue() { --sUndestroyedObjects; } BasicValue& operator=(const BasicValue& aOther) { mStatus = eWasCopyAssigned; mTag = aOther.mTag; return *this; } BasicValue& operator=(BasicValue&& aOther) { mStatus = eWasMoveAssigned; mTag = aOther.mTag; aOther.mStatus = eWasMovedFrom; aOther.mTag = 0; return *this; } bool operator==(const BasicValue& aOther) const { return mTag == aOther.mTag; } bool operator<(const BasicValue& aOther) const { return mTag < aOther.mTag; } Status GetStatus() const { return mStatus; } void SetTag(int aValue) { mTag = aValue; } int GetTag() const { return mTag; } private: Status mStatus; int mTag; }; struct UncopyableValue { UncopyableValue() : mStatus(eWasDefaultConstructed) { ++sUndestroyedObjects; } UncopyableValue(UncopyableValue&& aOther) : mStatus(eWasMoveConstructed) { ++sUndestroyedObjects; aOther.mStatus = eWasMovedFrom; } ~UncopyableValue() { --sUndestroyedObjects; } UncopyableValue& operator=(UncopyableValue&& aOther) { mStatus = eWasMoveAssigned; aOther.mStatus = eWasMovedFrom; return *this; } Status GetStatus() { return mStatus; } private: UncopyableValue(const UncopyableValue& aOther) = delete; UncopyableValue& operator=(const UncopyableValue& aOther) = delete; Status mStatus; }; struct UnmovableValue { UnmovableValue() : mStatus(eWasDefaultConstructed) { ++sUndestroyedObjects; } UnmovableValue(const UnmovableValue& aOther) : mStatus(eWasCopyConstructed) { ++sUndestroyedObjects; } ~UnmovableValue() { --sUndestroyedObjects; } UnmovableValue& operator=(const UnmovableValue& aOther) { mStatus = eWasCopyAssigned; return *this; } Status GetStatus() { return mStatus; } private: UnmovableValue(UnmovableValue&& aOther) = delete; UnmovableValue& operator=(UnmovableValue&& aOther) = delete; Status mStatus; }; struct UncopyableUnmovableValue { UncopyableUnmovableValue() : mStatus(eWasDefaultConstructed) { ++sUndestroyedObjects; } explicit UncopyableUnmovableValue(int) : mStatus(eWasConstructed) { ++sUndestroyedObjects; } ~UncopyableUnmovableValue() { --sUndestroyedObjects; } Status GetStatus() { return mStatus; } private: UncopyableUnmovableValue(const UncopyableUnmovableValue& aOther) = delete; UncopyableUnmovableValue& operator=(const UncopyableUnmovableValue& aOther) = delete; UncopyableUnmovableValue(UncopyableUnmovableValue&& aOther) = delete; UncopyableUnmovableValue& operator=(UncopyableUnmovableValue&& aOther) = delete; Status mStatus; }; static bool TestBasicFeatures() { // Check that a Maybe is initialized to Nothing. Maybe mayValue; static_assert(IsSame::value, "Should have BasicValue ValueType"); MOZ_RELEASE_ASSERT(!mayValue); MOZ_RELEASE_ASSERT(!mayValue.isSome()); MOZ_RELEASE_ASSERT(mayValue.isNothing()); // Check that emplace() default constructs and the accessors work. mayValue.emplace(); MOZ_RELEASE_ASSERT(mayValue); MOZ_RELEASE_ASSERT(mayValue.isSome()); MOZ_RELEASE_ASSERT(!mayValue.isNothing()); MOZ_RELEASE_ASSERT(*mayValue == BasicValue()); MOZ_RELEASE_ASSERT(mayValue.value() == BasicValue()); static_assert(IsSame::value, "value() should return a BasicValue"); MOZ_RELEASE_ASSERT(mayValue.ref() == BasicValue()); static_assert(IsSame::value, "ref() should return a BasicValue&"); MOZ_RELEASE_ASSERT(mayValue.ptr() != nullptr); static_assert(IsSame::value, "ptr() should return a BasicValue*"); MOZ_RELEASE_ASSERT(mayValue->GetStatus() == eWasDefaultConstructed); // Check that reset() works. mayValue.reset(); MOZ_RELEASE_ASSERT(!mayValue); MOZ_RELEASE_ASSERT(!mayValue.isSome()); MOZ_RELEASE_ASSERT(mayValue.isNothing()); // Check that emplace(T1) calls the correct constructor. mayValue.emplace(1); MOZ_RELEASE_ASSERT(mayValue); MOZ_RELEASE_ASSERT(mayValue->GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 1); mayValue.reset(); MOZ_RELEASE_ASSERT(!mayValue); // Check that Some() and Nothing() work. mayValue = Some(BasicValue(2)); MOZ_RELEASE_ASSERT(mayValue); MOZ_RELEASE_ASSERT(mayValue->GetStatus() == eWasMoveConstructed); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 2); mayValue = Nothing(); MOZ_RELEASE_ASSERT(!mayValue); // Check that the accessors work through a const ref. mayValue.emplace(); const Maybe& mayValueCRef = mayValue; MOZ_RELEASE_ASSERT(mayValueCRef); MOZ_RELEASE_ASSERT(mayValueCRef.isSome()); MOZ_RELEASE_ASSERT(!mayValueCRef.isNothing()); MOZ_RELEASE_ASSERT(*mayValueCRef == BasicValue()); MOZ_RELEASE_ASSERT(mayValueCRef.value() == BasicValue()); static_assert(IsSame::value, "value() should return a BasicValue"); MOZ_RELEASE_ASSERT(mayValueCRef.ref() == BasicValue()); static_assert(IsSame::value, "ref() should return a const BasicValue&"); MOZ_RELEASE_ASSERT(mayValueCRef.ptr() != nullptr); static_assert(IsSame::value, "ptr() should return a const BasicValue*"); MOZ_RELEASE_ASSERT(mayValueCRef->GetStatus() == eWasDefaultConstructed); mayValue.reset(); return true; } static bool TestCopyAndMove() { // Check that we get moves when possible for types that can support both moves // and copies. Maybe mayBasicValue = Some(BasicValue(1)); MOZ_RELEASE_ASSERT(mayBasicValue->GetStatus() == eWasMoveConstructed); MOZ_RELEASE_ASSERT(mayBasicValue->GetTag() == 1); mayBasicValue = Some(BasicValue(2)); MOZ_RELEASE_ASSERT(mayBasicValue->GetStatus() == eWasMoveAssigned); MOZ_RELEASE_ASSERT(mayBasicValue->GetTag() == 2); mayBasicValue.reset(); mayBasicValue.emplace(BasicValue(3)); MOZ_RELEASE_ASSERT(mayBasicValue->GetStatus() == eWasMoveConstructed); MOZ_RELEASE_ASSERT(mayBasicValue->GetTag() == 3); // Check that we get copies when moves aren't possible. Maybe mayBasicValue2 = Some(*mayBasicValue); MOZ_RELEASE_ASSERT(mayBasicValue2->GetStatus() == eWasCopyConstructed); MOZ_RELEASE_ASSERT(mayBasicValue2->GetTag() == 3); mayBasicValue->SetTag(4); mayBasicValue2 = mayBasicValue; // This test should work again when we fix bug 1052940. //MOZ_RELEASE_ASSERT(mayBasicValue2->GetStatus() == eWasCopyAssigned); MOZ_RELEASE_ASSERT(mayBasicValue2->GetTag() == 4); mayBasicValue->SetTag(5); mayBasicValue2.reset(); mayBasicValue2.emplace(*mayBasicValue); MOZ_RELEASE_ASSERT(mayBasicValue2->GetStatus() == eWasCopyConstructed); MOZ_RELEASE_ASSERT(mayBasicValue2->GetTag() == 5); // Check that Move() works. (Another sanity check for move support.) Maybe mayBasicValue3 = Some(Move(*mayBasicValue)); MOZ_RELEASE_ASSERT(mayBasicValue3->GetStatus() == eWasMoveConstructed); MOZ_RELEASE_ASSERT(mayBasicValue3->GetTag() == 5); MOZ_RELEASE_ASSERT(mayBasicValue->GetStatus() == eWasMovedFrom); mayBasicValue2->SetTag(6); mayBasicValue3 = Some(Move(*mayBasicValue2)); MOZ_RELEASE_ASSERT(mayBasicValue3->GetStatus() == eWasMoveAssigned); MOZ_RELEASE_ASSERT(mayBasicValue3->GetTag() == 6); MOZ_RELEASE_ASSERT(mayBasicValue2->GetStatus() == eWasMovedFrom); Maybe mayBasicValue4; mayBasicValue4.emplace(Move(*mayBasicValue3)); MOZ_RELEASE_ASSERT(mayBasicValue4->GetStatus() == eWasMoveConstructed); MOZ_RELEASE_ASSERT(mayBasicValue4->GetTag() == 6); MOZ_RELEASE_ASSERT(mayBasicValue3->GetStatus() == eWasMovedFrom); // Check that we always get copies for types that don't support moves. // XXX(seth): These tests fail but probably shouldn't. For now we'll just // consider using Maybe with types that allow copies but have deleted or // private move constructors, or which do not support copy assignment, to // be supported only to the extent that we need for existing code to work. // These tests should work again when we fix bug 1052940. /* Maybe mayUnmovableValue = Some(UnmovableValue()); MOZ_RELEASE_ASSERT(mayUnmovableValue->GetStatus() == eWasCopyConstructed); mayUnmovableValue = Some(UnmovableValue()); MOZ_RELEASE_ASSERT(mayUnmovableValue->GetStatus() == eWasCopyAssigned); mayUnmovableValue.reset(); mayUnmovableValue.emplace(UnmovableValue()); MOZ_RELEASE_ASSERT(mayUnmovableValue->GetStatus() == eWasCopyConstructed); */ // Check that types that only support moves, but not copies, work. Maybe mayUncopyableValue = Some(UncopyableValue()); MOZ_RELEASE_ASSERT(mayUncopyableValue->GetStatus() == eWasMoveConstructed); mayUncopyableValue = Some(UncopyableValue()); MOZ_RELEASE_ASSERT(mayUncopyableValue->GetStatus() == eWasMoveAssigned); mayUncopyableValue.reset(); mayUncopyableValue.emplace(UncopyableValue()); MOZ_RELEASE_ASSERT(mayUncopyableValue->GetStatus() == eWasMoveConstructed); // Check that types that support neither moves or copies work. Maybe mayUncopyableUnmovableValue; mayUncopyableUnmovableValue.emplace(); MOZ_RELEASE_ASSERT(mayUncopyableUnmovableValue->GetStatus() == eWasDefaultConstructed); mayUncopyableUnmovableValue.reset(); mayUncopyableUnmovableValue.emplace(0); MOZ_RELEASE_ASSERT(mayUncopyableUnmovableValue->GetStatus() == eWasConstructed); return true; } static BasicValue* sStaticBasicValue = nullptr; static BasicValue MakeBasicValue() { return BasicValue(9); } static BasicValue& MakeBasicValueRef() { return *sStaticBasicValue; } static BasicValue* MakeBasicValuePtr() { return sStaticBasicValue; } static bool TestFunctionalAccessors() { BasicValue value(9); sStaticBasicValue = new BasicValue(9); // Check that the 'some' case of functional accessors works. Maybe someValue = Some(BasicValue(3)); MOZ_RELEASE_ASSERT(someValue.valueOr(value) == BasicValue(3)); static_assert(IsSame::value, "valueOr should return a BasicValue"); MOZ_RELEASE_ASSERT(someValue.valueOrFrom(&MakeBasicValue) == BasicValue(3)); static_assert(IsSame::value, "valueOrFrom should return a BasicValue"); MOZ_RELEASE_ASSERT(someValue.ptrOr(&value) != &value); static_assert(IsSame::value, "ptrOr should return a BasicValue*"); MOZ_RELEASE_ASSERT(*someValue.ptrOrFrom(&MakeBasicValuePtr) == BasicValue(3)); static_assert(IsSame::value, "ptrOrFrom should return a BasicValue*"); MOZ_RELEASE_ASSERT(someValue.refOr(value) == BasicValue(3)); static_assert(IsSame::value, "refOr should return a BasicValue&"); MOZ_RELEASE_ASSERT(someValue.refOrFrom(&MakeBasicValueRef) == BasicValue(3)); static_assert(IsSame::value, "refOrFrom should return a BasicValue&"); // Check that the 'some' case works through a const reference. const Maybe& someValueCRef = someValue; MOZ_RELEASE_ASSERT(someValueCRef.valueOr(value) == BasicValue(3)); static_assert(IsSame::value, "valueOr should return a BasicValue"); MOZ_RELEASE_ASSERT(someValueCRef.valueOrFrom(&MakeBasicValue) == BasicValue(3)); static_assert(IsSame::value, "valueOrFrom should return a BasicValue"); MOZ_RELEASE_ASSERT(someValueCRef.ptrOr(&value) != &value); static_assert(IsSame::value, "ptrOr should return a const BasicValue*"); MOZ_RELEASE_ASSERT(*someValueCRef.ptrOrFrom(&MakeBasicValuePtr) == BasicValue(3)); static_assert(IsSame::value, "ptrOrFrom should return a const BasicValue*"); MOZ_RELEASE_ASSERT(someValueCRef.refOr(value) == BasicValue(3)); static_assert(IsSame::value, "refOr should return a const BasicValue&"); MOZ_RELEASE_ASSERT(someValueCRef.refOrFrom(&MakeBasicValueRef) == BasicValue(3)); static_assert(IsSame::value, "refOrFrom should return a const BasicValue&"); // Check that the 'none' case of functional accessors works. Maybe noneValue; MOZ_RELEASE_ASSERT(noneValue.valueOr(value) == BasicValue(9)); static_assert(IsSame::value, "valueOr should return a BasicValue"); MOZ_RELEASE_ASSERT(noneValue.valueOrFrom(&MakeBasicValue) == BasicValue(9)); static_assert(IsSame::value, "valueOrFrom should return a BasicValue"); MOZ_RELEASE_ASSERT(noneValue.ptrOr(&value) == &value); static_assert(IsSame::value, "ptrOr should return a BasicValue*"); MOZ_RELEASE_ASSERT(*noneValue.ptrOrFrom(&MakeBasicValuePtr) == BasicValue(9)); static_assert(IsSame::value, "ptrOrFrom should return a BasicValue*"); MOZ_RELEASE_ASSERT(noneValue.refOr(value) == BasicValue(9)); static_assert(IsSame::value, "refOr should return a BasicValue&"); MOZ_RELEASE_ASSERT(noneValue.refOrFrom(&MakeBasicValueRef) == BasicValue(9)); static_assert(IsSame::value, "refOrFrom should return a BasicValue&"); // Check that the 'none' case works through a const reference. const Maybe& noneValueCRef = noneValue; MOZ_RELEASE_ASSERT(noneValueCRef.valueOr(value) == BasicValue(9)); static_assert(IsSame::value, "valueOr should return a BasicValue"); MOZ_RELEASE_ASSERT(noneValueCRef.valueOrFrom(&MakeBasicValue) == BasicValue(9)); static_assert(IsSame::value, "valueOrFrom should return a BasicValue"); MOZ_RELEASE_ASSERT(noneValueCRef.ptrOr(&value) == &value); static_assert(IsSame::value, "ptrOr should return a const BasicValue*"); MOZ_RELEASE_ASSERT(*noneValueCRef.ptrOrFrom(&MakeBasicValuePtr) == BasicValue(9)); static_assert(IsSame::value, "ptrOrFrom should return a const BasicValue*"); MOZ_RELEASE_ASSERT(noneValueCRef.refOr(value) == BasicValue(9)); static_assert(IsSame::value, "refOr should return a const BasicValue&"); MOZ_RELEASE_ASSERT(noneValueCRef.refOrFrom(&MakeBasicValueRef) == BasicValue(9)); static_assert(IsSame::value, "refOrFrom should return a const BasicValue&"); // Clean up so the undestroyed objects count stays accurate. delete sStaticBasicValue; sStaticBasicValue = nullptr; return true; } static bool gFunctionWasApplied = false; static void IncrementTag(BasicValue& aValue) { gFunctionWasApplied = true; aValue.SetTag(aValue.GetTag() + 1); } static void IncrementTagBy(BasicValue& aValue, int aAmount) { gFunctionWasApplied = true; aValue.SetTag(aValue.GetTag() + aAmount); } static void AccessValue(const BasicValue&) { gFunctionWasApplied = true; } static void AccessValueWithArg(const BasicValue&, int) { gFunctionWasApplied = true; } struct IncrementTagFunctor { IncrementTagFunctor() : mBy(1), mArgMoved(false) { } void operator()(BasicValue& aValue) { aValue.SetTag(aValue.GetTag() + mBy.GetTag()); } void operator()(BasicValue& aValue, const BasicValue& aArg) { mArgMoved = false; aValue.SetTag(aValue.GetTag() + aArg.GetTag()); } void operator()(BasicValue& aValue, BasicValue&& aArg) { mArgMoved = true; aValue.SetTag(aValue.GetTag() + aArg.GetTag()); } BasicValue mBy; bool mArgMoved; }; static bool TestApply() { // Check that apply handles the 'Nothing' case. gFunctionWasApplied = false; Maybe mayValue; mayValue.apply(&IncrementTag); mayValue.apply(&AccessValue); mayValue.apply(&IncrementTagBy, 1); mayValue.apply(&AccessValueWithArg, 1); MOZ_RELEASE_ASSERT(!gFunctionWasApplied); // Check that apply handles the 'Some' case. mayValue = Some(BasicValue(1)); mayValue.apply(&IncrementTag); MOZ_RELEASE_ASSERT(gFunctionWasApplied); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 2); gFunctionWasApplied = false; mayValue.apply(&AccessValue); MOZ_RELEASE_ASSERT(gFunctionWasApplied); gFunctionWasApplied = false; mayValue.apply(&IncrementTagBy, 2); MOZ_RELEASE_ASSERT(gFunctionWasApplied); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 4); gFunctionWasApplied = false; mayValue.apply(&AccessValueWithArg, 1); MOZ_RELEASE_ASSERT(gFunctionWasApplied); // Check that apply works with a const reference. const Maybe& mayValueCRef = mayValue; gFunctionWasApplied = false; mayValueCRef.apply(&AccessValue); MOZ_RELEASE_ASSERT(gFunctionWasApplied); gFunctionWasApplied = false; mayValueCRef.apply(&AccessValueWithArg, 1); MOZ_RELEASE_ASSERT(gFunctionWasApplied); // Check that apply works with functors. IncrementTagFunctor tagIncrementer; MOZ_RELEASE_ASSERT(tagIncrementer.mBy.GetStatus() == eWasConstructed); mayValue = Some(BasicValue(1)); mayValue.apply(tagIncrementer); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 2); MOZ_RELEASE_ASSERT(tagIncrementer.mBy.GetStatus() == eWasConstructed); mayValue.apply(tagIncrementer, BasicValue(2)); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 4); MOZ_RELEASE_ASSERT(tagIncrementer.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(tagIncrementer.mArgMoved == true); BasicValue incrementBy(3); mayValue.apply(tagIncrementer, incrementBy); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 7); MOZ_RELEASE_ASSERT(tagIncrementer.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(tagIncrementer.mArgMoved == false); return true; } static int TimesTwo(const BasicValue& aValue) { return aValue.GetTag() * 2; } static int TimesTwoAndResetOriginal(BasicValue& aValue) { int tag = aValue.GetTag(); aValue.SetTag(1); return tag * 2; } static int TimesNum(const BasicValue& aValue, int aNum) { return aValue.GetTag() * aNum; } static int TimesNumAndResetOriginal(BasicValue& aValue, int aNum) { int tag = aValue.GetTag(); aValue.SetTag(1); return tag * aNum; } struct MultiplyTagFunctor { MultiplyTagFunctor() : mBy(2), mArgMoved(false) { } int operator()(BasicValue& aValue) { return aValue.GetTag() * mBy.GetTag(); } int operator()(BasicValue& aValue, const BasicValue& aArg) { mArgMoved = false; return aValue.GetTag() * aArg.GetTag(); } int operator()(BasicValue& aValue, BasicValue&& aArg) { mArgMoved = true; return aValue.GetTag() * aArg.GetTag(); } BasicValue mBy; bool mArgMoved; }; static bool TestMap() { // Check that map handles the 'Nothing' case. Maybe mayValue; MOZ_RELEASE_ASSERT(mayValue.map(&TimesTwo) == Nothing()); static_assert(IsSame, DECLTYPE(mayValue.map(&TimesTwo))>::value, "map(TimesTwo) should return a Maybe"); MOZ_RELEASE_ASSERT(mayValue.map(&TimesTwoAndResetOriginal) == Nothing()); MOZ_RELEASE_ASSERT(mayValue.map(&TimesNum, 3) == Nothing()); static_assert(IsSame, DECLTYPE(mayValue.map(&TimesNum, 3))>::value, "map(TimesNum, 3) should return a Maybe"); MOZ_RELEASE_ASSERT(mayValue.map(&TimesNumAndResetOriginal, 3) == Nothing()); // Check that map handles the 'Some' case. mayValue = Some(BasicValue(2)); MOZ_RELEASE_ASSERT(mayValue.map(&TimesTwo) == Some(4)); MOZ_RELEASE_ASSERT(mayValue.map(&TimesTwoAndResetOriginal) == Some(4)); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 1); mayValue = Some(BasicValue(2)); MOZ_RELEASE_ASSERT(mayValue.map(&TimesNum, 3) == Some(6)); MOZ_RELEASE_ASSERT(mayValue.map(&TimesNumAndResetOriginal, 3) == Some(6)); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 1); // Check that map works with a const reference. mayValue->SetTag(2); const Maybe& mayValueCRef = mayValue; MOZ_RELEASE_ASSERT(mayValueCRef.map(&TimesTwo) == Some(4)); static_assert(IsSame, DECLTYPE(mayValueCRef.map(&TimesTwo))>::value, "map(TimesTwo) should return a Maybe"); MOZ_RELEASE_ASSERT(mayValueCRef.map(&TimesNum, 3) == Some(6)); static_assert(IsSame, DECLTYPE(mayValueCRef.map(&TimesNum, 3))>::value, "map(TimesNum, 3) should return a Maybe"); // Check that map works with functors. // XXX(seth): Support for functors will be added in bug 1054115; it had to be // ripped out temporarily because of incompatibilities with GCC 4.4. /* MultiplyTagFunctor tagMultiplier; MOZ_RELEASE_ASSERT(tagMultiplier.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(mayValue.map(tagMultiplier) == Some(4)); MOZ_RELEASE_ASSERT(tagMultiplier.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(mayValue.map(tagMultiplier, BasicValue(3)) == Some(6)); MOZ_RELEASE_ASSERT(tagMultiplier.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(tagMultiplier.mArgMoved == true); BasicValue multiplyBy(3); MOZ_RELEASE_ASSERT(mayValue.map(tagMultiplier, multiplyBy) == Some(6)); MOZ_RELEASE_ASSERT(tagMultiplier.mBy.GetStatus() == eWasConstructed); MOZ_RELEASE_ASSERT(tagMultiplier.mArgMoved == false); */ return true; } static bool TestToMaybe() { BasicValue value(1); BasicValue* nullPointer = nullptr; // Check that a non-null pointer translates into a Some value. Maybe mayValue = ToMaybe(&value); static_assert(IsSame, DECLTYPE(ToMaybe(&value))>::value, "ToMaybe should return a Maybe"); MOZ_RELEASE_ASSERT(mayValue.isSome()); MOZ_RELEASE_ASSERT(mayValue->GetTag() == 1); MOZ_RELEASE_ASSERT(mayValue->GetStatus() == eWasCopyConstructed); MOZ_RELEASE_ASSERT(value.GetStatus() != eWasMovedFrom); // Check that a null pointer translates into a Nothing value. mayValue = ToMaybe(nullPointer); static_assert(IsSame, DECLTYPE(ToMaybe(nullPointer))>::value, "ToMaybe should return a Maybe"); MOZ_RELEASE_ASSERT(mayValue.isNothing()); return true; } static bool TestComparisonOperators() { Maybe nothingValue = Nothing(); Maybe anotherNothingValue = Nothing(); Maybe oneValue = Some(BasicValue(1)); Maybe anotherOneValue = Some(BasicValue(1)); Maybe twoValue = Some(BasicValue(2)); // Check equality. MOZ_RELEASE_ASSERT(nothingValue == anotherNothingValue); MOZ_RELEASE_ASSERT(oneValue == anotherOneValue); // Check inequality. MOZ_RELEASE_ASSERT(nothingValue != oneValue); MOZ_RELEASE_ASSERT(oneValue != nothingValue); MOZ_RELEASE_ASSERT(oneValue != twoValue); // Check '<'. MOZ_RELEASE_ASSERT(nothingValue < oneValue); MOZ_RELEASE_ASSERT(oneValue < twoValue); // Check '<='. MOZ_RELEASE_ASSERT(nothingValue <= anotherNothingValue); MOZ_RELEASE_ASSERT(nothingValue <= oneValue); MOZ_RELEASE_ASSERT(oneValue <= oneValue); MOZ_RELEASE_ASSERT(oneValue <= twoValue); // Check '>'. MOZ_RELEASE_ASSERT(oneValue > nothingValue); MOZ_RELEASE_ASSERT(twoValue > oneValue); // Check '>='. MOZ_RELEASE_ASSERT(nothingValue >= anotherNothingValue); MOZ_RELEASE_ASSERT(oneValue >= nothingValue); MOZ_RELEASE_ASSERT(oneValue >= oneValue); MOZ_RELEASE_ASSERT(twoValue >= oneValue); return true; } int main() { RUN_TEST(TestBasicFeatures); RUN_TEST(TestCopyAndMove); RUN_TEST(TestFunctionalAccessors); RUN_TEST(TestApply); RUN_TEST(TestMap); RUN_TEST(TestToMaybe); RUN_TEST(TestComparisonOperators); return 0; } /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 * Copyright (C) 2013 */ #ifdef HAVE_EIGEN3 #include #include #include #include using namespace shogun; TEST(Distance, custom_mahalanobis) { // Create a couple of simple 2D features SGMatrix feat_mat(2,2); // First feature vector feat_mat[0] = 1.0, feat_mat[1] = 1.0; // Second feature vector feat_mat[2] = 2.0, feat_mat[3] = 2.0; // Create features object CDenseFeatures* feats = new CDenseFeatures(feat_mat); // Create a simple Mahalanobis matrix, equal to the identity SGMatrix eye_mat = SGMatrix::create_identity_matrix(2, 1.0); CCustomMahalanobisDistance* distance = new CCustomMahalanobisDistance(feats, feats, eye_mat); // The distance is equal to zero between equal points EXPECT_EQ(distance->distance(0,0), 0.0); EXPECT_EQ(distance->distance(1,1), 0.0); // The distance is symmetric EXPECT_EQ(distance->distance(0,1), distance->distance(1,0)); // Compare with the actual value computed a priori EXPECT_EQ(distance->distance(0,1), 2.0); SG_UNREF(distance) } #endif /* HAVE_EIGEN3 */ // conceptsIntegral.cpp #include #include template concept bool Integral(){ return std::is_integral::value; } template requires Integral() T gcd(T a, T b){ if( b == 0 ){ return a; } else{ return gcd(b, a % b); } } int main(){ std::cout << std::endl; std::cout << "gcd(100, 10)= " << gcd(100, 10) << std::endl; std::cout << "gcd(100, 33)= " << gcd(100, 33) << std::endl; // std::cout << "gcd(5.5, 4,5)= " << gcd(5.5, 4.5) << std::endl; std::cout << std::endl; } aminPial/Competitive-Programming-Library #include using namespace std; bool check(int N, int pos){ return (bool) (N & (1<>5],i&31)==0) { // // status[idx]==0 then we chop i*i ->... // // i%32 th bit of [i/32]th index // for (int j = i * i; j <= N; j += i<<1) // i << 1==2*i // { // // status[j/32]=Set(status[j/32], j%32); // status[j>>5]=Set(status[j>>5], j&31); // } // } // } // puts("2"); // for(int i=3;i<=N;i+=2) // if( check(status[i/32],i%32)==0) // cout << i << "\n"; // } const int N = 1000000; bool stat[N+5]; void siv() { int sq = sqrt(N);for(int i =4;i<=N;i+=2)stat[i]=1; for(int i=3;i<=sq;i+=2)if(!stat[i])for(int j=i*i;j<=N;j+=2*i)stat[j]=1; stat[1]=1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); siv(); int q;cin>>q; while(q--) { int n; cin >> n; if(stat[n]==0) cout << n << " is a prime number." << "\n"; else cout << n << " is not a prime number." << "\n"; } return 0; } /* // normal sieve bool status[1100002]; void siv() { int N=1000000; int sq=sqrt(N); for(int i=4;i<=N;i+=2) status[i]=1; for(int i=3;i<=sq;i+=2){ if(status[i]==0) { for(int j=i*i;j<=N;j+=i) status[j]=1; } } status[1]=1; } */RobertDamerius/GroundControlStation #pragma once #include class ShaderLine: protected RD::Engine::Shader { public: using RD::Engine::Shader::Use; using RD::Engine::Shader::Delete; /** * @brief Create line shader. */ ShaderLine(); /** * @brief Delete line shader. */ ~ShaderLine(); /** * @brief Generate the shader. * @return True if success, false otherwise. */ bool Generate(void); /** * @brief Set model matrix. * @param [in] matrix The model matrix. */ void SetModelMatrix(glm::mat4& matrix); /** * @brief Set the line width. * @param [in] width Line width (will be ensured to be greater than or equal to 1.0f). */ void SetLineWidth(GLfloat width); /** * @brief Set the screen resolution. * @param [in] size The screen size in pixels (will be ensured to be greater than or equal to [1, 1]). */ void SetResolution(glm::ivec2 size); /** * @brief Set color multiplier. * @param [in] color Color multiplier. */ void SetColor(glm::vec3 color); private: GLint locationModelMatrix; GLint locationLineWidth; GLint locationInfoScreenSize; GLint locationColor; }; elailai94/Distributed-System #include #include #include #include #include #include #include #include "segment.h" #include "message.h" #include "register_success_message.h" #include "register_failure_message.h" #include "register_request_message.h" #include "loc_success_message.h" #include "loc_failure_message.h" #include "loc_request_message.h" #include "terminate_message.h" #include "constants.h" #include "network.h" #include "helper_functions.h" using namespace std; // Global variables for binder static map, ps_compare> procLocDict; static list roundRobinList; static list serverList; static bool isTerminated = false; // Handles a registration request from the server void handleRegistrationRequest(RegisterRequestMessage *message, int sock) { const char *name = message->getName().c_str(); int *argTypes = message->getArgTypes(); string server_identifier = message->getServerIdentifier(); int port = message->getPort(); procedure_signature key(name, argTypes); int result = SUCCESS_CODE; try { // If 'key' doesn't exist in map, add it to the map and round robin if (procLocDict.find(key) == procLocDict.end()) { /* * The purpose of this function is so we can have copy of the argTypes * that is not the original */ int *memArgTypes = copyArgTypes(argTypes); key = procedure_signature(name, memArgTypes); procLocDict[key] = list(); // This is bad we shouldn't need a newKey and we should be able to use the key above // due to &* reasones I made a variable newKey for the 'info' object procedure_signature *newKey = new procedure_signature(name, memArgTypes); server_info *entry = new server_info(server_identifier, port, sock); server_function_info *info = new server_function_info(entry, newKey); // Adding to roundRobinList if server is not found roundRobinList.push_back(info); // Adding to serverList if server is not found bool serverExist = false; for (list::iterator it = serverList.begin(); it != serverList.end(); it++) { if ((*it)->server_identifier == entry->server_identifier && (*it)->port == entry->port && (*it)->socket == entry->socket) { serverExist = true; break; } } if (!serverExist) { serverList.push_back(entry); } } else { bool sameLoc = false; list hostList = procLocDict[key]; for (list::iterator it = hostList.begin(); it != hostList.end(); it++) { if((*it)->server_identifier == server_identifier && (*it)->port == port && (*it)->socket == sock) { // If they have the same socket, then must be same server_address/port // The same procedure signature already exists on the same location sameLoc = true; result = WARNING_CODE_DUPLICATED_PROCEDURE; } } if (!sameLoc) { // Same procedure but different socket server_info *new_msg_loc = new server_info(server_identifier, port, sock); hostList.push_back(new_msg_loc); int *newArgTypes = copyArgTypes(argTypes); procedure_signature *useFulKey = new procedure_signature(name, newArgTypes); server_function_info *info = new server_function_info(new_msg_loc, useFulKey); // Adding to roundRobinList if server is not found roundRobinList.push_back(info); // Adding to serverList if server is not found bool serverExist = false; for (list::iterator it = serverList.begin(); it != serverList.end(); it++) { if ((*it)->server_identifier == new_msg_loc->server_identifier && (*it)->port == new_msg_loc->port && (*it)->socket == new_msg_loc->socket) { serverExist = true; break; } } if (!serverExist) { serverList.push_back(new_msg_loc); } } } } catch (...) { result = ERROR_CODE_PROCEDURE_REGISTRATION_FAILED; } if (result >= 0) { RegisterSuccessMessage messageToServer = RegisterSuccessMessage(result); Segment segmentToServer = Segment(messageToServer.getLength(), MSG_TYPE_REGISTER_SUCCESS, &messageToServer); segmentToServer.send(sock); } else { RegisterFailureMessage messageToServer = RegisterFailureMessage(result); Segment segmentToServer = Segment(messageToServer.getLength(), MSG_TYPE_REGISTER_FAILURE, &messageToServer); segmentToServer.send(sock); } } // Handles a location request from the client void handleLocationRequest(LocRequestMessage *message, int sock) { bool exist = false; string serverIdToPushBack; int portToPushBack; int socketToPushBack; for (list::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){ //If the name are the same and argTypes if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){ exist = true; serverIdToPushBack = (*it)->si->server_identifier; portToPushBack = (*it)->si->port; socketToPushBack = (*it)->si->socket; LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier.c_str(), (*it)->si->port); Segment locSuccessSeg = Segment(locSuccessMsg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg); locSuccessSeg.send(sock); break; } } if (exist) { list::iterator i = roundRobinList.begin(); list tempList; while (i != roundRobinList.end()){ if((*i)->si->server_identifier == serverIdToPushBack && (*i)->si->port == portToPushBack && (*i)->si->socket == socketToPushBack){ tempList.push_back(*i); roundRobinList.erase(i++); // alternatively, i = items.erase(i); }else{ ++i; } } roundRobinList.splice(roundRobinList.end(), tempList); } else { LocFailureMessage locFailMsg = LocFailureMessage(ERROR_CODE_PROCEDURE_NOT_FOUND); Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg); locFailSeg.send(sock); } } // Handles a termination request from the client void handleTerminationRequest() { // Informs all the servers to terminate for (list::const_iterator it = serverList.begin(); it != serverList.end(); it++) { TerminateMessage messageToServer = TerminateMessage(); Segment segmentToServer = Segment(messageToServer.getLength(), MSG_TYPE_TERMINATE, &messageToServer); segmentToServer.send((*it)->socket); } // Signals the binder to terminate isTerminated = true; } // Handles a request from the client/server void handleRequest(Segment *segment, int socket) { switch (segment->getType()) { case MSG_TYPE_REGISTER_REQUEST: { RegisterRequestMessage *messageFromServer = dynamic_cast(segment->getMessage()); handleRegistrationRequest(messageFromServer, socket); break; } case MSG_TYPE_LOC_REQUEST: { LocRequestMessage *messageFromClient = dynamic_cast(segment->getMessage()); handleLocationRequest(messageFromClient, socket); break; } case MSG_TYPE_TERMINATE: { handleTerminationRequest(); break; } } } int main() { fd_set allSockets; fd_set readSockets; /* * Clears all entries from the all sockets set and the read * sockets set */ FD_ZERO(&allSockets); FD_ZERO(&readSockets); /* * Creates the welcome socket, adds it to the all sockets set and * sets it as the maximum socket so far */ int welcomeSocket = createSocket(); if (welcomeSocket < 0) { return welcomeSocket; } int result = setUpToListen(welcomeSocket); if (result < 0) { return result; } FD_SET(welcomeSocket, &allSockets); int maxSocket = welcomeSocket; /* * Prints the binder address and the binder port on the binder's * standard output */ string binderIdentifier = getHostAddress(); if (binderIdentifier == "") { return ERROR_CODE_HOST_ADDRESS_NOT_FOUND; } int port = getSocketPort(welcomeSocket); if (port < 0) { return port; } cout << "BINDER_ADDRESS " << binderIdentifier << endl; cout << "BINDER_PORT " << port << endl; while (!isTerminated) { readSockets = allSockets; // Checks if some of the sockets are ready to be read from int result = select(maxSocket + 1, &readSockets, 0, 0, 0); if (result < 0) { continue; } for (int i = 0; i <= maxSocket; i++) { if (!FD_ISSET(i, &readSockets)) { continue; } if (i == welcomeSocket) { /* * Creates the connection socket when a connection is made * to the welcome socket */ int connectionSocket = acceptConnection(i); if (connectionSocket < 0) { continue; } // Adds the connection socket to the all sockets set FD_SET(connectionSocket, &allSockets); /* * Sets the connection socket as the maximum socket so far * if necessary */ if (connectionSocket > maxSocket) { maxSocket = connectionSocket; } } else { /* * Creates a segment to receive data from the client/server and * reads into it from the connection socket */ Segment *segment = 0; result = 0; result = Segment::receive(i, segment); if (result < 0) { /* * Closes the connection socket and removes it from the * all sockets set */ destroySocket(i); FD_CLR(i, &allSockets); continue; } // Handles a request from the client/server handleRequest(segment, i); } } } // Destroys the welcome socket destroySocket(welcomeSocket); return SUCCESS_CODE; } Foxyy420/foxyy_private #include "bhop.hpp" #include "../Strafer.h" void Misc::OnCreateMove(CUserCmd* cmd) { static bool jumped_last_tick = false; static bool should_fake_jump = false; if (!jumped_last_tick && should_fake_jump) { should_fake_jump = false; cmd->buttons |= IN_JUMP; } else if (cmd->buttons & IN_JUMP) { if (g_LocalPlayer->m_fFlags() & FL_ONGROUND) { jumped_last_tick = true; should_fake_jump = true; } else { cmd->buttons &= ~IN_JUMP; jumped_last_tick = false; } } else { jumped_last_tick = false; should_fake_jump = false; } } template T clamp(T in, U low, U high) { if (in <= low) return low; if (in >= high) return high; return in; } static vec_t Normalize_y(vec_t ang) { while (ang < -180.0f) ang += 360.0f; while (ang > 180.0f) ang -= 360.0f; return ang; } void Misc::AutoStrafe(CUserCmd* cmd, QAngle oldangles) { static AutoStrafer Strafer; static float move = 450; float s_move = move * 0.5065f; if (g_LocalPlayer->GetMoveType() & (MOVETYPE_NOCLIP | MOVETYPE_LADDER)) return; if (cmd->buttons & (IN_FORWARD | IN_MOVERIGHT | IN_MOVELEFT | IN_BACK)) return; if (cmd->buttons & IN_JUMP | !(g_LocalPlayer->m_fFlags() & FL_ONGROUND)) { if (g_LocalPlayer->m_vecVelocity().Length2D() == 0 && (cmd->forwardmove == 0 && cmd->sidemove == 0)) { cmd->forwardmove = 450.f; } else if (cmd->forwardmove == 0 && cmd->sidemove == 0) { if (cmd->mousedx > 0 || cmd->mousedx > -0) { cmd->sidemove = cmd->mousedx < 0.f ? -450.f : 450.f; } else { auto airaccel = g_CVar->FindVar("sv_airaccelerate"); auto maxspeed = g_CVar->FindVar("sv_maxspeed"); static int zhop = 0; double yawrad = Normalize_y(oldangles.yaw) * PI / 180; float speed = maxspeed->GetFloat(); if (cmd->buttons & IN_DUCK) speed *= 0.333; double tau = g_GlobalVars->interval_per_tick, MA = speed * airaccel->GetFloat(); int Sdir = 0, Fdir = 0; Vector velocity = g_LocalPlayer->m_vecVelocity(); double vel[3] = { velocity[0], velocity[1], velocity[2] }; double pos[2] = { 0, 0 }; double dir[2] = { std::cos((oldangles[1] + 10 * zhop) * PI / 180), std::sin((oldangles[1] + 10 * zhop) * PI / 180) }; oldangles.yaw = Normalize_y(yawrad * 180 / PI); Strafer.strafe_line_opt(yawrad, Sdir, Fdir, vel, pos, 30.0, tau, MA, pos, dir); cmd->sidemove = Sdir * 450; } } } } 10-100 /**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corporation, 1997 - 1998 **/ /**********************************************************************/ /* rtrsnap.cpp Snapin entry points/registration functions Note: Proxy/Stub Information To build a separate proxy/stub DLL, run nmake -f Snapinps.mak in the project directory. FILE HISTORY: */ #include "stdafx.h" #include "ipxcomp.h" #include "ripcomp.h" #include "sapcomp.h" #include "register.h" #include "ipxguid.h" #include "dialog.h" #ifdef _DEBUG void DbgVerifyInstanceCounts(); #define DEBUG_VERIFY_INSTANCE_COUNTS DbgVerifyInstanceCounts() #else #define DEBUG_VERIFY_INSTANCE_COUNTS #endif CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_IPXAdminExtension, CIPXComponentDataExtension) OBJECT_ENTRY(CLSID_IPXAdminAbout, CIPXAbout) OBJECT_ENTRY(CLSID_IPXRipExtension, CRipComponentData) OBJECT_ENTRY(CLSID_IPXRipExtensionAbout, CRipAbout) OBJECT_ENTRY(CLSID_IPXSapExtension, CSapComponentData) OBJECT_ENTRY(CLSID_IPXSapExtensionAbout, CSapAbout) END_OBJECT_MAP() /*--------------------------------------------------------------------------- This is a list of snapins to be registered into the main snapin list. ---------------------------------------------------------------------------*/ struct RegisteredSnapins { const GUID * m_pGuid; const GUID * m_pGuidAbout; UINT m_uDesc; LPCTSTR m_pszVersion; }; const static RegisteredSnapins s_rgRegisteredSnapins[] = { { &CLSID_IPXAdminExtension, &CLSID_IPXAdminAbout, IDS_IPXADMIN_DISPLAY_NAME, _T("1.0") }, { &CLSID_IPXRipExtension, &CLSID_IPXRipExtensionAbout, IDS_IPXRIP_DISPLAY_NAME, _T("1.0") }, { &CLSID_IPXSapExtension, &CLSID_IPXSapExtensionAbout, IDS_IPXSAP_DISPLAY_NAME, _T("1.0") }, }; /*--------------------------------------------------------------------------- This is a list of nodetypes that need to be registered. ---------------------------------------------------------------------------*/ struct RegisteredNodeTypes { const GUID *m_pGuidSnapin; const GUID *m_pGuid; LPCTSTR m_pszName; }; const static RegisteredNodeTypes s_rgNodeTypes[] = { { &CLSID_IPXAdminExtension, &GUID_IPXRootNodeType, _T("Root of IPX Admin Snapin") }, { &CLSID_IPXAdminExtension, &GUID_IPXNodeType, _T("IPX Admin Snapin") }, { &CLSID_IPXAdminExtension, &GUID_IPXSummaryNodeType, _T("IPX General") }, { &CLSID_IPXAdminExtension, &GUID_IPXSummaryInterfaceNodeType, _T("IPX Interface General") }, { &CLSID_IPXAdminExtension, &GUID_IPXNetBIOSBroadcastsNodeType, _T("IPX NetBIOS Broadcasts") }, { &CLSID_IPXAdminExtension, &GUID_IPXNetBIOSBroadcastsInterfaceNodeType, _T("IPX Interface NetBIOS Broadcasts") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticRoutesNodeType, _T("IPX Static Routes") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticRoutesResultNodeType, _T("IPX Static Routes result item") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticServicesNodeType, _T("IPX Static Services") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticServicesResultNodeType, _T("IPX Static Services result item") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticNetBIOSNamesNodeType, _T("IPX Static NetBIOS Names") }, { &CLSID_IPXAdminExtension, &GUID_IPXStaticNetBIOSNamesResultNodeType, _T("IPX Static NetBIOS Names result item") }, { &CLSID_IPXRipExtension, &GUID_IPXRipNodeType, _T("IPX RIP") }, { &CLSID_IPXSapExtension, &GUID_IPXSapNodeType, _T("IPX SAP") }, }; /*--------------------------------------------------------------------------- This is a list of GUIDs that the IPX admin extension extends. ---------------------------------------------------------------------------*/ const static GUID * s_pExtensionGuids[] = { // &GUID_RouterIfAdminNodeType, &GUID_RouterMachineNodeType, }; /*--------------------------------------------------------------------------- This is a list of GUIDS that extend the IPX root node ---------------------------------------------------------------------------*/ struct RegisteredExtensions { const CLSID *m_pClsid; LPCTSTR m_pszName; }; const static RegisteredExtensions s_rgIPXExtensions[] = { { &CLSID_IPXRipExtension, _T("IPX RIP") }, { &CLSID_IPXSapExtension, _T("IPX SAP") }, }; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif class CIPXAdminSnapinApp : public CWinApp { public: virtual BOOL InitInstance(); virtual int ExitInstance(); }; CIPXAdminSnapinApp theApp; BOOL CIPXAdminSnapinApp::InitInstance() { _Module.Init(ObjectMap, m_hInstance); // Initialize the error handling system InitializeTFSError(); // Create an error object for this thread CreateTFSErrorInfo(0); // Setup the proper help file free((void *) m_pszHelpFilePath); m_pszHelpFilePath = _tcsdup(_T("mprsnap.hlp")); // Setup the global help function extern DWORD * IpxSnapHelpMap(DWORD dwIDD); SetGlobalHelpMapFunction(IpxSnapHelpMap); return CWinApp::InitInstance(); } int CIPXAdminSnapinApp::ExitInstance() { _Module.Term(); // Destroy the TFS error information for this thread DestroyTFSErrorInfo(0); // Cleanup the entire error system CleanupTFSError(); DEBUG_VERIFY_INSTANCE_COUNTS; return CWinApp::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return (AfxDllCanUnloadNow()==S_OK && _Module.GetLockCount()==0) ? S_OK : S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _Module.GetClassObject(rclsid, riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); int i; CString st; CString stNameStringIndirect; TCHAR moduleFileName[MAX_PATH * 2]; GetModuleFileNameOnly(_Module.GetModuleInstance(), moduleFileName, MAX_PATH * 2); // registers object, typelib and all interfaces in typelib // HRESULT hr = _Module.RegisterServer(/* bRegTypeLib */ FALSE); Assert(SUCCEEDED(hr)); if (FAILED(hr)) return hr; // Register he extension snapins into the snapin list. for (i=0; i0 #include "python/pySpriteComponent.h" #include "python/pySpriteComponent_doc_en.h" #include "components/SpriteComponent.h" #include "utils/PyxieHeaders.h" using namespace pyxie; #include #include namespace ige::scene { void SpriteComponent_dealloc(PyObject_SpriteComponent *self) { if (self && self->component) { self->component = nullptr; } PyObject_Del(self); } PyObject *SpriteComponent_str(PyObject_SpriteComponent *self) { return PyUnicode_FromString("C++ SpriteComponent object"); } // Get path PyObject *SpriteComponent_getPath(PyObject_SpriteComponent *self) { return PyUnicode_FromString(self->component->getPath().c_str()); } // Set path int SpriteComponent_setPath(PyObject_SpriteComponent *self, PyObject *value) { if (PyUnicode_Check(value)) { const char* name = PyUnicode_AsUTF8(value); self->component->setPath(std::string(name)); return 0; } return -1; } // Get size PyObject *SpriteComponent_getSize(PyObject_SpriteComponent *self) { auto vec2Obj = PyObject_New(vec_obj, _Vec2Type); vmath_cpy(self->component->getSize().P(), 2, vec2Obj->v); vec2Obj->d = 2; return (PyObject *)vec2Obj; } // Set size int SpriteComponent_setSize(PyObject_SpriteComponent *self, PyObject *value) { int d; float buff[4]; auto v = pyObjToFloat((PyObject *)value, buff, d); if (!v) return -1; self->component->setSize(*((Vec2 *)v)); return 0; } PyObject* SpriteComponent_isBillboard(PyObject_SpriteComponent* self) { return PyBool_FromLong(self->component->isBillboard()); } int SpriteComponent_setBillboard(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto isActive = (uint32_t)PyLong_AsLong(value) != 0; self->component->setBillboard(isActive); return 0; } return -1; } // Get color PyObject* SpriteComponent_getColor(PyObject_SpriteComponent* self) { auto vec4Obj = PyObject_New(vec_obj, _Vec4Type); vmath_cpy(self->component->getColor().P(), 4, vec4Obj->v); vec4Obj->d = 4; return (PyObject*)vec4Obj; } // Set color int SpriteComponent_setColor(PyObject_SpriteComponent* self, PyObject* value) { int d; float buff[4]; auto v = pyObjToFloat((PyObject*)value, buff, d); if (!v) return -1; self->component->setColor(*((Vec4*)v)); return 0; } // Get Fill Method PyObject* SpriteComponent_getFillMethod(PyObject_SpriteComponent* self) { return PyLong_FromLong((int)self->component->getFillMethod()); } // Set Fill Method int SpriteComponent_setFillMethod(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value); self->component->setFillMethod(val); return 0; } return -1; } // Get Fill Origin PyObject* SpriteComponent_getFillOrigin(PyObject_SpriteComponent* self) { return PyLong_FromLong((int)self->component->getFillOrigin()); } // Set Fill Origin int SpriteComponent_setFillOrigin(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value); self->component->setFillOrigin(val); return 0; } return -1; } // Get Fill Amount PyObject* SpriteComponent_getFillAmount(PyObject_SpriteComponent* self) { return PyFloat_FromDouble(self->component->getFillAmount()); } // Set Fill Amount int SpriteComponent_setFillAmount(PyObject_SpriteComponent* self, PyObject* value) { if (PyFloat_Check(value)) { auto val = (float)PyFloat_AsDouble(value); self->component->setFillAmount(val); return 0; } return -1; } // Get Fill Clockwise PyObject* SpriteComponent_getClockwise(PyObject_SpriteComponent* self) { return PyBool_FromLong(self->component->getClockwise()); } // Set Fill Clockwise int SpriteComponent_setClockwise(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value) != 0; self->component->setClockwise(val); return 0; } return -1; } PyGetSetDef SpriteComponent_getsets[] = { {"path", (getter)SpriteComponent_getPath, (setter)SpriteComponent_setPath, SpriteComponent_path_doc, NULL}, {"size", (getter)SpriteComponent_getSize, (setter)SpriteComponent_setSize, SpriteComponent_size_doc, NULL}, {"isBillboard", (getter)SpriteComponent_isBillboard, (setter)SpriteComponent_setBillboard, SpriteComponent_isBillboard_doc, NULL}, {"color", (getter)SpriteComponent_getColor, (setter)SpriteComponent_setColor, NULL, NULL}, {"fillMethod", (getter)SpriteComponent_getFillMethod, (setter)SpriteComponent_setFillMethod, NULL, NULL}, {"fillOrigin", (getter)SpriteComponent_getFillOrigin, (setter)SpriteComponent_setFillOrigin, NULL, NULL}, {"fillAmount", (getter)SpriteComponent_getFillAmount, (setter)SpriteComponent_setFillAmount, NULL, NULL}, {"clockwise", (getter)SpriteComponent_getClockwise, (setter)SpriteComponent_setClockwise, NULL, NULL}, {NULL, NULL}}; PyTypeObject PyTypeObject_SpriteComponent = { PyVarObject_HEAD_INIT(NULL, 0) "igeScene.Sprite", /* tp_name */ sizeof(PyObject_SpriteComponent), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SpriteComponent_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)SpriteComponent_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ SpriteComponent_getsets, /* tp_getset */ &PyTypeObject_Component, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; } // namespace ige::scene // ////////////////////////////////////////////////////////////////////// #include "flux/SpectrumFactoryTable.h" #include #include SpectrumFactoryTable* SpectrumFactoryTable::s_instance = 0; ISpectrum* SpectrumFactoryTable::instantiate(const std::string& name, const std::string& params) const { const_iterator returnloc = find(name); return returnloc==end() ? 0: (*returnloc).second->instantiate(params); } ISpectrum* SpectrumFactoryTable::instantiate(const std::string& name) const { const_iterator returnloc = find(name); std::string params; // dummy return returnloc==end() ? 0: (*returnloc).second->instantiate(params); } std::list SpectrumFactoryTable::spectrumList()const { std::list outstr; for( const_iterator tableiter = begin(); tableiter!=end() ; ++tableiter){ outstr.push_back(tableiter->first); } return outstr; } src/common/util/mmap.hpp /* * mmap.hpp * * Author: wqy */ #ifndef MMAP_HPP_ #define MMAP_HPP_ #include "common.hpp" namespace ardb { class MMapBuf { public: char* m_buf; uint64 m_size; public: MMapBuf() : m_buf(0), m_size(0) { } int Init(const std::string& path, uint64 size, int advice_flag); ~MMapBuf(); }; } #endif /* MMAP_HPP_ */ 10-100 /* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ // Common specific product patches applied to release 2011_2. // This file is #included by hkPatches_2011_2.cpp HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSetunsignedinthkContainerHeapAllocatorhkMapOperationsunsignedint", 0) HK_PATCH_MEMBER_ADDED("elem", TYPE_ARRAY_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("numElems", TYPE_INT, HK_NULL, 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSetUint32", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkSetunsignedinthkContainerHeapAllocatorhkMapOperationsunsignedint") HK_PATCH_DEPENDS("hkSetunsignedinthkContainerHeapAllocatorhkMapOperationsunsignedint", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkxBlob", 1) HK_PATCH_PARENT_SET(HK_NULL, "hkReferencedObject") HK_PATCH_MEMBER_ADDED("data", TYPE_ARRAY_BYTE, HK_NULL, 0) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSkinnedMeshShapePart", 0) HK_PATCH_MEMBER_ADDED("startVertex", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("numVertices", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("startIndex", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("numIndices", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("boneIndex", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("meshSectionIndex", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("boundingSphere", TYPE_VEC_4, HK_NULL, 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSkinnedMeshShapeBoneSection", 0) HK_PATCH_MEMBER_ADDED("meshBuffer", TYPE_OBJECT, "hkMeshShape", 0) HK_PATCH_MEMBER_ADDED("startBoneIndex", TYPE_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("numBones", TYPE_INT, HK_NULL, 0) HK_PATCH_DEPENDS("hkMeshShape", 0) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSkinnedMeshShape", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkReferencedObject") HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkSkinnedRefMeshShape", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkMeshShape") HK_PATCH_MEMBER_ADDED("skinnedMeshShape", TYPE_OBJECT, "hkSkinnedMeshShape", 0) HK_PATCH_MEMBER_ADDED("bones", TYPE_ARRAY_INT, HK_NULL, 0) HK_PATCH_MEMBER_ADDED("localFromRootTransforms", TYPE_ARRAY_STRUCT, "hkQTransform", 0) HK_PATCH_MEMBER_ADDED("name", TYPE_CSTRING, HK_NULL, 0) HK_PATCH_DEPENDS("hkMeshShape", 0) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkSkinnedMeshShape", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_DEPENDS("hkQTransform", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkStorageSkinnedMeshShape", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkSkinnedMeshShape") HK_PATCH_MEMBER_ADDED("boneSections", TYPE_ARRAY_STRUCT, "hkSkinnedMeshShapeBoneSection", 0) HK_PATCH_MEMBER_ADDED("parts", TYPE_ARRAY_STRUCT, "hkSkinnedMeshShapePart", 0) HK_PATCH_MEMBER_ADDED("name", TYPE_CSTRING, HK_NULL, 0) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkSkinnedMeshShape", 0) HK_PATCH_DEPENDS("hkSkinnedMeshShapeBoneSection", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_DEPENDS("hkSkinnedMeshShapePart", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkxBlobMeshShape", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkMeshShape") HK_PATCH_MEMBER_ADDED("blob", TYPE_STRUCT, "hkxBlob", 0) HK_PATCH_MEMBER_ADDED("name", TYPE_CSTRING, HK_NULL, 0) HK_PATCH_DEPENDS("hkMeshShape", 0) HK_PATCH_DEPENDS("hkxBlob", 1) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */ //-------------------------------------------------------------------------------- // IsrOverheadTestScene.cpp //-------------------------------------------------------------------------------- // Measures the overhead of the current interrupt service routine //-------------------------------------------------------------------------------- #include "IsrOverheadTestScene.hpp" #include "data/fonts/monogram_extended.hpp" #include "colors.hpp" #include volatile int cycleCount IWRAM_DATA; extern "C" void hblankReportCycles() IWRAM_CODE; void vcountInterrupt() { // This -192 is experimental constexpr s16 CalculatedVal = 240 * 4 - 192; REG_TM2D = -CalculatedVal; REG_TM2CNT = TM_IRQ | TM_ENABLE; } IsrOverheadTestScene::IsrOverheadTestScene() : IScene(), writer(vid_mem) { // Set the display registers REG_DISPCNT = DCNT_MODE3 | DCNT_BG2; REG_DISPSTAT = (REG_DISPSTAT &~ DSTAT_VCT_MASK) | DSTAT_VCT(24); cycleCount = -1; irq_add(II_VCOUNT, vcountInterrupt); irq_add(II_TIMER2, hblankReportCycles); } void IsrOverheadTestScene::update() { const auto& font = data::fonts::monogram_extended.ttf; // Clear some lines memset32(vid_mem+240*80, 0, 240*20/2); StringBuilder<64> sb; sb.append("Available hblank cycles: ", cycleCount, " cycles."); writer.write(4, 96, sb, colors::LimeGreen, font); } lab_03/lab_03/model.cpp #include "model.h" cModel::cModel(std::string _name) : cObject(_name) { } cModel::cModel(const cModel& _model) : cObject(_model.objName) { points = _model.points; edges = _model.edges; } cModel::cModel(cModel&& _model) : cObject(_model.objName) { points = _model.points; edges = _model.edges; _model.~cModel(); } bool cModel::visible() { return true; } bool cModel::isComposite() { return false; } void cModel::addPoint(cPoint3d point) { points.push_back(point); } void cModel::addEdge(cEdge edge) { edges.push_back(edge); } void cModel::removePoint(int index) { if (points.empty()) throw cModelNoPoints(); points.erase(points.begin() + index); } void cModel::removeEdge(int index) { if (edges.empty()) throw cModelNoEdges(); edges.erase(edges.begin() + index); } cModel& cModel::operator =(const cModel& _model) { points = _model.points; edges = _model.edges; return *this; } cModel& cModel::operator =(cModel&& _model) { points = _model.points; edges = _model.edges; _model.~cModel(); return *this; } void cModel::draw(cBaseDrawer& drawer, cPosition position) { if (points.empty()) throw cModelNoPoints(); if (edges.empty()) throw cModelNoEdges(); for (size_t i = 0; i < edges.size(); i++) { cPoint3d p1 = points[edges[i].getStart()]; cPoint3d p2 = points[edges[i].getEnd()]; /*p1.Run(position.pos[0], position.pos[1], position.pos[2]);*/p1.shift(position.pos[0], position.pos[1], position.pos[2]); p2.shift(position.pos[0], position.pos[1], position.pos[2]); p1.rotateX(position.orientation[0]); p2.rotateX(position.orientation[0]); p1.rotateY(position.orientation[1]); p2.rotateY(position.orientation[1]); p1.rotateZ(position.orientation[2]); p2.rotateZ(position.orientation[2]); drawer.drawLine(p1, p2); } } const std::vector cModel::getPoints() const { return points; } const std::vector cModel::getEdges() const { return edges; } int cModel::getCountPoints() const { return points.size(); } int cModel::getCountEdges() const { return edges.size(); } #include #include using namespace std; class Point3D { double x; double y; double z; public: Point3D(double x, double y, double z) { setX(x); setY(y); setZ(z); } double getX() { return x; } double getY() { return y; } double getZ() { return z; } void setX(double newX) { x = newX; } void setY(double newY) { y = newY; } void setZ(double newZ) { z = newZ; } void translate(Point3D translationVector) { setX(getX() + translationVector.getX()); setY(getY() + translationVector.getY()); setZ(getZ() + translationVector.getZ()); } double distanceTo(Point3D other) { return sqrt(pow(getX() - other.getX(), 2) + pow(getY() - other.getY(), 2) + pow(getZ() - other.getZ(), 2)); } void print() { cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n'; } }; void testTranslate() { Point3D point(3, 5, 2); point.translate(Point3D(4, 7, 1)); point.print(); } void testDistanceBetween() { Point3D firstPoint(3, 5, 2); Point3D secondPoint(4, 1, 7); cout << firstPoint.distanceTo(secondPoint) << '\n'; } int main() { testTranslate(); testDistanceBetween(); return 0; }0 #define PROBLEM "https://judge.yosupo.jp/problem/sum_of_floor_of_linear" #include "Mathematics/sum_of_floor_of_linear.hpp" #include int main() { int T; scanf("%d", &T); using ll = long long; while (T--) { int n, m, a, b; scanf("%d %d %d %d", &n, &m, &a, &b); printf("%lld\n", tk::sum_of_floor_of_linear(n, m, a, b)); } }// // OpenTissue Template Library // - A generic toolbox for physics-based modeling and simulation. // Copyright (C) 2008 Department of Computer Science, University of Copenhagen. // // OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php // #include "OpenTissue/graphics/glut/glut_application.h" #include #include "OpenTissue/graphics/glut/glut_window.h" #include "OpenTissue/graphics/core/event.h" namespace OpenTissue { namespace graphics { GlutApplication::GlutApplication(const std::string &title) : Application(title) { } //------------------------------------------------------------------------------------------- void GlutApplication::idle() { return; } //------------------------------------------------------------------------------------------- void GlutApplication::run() { glutMainLoop(); } //------------------------------------------------------------------------------------------- bool GlutApplication::on_event(const Event &) { glutPostRedisplay(); return true; } } // namespace graphics } // namespace OpenTissue 1-10 /* fastreg includes */ #include /* * VECTOR FIELD */ fastreg::cuda::VectorField::VectorField(cv::Vec3i dims_) : dims(dims_) { int no_voxels = dims[0] * dims[1] * dims[2]; data.create(no_voxels * sizeof(float4)); clear(); } fastreg::cuda::VectorField::~VectorField() = default; cv::Vec3i fastreg::cuda::VectorField::get_dims() const { return dims; } CudaData fastreg::cuda::VectorField::get_data() { return data; } const CudaData fastreg::cuda::VectorField::get_data() const { return data; } void fastreg::cuda::VectorField::set_data(CudaData& data) { data = data; } void fastreg::cuda::VectorField::clear() { int3 d = make_int3(dims[0], dims[1], dims[2]); fastreg::device::VectorField field(data.ptr(), d); fastreg::device::clear(field); } void fastreg::cuda::VectorField::print() { int sizes[3] = {dims[0], dims[1], dims[2]}; cv::Mat* mat = new cv::Mat(3, sizes, CV_32FC4); get_data().download(mat->ptr()); std::cout << "--- FIELD ---" << std::endl; for (int i = 0; i < dims[0]; i++) { for (int j = 0; j < dims[1]; j++) { for (int k = 0; k < dims[2]; k++) { float u = mat->at(k, j, i).x; float v = mat->at(k, j, i).y; float w = mat->at(k, j, i).z; if (fabs(u) > 1e-5f || fabs(v) > 1e-5f || fabs(w) > 1e-5f) { std::cout << "(x,y,z)=(" << i << ", " << j << ", " << k << "), (u,v,w)=(" << u << ", " << v << "," << w << ")" << std::endl; } } } } delete mat; } int fastreg::cuda::VectorField::get_no_nans() { int sizes[3] = {dims[0], dims[1], dims[2]}; cv::Mat* mat = new cv::Mat(3, sizes, CV_32FC4); get_data().download(mat->ptr()); int no_nan = 0; for (int i = 0; i < dims[0]; i++) { for (int j = 0; j < dims[1]; j++) { for (int k = 0; k < dims[2]; k++) { float u = mat->at(k, j, i).x; float v = mat->at(k, j, i).y; float w = mat->at(k, j, i).z; if (std::isnan(u) || std::isnan(v) || std::isnan(w)) { no_nan++; } } } } delete mat; return no_nan; } /* * DEFORMATION FIELD */ fastreg::cuda::DeformationField::DeformationField(cv::Vec3i dims_) : VectorField(dims_) { clear(); } fastreg::cuda::DeformationField::~DeformationField() = default; void fastreg::cuda::DeformationField::clear() { int3 d = fastreg::device_cast(get_dims()); fastreg::device::DeformationField psi(get_data().ptr(), d); fastreg::device::init_identity(psi); } void fastreg::cuda::DeformationField::get_inverse(fastreg::cuda::DeformationField& psi_inv) { int3 d = fastreg::device_cast(get_dims()); fastreg::device::DeformationField psi_device(get_data().ptr(), d); fastreg::device::DeformationField psi_inverse_device(psi_inv.get_data().ptr(), d); fastreg::device::estimate_inverse(psi_device, psi_inverse_device); } void fastreg::cuda::DeformationField::apply(std::shared_ptr phi_n, std::shared_ptr phi_n_psi) { int3 d = fastreg::device_cast(phi_n->get_dims()); fastreg::device::Volume phi_device(phi_n->get_data().ptr(), d); fastreg::device::Volume phi_warped_device(phi_n_psi->get_data().ptr(), d); fastreg::device::DeformationField psi_device(get_data().ptr(), d); fastreg::device::apply(phi_device, phi_warped_device, psi_device); } /* * JACOBIAN */ fastreg::cuda::Jacobian::Jacobian(cv::Vec3i dims_) : dims(dims_) { int no_voxels = dims[0] * dims[1] * dims[2]; data.create(no_voxels * sizeof(Mat4f)); clear(); } fastreg::cuda::Jacobian::~Jacobian() = default; CudaData fastreg::cuda::Jacobian::get_data() { return data; } const CudaData fastreg::cuda::Jacobian::get_data() const { return data; } void fastreg::cuda::Jacobian::clear() { int3 d = make_int3(dims[0], dims[1], dims[2]); fastreg::device::Jacobian J(data.ptr(), d); fastreg::device::clear(J); } /* * SPATIAL GRADIENTS */ fastreg::cuda::SpatialGradients::SpatialGradients(cv::Vec3i dims_) { nabla_phi_n = new fastreg::cuda::VolumeGradient(dims_); nabla_phi_n_o_psi = new fastreg::cuda::VolumeGradient(dims_); J = new fastreg::cuda::Jacobian(dims_); J_inv = new fastreg::cuda::Jacobian(dims_); L = new fastreg::cuda::Laplacian(dims_); L_o_psi_inv = new fastreg::cuda::Laplacian(dims_); dv_v = new fastreg::cuda::DVV(dims_); delta_v = new fastreg::cuda::Laplacian(dims_); nabla_U = new fastreg::cuda::PotentialGradient(dims_); } fastreg::cuda::SpatialGradients::~SpatialGradients() { delete nabla_phi_n, nabla_phi_n_o_psi, J, J_inv, L, L_o_psi_inv, dv_v, delta_v, nabla_U; } #include #include #include #include #include using namespace rv; namespace { } class ParameterListIteratorTest: public ::testing::Test { }; //void ParameterListIteratorTestCase::testCopy() //{ // ParameterList params1; // params1.insert(IntegerParameter("foo", 1337)); // params1.insert(StringParameter("bar", "bla")); // ParameterList rlist; // rlist.insert(IntegerParameter("value0", 1)); // rlist.insert(IntegerParameter("value1", 3)); // rlist.insert(IntegerParameter("value2", 3)); // rlist.insert(IntegerParameter("value3", 7)); // RangeParameter rparam("range", rlist); // params1.insert(rparam); // // ParameterListIterator it(params1); // it.next(); // it.next(); // // /** now testing the copy actions. **/ // ParameterListIterator it2(it); // ParameterListIterator it3(params1); // it3 = it; // // ASSERT_TRUE(it.hasNext()); // ASSERT_EQ(it.hasNext(), it2.hasNext()); // ASSERT_EQ(it.hasNext(), it3.hasNext()); // // const ParameterList& goldparams = it.next(); // const ParameterList& testparams1 = it2.next(); // const ParameterList& testparams2 = it3.next(); // // ASSERT_TRUE((goldparams == testparams1)); // ASSERT_TRUE((goldparams == testparams2)); // //} TEST_F(ParameterListIteratorTest, testIterate) { { ParameterList params1; params1.insert(IntegerParameter("foo", 1337)); params1.insert(StringParameter("bar", "bla")); ParameterListIterator it(params1); ASSERT_TRUE(it.hasNext()); const ParameterList& params = it.next(); ASSERT_FALSE(it.hasNext()); ASSERT_TRUE(params.hasParam("foo")); ASSERT_TRUE(params.hasParam("bar")); ASSERT_EQ(1337, params.getValue("foo")); ASSERT_EQ("bla", params.getValue("bar")); } { ParameterList params1; params1.insert(IntegerParameter("foo", 1337)); params1.insert(StringParameter("bar", "bla")); ParameterList rlist; rlist.insert(IntegerParameter("value0", 1)); rlist.insert(IntegerParameter("value1", 3)); rlist.insert(IntegerParameter("value2", 3)); rlist.insert(IntegerParameter("value3", 7)); RangeParameter rparam("range", rlist); params1.insert(rparam); ParameterListIterator it(params1); double values[] = { 1, 3, 3, 7 }; for (uint32_t i = 0; i < 4; ++i) { ASSERT_TRUE(it.hasNext()); const ParameterList& params = it.next(); ASSERT_TRUE(params.hasParam("foo")); ASSERT_TRUE(params.hasParam("bar")); ASSERT_TRUE(params.hasParam("range")); ASSERT_EQ(1337, params.getValue("foo")); ASSERT_EQ("bla", params.getValue("bar")); ASSERT_EQ(values[i], params.getValue("range")); } ASSERT_FALSE(it.hasNext()); } { ParameterList params1; params1.insert(IntegerParameter("foo", 1337)); params1.insert(StringParameter("bar", "bla")); ParameterList range; range.insert(IntegerParameter("value0", 1)); range.insert(IntegerParameter("value1", 3)); RangeParameter rparam("range1", range); params1.insert(rparam); range.insert(IntegerParameter("value0", 4)); range.insert(IntegerParameter("value1", 7)); RangeParameter rparam2("range2", range); ParameterList cparam_list; cparam_list.insert(FloatParameter("foo", 1.337)); cparam_list.insert(rparam2); CompositeParameter cparam("comp", cparam_list); params1.insert(cparam); // std::cout << "----------------------------" << std::endl; // for (ParameterList::const_iterator it = params1.begin(); it != params1.end(); ++it) // std::cout << *it << std::endl; ParameterListIterator it(params1); double values1[] = { 1, 1, 3, 3 }; double values2[] = { 4, 7, 4, 7 }; for (uint32_t i = 0; i < 4; ++i) { ASSERT_TRUE(it.hasNext()); const ParameterList& params = it.next(); // std::cout << "number of parameters = " << params.size() << std::endl; // for (ParameterList::const_iterator it = params.begin(); it != params.end(); ++it) // std::cout << *it << std::endl; ASSERT_TRUE(params.hasParam("foo")); ASSERT_TRUE(params.hasParam("bar")); ASSERT_TRUE(params.hasParam("range1")); ASSERT_TRUE(params.hasParam("comp")); ASSERT_EQ(1337, params.getValue("foo")); ASSERT_EQ("bla", params.getValue("bar")); ASSERT_EQ(values1[i], params.getValue("range1")); const CompositeParameter* cparam1 = params.getParameter("comp"); const ParameterList& clist = cparam1->getParams(); ASSERT_TRUE(clist.hasParam("foo")); ASSERT_TRUE(clist.hasParam("range2")); ASSERT_NEAR(1.337, clist.getValue("foo"), 0.0001); ASSERT_EQ(values2[i], clist.getValue("range2")); } ASSERT_FALSE(it.hasNext()); } /** now testing with some filter. **/ { ParameterList params1; params1.insert(IntegerParameter("foo", 1337)); params1.insert(StringParameter("bar", "bla")); ParameterList rlist; rlist.insert(IntegerParameter("value0", 1)); rlist.insert(IntegerParameter("value1", 3)); rlist.insert(IntegerParameter("value2", 3)); rlist.insert(IntegerParameter("value3", 7)); RangeParameter rparam("range", rlist); params1.insert(rparam); ParameterList rlist2; rlist2.insert(IntegerParameter("value0", 10)); rlist2.insert(IntegerParameter("value1", 11)); rlist2.insert(IntegerParameter("value2", 12)); RangeParameter rparam2("another-range", rlist2); params1.insert(rparam2); std::vector filtered_names; filtered_names.push_back("range"); ParameterListIterator it(params1, filtered_names); double values[] = { 1, 3, 3, 7 }; for (uint32_t i = 0; i < 4; ++i) { ASSERT_TRUE(it.hasNext()); const ParameterList& params = it.next(); // std::cout << " ===== current params ==== " << std::endl; // for (ParameterList::const_iterator pit = params.begin(); pit != params.end(); ++pit) // std::cout << *pit << std::endl; ASSERT_TRUE(params.hasParam("foo")); ASSERT_TRUE(params.hasParam("bar")); ASSERT_TRUE(params.hasParam("range")); ASSERT_TRUE(params.hasParam("another-range")); ASSERT_EQ(1337, params.getValue("foo")); ASSERT_EQ("bla", params.getValue("bar")); ASSERT_EQ(values[i], params.getValue("range")); ASSERT_EQ("range", params["another-range"].type()); ParameterListIterator it2(params); int values2[] = { 10, 11, 12 }; for (uint32_t j = 0; j < 3; ++j) { ASSERT_TRUE(it2.hasNext()); const ParameterList& params2 = it2.next(); ASSERT_TRUE(params2.hasParam("foo")); ASSERT_TRUE(params2.hasParam("bar")); ASSERT_TRUE(params2.hasParam("range")); ASSERT_TRUE(params2.hasParam("another-range")); ASSERT_EQ(1337, params2.getValue("foo")); ASSERT_EQ("bla", params2.getValue("bar")); ASSERT_EQ(values[i], params2.getValue("range")); ASSERT_EQ(values2[j], params2.getValue("another-range")); } ASSERT_FALSE(it2.hasNext()); } ASSERT_FALSE(it.hasNext()); } } #include #include #include TEST(prob_transform, lub) { EXPECT_FLOAT_EQ(2.0 + (5.0 - 2.0) * stan::math::inv_logit(-1.0), stan::math::lub_constrain(-1.0,2.0,5.0)); EXPECT_FLOAT_EQ(1.7, stan::math::lub_constrain(1.7, -std::numeric_limits::infinity(), +std::numeric_limits::infinity())); EXPECT_FLOAT_EQ(stan::math::lb_constrain(1.8,3.0), stan::math::lub_constrain(1.8, 3.0, +std::numeric_limits::infinity())); EXPECT_FLOAT_EQ(stan::math::ub_constrain(1.9,-12.5), stan::math::lub_constrain(1.9, -std::numeric_limits::infinity(), -12.5)); } TEST(prob_transform, lub_j) { double lp = -17.0; double L = 2.0; double U = 5.0; double x = -1.0; EXPECT_FLOAT_EQ(L + (U - L) * stan::math::inv_logit(x), stan::math::lub_constrain(x,L,U,lp)); EXPECT_FLOAT_EQ(-17.0 + log(U - L) + log(stan::math::inv_logit(x)) + log(1.0 - stan::math::inv_logit(x)), lp); double lp1 = -12.9; EXPECT_FLOAT_EQ(1.7, stan::math::lub_constrain(1.7, -std::numeric_limits::infinity(), +std::numeric_limits::infinity(), lp1)); EXPECT_FLOAT_EQ(-12.9,lp1); double lp2 = -19.8; double lp2_expected = -19.8; EXPECT_FLOAT_EQ(stan::math::lb_constrain(1.8,3.0,lp2_expected), stan::math::lub_constrain(1.8, 3.0, +std::numeric_limits::infinity(), lp2)); EXPECT_FLOAT_EQ(lp2_expected, lp2); double lp3 = -422; double lp3_expected = -422; EXPECT_FLOAT_EQ(stan::math::ub_constrain(1.9,-12.5,lp3_expected), stan::math::lub_constrain(1.9, -std::numeric_limits::infinity(), -12.5, lp3)); EXPECT_FLOAT_EQ(lp3_expected,lp3); } TEST(ProbTransform, lubException) { using stan::math::lub_constrain; EXPECT_THROW(lub_constrain(5.0,1.0,1.0), std::domain_error); EXPECT_NO_THROW(lub_constrain(5.0,1.0,1.01)); double lp = 12; EXPECT_THROW(lub_constrain(5.0,1.0,1.0,lp), std::domain_error); EXPECT_NO_THROW(lub_constrain(5.0,1.0,1.01,lp)); } TEST(prob_transform, lub_f) { double L = -10.0; double U = 27.0; double y = 3.0; EXPECT_FLOAT_EQ(stan::math::logit((y - L) / (U - L)), stan::math::lub_free(y,L,U)); EXPECT_FLOAT_EQ(14.2, stan::math::lub_free(14.2, -std::numeric_limits::infinity(), std::numeric_limits::infinity())); EXPECT_FLOAT_EQ(stan::math::ub_free(-18.3,7.6), stan::math::lub_free(-18.3, -std::numeric_limits::infinity(), 7.6)); EXPECT_FLOAT_EQ(stan::math::lb_free(763.9, -3122.2), stan::math::lub_free(763.9, -3122.2, std::numeric_limits::infinity())); } TEST(prob_transform, lub_f_exception) { double L = -10.0; double U = 27.0; EXPECT_THROW(stan::math::lub_free (L-0.01,L,U), std::domain_error); EXPECT_THROW(stan::math::lub_free (U+0.01,L,U), std::domain_error); EXPECT_THROW(stan::math::lub_free ((L+U)/2,U,L), std::domain_error); } TEST(prob_transform, lub_rt) { double x = -1.0; double xc = stan::math::lub_constrain(x,2.0,4.0); double xcf = stan::math::lub_free(xc,2.0,4.0); EXPECT_FLOAT_EQ(x,xcf); double xcfc = stan::math::lub_constrain(xcf,2.0,4.0); EXPECT_FLOAT_EQ(xc,xcfc); } #include "stdafx.h" #include "ToolRoadAdd.h" #include "WorldRoad.h" #include "WorldNode.h" #include "WorldFrame.h" using namespace Ogre; ToolRoadAdd::ToolRoadAdd(WorldFrame* wf, SceneManager* sm, RoadGraph &g, RoadGraph &s) : ToolView(wf), _roadGraph(g), _simpleRoadGraph(s) { _sceneManager = sm; } void ToolRoadAdd::OnMouseMove(wxMouseEvent &e) { if(alternate(e) == true) { _worldFrame->highlightNode(0); ToolView::OnMouseMove(e); return; } WorldNode *wn; if(_worldFrame->pickNode(e, 7, wn)) _worldFrame->highlightNode(wn); else _worldFrame->highlightNode(0); _worldFrame->Refresh(); } void ToolRoadAdd::OnLeftPressed(wxMouseEvent &e) { if(alternate(e) == true) { _worldFrame->highlightNode(0); ToolView::OnLeftPressed(e); return; } //TODO: if(_worldFrame->getSelectedNode()) { // delete a road WorldNode *wn; if(_worldFrame->pickNode(e, 7, wn)) { if(wn == _worldFrame->getSelectedNode()) { // deselect node _worldFrame->selectNode(0); _worldFrame->Refresh(); return; } // need to check this road can't create it willy nilly WorldNode* proposedNode = _worldFrame->createNode(); proposedNode->setPosition3D(wn->getPosition3D()); WorldRoad* wr = new WorldRoad(_worldFrame->getSelectedNode(), wn, _roadGraph, _simpleRoadGraph, _sceneManager); int snapState; WorldRoad* intersectingRoad; WorldNode* snapNode; Ogre::Vector2 newPos; // needs a good studying snapState = wr->snapInfo(5, newPos, snapNode, intersectingRoad); delete wr; _worldFrame->deleteNode(proposedNode); if(snapState != 0) { Ogre::LogManager::getSingleton().logMessage("INVALID OPERATION: Cannot add a road that intersect with others. Try reducing the road deviation or use the add node tool."); //if(snapState == 1) _worldFrame->selectRoad(intersectingRoad); } else { _worldFrame->createRoad(_worldFrame->getSelectedNode(), wn); _worldFrame->selectNode(wn); } _worldFrame->Refresh(); } } else { // just select a node WorldNode *wn; if(_worldFrame->pickNode(e, 7, wn)) { _worldFrame->selectNode(wn); _worldFrame->Refresh(); } } } bool ToolRoadAdd::alternate(wxMouseEvent &e) { if(e.ControlDown()) return true; else return false; } void ToolRoadAdd::OnMiddlePressed(wxMouseEvent &e) { if(alternate(e) == true) return ToolView::OnMiddlePressed(e); } void ToolRoadAdd::OnRightPressed(wxMouseEvent &e) { if(alternate(e) == true) return ToolView::OnRightPressed(e); } 0 #include "IFCC_EntityBase.h" #include #include #include "IFCC_Helper.h" namespace IFCC { EntityBase::EntityBase(int id) : m_id(id) { } bool EntityBase::set(std::shared_ptr ifcObject) { if(ifcObject == nullptr) return false; m_name = label2s(ifcObject->m_Name); m_description = text2s(ifcObject->m_Description); std::wstring_convert, wchar_t> converterX; m_guid = converterX.to_bytes(ifcObject->m_GlobalId->m_value); return true; } } // namespace IFCC onnxruntime/server/http/json_handling.cc // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include #include #include #include "predict.pb.h" #include "json_handling.h" namespace protobufutil = google::protobuf::util; namespace onnxruntime { namespace server { protobufutil::Status GetRequestFromJson(const std::string& json_string, /* out */ onnxruntime::server::PredictRequest& request) { protobufutil::JsonParseOptions options; options.ignore_unknown_fields = true; protobufutil::Status result = JsonStringToMessage(json_string, &request, options); return result; } protobufutil::Status GenerateResponseInJson(const onnxruntime::server::PredictResponse& response, /* out */ std::string& json_string) { protobufutil::JsonPrintOptions options; options.add_whitespace = false; options.always_print_primitive_fields = false; options.always_print_enums_as_ints = false; options.preserve_proto_field_names = false; protobufutil::Status result = MessageToJsonString(response, &json_string, options); return result; } std::string CreateJsonError(const http::status error_code, const std::string& error_message) { auto escaped_message = escape_string(error_message); return R"({"error_code": )" + std::to_string(int(error_code)) + R"(, "error_message": ")" + escaped_message + R"("})" + "\n"; } std::string escape_string(const std::string& message) { std::ostringstream o; for (char c : message) { switch (c) { case '"': o << "\\\""; break; case '\\': o << "\\\\"; break; case '\b': o << "\\b"; break; case '\f': o << "\\f"; break; case '\n': o << "\\n"; break; case '\r': o << "\\r"; break; case '\t': o << "\\t"; break; default: if ('\x00' <= c && c <= '\x1f') { o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (int)c; } else { o << c; } } } return o.str(); } } // namespace server } // namespace onnxruntimesrc/plugins/inspection/inspection.cpp #include "inspection_impl.h" #include "plugins/inspection/inspection.h" namespace mavsdk { Inspection::Inspection(System& system) : PluginBase(), _impl{new InspectionImpl(system)} {} Inspection::Inspection(std::shared_ptr system) : PluginBase(), _impl{new InspectionImpl(system)} {} Inspection::~Inspection() {} void Inspection::upload_inspection_async( InspectionBase::WaypointList list, const InspectionBase::ResultAckCallback callback) { _impl->upload_inspection_async(list, callback); } std::pair Inspection::upload_inspection(InspectionBase::WaypointList list) const { return _impl->upload_inspection(list); } InspectionBase::Result Inspection::cancel_inspection_upload() const { return _impl->cancel_inspection_upload(); } void Inspection::download_inspection_async( const InspectionBase::DownloadInspectionCallback callback) { _impl->download_inspection_async(callback); } std::pair Inspection::download_inspection() const { return _impl->download_inspection(); } InspectionBase::Result Inspection::cancel_inspection_download() const { return _impl->cancel_inspection_download(); } void Inspection::set_current_inspection_item(uint16_t index) const { _impl->set_current_inspection_item(index); } void Inspection::subscribe_inspection_progress(InspectionBase::InspectionProgressCallback callback) { _impl->inspection_progress_async(callback); } InspectionBase::InspectionProgress Inspection::inspection_progress() const { return _impl->inspection_progress(); } } // namespace mavsdk SammyEnigma/QuickStreams10-100 #include "QuickStreamsTest.hpp" // Verify the error received by the failure stream // is the same as the error thrown in the failed stream // given the error is of non-exception type: QString void QuickStreamsTest::failure_data_string() { Trigger cpFirst; Trigger cpFailure; Error receivedError; auto firstStream = streams->create([&]( const StreamHandle& stream, const QVariant& data ) { Q_UNUSED(data) cpFirst.trigger(); throw "something went wrong"; stream.close(); }); auto failureStream = firstStream->failure([&](const QVariant& error) { receivedError = error.value(); cpFailure.trigger(); return QVariant(); }); Q_UNUSED(failureStream) QVERIFY(cpFirst.wait(100)); QVERIFY(cpFailure.wait(100)); // Ensure the error received by the failure stream is of type Exception // because QString is not a supported error type QVERIFY(receivedError.is(exception::Exception::type())); QCOMPARE(receivedError.message(), QString("something went wrong")); } DeltaGoldenFlag/JuniorEngine1-10 /* * Author: * Email: * Date Created: 11 Sep 2018 * Last Modified: 18 Apr 2019 * File Name: ResourceManager.h * Description: Describes the Resource Manager */ // Includes #include "ResourceManager.h" #include "Resource.h" // Resource #include "Debug.h" // Debug // Private Member Functions Junior::ResourceManager::ResourceManager() : GameSystem("ResourceManager"), garbageCollectionDuration_(30.0), garbageCollectionTimer_(0.0) { } Junior::ResourceManager::ResourceManager(const ResourceManager&) : GameSystem("ResourceManager"), garbageCollectionDuration_(30.0), garbageCollectionTimer_(0.0) { } bool Junior::ResourceManager::Load() { return true; } bool Junior::ResourceManager::Initialize() { return true; } void Junior::ResourceManager::Update(double dt) { garbageCollectionTimer_ += dt; if (garbageCollectionTimer_ >= garbageCollectionDuration_) { Debug::GetInstance().Print(Debug::GetInstance().GetDebugLevelName(DebugLevel::NOTIFICATION)); Debug::GetInstance().PrintLn("Collecting any garbage resources"); garbageCollectionTimer_ = 0.0; // Check garbage resources for (auto begin = resources_.begin(); begin != resources_.end(); ) { if (begin->second->GetResourceCount() == 0) { // If we found a garbage resource, remove it delete begin->second; begin = resources_.erase(begin); } else { ++begin; } } } } void Junior::ResourceManager::Render() { } void Junior::ResourceManager::Shutdown() { } void Junior::ResourceManager::Unload() { if (resources_.size() == 0) return; // Go through every resource and delete it for (auto begin = resources_.begin(); begin != resources_.end(); ++begin) { if (begin->second->GetResourceCount() > 0) { // If we found a resource still sharing itself to other resources Debug::GetInstance().Print(Debug::GetInstance().GetDebugLevelName(DebugLevel::WARNING)); Debug::GetInstance().Print(begin->second->GetResourceDir()); Debug::GetInstance().PrintLn(" still has resources attached to it!"); } begin->second->CleanUp(); delete begin->second; } resources_.clear(); } Junior::ResourceManager::~ResourceManager() { Unload(); } // Public Static Member Functions void Junior::ResourceManager::AddResource(Junior::Resource* resource) { resources_[resource->GetResourceDir()] = resource; } void Junior::ResourceManager::RemoveResource(const std::string& resourceDir) { delete resources_[resourceDir]; resources_.erase(resourceDir); } Junior::ResourceManager& Junior::ResourceManager::GetInstance() { static ResourceManager manager; return manager; }class CfgPatches { class lambs_danger { units[] = {}; weapons[] = {}; requiredVersion = 1.82; requiredAddons[] = { "A3_Characters_F" }; version = "1.0"; versionStr = "1.0"; author = "nkenny"; authorUrl = "http://www.nopryl.no"; }; }; // compile functions #include "cfgFunctions.hpp" // add new FSM class CfgVehicles { class CAManBase; class SoldierWB: CAManBase { fsmDanger = "danger\scripts\lambs_danger.fsm"; }; class SoldierEB: CAManBase { fsmDanger = "danger\scripts\lambs_danger.fsm"; }; class SoldierGB: CAManBase { fsmDanger = "danger\scripts\lambs_danger.fsm"; }; class Civilian_F : CAManBase { fsmDanger = "danger\scripts\lambs_dangerCivilian.fsm"; }; };SAIC-ATS/ARTTECH3135 #include "ofApp.h" void ofApp::setup() { pixels.allocate(256, 256, OF_PIXELS_RGB); pixels.set(0); } void ofApp::draw() { ofBackground(255); for (int x = 0; x < pixels.getWidth(); x++) { for (int y = 0; y < pixels.getHeight(); y++) { float scaleX = ofMap(mouseX, 0.1, ofGetWidth(), 0, 1000, true); float scaleY = ofMap(mouseY, 0.1, ofGetHeight(), 0, 1000, true); float offsetX = ofMap(mouseX, 0.1, ofGetWidth(), 0, 10, true); float offsetY = ofMap(mouseY, 0.1, ofGetHeight(), 0, 10, true); // For each channel, R, G, B we get a slightly different noise value. float noiseR = 255 * ofNoise(x / scaleX + offsetX * 1, y / scaleY + offsetY * 1); float noiseG = 255 * ofNoise(x / scaleX, y / scaleY); float noiseB = 255 * ofNoise(x / scaleX + offsetX * 2, y / scaleY + offsetY * 2); ofColor color = ofColor(noiseR, noiseG, noiseB); pixels.setColor(x, y, color); } } texture.loadData(pixels); texture.draw(0, 0); } class FirstUnique { public: map mp; deque dq; FirstUnique(vector &nums) { for (auto num : nums) { mp[num]++; if (mp[num] == 1) dq.push_back(num); } } int showFirstUnique() { if (dq.empty()) return -1; while (!dq.empty() && mp[dq.front()] > 1) { dq.pop_front(); } if (dq.empty()) return -1; return dq.front(); } void add(int value) { mp[value]++; if (mp[value] == 1) dq.push_back(value); } }; /** * Your FirstUnique object will be instantiated and called as such: * FirstUnique* obj = new FirstUnique(nums); * int param_1 = obj->showFirstUnique(); * obj->add(value); */MonoNative.Tests/mscorlib/System/Runtime/Remoting/Channels/mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture.cpp // Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Runtime.Remoting.Channels // Name: IClientChannelSink // C++ Typed Name: mscorlib::System::Runtime::Remoting::Channels::IClientChannelSink #include #include #include #include namespace mscorlib { namespace System { namespace Runtime { namespace Remoting { namespace Channels { //Public Methods Tests // Method AsyncProcessRequest // Signature: mscorlib::System::Runtime::Remoting::Channels::IClientChannelSinkStack sinkStack, mscorlib::System::Runtime::Remoting::Messaging::IMessage msg, mscorlib::System::Runtime::Remoting::Channels::ITransportHeaders headers, mscorlib::System::IO::Stream stream TEST(mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture,AsyncProcessRequest_Test) { } // Method AsyncProcessResponse // Signature: mscorlib::System::Runtime::Remoting::Channels::IClientResponseChannelSinkStack sinkStack, mscorlib::System::Object state, mscorlib::System::Runtime::Remoting::Channels::ITransportHeaders headers, mscorlib::System::IO::Stream stream TEST(mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture,AsyncProcessResponse_Test) { } // Method GetRequestStream // Signature: mscorlib::System::Runtime::Remoting::Messaging::IMessage msg, mscorlib::System::Runtime::Remoting::Channels::ITransportHeaders headers TEST(mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture,GetRequestStream_Test) { } // Method ProcessMessage // Signature: mscorlib::System::Runtime::Remoting::Messaging::IMessage msg, mscorlib::System::Runtime::Remoting::Channels::ITransportHeaders requestHeaders, mscorlib::System::IO::Stream requestStream, mscorlib::System::Runtime::Remoting::Channels::ITransportHeaders responseHeaders, mscorlib::System::IO::Stream responseStream TEST(mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture,ProcessMessage_Test) { } //Public Properties Tests // Property NextChannelSink // Return Type: mscorlib::System::Runtime::Remoting::Channels::IClientChannelSink // Property Get Method TEST(mscorlib_System_Runtime_Remoting_Channels_IClientChannelSink_Fixture,get_NextChannelSink_Test) { } } } } } } 0 #include using gsl::complex; using gsl::vector_view; using std::cout; using std::endl; // Example-usage of gsl::vector_view. int main() { complex const a1[]= {{1.0f, -1.0f}, {0.5f, 0.6f}}; // Deduce vector_view,2>. vector_view v1= a1; cout << "\n" << "Instance of gsl_vector_view consumes 40 bytes on 64-bit hardware.\n" << "sizeof(v1)=" << sizeof(v1) << " v1=" << v1 << "\n" << "v1.get(1)=" << v1.get(1) << endl; float a4[]= {1, 2, 3, 4, 5, 6}; // Deduce vector_view, and set size to four. The output contains // a subvector of v4: length 2, starting at offset 1 into v4, and with stride // 2 relative to v4. vector_view v4(a4, 4); cout << "\n" << "sizeof(v4)=" << sizeof(v4) << " v4=" << v4 << "\n" << "v4.subvector(2, 1, 2)=" << v4.subvector(2, 1, 2) << endl; short a5[]= {1, 2, 3, 4, 5, 6}; // Deduce vector_view, set size to 3, and set stride to 2. vector_view v5(a5, 3, 2); cout << "\n" << "sizeof(v5)=" << sizeof(v5) << " v5=" << v5 << "\n" << "v5.max_index()=" << v5.max_index() << endl; } 1-10 /* * PROJECT: Universal C++ RunTime (UCXXRT) * FILE: except.cpp * DATA: 2020/02/11 * * PURPOSE: Universal C++ RunTime * * LICENSE: Relicensed under The MIT License from The CC BY 4.0 License * * DEVELOPER: MiroKaku (miro.kaku AT Outlook.com) */ #include #include "vcruntime/ehassert.h" #include "vcruntime/ehhooks.h" #include "shared/image.h" namespace ucxxrt { EXTERN_C [[noreturn]] void __RaiseException( _In_ PEXCEPTION_RECORD ExceptionRecord, _In_ PCONTEXT /*ContextRecord*/ ) { RtlRaiseException(ExceptionRecord); } EXTERN_C [[noreturn]] void __CxxRaiseException( _In_ DWORD dwExceptionCode, _In_ DWORD dwExceptionFlags, _In_ DWORD nNumberOfArguments, _In_reads_opt_(nNumberOfArguments) CONST ULONG_PTR * lpArguments ) { /* * Exception Record */ EXCEPTION_RECORD ExceptionRecord{}; ExceptionRecord.ExceptionCode = dwExceptionCode; ExceptionRecord.ExceptionRecord = nullptr; ExceptionRecord.ExceptionAddress= _ReturnAddress(); ExceptionRecord.ExceptionFlags = dwExceptionFlags & EXCEPTION_NONCONTINUABLE; /* Check if we have arguments */ if (!lpArguments) { /* We don't */ ExceptionRecord.NumberParameters = 0; } else { /* We do, normalize the count */ if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS) nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS; /* Set the count of parameters and copy them */ ExceptionRecord.NumberParameters = nNumberOfArguments; RtlCopyMemory(ExceptionRecord.ExceptionInformation, lpArguments, nNumberOfArguments * sizeof(ULONG_PTR)); } /* * Exception Context */ CONTEXT Context{}; RtlCaptureContext(&Context); /* Write the context flag */ Context.ContextFlags = CONTEXT_FULL; __CxxDispatchException(&ExceptionRecord, &Context); } EXTERN_C [[noreturn]] void __CxxDispatchException( _In_ PEXCEPTION_RECORD ExceptionRecord, _In_ PCONTEXT ContextRecord ) { auto ScopeIndex = 0ul; auto NestedFrame = 0Ui64; auto UnwindHistoryTableBuf = UNWIND_HISTORY_TABLE{}; auto UnwindHistoryTable = &UnwindHistoryTableBuf; auto NonContinuableExceptionRecord = EXCEPTION_RECORD{}; for (;;) { DWORD64 ImageBase = ExceptionRecord->ExceptionInformation[3]; DWORD64 ControlPc = ContextRecord->Rip; PVOID HandlerData = nullptr; DWORD64 EstablisherFrame = 0; auto RuntimeFunctionItem = RtlLookupFunctionEntry(ContextRecord->Rip, &ImageBase, UnwindHistoryTable); if (!RuntimeFunctionItem) { if (ContextRecord->Rip == 0) { NonContinuableExceptionRecord.ExceptionCode = EXCEPTION_NONCONTINUABLE_EXCEPTION; NonContinuableExceptionRecord.ExceptionFlags |= EXCEPTION_NONCONTINUABLE | EXCEPTION_UNWINDING; NonContinuableExceptionRecord.ExceptionRecord = ExceptionRecord; NonContinuableExceptionRecord.NumberParameters = 0; __RaiseException(&NonContinuableExceptionRecord, ContextRecord); break; } // // If we don't have a RUNTIME_FUNCTION, then we've encountered // a leaf function. Adjust the stack approprately. // ContextRecord->Rip = (ULONG64)(*(PULONG64)ContextRecord->Rsp); ContextRecord->Rsp += sizeof(void*); continue; } // // Otherwise, call upon RtlVirtualUnwind to execute the unwind for // us. // ControlPc = ContextRecord->Rip; auto FrameHandler = RtlVirtualUnwind( UNW_FLAG_EHANDLER, // let it find the FrameHandler ImageBase, ControlPc, RuntimeFunctionItem, ContextRecord, &HandlerData, &EstablisherFrame, nullptr); if (EstablisherFrame & STACK_MISALIGNMENT) { /* Set up the exception record */ NonContinuableExceptionRecord.ExceptionCode = EXCEPTION_NONCONTINUABLE_EXCEPTION; NonContinuableExceptionRecord.ExceptionFlags |= EXCEPTION_NONCONTINUABLE | EXCEPTION_STACK_INVALID | EXCEPTION_UNWINDING; NonContinuableExceptionRecord.ExceptionRecord = ExceptionRecord; NonContinuableExceptionRecord.NumberParameters = 0; /* Raise the exception */ __RaiseException(&NonContinuableExceptionRecord, ContextRecord); break; } if (FrameHandler == nullptr) { continue; } auto DispatcherContext = DISPATCHER_CONTEXT{}; DispatcherContext.ControlPc = ControlPc; DispatcherContext.ImageBase = ImageBase; DispatcherContext.FunctionEntry = RuntimeFunctionItem; DispatcherContext.EstablisherFrame = EstablisherFrame; DispatcherContext.TargetIp = 0; DispatcherContext.ContextRecord = ContextRecord; DispatcherContext.LanguageHandler = FrameHandler; DispatcherContext.HandlerData = HandlerData; DispatcherContext.HistoryTable = UnwindHistoryTable; DispatcherContext.ScopeIndex = ScopeIndex; auto Disposition = __CxxExecuteHandlerForException( ExceptionRecord, (PVOID)EstablisherFrame, ContextRecord, &DispatcherContext, FrameHandler); if (NestedFrame == EstablisherFrame) { ExceptionRecord->ExceptionFlags &= ~EXCEPTION_NESTED_CALL; NestedFrame = 0; } switch (Disposition) { case ExceptionContinueExecution: { /* Continue execution */ /* Check if it was non-continuable */ if (ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) { /* Set up the exception record */ NonContinuableExceptionRecord.ExceptionCode = EXCEPTION_NONCONTINUABLE_EXCEPTION; NonContinuableExceptionRecord.ExceptionFlags = EXCEPTION_NONCONTINUABLE; NonContinuableExceptionRecord.ExceptionRecord = ExceptionRecord; NonContinuableExceptionRecord.NumberParameters = 0; /* Raise the exception */ __RaiseException(&NonContinuableExceptionRecord, ContextRecord); } break; } case ExceptionNestedException: { /* Nested exception */ /* Turn the nested flag on */ ExceptionRecord->ExceptionFlags |= EXCEPTION_NESTED_CALL; /* Update the current nested frame */ if (DispatcherContext.EstablisherFrame > NestedFrame) { /* Get the frame from the dispatcher context */ NestedFrame = DispatcherContext.EstablisherFrame; } break; } case ExceptionContinueSearch: { /* Continue searching */ break; } default: { /* Anything else */ /* Set up the exception record */ NonContinuableExceptionRecord.ExceptionCode = STATUS_INVALID_DISPOSITION; NonContinuableExceptionRecord.ExceptionFlags = EXCEPTION_NONCONTINUABLE; NonContinuableExceptionRecord.ExceptionRecord = ExceptionRecord; NonContinuableExceptionRecord.NumberParameters = 0; /* Raise the exception */ __RaiseException(&NonContinuableExceptionRecord, ContextRecord); break; } } } } EXTERN_C EXCEPTION_DISPOSITION __CxxExecuteHandlerForException( PEXCEPTION_RECORD ExceptionRecord, PVOID EstablisherFrame, PCONTEXT Context, PVOID DispatcherContext, PEXCEPTION_ROUTINE ExceptionHandler ) { return ExceptionHandler(ExceptionRecord, EstablisherFrame, Context, DispatcherContext); } } /* * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtp_rtcp/rtp_dependency_descriptor_extension.h" #include #include "rtc_base/array_view.h" #include "video/generic_frame_info.h" #include "rtp_rtcp/rtp_rtcp_defines.h" #include "rtp_rtcp/rtp_dependency_descriptor_reader.h" #include "rtp_rtcp/rtp_dependency_descriptor_writer.h" #include "rtc_base/divide_round.h" namespace webrtc { constexpr RTPExtensionType RtpDependencyDescriptorExtension::kId; constexpr char RtpDependencyDescriptorExtension::kUri[]; bool RtpDependencyDescriptorExtension::Parse( rtc::ArrayView data, const FrameDependencyStructure* structure, DependencyDescriptor* descriptor) { RtpDependencyDescriptorReader reader(data, structure, descriptor); return reader.ParseSuccessful(); } size_t RtpDependencyDescriptorExtension::ValueSize( const FrameDependencyStructure& structure, const DependencyDescriptor& descriptor) { RtpDependencyDescriptorWriter writer(/*data=*/{}, structure, descriptor); return DivideRoundUp(writer.ValueSizeBits(), 8); } bool RtpDependencyDescriptorExtension::Write( rtc::ArrayView data, const FrameDependencyStructure& structure, const DependencyDescriptor& descriptor) { RtpDependencyDescriptorWriter writer(data, structure, descriptor); return writer.Write(); } } // namespace webrtc 0 /* ************************************************************************ * Copyright 2018-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "cblas_interface.hpp" #include "flops.hpp" #include "near.hpp" #include "norm.hpp" #include "rocblas.hpp" #include "rocblas_datatype2string.hpp" #include "rocblas_init.hpp" #include "rocblas_math.hpp" #include "rocblas_random.hpp" #include "rocblas_test.hpp" #include "rocblas_vector.hpp" #include "unit.hpp" #include "utility.hpp" template void testing_trmm_strided_batched_bad_arg(const Arguments& arg) { const rocblas_int M = 100; const rocblas_int N = 100; const rocblas_int lda = 100; const rocblas_int ldb = 100; const rocblas_int batch_count = 5; const T alpha = 1.0; const rocblas_side side = rocblas_side_left; const rocblas_fill uplo = rocblas_fill_upper; const rocblas_operation transA = rocblas_operation_none; const rocblas_diagonal diag = rocblas_diagonal_non_unit; rocblas_local_handle handle; rocblas_int K = side == rocblas_side_left ? M : N; const rocblas_stride stride_a = lda * K; const rocblas_stride stride_b = ldb * N; size_t size_A = batch_count * stride_a; size_t size_B = batch_count * stride_b; // allocate memory on device device_vector dA(size_A); device_vector dB(size_B); CHECK_DEVICE_ALLOCATION(dA.memcheck()); CHECK_DEVICE_ALLOCATION(dB.memcheck()); EXPECT_ROCBLAS_STATUS(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, &alpha, nullptr, lda, stride_a, dB, ldb, stride_b, batch_count), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, &alpha, dA, lda, stride_a, nullptr, ldb, stride_b, batch_count), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, nullptr, dA, lda, stride_a, dB, ldb, stride_b, batch_count), rocblas_status_invalid_pointer); EXPECT_ROCBLAS_STATUS(rocblas_trmm_strided_batched(nullptr, side, uplo, transA, diag, M, N, &alpha, dA, lda, stride_a, dB, ldb, stride_b, batch_count), rocblas_status_invalid_handle); } template void testing_trmm_strided_batched(const Arguments& arg) { bool nantest = rocblas_isnan(arg.alpha) || rocblas_isnan(arg.alphai); if(!std::is_same{} && !std::is_same{} && !std::is_same{} && !is_complex && nantest) return; // Exclude integers or other types which don't support NaN rocblas_int M = arg.M; rocblas_int N = arg.N; rocblas_int lda = arg.lda; rocblas_int ldb = arg.ldb; rocblas_int stride_a = arg.stride_a; rocblas_int stride_b = arg.stride_b; rocblas_int batch_count = arg.batch_count; char char_side = arg.side; char char_uplo = arg.uplo; char char_transA = arg.transA; char char_diag = arg.diag; T alpha = arg.get_alpha(); rocblas_side side = char2rocblas_side(char_side); rocblas_fill uplo = char2rocblas_fill(char_uplo); rocblas_operation transA = char2rocblas_operation(char_transA); rocblas_diagonal diag = char2rocblas_diagonal(char_diag); rocblas_int K = side == rocblas_side_left ? M : N; if((stride_a > 0) && (stride_a < lda * K)) rocblas_cout << "WARNING: stride_a < lda * (side == rocblas_side_left ? M : N)" << std::endl; if((stride_b > 0) && (stride_b < ldb * N)) rocblas_cout << "WARNING: stride_b < ldb * N" << std::endl; size_t size_A = batch_count * stride_a; size_t size_B = batch_count * stride_b; rocblas_local_handle handle; // ensure invalid sizes and quick return checked before pointer check bool invalid_size = M < 0 || N < 0 || lda < K || ldb < M || batch_count < 0; if(M == 0 || N == 0 || batch_count == 0 || invalid_size) { EXPECT_ROCBLAS_STATUS(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, nullptr, nullptr, lda, stride_a, nullptr, ldb, stride_b, batch_count), invalid_size ? rocblas_status_invalid_size : rocblas_status_success); return; } // Naming: dK is in GPU (device) memory. hK is in CPU (host) memory host_vector h_alpha(1); host_vector hA(size_A); host_vector hB(size_B); host_vector hB_1(size_B); host_vector hB_2(size_B); host_vector cpuB(size_B); CHECK_HIP_ERROR(h_alpha.memcheck()); CHECK_HIP_ERROR(hA.memcheck()); CHECK_HIP_ERROR(hB.memcheck()); CHECK_HIP_ERROR(hB_1.memcheck()); CHECK_HIP_ERROR(hB_2.memcheck()); CHECK_HIP_ERROR(cpuB.memcheck()); double gpu_time_used, cpu_time_used; double rocblas_gflops, cblas_gflops; double rocblas_error = 0.0; // allocate memory on device device_vector dA(size_A); device_vector dB(size_B); device_vector d_alpha(1); CHECK_DEVICE_ALLOCATION(dA.memcheck()); CHECK_DEVICE_ALLOCATION(dB.memcheck()); CHECK_DEVICE_ALLOCATION(d_alpha.memcheck()); // initialize full random matrix hA and hB h_alpha[0] = alpha; rocblas_seedrand(); rocblas_init(hA); rocblas_init(hB); hB_1 = hB; // hXorB <- B hB_2 = hB; // hXorB <- B cpuB = hB; // cpuB <- B // copy data from CPU to device CHECK_HIP_ERROR(dA.transfer_from(hA)); if(arg.unit_check || arg.norm_check) { // calculate dB <- A^(-1) B rocblas_device_pointer_host CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_HIP_ERROR(dB.transfer_from(hB_1)); CHECK_ROCBLAS_ERROR(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, &h_alpha[0], dA, lda, stride_a, dB, ldb, stride_b, batch_count)); CHECK_HIP_ERROR(hB_1.transfer_from(dB)); CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); CHECK_HIP_ERROR(dB.transfer_from(hB_2)); CHECK_HIP_ERROR(d_alpha.transfer_from(h_alpha)); CHECK_ROCBLAS_ERROR(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, d_alpha, dA, lda, stride_a, dB, ldb, stride_b, batch_count)); CHECK_HIP_ERROR(hB_2.transfer_from(dB)); // CPU BLAS if(arg.timing) { cpu_time_used = get_time_us(); } for(int i = 0; i < batch_count; i++) { cblas_trmm(side, uplo, transA, diag, M, N, alpha, hA + i * stride_a, lda, cpuB + i * stride_b, ldb); } if(arg.timing) { cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = trmm_gflop_count(M, N, side) * batch_count / cpu_time_used * 1e6; } if(arg.unit_check) { if(std::is_same{} && K > 10000) { // For large K, rocblas_half tends to diverge proportional to K // Tolerance is slightly greater than 1 / 1024.0 const double tol = K * sum_error_tolerance; near_check_general(M, N, ldb, stride_b, cpuB, hB_1, batch_count, tol); near_check_general(M, N, ldb, stride_b, cpuB, hB_2, batch_count, tol); } else { unit_check_general(M, N, ldb, stride_b, cpuB, hB_1, batch_count); unit_check_general(M, N, ldb, stride_b, cpuB, hB_2, batch_count); } } if(arg.norm_check) { auto err1 = std::abs( norm_check_general('F', M, N, ldb, stride_b, cpuB, hB_1, batch_count)); auto err2 = std::abs( norm_check_general('F', M, N, ldb, stride_b, cpuB, hB_2, batch_count)); rocblas_error = err1 > err2 ? err1 : err2; } } if(arg.timing) { int number_cold_calls = arg.cold_iters; int number_hot_calls = arg.iters; CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); for(int i = 0; i < number_cold_calls; i++) { CHECK_ROCBLAS_ERROR(rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, &h_alpha[0], dA, lda, stride_a, dB, ldb, stride_b, batch_count)); } gpu_time_used = get_time_us(); // in microseconds for(int i = 0; i < number_hot_calls; i++) { rocblas_trmm_strided_batched(handle, side, uplo, transA, diag, M, N, &h_alpha[0], dA, lda, stride_a, dB, ldb, stride_b, batch_count); } gpu_time_used = get_time_us() - gpu_time_used; rocblas_gflops = trmm_gflop_count(M, N, side) * batch_count * number_hot_calls / gpu_time_used * 1e6; rocblas_cout << "M,N,batch_count,alpha,lda,stride_a,ldb,stride_b,side,uplo,transA,diag," "rocblas-Gflops,us"; if(arg.unit_check || arg.norm_check) rocblas_cout << ",CPU-Gflops,us,norm-error"; rocblas_cout << std::endl; rocblas_cout << M << ',' << N << ',' << batch_count << ',' << alpha << ',' << lda << ',' << stride_a << ',' << ldb << ',' << stride_b << ',' << char_side << ',' << char_uplo << ',' << char_transA << ',' << char_diag << ',' << rocblas_gflops << "," << gpu_time_used / number_hot_calls; if(arg.unit_check || arg.norm_check) rocblas_cout << ", " << cblas_gflops << ", " << cpu_time_used << ", " << rocblas_error; rocblas_cout << std::endl; } } 0 #ifndef RBMAZE_HPP #define RBMAZE_HPP #include "maze.hpp" class RBMaze final : public Maze { unsigned difficulty_; public: RBMaze(unsigned difficulty); void generate() override; }; #endif // RBMAZE_HPP #include #include #include template std::istream& operator >>(std::istream& input, std::vector& v) { for (T& a : v) input >> a; return input; } void answer(bool v) { constexpr const char* s[2] = { "NO", "YES" }; std::cout << s[v] << '\n'; } void solve(const std::vector& a) { const std::set r(a.cbegin(), a.cend()); if (r.size() > 3) return answer(false); if (r.size() < 3) return answer(true); const unsigned x = *std::next(r.cbegin()); answer(x - *r.cbegin() == *r.crbegin() - x); } int main() { size_t n; std::cin >> n; std::vector a(n); std::cin >> a; solve(a); return 0; } // // Created by valdemar on 14.10.17. // #include "UIController.h" #include #include #include #include #include struct UIController::wnd_t { bool show_style_editor = false; bool show_fps_overlay = true; bool show_info = true; bool show_playback_control = true; bool show_ui_help = false; bool show_shortcuts_help = false; bool show_metrics = false; bool show_mouse_pos_tooltip = false; }; UIController::UIController(Camera *camera) : camera_(camera) { // Setup ImGui binding ImGui_ImplGlfwGL3_Init(glfwGetCurrentContext(), true); wnd_ = std::make_unique(); setup_custom_style(false); auto &io = ImGui::GetIO(); io.IniFilename = "rewindviewer.ini"; //Load and merge fontawesome to current font io.Fonts->AddFontDefault(); const ImWchar icons_range[] = {ICON_MIN_FA, ICON_MAX_FA, 0}; ImFontConfig icons_config; icons_config.MergeMode = true; icons_config.PixelSnapH = true; io.Fonts->AddFontFromFileTTF("resources/fonts/fontawesome-webfont.ttf", 14.0f, &icons_config, icons_range); //Need to call it here, otherwise fontawesome glyph ranges would be corrupted on Windows ImGui_ImplGlfwGL3_CreateDeviceObjects(); } UIController::~UIController() { // Cleanup imgui ImGui_ImplGlfwGL3_Shutdown(); } void UIController::next_frame(Scene *scene, NetListener::ConStatus client_status) { // Start new frame ImGui_ImplGlfwGL3_NewFrame(); //Clear data option if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu(ICON_FA_PENCIL_SQUARE_O " Edit", true)) { //if (ImGui::MenuItem(ICON_FA_RECYCLE " Clear frames data", "CTRL+R", false, scene->has_data())) { // scene->clear_data(true); //} ImGui::Checkbox("Close window by Escape key", &close_with_esc_); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } //Update windows status main_menu_bar(); if (wnd_->show_fps_overlay) { fps_overlay_widget(client_status); } if (wnd_->show_info) { info_widget(scene); } if (wnd_->show_playback_control) { playback_control_widget(scene); } if (wnd_->show_style_editor) { ImGui::Begin("Style editor", &wnd_->show_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } if (wnd_->show_metrics) { ImGui::ShowMetricsWindow(&wnd_->show_metrics); } if (wnd_->show_ui_help) { ImGui::Begin(ICON_FA_INFO_CIRCLE " UI guide", &wnd_->show_ui_help, ImGuiWindowFlags_AlwaysAutoResize); ImGui::ShowUserGuide(); ImGui::End(); } if (wnd_->show_shortcuts_help) { ImGui::Begin(ICON_FA_KEYBOARD_O " Controls help", &wnd_->show_shortcuts_help, ImGuiWindowFlags_AlwaysAutoResize); ImGui::BulletText("Mouse drag on map to move camera"); ImGui::BulletText("Mouse wheel to zoom"); ImGui::BulletText("Space - play/stop frame playback"); ImGui::BulletText("Left, right arrow - manually change frames"); ImGui::BulletText("Esc - close application"); ImGui::BulletText("Ctrl+g - go to tick"); ImGui::BulletText("g - Toggle grid draw state"); ImGui::BulletText("p - Show tooltip with cursor world coordinates"); ImGui::BulletText("1-5 - Toggle layers visibility"); ImGui::End(); } const auto &io = ImGui::GetIO(); if (!io.WantCaptureMouse && wnd_->show_mouse_pos_tooltip) { ImGui::BeginTooltip(); auto wmouse_pos = camera_->screen2world(io.MousePos); ImGui::Text("(%.3f, %.3f)", wmouse_pos.x, wmouse_pos.y); ImGui::EndTooltip(); } //Checking hotkeys if (!io.WantTextInput) { if (key_pressed_once(GLFW_KEY_SPACE)) { autoplay_scene_ = !autoplay_scene_; } if (key_pressed_once(GLFW_KEY_G) && !io.KeyCtrl) { scene->opt().show_grid = !scene->opt().show_grid; } if (key_pressed_once(GLFW_KEY_P)) { wnd_->show_mouse_pos_tooltip = !wnd_->show_mouse_pos_tooltip; } if (io.KeysDown[GLFW_KEY_D] && io.KeyCtrl) { developer_mode_ = true; } auto &enabled_layers = scene->opt().enabled_layers; for (size_t layer_idx = 0; layer_idx < enabled_layers.size(); ++layer_idx) { if (key_pressed_once(static_cast(GLFW_KEY_1 + layer_idx))) { enabled_layers[layer_idx] = !enabled_layers[layer_idx]; } } if (scene->has_data() && io.KeysDown[GLFW_KEY_R] && io.KeyCtrl) { scene->clear_data(false); } } request_exit_ = close_with_esc_ && io.KeysDown[GLFW_KEY_ESCAPE]; //Hittest for detailed unit info if (!ImGui::GetIO().WantCaptureMouse) { scene->show_detailed_info(camera_->screen2world(ImGui::GetIO().MousePos)); } //Background color glClearColor(clear_color_.r, clear_color_.g, clear_color_.b, 1.0f); } void UIController::frame_end() { ImGui::Render(); } bool UIController::close_requested() { return request_exit_; } void UIController::main_menu_bar() { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu(ICON_FA_EYE " View", true)) { ImGui::Checkbox("FPS overlay", &wnd_->show_fps_overlay); ImGui::Checkbox("Utility window", &wnd_->show_info); if (developer_mode_) { ImGui::Separator(); ImGui::Checkbox("Style editor", &wnd_->show_style_editor); ImGui::Checkbox("Metrics", &wnd_->show_metrics); } ImGui::EndMenu(); } if (ImGui::BeginMenu(ICON_FA_QUESTION_CIRCLE_O " Help", true)) { ImGui::MenuItem(ICON_FA_INFO_CIRCLE " UI guide", nullptr, &wnd_->show_ui_help); ImGui::MenuItem(ICON_FA_KEYBOARD_O " Controls", nullptr, &wnd_->show_shortcuts_help); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } } void UIController::fps_overlay_widget(NetListener::ConStatus net_status) { ImGui::SetNextWindowPos(ImVec2(10, 20)); const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; if (ImGui::Begin("FPS Overlay", &wnd_->show_fps_overlay, ImVec2{0, 0}, 0.3, flags)) { ImGui::BeginGroup(); ImGui::TextColored({1.0, 1.0, 0.0, 1.0}, "FPS %.1f", ImGui::GetIO().Framerate); ImGui::SameLine(); ImGui::Text("[%.1f ms]", 1000.0f / ImGui::GetIO().Framerate); ImGui::EndGroup(); std::string strstatus; ImVec4 color; static const float intensity = 1.0; switch (net_status) { case NetListener::ConStatus::WAIT: strstatus = "WAITING"; color = {intensity, intensity, 0.0, 1.0}; break; case NetListener::ConStatus::ESTABLISHED: strstatus = "CONNECTED"; color = {0.0, intensity, 0.0, 1.0}; break; case NetListener::ConStatus::CLOSED: strstatus = "CLOSED"; color = {intensity, 0.0, 0.0, 1.0}; break; } ImGui::TextColored(color, ICON_FA_PLUG " %s", strstatus.c_str()); ImGui::End(); } } void UIController::info_widget(Scene *scene) { int width, height; glfwGetWindowSize(glfwGetCurrentContext(), &width, &height); const float desired_width = 300; ImGui::SetNextWindowPos({width - desired_width, 20}, ImGuiCond_Always); ImGui::SetNextWindowSize({desired_width, static_cast(height - 20 - 30)}, ImGuiCond_Always); ImGui::Begin("Info", &wnd_->show_info, ImGuiWindowFlags_NoTitleBar); const auto flags = ImGuiTreeNodeFlags_DefaultOpen; if (ImGui::CollapsingHeader(ICON_FA_COGS " Settings")) { if (ImGui::CollapsingHeader(ICON_FA_VIDEO_CAMERA " Camera", flags)) { ImGui::PushItemWidth(150); ImGui::InputFloat2("Position", glm::value_ptr(camera_->pos_), 1); ImGui::InputFloat("Viewport size", &camera_->opt().viewport_size, 50.0, 1000.0, 0); ImGui::PopItemWidth(); } if (ImGui::CollapsingHeader(ICON_FA_EYEDROPPER " Colors", flags)) { ImGui::SetColorEditOptions(ImGuiColorEditFlags_NoInputs); ImGui::ColorEdit3("Background", glm::value_ptr(clear_color_)); ImGui::ColorEdit3("Grid", glm::value_ptr(scene->opt().grid_color)); } if (ImGui::CollapsingHeader(ICON_FA_MAP_O " Options", flags)) { ImGui::Checkbox("Show full life bars", &scene->opt().show_full_hp_bars); ImGui::Checkbox("Show detailed unit info on hover", &scene->opt().show_detailed_info_on_hover); ImGui::Checkbox("World origin on top left", &camera_->opt().origin_on_top_left); ImGui::Checkbox("Draw grid", &scene->opt().show_grid); static const ImVec4 button_colors[] = { ImVec4(0.5, 0.5, 0.5, 1.0), ImVec4(0.58, 0.941, 0.429, 1.0) }; size_t idx = 0; static const std::array(Frame::LAYERS_COUNT)> captions{ {"##layer0", "##layer1", "##layer2", "##layer3", "##layer4"} }; for (bool &enabled : scene->opt().enabled_layers) { if (ImGui::ColorButton(captions[idx], button_colors[enabled], ImGuiColorEditFlags_NoTooltip)) { enabled = !enabled; } ++idx; ImGui::SameLine(); } ImGui::LabelText("##layers", "%s", "Visible layers"); } } if (ImGui::CollapsingHeader(ICON_FA_COMMENT_O " Frame message", flags)) { ImGui::BeginChild("FrameMsg", {0, 0}, true); ImGui::TextWrapped("%s", scene->get_frame_user_message()); ImGui::EndChild(); } ImGui::End(); } void UIController::playback_control_widget(Scene *scene) { static const auto button_size = ImVec2{0, 0}; static const float buttons_spacing = 5.0f; auto &io = ImGui::GetIO(); auto width = io.DisplaySize.x; ImGui::SetNextWindowPos({0, io.DisplaySize.y - 20 - 2 * ImGui::GetStyle().WindowPadding.y}); ImGui::SetNextWindowSize({width, 30}); static const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; if (ImGui::Begin("Playback control", &wnd_->show_playback_control, flags)) { ImGui::BeginGroup(); int tick = scene->get_frame_index(); if (!io.WantTextInput) { if (io.KeyCtrl) { tick -= key_pressed_once(GLFW_KEY_LEFT); tick += key_pressed_once(GLFW_KEY_RIGHT); } else { tick -= io.KeysDown[GLFW_KEY_LEFT]; tick += io.KeysDown[GLFW_KEY_RIGHT]; } } ImGui::Button(ICON_FA_FAST_BACKWARD "##fastprev", button_size); if (ImGui::IsItemActive()) { tick -= fast_skip_speed_; } ImGui::SameLine(0.0f, buttons_spacing); if (ImGui::Button(ICON_FA_BACKWARD "##prev", button_size)) { --tick; } ImGui::SameLine(0.0f, buttons_spacing); if (autoplay_scene_) { autoplay_scene_ = !ImGui::Button(ICON_FA_PAUSE "##pause", button_size); } else { autoplay_scene_ = ImGui::Button(ICON_FA_PLAY "##play", button_size); } ImGui::SameLine(0.0f, buttons_spacing); if (ImGui::Button(ICON_FA_FORWARD "##next", button_size)) { ++tick; } ImGui::SameLine(0.0f, buttons_spacing); ImGui::Button(ICON_FA_FAST_FORWARD "##fastnext", button_size); if (ImGui::IsItemActive()) { tick += fast_skip_speed_; } ImGui::SameLine(); tick += autoplay_scene_; const auto frames_cnt = scene->get_frames_count(); if (frames_cnt > 0) { tick = std::min(tick, frames_cnt); float ftick = tick; ImGui::PushItemWidth(-1); if (io.KeyCtrl && io.KeysDown[GLFW_KEY_G]) { ImGui::SetKeyboardFocusHere(); } if (ImGui::TickBar("##empty", &ftick, 0, frames_cnt, {0.0f, 0.0f})) { tick = static_cast(ftick); } ImGui::PopItemWidth(); scene->set_frame_index(tick); } else { ImGui::Text("Frame list empty"); } ImGui::EndGroup(); ImGui::End(); } } bool UIController::key_pressed_once(int key_desc) { const auto &io = ImGui::GetIO(); if (io.KeysDown[key_desc]) { if (!key_pressed_[key_desc]) { key_pressed_[key_desc] = true; return true; } } else { key_pressed_[key_desc] = false; } return false; } /** * @copyright Copyright 2016 The J-PET Framework Authors. 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 find a copy of the License in the LICENCE file. * * 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 TaskD.cpp */ #include #include #include "TaskD.h" TaskD::TaskD(const char * name, const char * description):JPetTask(name, description){} void TaskD::init(const JPetTaskInterface::Options&){ fBarrelMap.buildMappings(getParamBank()); // create histograms for time differences at each slot and each threshold for(auto & scin : getParamBank().getScintillators()){ for (int thr=1;thr<=4;thr++){ const char * histo_name = formatUniqueSlotDescription(scin.second->getBarrelSlot(), thr, "timeDiffAB_"); getStatistics().createHistogram( new TH1F(histo_name, histo_name, 2000, -20., 20.) ); } } // create histograms for time diffrerence vs slot ID for(auto & layer : getParamBank().getLayers()){ for (int thr=1;thr<=4;thr++){ const char * histo_name = Form("TimeDiffVsID_layer_%d_thr_%d", fBarrelMap.getLayerNumber(*layer.second), thr); const char * histo_titile = Form("%s;Slot ID; TimeDiffAB [ns]", histo_name); int n_slots_in_layer = fBarrelMap.getNumberOfSlots(*layer.second); getStatistics().createHistogram( new TH2F(histo_name, histo_titile, n_slots_in_layer, 0.5, n_slots_in_layer+0.5, 120, -20., 20.) ); } } } void TaskD::exec(){ //getting the data from event in propriate format if(auto hit =dynamic_cast(getEvent())){ fillHistosForHit(*hit); fWriter->write(*hit); } } void TaskD::terminate(){ // save timeDiffAB mean values for each slot and each threshold in a JPetAuxilliaryData object // so that they are available to the consecutive modules getAuxilliaryData().createMap("timeDiffAB mean values"); for(auto & slot : getParamBank().getBarrelSlots()){ for (int thr=1;thr<=4;thr++){ const char * histo_name = formatUniqueSlotDescription(*(slot.second), thr, "timeDiffAB_"); double mean = getStatistics().getHisto1D(histo_name).GetMean(); getAuxilliaryData().setValue("timeDiffAB mean values", histo_name, mean); } } } void TaskD::fillHistosForHit(const JPetHit & hit){ auto lead_times_A = hit.getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading); auto lead_times_B = hit.getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading); for(auto & thr_time_pair : lead_times_A){ int thr = thr_time_pair.first; if( lead_times_B.count(thr) > 0 ){ // if there was leading time at the same threshold at opposite side double timeDiffAB = lead_times_A[thr] - lead_times_B[thr]; timeDiffAB /= 1000.; // we want the plots in ns instead of ps // fill the appropriate histogram const char * histo_name = formatUniqueSlotDescription(hit.getBarrelSlot(), thr, "timeDiffAB_"); getStatistics().getHisto1D(histo_name).Fill( timeDiffAB ); // fill the timeDiffAB vs slot ID histogram int layer_number = fBarrelMap.getLayerNumber( hit.getBarrelSlot().getLayer() ); int slot_number = fBarrelMap.getSlotNumber( hit.getBarrelSlot() ); getStatistics().getHisto2D(Form("TimeDiffVsID_layer_%d_thr_%d", layer_number, thr)).Fill( slot_number, timeDiffAB); } } } const char * TaskD::formatUniqueSlotDescription(const JPetBarrelSlot & slot, int threshold, const char * prefix = ""){ int slot_number = fBarrelMap.getSlotNumber(slot); int layer_number = fBarrelMap.getLayerNumber(slot.getLayer()); return Form("%slayer_%d_slot_%d_thr_%d", prefix, layer_number, slot_number, threshold ); } void TaskD::setWriter(JPetWriter* writer){fWriter =writer;} ///:include "../../NodeType.fypp" #include "../../NodePool.hpp" #include "../../c-interface/c_oa_type.hpp" #include "new_node.hpp" using namespace oa::ops; extern "C"{ ///:for op in [i for i in L if i[3] in ['A','B','F','H']] void c_new_node_${op[1]}$(NodePtr*& A, const NodePtr*& u, const NodePtr*& v){ if(A == NULL) A = new NodePtr(); *A = new_node_${op[1]}$(*u, *v); } ///:endfor ///:for op in [i for i in L if i[3] == 'C'] void c_new_node_${op[1]}$(NodePtr*& A, const NodePtr*& u){ if(A == NULL) A = new NodePtr(); *A = new_node_${op[1]}$(*u); } ///:endfor } 0 /** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_RESV #include "sql/resolver/dml/ob_sequence_namespace_checker.h" #include "lib/charset/ob_charset.h" #include "sql/resolver/dml/ob_dml_stmt.h" #include "sql/resolver/dml/ob_select_stmt.h" #include "sql/resolver/ob_resolver_define.h" #include "sql/resolver/ob_resolver_utils.h" #include "sql/resolver/ob_schema_checker.h" #include "sql/resolver/ob_stmt_resolver.h" namespace oceanbase { using namespace common; namespace sql { int ObSequenceNamespaceChecker::check_sequence_namespace( const ObQualifiedName& q_name, ObSynonymChecker& syn_checker, uint64_t& sequence_id) { return check_sequence_namespace(q_name, syn_checker, params_.session_info_, params_.schema_checker_, sequence_id); } int ObSequenceNamespaceChecker::check_sequence_namespace(const ObQualifiedName& q_name, ObSynonymChecker& syn_checker, ObSQLSessionInfo* session_info, ObSchemaChecker* schema_checker, uint64_t& sequence_id) { int ret = OB_NOT_IMPLEMENT; if (OB_ISNULL(schema_checker) || OB_ISNULL(session_info)) { ret = OB_NOT_INIT; LOG_WARN("schema checker is null", K(ret)); } else if (!is_curr_or_next_val(q_name.col_name_)) { ret = OB_ERR_BAD_FIELD_ERROR; } else if (session_info->get_database_name().empty()) { ret = OB_ERR_NO_DB_SELECTED; LOG_WARN("No database selected", K(q_name), K(ret)); } else { const ObString& database_name = q_name.database_name_.empty() ? session_info->get_database_name() : q_name.database_name_; const ObString& sequence_name = q_name.tbl_name_; const ObString& sequence_expr = q_name.col_name_; uint64_t tenant_id = session_info->get_effective_tenant_id(); uint64_t database_id = OB_INVALID_ID; bool exist = false; if (OB_FAIL(schema_checker->get_database_id(tenant_id, database_name, database_id))) { LOG_WARN("failed to get database id", K(ret), K(tenant_id), K(database_name)); } else if (OB_FAIL(check_sequence_with_synonym_recursively( tenant_id, database_id, sequence_name, syn_checker, schema_checker, exist, sequence_id))) { LOG_WARN("fail recursively check sequence with name", K(q_name), K(database_name), K(ret)); } else if (!exist) { ret = OB_ERR_BAD_FIELD_ERROR; } else if (0 != sequence_expr.case_compare("NEXTVAL") && 0 != sequence_expr.case_compare("CURRVAL")) { ret = OB_ERR_BAD_FIELD_ERROR; } } return ret; } int ObSequenceNamespaceChecker::check_sequence_with_synonym_recursively(const uint64_t tenant_id, const uint64_t database_id, const common::ObString& sequence_name, ObSynonymChecker& syn_checker, ObSchemaChecker* schema_checker, bool& exists, uint64_t& sequence_id) { int ret = OB_SUCCESS; bool exist_with_synonym = false; ObString object_seq_name; uint64_t object_db_id; uint64_t synonym_id; if (OB_FAIL( schema_checker->check_sequence_exist_with_name(tenant_id, database_id, sequence_name, exists, sequence_id))) { LOG_WARN("failed to check sequence with name", K(ret), K(sequence_name), K(database_id)); } else if (!exists) { // check synonym if (OB_FAIL(schema_checker->get_synonym_schema( tenant_id, database_id, sequence_name, object_db_id, synonym_id, object_seq_name, exist_with_synonym))) { LOG_WARN("get synonym failed", K(ret), K(tenant_id), K(database_id), K(sequence_name)); } else if (exist_with_synonym) { syn_checker.set_synonym(true); if (OB_FAIL(syn_checker.add_synonym_id(synonym_id))) { LOG_WARN("failed to add synonym id", K(ret)); } else { if (OB_FAIL(check_sequence_with_synonym_recursively( tenant_id, object_db_id, object_seq_name, syn_checker, schema_checker, exists, sequence_id))) { LOG_WARN("failed to check sequence with synonym recursively", K(ret)); } } } else { exists = false; LOG_INFO("sequence object does not exist", K(sequence_name), K(tenant_id), K(database_id)); } } return ret; } } // namespace sql } // namespace oceanbase //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Create a muzzle flash temp ent // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basetempentity.h" #include "coordsize.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CTETFBlood : public CBaseTempEntity { public: DECLARE_CLASS( CTETFBlood, CBaseTempEntity ); DECLARE_SERVERCLASS(); CTETFBlood( const char *name ); virtual void Test( const Vector& current_origin, const QAngle& current_angles ) {} public: Vector m_vecOrigin; Vector m_vecNormal; int m_nEntIndex; }; // Singleton to fire TEMuzzleFlash objects static CTETFBlood g_TETFBlood( "TFBlood" ); //----------------------------------------------------------------------------- // Purpose: // Input : *name - //----------------------------------------------------------------------------- CTETFBlood::CTETFBlood( const char *name ) : CBaseTempEntity( name ) { m_vecOrigin.Init(); m_vecNormal.Init(); m_nEntIndex = 0; } IMPLEMENT_SERVERCLASS_ST( CTETFBlood, DT_TETFBlood ) SendPropFloat( SENDINFO_NOCHECK( m_vecOrigin[0] ), -1, SPROP_COORD_MP_INTEGRAL ), SendPropFloat( SENDINFO_NOCHECK( m_vecOrigin[1] ), -1, SPROP_COORD_MP_INTEGRAL ), SendPropFloat( SENDINFO_NOCHECK( m_vecOrigin[2] ), -1, SPROP_COORD_MP_INTEGRAL ), SendPropVector( SENDINFO_NOCHECK( m_vecNormal ), 6, 0, -1.0f, 1.0f ), SendPropInt( SENDINFO_NAME( m_nEntIndex, entindex ), MAX_EDICT_BITS, SPROP_UNSIGNED ), END_SEND_TABLE() void TE_TFBlood( IRecipientFilter& filter, float delay, const Vector &origin, const Vector &normal, int nEntIndex ) { g_TETFBlood.m_vecOrigin = origin; g_TETFBlood.m_vecNormal = normal; g_TETFBlood.m_nEntIndex = nEntIndex; // Send it over the wire g_TETFBlood.Create( filter, delay ); }10-100 #include "box_container.h" #include "ray_axis_aligned_box_intersection.h" namespace cgv { namespace nui { box_container::box_container(nui_node* _parent, bool _use_colors, bool _use_orientations, BoxRenderType _render_type) : primitive_container(_parent, PT_BOX, _use_colors, _use_orientations, SM_NON_UNIFORM), render_type(_render_type) { } std::string box_container::get_primitive_type() const { return "box"; } uint32_t box_container::add_box(const box3& box) { center_positions.push_back(box.get_center()); scales.push_back(box.get_extent()); if (use_colors) colors.push_back(rgba(0.5f, 0.5f, 0.5f, 1)); if (use_orientations) orientations.push_back(quat(1.0f, 0.0f, 0.0f, 0.0f)); return uint32_t(center_positions.size() - 1); } uint32_t box_container::add_box(const box3& box, const quat& orientation) { center_positions.push_back(box.get_center()); scales.push_back(box.get_extent()); if (use_colors) colors.push_back(rgba(0.5f, 0.5f, 0.5f, 1)); if (use_orientations) orientations.push_back(orientation); return uint32_t(center_positions.size() - 1); } uint32_t box_container::add_box(const box3& box, const rgba& color) { center_positions.push_back(box.get_center()); scales.push_back(box.get_extent()); if (use_colors) colors.push_back(color); if (use_orientations) orientations.push_back(quat(1.0f, 0.0f, 0.0f, 0.0f)); return uint32_t(center_positions.size() - 1); } uint32_t box_container::add_box(const box3& box, const quat& orientation, const rgba& color) { center_positions.push_back(box.get_center()); scales.push_back(box.get_extent()); if (use_colors) colors.push_back(color); if (use_orientations) orientations.push_back(orientation); return uint32_t(center_positions.size() - 1); } box_container::box3 box_container::get_oriented_bounding_box(uint32_t i) const { const vec3& c = center_positions[i]; vec3 e = scales[i]; return box3(c - 0.5f * e, c + 0.5f * e); } bool box_container::compute_closest_point(contact_info& info, const vec3& pos) { bool result = false; contact_info::contact C; C.container = this; C.node = get_parent(); for (const auto& c : center_positions) { C.primitive_index = uint32_t(&c - ¢er_positions.front()); compute_closest_box_point(C, pos, c, scales[C.primitive_index], use_orientations ? &orientations[C.primitive_index] : 0); if (info.consider_closest_contact(C)) result = true; } return result; } bool box_container::compute_first_intersection(contact_info& info, const vec3& start, const vec3& direction) { bool result = false; contact_info::contact C; C.container = this; C.node = get_parent(); for (const auto& c : center_positions) { C.primitive_index = uint32_t(&c - ¢er_positions.front()); const vec3& e = scales[C.primitive_index]; if ((use_orientations ? compute_box_intersection(c, e, get_rotation(C.primitive_index), start, direction, C) : compute_box_intersection(c, e, start, direction, C)) > 0) { if (info.consider_closest_contact(C)) result = true; } } return result; } int box_container::compute_all_intersections(contact_info& info, const vec3& start, const vec3& direction, bool only_entry_points) { int result = 0; contact_info::contact C1, C2; C1.container = C2.container = this; C1.node = C2.node = get_parent(); for (const auto& c : center_positions) { C1.primitive_index = C2.primitive_index = uint32_t(&c - ¢er_positions.front()); const vec3& e = scales[C1.primitive_index]; contact_info::contact ci1, ci2; int nr_intersections = use_orientations ? compute_box_intersection(c, e, get_rotation(C1.primitive_index), start, direction, C1, &C2) : compute_box_intersection(c, e, start, direction, C1, &C2); if (nr_intersections == 0) continue; ++result; info.contacts.push_back(C1); if (nr_intersections == 1) continue; ++result; info.contacts.push_back(C2); } return result; } bool box_container::init(cgv::render::context& ctx) { cgv::render::ref_box_renderer(ctx, 1); cgv::render::ref_box_wire_renderer(ctx, 1); return true; } void box_container::clear(cgv::render::context& ctx) { cgv::render::ref_box_renderer(ctx, -1); cgv::render::ref_box_wire_renderer(ctx, -1); } void box_container::prepare_render(cgv::render::context& ctx, cgv::render::renderer& r, const cgv::render::render_style& rs, const std::vector* indices_ptr) const { primitive_container::prepare_render(ctx, r, rs, indices_ptr); if (&rs == &brs) { auto& br = reinterpret_cast(r); br.set_extent_array(ctx, scales); if (use_orientations) br.set_rotation_array(ctx, orientations); } else { auto& bwr = reinterpret_cast(r); bwr.set_extent_array(ctx, scales); if (use_orientations) bwr.set_rotation_array(ctx, orientations); } } void box_container::draw(cgv::render::context& ctx) { switch (render_type) { case BRT_SOLID: render(ctx, cgv::render::ref_box_renderer(ctx), brs); break; case BRT_WIREFRAME: render(ctx, cgv::render::ref_box_wire_renderer(ctx), bwrs); break; case BRT_SOLID_AND_WIREFRAME: render(ctx, cgv::render::ref_box_wire_renderer(ctx), bwrs); render(ctx, cgv::render::ref_box_renderer(ctx), brs); break; } } const cgv::render::render_style* box_container::get_render_style() const { if (render_type == BRT_SOLID) return &brs; else return &bwrs; } } }0 #include using namespace std; //#include #include int opstk[100],top=-1; char symb,tsymb; void push(char); int pop(void); int pred(char); void reverseStr(string& str) { int n = str.length(); for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } int pop() { return (opstk[top--]); } void push(char x) { top++; opstk[top]=x; } int pred(char c) { if(c == '*' || c == '/') return 2; else if(c == '+' || c == '-') return 1; else return 0; } int main() { string ex, ps; int c=0,q=0; cout<<"Enter an expression"; cin>>ex; reverseStr(ex); while(ex[c] != '\0') { symb=ex[c]; if((symb>='0'&&symb<='9')||(symb>='a'&&symb<='z')||(symb>='A'&&symb<='Z')) ps+=symb; else { while (opstk!=NULL&& (pred(opstk[top])>pred(symb))) { tsymb=pop(); ps+=tsymb; } push(symb); } c++; } while(top!=-1) { tsymb=pop(); ps+=tsymb; } reverseStr(ps); cout<<"\nPrefix="< #include #include #include #include #include using namespace std; int main() { return 0; }#pragma once #include "ThreadWorker.hpp" #include "ThreadTaskQueue.hpp" #include "../vulkan/GlobalDeviceObjects.h" #include "../vulkan/SwapChain.h" #include "../class/FrameWorkManager.h" ThreadWorker::ThreadWorker(const std::shared_ptr& pDevice, uint32_t frameRoundBinCount) : m_isWorking(false) { for (uint32_t i = 0; i < frameRoundBinCount; i++) m_frameRes.push_back(FrameWorkManager::GetInstance()->AllocatePerFrameResource(i)); m_worker = std::thread(&ThreadWorker::Loop, this); } ThreadWorker::~ThreadWorker() { if (m_worker.joinable()) { WaitForFree(); std::unique_lock lock(m_queueMutex); m_isDestroying = true; lock.unlock(); m_condition.notify_one(); m_worker.join(); } } void ThreadWorker::Loop() { while (true) { ThreadJob job; { std::unique_lock lock(m_queueMutex); m_condition.wait(lock, [this] { return !m_jobQueue.empty() || m_isDestroying; }); if (m_isDestroying) { break; } job = m_jobQueue.front(); m_jobQueue.pop(); m_isWorking = true; } job.job(m_frameRes[job.frameIndex]); { std::unique_lock lock(m_queueMutex); m_isWorking = false; m_condition.notify_one(); } } } void ThreadWorker::AppendJob(ThreadJob job) { std::unique_lock lock(m_queueMutex); m_jobQueue.push(job); m_condition.notify_one(); } bool ThreadWorker::IsTaskQueueFree() { bool ret = false; { std::unique_lock lock(m_queueMutex); ret = m_jobQueue.size() < m_jobQueueSize; } return ret; } bool ThreadWorker::IsWorking() { bool ret = false; { std::unique_lock lock(m_queueMutex); ret = m_isWorking; } return ret; } void ThreadWorker::WaitForFree() { std::unique_lock lock(m_queueMutex); m_condition.wait(lock, [this] { return m_jobQueue.empty() && !m_isWorking; }); } npocmaka/Windows-Server-2003 /*++ Copyright (c) 1995 Microsoft Corporation Module Name: headers.cxx Abstract: Contents: HTTP_REQUEST_HANDLE_OBJECT::CreateRequestBuffer HTTP_REQUEST_HANDLE_OBJECT::QueryRequestHeader HTTP_REQUEST_HANDLE_OBJECT::AddInternalResponseHeader HTTP_REQUEST_HANDLE_OBJECT::UpdateResponseHeaders HTTP_REQUEST_HANDLE_OBJECT::CreateResponseHeaders HTTP_REQUEST_HANDLE_OBJECT::QueryResponseVersion HTTP_REQUEST_HANDLE_OBJECT::QueryStatusCode HTTP_REQUEST_HANDLE_OBJECT::QueryStatusText HTTP_REQUEST_HANDLE_OBJECT::QueryRawResponseHeaders HTTP_REQUEST_HANDLE_OBJECT::RemoveAllRequestHeadersByName HTTP_REQUEST_HANDLE_OBJECT::CheckWellKnownHeaders MapHttpMethodType CreateEscapedUrlPath (CalculateHashNoCase) Author: (rfirth) 20-Dec-1995 Revision History: 20-Dec-1995 rfirth Created --*/ #include #include #include "httpp.h" VOID HTTP_REQUEST_HANDLE_OBJECT::ReplaceStatusHeader( IN LPCSTR lpszStatus ) /* Description: Replace the status line in a header (eg. "200 OK") with the specified text. Arguments: lpszStatus - Status text (eg. "200 OK") Return Value: None */ { LockHeaders(); //INET_ASSERT (!_CacheWriteInProgress); LPSTR pszHeader = _ResponseHeaders.GetHeaderPointer(_ResponseBuffer, 0); INET_ASSERT(pszHeader); LPSTR pszStatus = StrChr (pszHeader, ' '); SKIPWS(pszStatus); INET_ASSERT (!memcmp(pszStatus, "206", 3)); memcpy(pszStatus, lpszStatus, lstrlen(lpszStatus)+1); _ResponseHeaders.ShrinkHeader(_ResponseBuffer, 0, HTTP_QUERY_STATUS_TEXT, HTTP_QUERY_STATUS_TEXT, (DWORD) (pszStatus - pszHeader) + lstrlen(lpszStatus)); UnlockHeaders(); } LPSTR HTTP_REQUEST_HANDLE_OBJECT::CreateRequestBuffer( OUT LPDWORD lpdwRequestLength, IN LPVOID lpOptional, IN DWORD dwOptionalLength, IN DWORD dwMaxPacketLength, OUT LPBOOL lpbCombinedData ) /*++ Routine Description: Creates a request buffer from the HTTP request and headers Arguments: lpdwRequestLength - pointer to returned buffer length lpOptional - pointer to optional data dwOptionalLength - length of optional data dwMaxPacketLength - maximum length of buffer lpbCombinedData - output TRUE if data successfully combined into one Return Value: LPSTR Success - pointer to allocated buffer Failure - NULL --*/ { DEBUG_ENTER((DBG_HTTP, Pointer, "HTTP_REQUEST_HANDLE_OBJECT::CreateRequestBuffer", "%#x, %#x, %d, %B, %d, %#x", lpdwRequestLength, lpOptional, dwOptionalLength, dwMaxPacketLength, lpbCombinedData )); PERF_ENTER(CreateRequestBuffer); LPSTR requestBuffer = NULL; *lpbCombinedData = FALSE; if (!_RequestHeaders.LockHeaders()) { goto quit; } DWORD headersLength; DWORD requestLength; DWORD optionalLength; HEADER_STRING * pRequest = _RequestHeaders.GetFirstHeader(); HEADER_STRING & request = *pRequest; /* WCHAR wszUrl[1024]; LPWSTR pwszUrl = NULL; BYTE utf8Url[2048]; LPBYTE pbUrl = NULL; */ LPSTR pszObject = _RequestHeaders.ObjectName(); DWORD dwObjectLength = _RequestHeaders.ObjectNameLength(); if (pRequest == NULL) { goto Cleanup; } UNREFERENCED_PARAMETER(request); INET_ASSERT(request.HaveString()); headersLength = _RequestHeaders.HeadersLength(); requestLength = headersLength + (sizeof("\r\n") - 1); /*------------------------------------------------------------------ GlobalEnableUtf8Encoding = FALSE; if (GlobalEnableUtf8Encoding && StringContainsHighAnsi(pszObject, dwObjectLength)) { pwszUrl = wszUrl; DWORD arrayElements = ARRAY_ELEMENTS(wszUrl); if (dwObjectLength > ARRAY_ELEMENTS(wszUrl)) { arrayElements = dwObjectLength; pwszUrl = (LPWSTR)ALLOCATE_FIXED_MEMORY(arrayElements * sizeof(*pwszUrl)); if (pwszUrl == NULL) { goto utf8_cleanup; } } PFNINETMULTIBYTETOUNICODE pfnMBToUnicode; pfnMBToUnicode = GetInetMultiByteToUnicode( ); if (pfnMBToUnicode == NULL) { goto utf8_cleanup; } HRESULT hr; DWORD dwMode; INT nMBChars; INT nWChars; nMBChars = dwObjectLength; nWChars = arrayElements; dwMode = 0; hr = pfnMBToUnicode(&dwMode, GetCodePage(), pszObject, &nMBChars, pwszUrl, &nWChars ); if (hr != S_OK || nWChars == 0) { goto utf8_cleanup; } DWORD nBytes; nBytes = CountUnicodeToUtf8(pwszUrl, (DWORD)nWChars, TRUE); pbUrl = utf8Url; if (nBytes > ARRAY_ELEMENTS(utf8Url)) { pbUrl = (LPBYTE)ALLOCATE_FIXED_MEMORY(nBytes); if (pbUrl == NULL) { goto utf8_cleanup; } } DWORD error; error = ConvertUnicodeToUtf8(pwszUrl, (DWORD)nWChars, pbUrl, nBytes, TRUE ); INET_ASSERT(error == ERROR_SUCCESS); if (error != ERROR_SUCCESS) { goto utf8_cleanup; } requestLength = requestLength - dwObjectLength + nBytes; headersLength = headersLength - dwObjectLength + nBytes; pszObject = (LPSTR)pbUrl; dwObjectLength = nBytes; goto after_utf8; utf8_cleanup: if ((pwszUrl != wszUrl) && (pwszUrl != NULL)) { FREE_MEMORY(pwszUrl); } pwszUrl = NULL; if ((pbUrl != utf8Url) && (pbUrl != NULL)) { FREE_MEMORY(pbUrl); } pbUrl = NULL; pszObject = NULL; dwObjectLength = 0; } after_utf8: ------------------------------------------------------------------*/ optionalLength = dwOptionalLength; if (requestLength + optionalLength <= dwMaxPacketLength) { requestLength += optionalLength; } else { optionalLength = 0; } requestBuffer = (LPSTR)ResizeBuffer(NULL, requestLength, FALSE); if (requestBuffer != NULL) { if (optionalLength != 0) { *lpbCombinedData = TRUE; } } else if (optionalLength != 0) { requestLength = headersLength + (sizeof("\r\n") - 1); optionalLength = 0; requestBuffer = (LPSTR)ResizeBuffer(NULL, requestLength, FALSE); } if (requestBuffer != NULL) { LPSTR buffer = requestBuffer; // // copy the headers. Remember: header 0 is the request // if (ERROR_SUCCESS != _RequestHeaders.CopyHeaders(&buffer, pszObject, dwObjectLength)) { ResizeBuffer(requestBuffer, 0, FALSE); requestBuffer = buffer = NULL; goto Cleanup; } // // terminate the request // *buffer++ = '\r'; *buffer++ = '\n'; if (optionalLength != 0) { if (dwOptionalLength != 0) { memcpy(buffer, lpOptional, dwOptionalLength); buffer += dwOptionalLength; } } INET_ASSERT((SIZE_T)(buffer-requestBuffer) == requestLength); *lpdwRequestLength = requestLength; } Cleanup: _RequestHeaders.UnlockHeaders(); DEBUG_PRINT(HTTP, INFO, ("request length = %d, combined = %B\n", *lpdwRequestLength, *lpbCombinedData )); /* if ((pbUrl != NULL) && (pbUrl != utf8Url)) { FREE_MEMORY(pbUrl); } if ((pwszUrl != NULL) && (pwszUrl != wszUrl)) { FREE_MEMORY(pwszUrl); } */ quit: PERF_LEAVE(CreateRequestBuffer); DEBUG_LEAVE(requestBuffer); return requestBuffer; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryRequestHeader( IN LPCSTR lpszHeaderName, IN DWORD dwHeaderNameLength, IN LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength, IN DWORD dwModifiers, IN OUT LPDWORD lpdwIndex ) /*++ Routine Description: Searches for an arbitrary request header and if found, returns its value Arguments: lpszHeaderName - pointer to the name of the header to find dwHeaderNameLength - length of the header lpBuffer - pointer to buffer for results lpdwBufferLength - IN: length of lpBuffer OUT: length of the returned header value, or required length of lpBuffer dwModifiers - how to return the data: as number, as SYSTEMTIME structure, etc. lpdwIndex - IN: 0-based index of header to find OUT: next header index if success returned Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER lpBuffer not large enough for results ERROR_HTTP_HEADER_NOT_FOUND Couldn't find the requested header --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "QueryRequestHeader", "%#x [%.*q], %d, %#x, %#x [%#x], %#x, %#x [%d]", lpszHeaderName, min(dwHeaderNameLength + 1, 80), lpszHeaderName, dwHeaderNameLength, lpBuffer, lpdwBufferLength, *lpdwBufferLength, dwModifiers, lpdwIndex, *lpdwIndex )); PERF_ENTER(QueryRequestHeader); DWORD error; error = _RequestHeaders.FindHeader(NULL, lpszHeaderName, dwHeaderNameLength, dwModifiers, lpBuffer, lpdwBufferLength, lpdwIndex ); PERF_LEAVE(QueryRequestHeader); DEBUG_LEAVE(error); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryRequestHeader( IN DWORD dwQueryIndex, IN LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength, IN DWORD dwModifiers, IN OUT LPDWORD lpdwIndex ) /*++ Routine Description: Searches for an arbitrary request header and if found, returns its value Arguments: lpszHeaderName - pointer to the name of the header to find dwHeaderNameLength - length of the header lpBuffer - pointer to buffer for results lpdwBufferLength - IN: length of lpBuffer OUT: length of the returned header value, or required length of lpBuffer dwModifiers - how to return the data: as number, as SYSTEMTIME structure, etc. lpdwIndex - IN: 0-based index of header to find OUT: next header index if success returned Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER lpBuffer not large enough for results ERROR_HTTP_HEADER_NOT_FOUND Couldn't find the requested header --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "QueryRequestHeader", "%u, %#x [%#x], %#x, %#x [%d]", dwQueryIndex, lpBuffer, lpdwBufferLength, *lpdwBufferLength, dwModifiers, lpdwIndex, *lpdwIndex )); PERF_ENTER(QueryRequestHeader); DWORD error; error = _RequestHeaders.FindHeader(NULL, dwQueryIndex, dwModifiers, lpBuffer, lpdwBufferLength, lpdwIndex ); PERF_LEAVE(QueryRequestHeader); DEBUG_LEAVE(error); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::AddInternalResponseHeader( IN DWORD dwHeaderIndex, IN LPSTR lpszHeader, IN DWORD dwHeaderLength ) /*++ Routine Description: Adds a created response header to the response header array. Unlike normal response headers, this will be a pointer to an actual string, not an offset into the response buffer. Even if the address of the response buffer changes, created response headers will remain fixed N.B. The header MUST NOT have a CR-LF terminator N.B.-2 This function must be called under the header lock. Arguments: dwHeaderIndex - index into header value we are actually creating lpszHeader - pointer to created (internal) header to add dwHeaderLength - length of response header, or -1 if ASCIIZ Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "AddInternalResponseHeader", "%u [%q], %q, %d", dwHeaderIndex, GlobalKnownHeaders[dwHeaderIndex].Text, lpszHeader, dwHeaderLength )); DWORD error; if (dwHeaderLength == (DWORD)-1) { dwHeaderLength = lstrlen(lpszHeader); } INET_ASSERT((lpszHeader[dwHeaderLength - 1] != '\r') && (lpszHeader[dwHeaderLength - 1] != '\n')); // // find the next slot for this header // HEADER_STRING * freeHeader; // // if we already have all the headers (the 'empty' header is the last one // in the array) then change the last header to be the one we are adding // and add a new empty header, else just add this one // DWORD iSlot; freeHeader = _ResponseHeaders.FindFreeSlot(&iSlot); if (freeHeader == NULL) { error = _ResponseHeaders.GetError(); INET_ASSERT(error != ERROR_SUCCESS); } else { HEADER_STRING * lastHeader; lastHeader = _ResponseHeaders.GetEmptyHeader(); if (lastHeader != NULL) { // // make copy of last header - its an offset string // *freeHeader = *lastHeader; // // use what was last header as free header // freeHeader = lastHeader; } freeHeader->MakeCopy(lpszHeader, dwHeaderLength); freeHeader->SetNextKnownIndex(_ResponseHeaders.FastAdd(dwHeaderIndex, iSlot)); error = ERROR_SUCCESS; } DEBUG_LEAVE(error); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::UpdateResponseHeaders( IN OUT LPBOOL lpbEof ) /*++ Routine Description: Given the next chunk of the response, updates the response headers. The buffer pointer, buffer length and number of bytes received values are all maintained in this object (_ResponseBuffer, _ResponseBufferLength and _BytesReceived, resp.) Arguments: lpbEof - IN: TRUE if we have reached the end of the response OUT: TRUE if we have reached the end of the response or the end of the headers Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "HTTP_REQUEST_HANDLE_OBJECT::UpdateResponseHeaders", "%#x [%.*q], %d, %d, %#x [%B]", _ResponseBuffer + _ResponseScanned, min(_ResponseBufferLength + 1, 80), _ResponseBuffer + _ResponseScanned, _ResponseBufferLength, _BytesReceived, lpbEof, *lpbEof )); PERF_ENTER(UpdateResponseHeaders); LPSTR lpszBuffer = (LPSTR)_ResponseBuffer + _ResponseScanned; DWORD dwBytesReceived = _BytesReceived - _ResponseScanned; DWORD error = ERROR_SUCCESS; BOOL success = TRUE; HEADER_STRING * statusLine; // // lock down the response headers for the duration of this request. The only // way another thread is going to wait on this lock is if the reference on // the HTTP request object goes to zero, which *shouldn't* happen // if (!_ResponseHeaders.LockHeaders()) { error = ERROR_NOT_ENOUGH_MEMORY; goto quit; } // // if input EOF is set then the caller is telling us that the end of the // response has been reached at transport level (the server closed the // connectiion) // if (*lpbEof) { SetEof(TRUE); } // // if we don't yet know whether we have a HTTP/1.0 (or greater) or HTTP/0.9 // response yet, then try to find out. // // Only responses greater than HTTP/0.9 start with the "HTTP/#.#" string // if (!IsDownLevel() && !IsUpLevel()) { #define MAKE_VERSION_ENTRY(string) string, sizeof(string) - 1 static struct { LPSTR Version; DWORD Length; } KnownVersionsStrings[] = { MAKE_VERSION_ENTRY("HTTP/"), MAKE_VERSION_ENTRY("S-HTTP/"), MAKE_VERSION_ENTRY("SHTTP/"), MAKE_VERSION_ENTRY("Secure-HTTP/"), // // allow for servers generating slightly off-the-wall responses // MAKE_VERSION_ENTRY("HTTP /") }; #define NUM_HTTP_VERSIONS ARRAY_ELEMENTS(KnownVersionsStrings) // // We know this is the start of a HTTP response, but there may be some // noise at the start from bad HTML authoring, or bad content-length on // the previous response on a keep-alive connection. We will try to sync // up to the HTTP header (we will only look for this - I have never seen // any of the others, and I doubt its worth the increased complexity and // processing time) // // // Due to possible DoS attacks outlined in RAID item 510295 we are to //be more stringent as to what sort of 'noise' is allowed before the start //of an HTTP response. We now allow the noise to consist of at most //8 characters of whitespace or '\0'. If the content-length is slightly //off because of a sloppy server, this should skip whatever terminators //the server expected us to use. // const DWORD c_dwSmallestAcceptableStatusLength = ARRAY_ELEMENTS("HTTP/1.1 100\r\n") - 1; const DWORD c_dwMaxNoiseAllowed = 8; const DWORD c_dwMaxPreHTTPLength = ARRAY_ELEMENTS("Secure-HTTP/")-1; LPSTR lpszBuf; DWORD bytesLeft; lpszBuf = lpszBuffer; bytesLeft = dwBytesReceived; // // Check that we've read enough bytes for a status line to be ready. // if ((dwBytesReceived < c_dwSmallestAcceptableStatusLength) && !IsEof()) { goto done; } // // Allow up to c_dwMaxNoiseAllowed bytes worth of noise // int noiseBytesLeft = min(bytesLeft, c_dwMaxNoiseAllowed); int noiseBytesScanned = 0; while ((noiseBytesLeft > 0) && (isspace((unsigned char)*lpszBuf) || *lpszBuffer == '\0')) { ++lpszBuf; --bytesLeft; --noiseBytesLeft; ++noiseBytesScanned; } // // scan for the known version strings // for (int i = 0; i < NUM_HTTP_VERSIONS; ++i) { LPSTR version = KnownVersionsStrings[i].Version; DWORD length = KnownVersionsStrings[i].Length; if ((bytesLeft >= length) // // try the most common case as a direct comparison. memcmp() // should expand to cmpsd && cmpsb on x86 (most common platform // and one on which we are most interested in improving perf) // && (((i == 0) && (memcmp(lpszBuf, "HTTP/", sizeof("HTTP/") - 1) == 0)) //&& (lpszBuf[0] == 'H') //&& (lpszBuf[1] == 'T') //&& (lpszBuf[2] == 'T') //&& (lpszBuf[3] == 'P') //&& (lpszBuf[4] == '/')) // // "Clients should be tolerant in parsing the Status-Line" // quote from HTTP/1.1 spec, therefore we perform a // case-insensitive string comparison here // || (_strnicmp(lpszBuf, version, length) == 0))) { // // it starts with one of the recognized protocol version strings. // We assume its not a down-level server, although it could be, // sending back a plain text document that has e.g. "HTTP/1.0..." // at its start // // According to the HTTP "spec", though, it is mentioned that 0.9 // servers typically only return HTML, hence we shouldn't see // even a 0.9 response start with non-HTML data // SetUpLevel(TRUE); _ResponseScanned += noiseBytesScanned; // // we have start of this response // lpszBuffer = lpszBuf; break; } } if (!IsUpLevel()) { // // if we didn't find the start of a valid HTTP response and we have // not filled the response buffer sufficiently then allow // re-entry to retry. // // if we didn't find the start of a valid HTTP response and we //have filled the buffer sufficiently to expect the response, //report the response as invalid. // if ((bytesLeft < c_dwMaxPreHTTPLength ) && !IsEof()) { goto done; } else { error = ERROR_WINHTTP_INVALID_SERVER_RESPONSE; goto Cleanup; } } } // // WinHTTP only accepts IsUpLevel() type responses. // INET_ASSERT(IsUpLevel()); // // Note: at this point we can't store pointers into the response buffer // because it might move during a subsequent reallocation. We have to // maintain offsets into the buffer and convert to pointers when we come to // read the data out of the buffer (when the response is complete, or at // least we've finished receiving headers) // // // if we haven't checked the response yet, then the first thing to // get is the status line // statusLine = GetStatusLine(); if (statusLine == NULL) { error = ERROR_NOT_ENOUGH_MEMORY; goto Cleanup; } if (!statusLine->HaveString()) { BOOL fNeedMoreBuffer; int majorVersion = 0; int minorVersion = 0; BOOL fSupportsHttp1_1; _StatusCode = 0; // // Parse the status line. It has already been checked up to the first '/' // error = _ResponseHeaders.ParseStatusLine( (LPSTR)_ResponseBuffer, _BytesReceived, IsEof(), &_ResponseScanned, &fNeedMoreBuffer, &_StatusCode, (LPDWORD)&majorVersion, (LPDWORD)&minorVersion ); if (error != ERROR_SUCCESS) { goto Cleanup; } if (fNeedMoreBuffer) { error = ERROR_SUCCESS; goto Cleanup; } DEBUG_PRINT(HTTP, INFO, ("Version = %d.%d\n", majorVersion, minorVersion )); DEBUG_PRINT(HTTP, INFO, ("_StatusCode = %d\n", _StatusCode )); fSupportsHttp1_1 = FALSE; if (majorVersion != 1) { // WinHttp shouldn't accept a response with a major version greater than 1. // The protocol can change drastically between major versions, we'd have //no idea how to parse a major version of 2. Accepting 1.x responses is OK, //the protocol won't change in a non-compatible way across minor versions. // // WinHttp should not accept a major version of 0 as it is usupported. // error = ERROR_HTTP_INVALID_SERVER_RESPONSE; goto Cleanup; } else if (majorVersion == 1 && minorVersion >= 1) { fSupportsHttp1_1 = TRUE; } SetResponseHttp1_1(fSupportsHttp1_1); // // record the server HTTP version in the server info object // CServerInfo * pServerInfo = GetServerInfo(); if (pServerInfo != NULL) { if (fSupportsHttp1_1) { pServerInfo->SetHttp1_1(); // // Set the max connections per HTTP 1.1 server. // pServerInfo->SetNewLimit(GetMaxConnectionsPerServer(WINHTTP_OPTION_MAX_CONNS_PER_SERVER)); } else { pServerInfo->SetHttp1_0(); // // Set the max connections per HTTP 1.0 server. // pServerInfo->SetNewLimit(GetMaxConnectionsPerServer(WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER)); } } } // // continue scanning headers here until we have tested all the current // buffer, or we have found the start of the data // BOOL fFoundEndOfHeaders; error = _ResponseHeaders.ParseHeaders( (LPSTR)_ResponseBuffer, _BytesReceived > _dwMaxResponseHeaderSize ? _dwMaxResponseHeaderSize : _BytesReceived, _BytesReceived > _dwMaxResponseHeaderSize ? FALSE : IsEof(), &_ResponseScanned, &success, &fFoundEndOfHeaders ); if ( error != ERROR_SUCCESS ) { goto Cleanup; } if ( !fFoundEndOfHeaders && _BytesReceived > _dwMaxResponseHeaderSize) { error = ERROR_WINHTTP_HEADER_SIZE_OVERFLOW; goto Cleanup; } if ( fFoundEndOfHeaders ) { // // we found the end of the headers // SetEof(TRUE); // // and the start of the data // SetData(TRUE); _DataOffset = _ResponseScanned; DEBUG_PRINT(HTTP, INFO, ("found end of headers. _DataOffset = %d\n", _DataOffset )); } done: // // if we have reached the end of the headers then we communicate this fact // to the caller // if (IsData() || IsEof()) { error = CheckWellKnownHeaders(); if (ERROR_SUCCESS != error) { goto Cleanup; } *lpbEof = TRUE; /* Set connection persistency based on these rules: persistent = (1.0Request && Con: K-A && 1.0Response && Con: K-A) || (1.1Request && Con: K-A && 1.0Response && Con: K-A) || (1.0Request && Con: K-A && 1.1Response && Con: K-A) || (1.1Request && !Con: Close && 1.1Response && !Con: Close) therefore, persistent = 1.1Request && 1.1Response ? (!Con: Close in request || response) : Con: K-A in request && response */ if (IsRequestHttp1_1() && IsResponseHttp1_1()) { BOOL bHaveConnCloseRequest; bHaveConnCloseRequest = FindConnCloseRequestHeader( IsRequestUsingProxy() ? HTTP_QUERY_PROXY_CONNECTION : HTTP_QUERY_CONNECTION ); if (!(IsConnCloseResponse() || bHaveConnCloseRequest)) { DEBUG_PRINT(HTTP, INFO, ("HTTP/1.1 persistent connection\n" )); SetKeepAlive(TRUE); SetPersistentConnection(IsRequestUsingProxy() && !IsTalkingToSecureServerViaProxy() ); } else { DEBUG_PRINT(HTTP, INFO, ("HTTP/1.1 non-persistent connection: close on: request: %B; response: %B\n", bHaveConnCloseRequest, IsConnCloseResponse() )); SetKeepAlive(FALSE); SetNoLongerKeepAlive(); ClearPersistentConnection(); } } } Cleanup: // // we are finished updating the response headers (no other thread should be // waiting for this if the reference count and object state is correct) // _ResponseHeaders.UnlockHeaders(); quit: PERF_LEAVE(UpdateResponseHeaders); DEBUG_LEAVE(error); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::CreateResponseHeaders( IN OUT LPSTR* ppszBuffer, IN DWORD dwBufferLength ) /*++ Routine Description: Create the response headers given a buffer containing concatenated headers. Called when we are creating this object from the cache Arguments: lpszBuffer - pointer to buffer containing headers dwBufferLength - length of lpszBuffer Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY Couldn't create headers --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "HTTP_REQUEST_HANDLE_OBJECT::CreateResponseHeaders", "%.32q, %d", ppszBuffer, dwBufferLength )); // // there SHOULD NOT already be a response buffer if we're adding an // external buffer // INET_ASSERT(_ResponseBuffer == NULL); DWORD error; BOOL eof = FALSE; _ResponseBuffer = (LPBYTE) *ppszBuffer; _ResponseBufferLength = dwBufferLength; _BytesReceived = dwBufferLength; error = UpdateResponseHeaders(&eof); if (error != ERROR_SUCCESS) { // // if we failed, we will clean up our variables including clearing // out the response buffer address and length, but leave freeing // the buffer to the caller // _ResponseBuffer = NULL; _ResponseBufferLength = 0; ResetResponseVariables(); } else { // // Success - the object owns the buffer so the caller should not free. // *ppszBuffer = NULL; } DEBUG_LEAVE(error); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryResponseVersion( IN LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength ) /*++ Routine Description: Returns the HTTP version string from the status line Arguments: lpBuffer - pointer to buffer to copy version string into lpdwBufferLength - IN: size of lpBuffer OUT: size of version string excluding terminating '\0' if successful, else required buffer length Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER --*/ { PERF_ENTER(QueryResponseVersion); DWORD error; HEADER_STRING * statusLine = GetStatusLine(); if ((statusLine == NULL) || statusLine->IsError()) { error = ERROR_WINHTTP_INTERNAL_ERROR; goto quit; } LPSTR string; DWORD length; // // get a pointer into the response buffer where the status line starts // and its length // string = statusLine->StringAddress((LPSTR)_ResponseBuffer); length = (DWORD)statusLine->StringLength(); // // the version string is the first token on the line, delimited by spaces // DWORD index; for (index = 0; index < length; ++index) { // // we'll also check for CR and LF, although just space should be // sufficient // if ((string[index] == ' ') || (string[index] == '\r') || (string[index] == '\n')) { break; } } if (*lpdwBufferLength > index) { memcpy(lpBuffer, (LPVOID)string, index); ((LPSTR)lpBuffer)[index] = '\0'; *lpdwBufferLength = index; error = ERROR_SUCCESS; } else { *lpdwBufferLength = index + 1; error = ERROR_INSUFFICIENT_BUFFER; } quit: PERF_LEAVE(QueryResponseVersion); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryStatusCode( IN LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength, IN DWORD dwModifiers ) /*++ Routine Description: Returns the status code as a string or a number Arguments: lpBuffer - pointer to buffer where results written lpdwBufferLength - IN: length of buffer OUT: size of returned information, or required size' of buffer dwModifiers - flags which modify returned value Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER --*/ { PERF_ENTER(QueryStatusCode); DWORD error; DWORD requiredSize; if (dwModifiers & HTTP_QUERY_FLAG_NUMBER) { requiredSize = sizeof(_StatusCode); if (*lpdwBufferLength >= requiredSize) { *(LPDWORD)lpBuffer = _StatusCode; error = ERROR_SUCCESS; } else { error = ERROR_INSUFFICIENT_BUFFER; } } else { // // the number should always be only 3 characters long, but we'll be // flexible (just in case) // char numBuf[sizeof("4294967296")]; requiredSize = wsprintf(numBuf, "%u", _StatusCode) + 1; #ifdef DEBUG // Debug check to make sure everything is good because the above // used to be ultoa. char debugBuf[sizeof("4294967296")]; ultoa(_StatusCode, debugBuf, 10); if (strcmp(debugBuf,numBuf)) { INET_ASSERT(FALSE); } INET_ASSERT(requiredSize == lstrlen(numBuf) + 1); #endif if (*lpdwBufferLength >= requiredSize) { memcpy(lpBuffer, (LPVOID)numBuf, requiredSize); *lpdwBufferLength = requiredSize - 1; error = ERROR_SUCCESS; } else { *lpdwBufferLength = requiredSize; error = ERROR_INSUFFICIENT_BUFFER; } } PERF_LEAVE(QueryStatusCode); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryStatusText( IN LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength ) /*++ Routine Description: Returns the status text - if any - returned by the server in the status line Arguments: lpBuffer - pointer to buffer where status text is written lpdwBufferLength - IN: size of lpBuffer OUT: length of the status text string minus 1 for the '\0', or the required buffer length if we return ERROR_INSUFFICIENT_BUFFER Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER --*/ { PERF_ENTER(QueryStatusText); DWORD error; HEADER_STRING * statusLine = GetStatusLine(); if ((statusLine == NULL) || statusLine->IsError()) { error = ERROR_WINHTTP_INTERNAL_ERROR; goto quit; } LPSTR str; DWORD len; // // find the third token on the status line. The status line has the form // // "HTTP/1.0 302 Try again\r\n" // // ^ ^ ^ // | | | // | | +- status text // | +- status code // +- version // str = statusLine->StringAddress((LPSTR)_ResponseBuffer); len = statusLine->StringLength(); DWORD i; i = 0; int j; for (j = 0; j < 2; ++j) { while ((i < len) && (str[i] != ' ')) { ++i; } while ((i < len) && (str[i] == ' ')) { ++i; } } len -= i; if (*lpdwBufferLength > len) { memcpy(lpBuffer, (LPVOID)&str[i], len); ((LPSTR)lpBuffer)[len] = '\0'; *lpdwBufferLength = len; error = ERROR_SUCCESS; } else { *lpdwBufferLength = len + 1; error = ERROR_INSUFFICIENT_BUFFER; } quit: PERF_LEAVE(QueryStatusText); return error; } DWORD HTTP_REQUEST_HANDLE_OBJECT::QueryRawResponseHeaders( IN BOOL bCrLfTerminated, OUT LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength ) /*++ Routine Description: Gets the raw response headers Arguments: bCrLfTerminated - TRUE if we want RAW_HEADERS_CRLF else RAW_HEADERS lpBuffer - pointer to buffer where headers returned lpdwBufferLength - IN: length of lpBuffer OUT: returned length of lpBuffer Return Value: DWORD Success - ERROR_SUCCESS Failure - --*/ { DEBUG_ENTER((DBG_HTTP, Dword, "QueryRawHeaders", "%B, %#x, %#x [%d]", bCrLfTerminated, lpBuffer, lpdwBufferLength, *lpdwBufferLength )); PERF_ENTER(QueryRawHeaders); DWORD error = _ResponseHeaders.QueryRawHeaders( (LPSTR)_ResponseBuffer, bCrLfTerminated, lpBuffer, lpdwBufferLength ); IF_DEBUG_CODE() { if (error == ERROR_INSUFFICIENT_BUFFER) { DEBUG_PRINT(HTTP, INFO, ("*lpdwBufferLength = %d\n", *lpdwBufferLength )); } } PERF_LEAVE(QueryRawHeaders); DEBUG_LEAVE(error); return error; } VOID HTTP_REQUEST_HANDLE_OBJECT::RemoveAllRequestHeadersByName( IN DWORD dwQueryIndex ) /*++ Routine Description: Removes all headers of a particular type from the request object Arguments: lpszHeaderName - name of header to remove Return Value: None. --*/ { DEBUG_ENTER((DBG_HTTP, None, "RemoveAllRequestHeadersByName", "%q, %u", GlobalKnownHeaders[dwQueryIndex].Text, dwQueryIndex )); PERF_ENTER(RemoveAllRequestHeadersByName); _RequestHeaders.RemoveAllByIndex(dwQueryIndex); PERF_LEAVE(RemoveAllRequestHeadersByName); DEBUG_LEAVE(0); } // // private methods // PRIVATE DWORD HTTP_REQUEST_HANDLE_OBJECT::CheckWellKnownHeaders( VOID ) /*++ Routine Description: Tests for a couple of well-known headers that are important to us as well as the app: "Connection: Keep-Alive" "Proxy-Connection: Keep-Alive" "Connection: Close" "Proxy-Connection: Close" "Transfer-Encoding: chunked" "Content-Length: ####" "Content-Range: bytes ####-####/####" The header DOES NOT contain CR-LF. That is, dwHeaderLength will not include any counts for line termination We need to know if the server honoured a request for a keep-alive connection so that we don't try to receive until we hit the end of the connection. The server will keep it open. We need to know the content length if we are talking over a persistent (keep alive) connection. If either header is found, we set the corresponding flag in the HTTP_HEADERS object, and in the case of "Content-Length:" we parse out the length. Arguments: None. Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_NOT_ENOUGH_MEMORY --*/ { DEBUG_ENTER((DBG_HTTP, None, "HTTP_REQUEST_HANDLE_OBJECT::CheckWellKnownHeaders", NULL )); DWORD dwError = ERROR_SUCCESS; // // check for "Content-Length:" // if ( IsResponseHeaderPresent(HTTP_QUERY_CONTENT_LENGTH) ) { HEADER_STRING * curHeader; DWORD dwHeaderLength; LPSTR lpszHeader; DWORD iSlotContentLength = _ResponseHeaders._bKnownHeaders[HTTP_QUERY_CONTENT_LENGTH]; curHeader = _ResponseHeaders.GetSlot(iSlotContentLength); lpszHeader = curHeader->StringAddress((LPSTR)_ResponseBuffer); dwHeaderLength = curHeader->StringLength(); dwHeaderLength -= GlobalKnownHeaders[HTTP_QUERY_CONTENT_LENGTH].Length+1; lpszHeader += GlobalKnownHeaders[HTTP_QUERY_CONTENT_LENGTH].Length+1; while (dwHeaderLength && (*lpszHeader == ' ')) { --dwHeaderLength; ++lpszHeader; } while (dwHeaderLength && isdigit(*lpszHeader)) { _ContentLength = _ContentLength * 10 + (*lpszHeader - '0'); --dwHeaderLength; ++lpszHeader; } // // once we have _ContentLength, we don't modify it (unless // we fix it up when using a 206 partial response to resume // a partial download.) The header value should be returned // by HttpQueryInfo(). Instead, we keep account of the // amount of keep-alive data left to copy in _BytesRemaining // _BytesRemaining = _ContentLength; // // although we said we may be one past the end of the header, in // reality, if we received a buffer with "Content-Length:" then we // expect it to be terminated by CR-LF (or CR-CR-LF or just LF, // depending on the wackiness quotient of the server) // // MSXML3 bug 56001: commenting-out this assert; it's informational // only and ignorable. // INET_ASSERT((*lpszHeader == '\r') || (*lpszHeader == '\n')); SetHaveContentLength(TRUE); DEBUG_PRINT(HTTP, INFO, ("_ContentLength = %d\n", _ContentLength )); _BytesInSocket = (_ContentLength != 0) ? (_ContentLength - (_BytesReceived - _DataOffset)) : 0; // // we could have multiple responses in the same buffer. If // the amount received is greater than the content length // then we have all the data; there are no bytes left in // the socket for the current response // if ((int)_BytesInSocket < 0) { _BytesInSocket = 0; } DEBUG_PRINT(HTTP, INFO, ("bytes left in socket = %d\n", _BytesInSocket )); } if ( IsResponseHeaderPresent(HTTP_QUERY_CONNECTION) || IsResponseHeaderPresent(HTTP_QUERY_PROXY_CONNECTION) ) { // // check for "Connection: Keep-Alive" or "Proxy-Connection: Keep-Alive". // This test protects us against the unlikely // event of a server returning to us a keep-alive response header (because // that would cause problems for the proxy) // if (IsWantKeepAlive() && (!IsKeepAlive() || IsResponseHttp1_1())) { HEADER_STRING * curHeader; DWORD dwHeaderLength, headerNameLength; LPSTR lpszHeader; DWORD iSlot; if (IsRequestUsingProxy() && IsResponseHeaderPresent(HTTP_QUERY_PROXY_CONNECTION)) { iSlot = _ResponseHeaders._bKnownHeaders[HTTP_QUERY_PROXY_CONNECTION]; headerNameLength = GlobalKnownHeaders[HTTP_QUERY_PROXY_CONNECTION].Length+1; } else if (IsResponseHeaderPresent(HTTP_QUERY_CONNECTION)) { iSlot = _ResponseHeaders._bKnownHeaders[HTTP_QUERY_CONNECTION]; headerNameLength = GlobalKnownHeaders[HTTP_QUERY_CONNECTION].Length+1; } else { iSlot = _ResponseHeaders._bKnownHeaders[HTTP_QUERY_PROXY_CONNECTION]; headerNameLength = GlobalKnownHeaders[HTTP_QUERY_PROXY_CONNECTION].Length+1; } curHeader = _ResponseHeaders.GetSlot(iSlot); lpszHeader = curHeader->StringAddress((LPSTR)_ResponseBuffer); dwHeaderLength = curHeader->StringLength(); dwHeaderLength -= headerNameLength; lpszHeader += headerNameLength; while (dwHeaderLength && (*lpszHeader == ' ')) { ++lpszHeader; --dwHeaderLength; } // // both headers use "Keep-Alive" as header-value ONLY for HTTP 1.0 servers // if (((int)dwHeaderLength >= KEEP_ALIVE_LEN) && !strnicmp(lpszHeader, KEEP_ALIVE_SZ, KEEP_ALIVE_LEN)) { DEBUG_PRINT(HTTP, INFO, ("Connection: Keep-Alive\n" )); // // BUGBUG - we are setting k-a when coming from cache! // SetKeepAlive(TRUE); SetPersistentConnection(headerNameLength == HTTP_PROXY_CONNECTION_LEN); } // // also check for "Close" as header-value ONLY for HTTP 1.1 servers // else if ((*lpszHeader == 'C' || *lpszHeader == 'c') && ((int)dwHeaderLength >= CLOSE_LEN) && IsResponseHttp1_1() && !strnicmp(lpszHeader, CLOSE_SZ, CLOSE_LEN)) { DEBUG_PRINT(HTTP, INFO, ("Connection: Close (HTTP/1.1)\n" )); SetConnCloseResponse(TRUE); } } } // // check for "Transfer-Encoding:" // if (IsResponseHeaderPresent(HTTP_QUERY_TRANSFER_ENCODING) && IsResponseHttp1_1()) { // // If Http 1.1, check for Chunked Transfer // HEADER_STRING * curHeader; DWORD dwHeaderLength; LPSTR lpszHeader; DWORD iSlot; iSlot = _ResponseHeaders._bKnownHeaders[HTTP_QUERY_TRANSFER_ENCODING]; curHeader = _ResponseHeaders.GetSlot(iSlot); lpszHeader = curHeader->StringAddress((LPSTR)_ResponseBuffer); dwHeaderLength = curHeader->StringLength(); dwHeaderLength -= GlobalKnownHeaders[HTTP_QUERY_TRANSFER_ENCODING].Length+1; lpszHeader += GlobalKnownHeaders[HTTP_QUERY_TRANSFER_ENCODING].Length+1; while (dwHeaderLength && (*lpszHeader == ' ')) { ++lpszHeader; --dwHeaderLength; } // // look for "chunked" entry that confirms that we're doing chunked transfer encoding // // //TODO We really should be able to handle multiple Transfer-Encoding headers. // (perhaps accepting an 'identity' encoding followed by a 'chunked' encoding // and recognizing that it is a chunked response, or rejecting a 'chunked' encoding // followed by an invalid encoding) // if (((int)dwHeaderLength >= CHUNKED_LEN) && !strnicmp(lpszHeader, CHUNKED_SZ, CHUNKED_LEN)) { INTERNET_HANDLE_OBJECT* pRoot = GetRootHandle(this); DWORD_PTR dwChunkFilterCtx = 0; // Now that we know this is a chunked response, allocate // a decoder context for parsing the data later. If anything // fails here, the request needs to fail. if (S_OK != pRoot->_ChunkFilter.RegisterContextEx(&dwChunkFilterCtx, _dwMaxResponseHeaderSize)) { dwError = ERROR_NOT_ENOUGH_MEMORY; goto quit; } else if (!_ResponseFilterList.Insert(&pRoot->_ChunkFilter, dwChunkFilterCtx)) { pRoot->_ChunkFilter.UnregisterContext(dwChunkFilterCtx); dwError = ERROR_NOT_ENOUGH_MEMORY; goto quit; } SetHaveChunkEncoding(TRUE); DEBUG_PRINT(HTTP, INFO, ("server is sending Chunked Transfer Encoding\n" )); // // if both "transfer-encoding: chunked" and "content-length:" // were received then the chunking takes precedence // DEBUG_PRINT(HTTP, INFO, ("server sent both Content-Length and Transfer-Encoding: chunked headers\n" )); if (IsContentLength()) { SetHaveContentLength(FALSE); } } else if (dwHeaderLength >= (DWORD)IDENTITY_LEN && !strnicmp(lpszHeader, IDENTITY_SZ, IDENTITY_LEN)) { //ignore } else { // // We can't be sure when we've reached the end of this request, //and so we'll disallow keep-alive to prevent the next response //from being corrupted. // SetNoLongerKeepAlive(); } } SetBadNSServer(FALSE); if (IsResponseHttp1_1()) { // // For IIS 4.0 Servers, and all other normal servers, if we make // a HEAD request, we should ignore the Content-Length. // // IIS 3.0 servers send an illegal body, and this is a bug in the server. // since they're not HTTP 1.1 we should be ok here. // if ( (GetMethodType() == HTTP_METHOD_TYPE_HEAD) && (_ContentLength > 0) && IsWantKeepAlive() ) { // // set length to 0 // _ContentLength = 0; _BytesInSocket = 0; _BytesRemaining = 0; } if ( IsRequestHttp1_1() ) { // // check for NS servers that don't return correct HTTP/1.1 responses // LPSTR buffer; DWORD buflen; DWORD status = FastQueryResponseHeader(HTTP_QUERY_SERVER, (LPVOID*)&buffer, &buflen, 0 ); #define NSEP "Netscape-Enterprise/3" #define NSEPLEN (sizeof(NSEP) - 1) #define NSFT "Netscape-FastTrack/3" #define NSFTLEN (sizeof(NSFT) - 1) #define NSCS "Netscape-Commerce/3" #define NSCSLEN (sizeof(NSCS) - 1) if (status == ERROR_SUCCESS) { BOOL fIsBadServer = ((buflen > NSEPLEN) && !strnicmp(buffer, NSEP, NSEPLEN)) || ((buflen > NSFTLEN) && !strnicmp(buffer, NSFT, NSFTLEN)) || ((buflen > NSCSLEN) && !strnicmp(buffer, NSCS, NSCSLEN)); if ( fIsBadServer ) { CServerInfo * pServerInfo = GetServerInfo(); SetBadNSServer(fIsBadServer); if (pServerInfo != NULL) { // // Note this Bad Server info in the server info obj, // as we they fail to do keep-alive with SSL properly // pServerInfo->SetBadNSServer(); } DEBUG_PRINT(HTTP, INFO, ("IsBadNSServer() == %B\n", IsBadNSServer() )); } } } // // BUGBUG - content-type: multipart/byteranges means we // also have data // DWORD statusCode = GetStatusCode(); if (!IsBadNSServer() && !IsContentLength() && !IsChunkEncoding() && (((statusCode >= HTTP_STATUS_CONTINUE) // 100 && (statusCode < HTTP_STATUS_OK)) // 200 || (statusCode == HTTP_STATUS_NO_CONTENT) // 204 || (statusCode == HTTP_STATUS_MOVED) // 301 || (statusCode == HTTP_STATUS_REDIRECT) // 302 || (statusCode == HTTP_STATUS_REDIRECT_METHOD) // 303 || (statusCode == HTTP_STATUS_NOT_MODIFIED) // 304 || (statusCode == HTTP_STATUS_REDIRECT_KEEP_VERB)) // 307 || (GetMethodType() == HTTP_METHOD_TYPE_HEAD)) { DEBUG_PRINT(HTTP, INFO, ("header-only HTTP/1.1 response\n" )); SetData(FALSE); } } quit: DEBUG_LEAVE(dwError); return dwError; } // // this array has the same order as the HTTP_METHOD_TYPE enum // #define MAKE_REQUEST_METHOD_TYPE(Type) \ sizeof(# Type) - 1, # Type, HTTP_METHOD_TYPE_ ## Type // // darrenmi - need a new macro because *_M-POST isn't a valid enum member. // we need a seperate enum type and string value. // // map HTTP_METHOD_TYPE_MPOST <=> "M-POST" // #define MAKE_REQUEST_METHOD_TYPE2(EnumType,Type) \ sizeof(# Type) - 1, # Type, HTTP_METHOD_TYPE_ ## EnumType static const struct _REQUEST_METHOD { int Length; LPSTR Name; HTTP_METHOD_TYPE MethodType; } MethodNames[] = { MAKE_REQUEST_METHOD_TYPE(GET), MAKE_REQUEST_METHOD_TYPE(HEAD), MAKE_REQUEST_METHOD_TYPE(POST), MAKE_REQUEST_METHOD_TYPE(PUT), MAKE_REQUEST_METHOD_TYPE(PROPFIND), MAKE_REQUEST_METHOD_TYPE(PROPPATCH), MAKE_REQUEST_METHOD_TYPE(LOCK), MAKE_REQUEST_METHOD_TYPE(UNLOCK), MAKE_REQUEST_METHOD_TYPE(COPY), MAKE_REQUEST_METHOD_TYPE(MOVE), MAKE_REQUEST_METHOD_TYPE(MKCOL), MAKE_REQUEST_METHOD_TYPE(CONNECT), MAKE_REQUEST_METHOD_TYPE(DELETE), MAKE_REQUEST_METHOD_TYPE(LINK), MAKE_REQUEST_METHOD_TYPE(UNLINK), MAKE_REQUEST_METHOD_TYPE(BMOVE), MAKE_REQUEST_METHOD_TYPE(BCOPY), MAKE_REQUEST_METHOD_TYPE(BPROPFIND), MAKE_REQUEST_METHOD_TYPE(BPROPPATCH), MAKE_REQUEST_METHOD_TYPE(BDELETE), MAKE_REQUEST_METHOD_TYPE(SUBSCRIBE), MAKE_REQUEST_METHOD_TYPE(UNSUBSCRIBE), MAKE_REQUEST_METHOD_TYPE(NOTIFY), MAKE_REQUEST_METHOD_TYPE(POLL), MAKE_REQUEST_METHOD_TYPE(CHECKIN), MAKE_REQUEST_METHOD_TYPE(CHECKOUT), MAKE_REQUEST_METHOD_TYPE(INVOKE), MAKE_REQUEST_METHOD_TYPE(SEARCH), MAKE_REQUEST_METHOD_TYPE(PIN), MAKE_REQUEST_METHOD_TYPE2(MPOST,M-POST) }; HTTP_METHOD_TYPE MapHttpRequestMethod( IN LPCSTR lpszVerb ) /*++ Routine Description: Maps request method string to type. Method names *are* case-sensitive Arguments: lpszVerb - method (verb) string Return Value: HTTP_METHOD_TYPE --*/ { int verbLen = strlen(lpszVerb); for (int i = 0; i < ARRAY_ELEMENTS(MethodNames); ++i) { if ((MethodNames[i].Length == verbLen) && (memcmp(lpszVerb, MethodNames[i].Name, verbLen) == 0)) { return MethodNames[i].MethodType; } } // // we now hande HTTP_METHOD_TYPE_UNKNOWN // return HTTP_METHOD_TYPE_UNKNOWN; } DWORD MapHttpMethodType( IN HTTP_METHOD_TYPE tMethod, OUT LPCSTR * lplpcszName ) /*++ Routine Description: Map a method type to the corresponding name and length Arguments: tMethod - to map lplpcszName - pointer to pointer to returned name Return Value: DWORD Success - length of method name Failure - (DWORD)-1 --*/ { DWORD length; if ((tMethod >= HTTP_METHOD_TYPE_FIRST) && (tMethod <= HTTP_METHOD_TYPE_LAST)) { *lplpcszName = MethodNames[tMethod].Name; length = MethodNames[tMethod].Length; } else { length = (DWORD)-1; } return length; } #if INET_DEBUG LPSTR MapHttpMethodType( IN HTTP_METHOD_TYPE tMethod ) { return (tMethod == HTTP_METHOD_TYPE_UNKNOWN) ? "Unknown" : MethodNames[tMethod].Name; } #endif #include "pch.h" #include "Interpreter.h" #include "../Core/Application.h" namespace Interpreter { Interpreter::Interpreter() : m_LineNumber{ 1 }, m_IntValue{ 0 }, m_RealValue{ 0.0 }, m_IsExponential{ false }, m_IsOperatorFound{ false }, m_IsEnd{ false } { } bool Interpreter::OpenFile(const std::string& filepath) { m_iFileStream.open(filepath); if (!m_iFileStream) { LOG_ERROR("Unable to open file: '{0}'", filepath); return false; } LOG_INFO("'{0}' opened successfully.", filepath); return true; } void Interpreter::ReadFile() { // Traverse the file line by line until the end while (std::getline(m_iFileStream, m_Line) && !m_IsEnd) { if (!IsSyntaxValid(m_Line)) ERROR(GetLastError()); InterpretLine(m_Line); m_IsOperatorFound = false; m_LineNumber++; } if (!m_IsEnd) ERROR(" statement not found!"); } bool Interpreter::IsSyntaxValid(const std::string& line) { std::istringstream iss{ line }; std::string word{}; while (iss >> word) { WordType wordType{}; if (word.front() == '"') { m_StringValue = word; while (m_StringValue.back() != '"' || m_StringValue.size() < 2) { iss >> word; m_StringValue += ' ' + word; } wordType = GetWordType(m_StringValue); } else wordType = GetWordType(word); if (wordType == WordType::Keyword) { KeywordType keywordType = Keyword::GetKeyword(word); if (keywordType == KeywordType::Comment) return true; } if (wordType == WordType::Invalid && word != "=") { m_ErrorWord = word; return false; } } return true; } void Interpreter::InterpretLine(const std::string& line) { std::istringstream iss{ line }; std::string word{}; iss >> word; WordType wordType{}; if (word.front() == '"') { m_StringValue = word; while (m_StringValue.back() != '"' || m_StringValue.size() < 2) { iss >> word; m_StringValue += ' ' + word; } wordType = GetWordType(m_StringValue); } else wordType = GetWordType(word); switch (wordType) { case WordType::Keyword: { // Get keyword type KeywordType keywordType = Keyword::GetKeyword(word); // Grab everything after the keyword std::string expression = GetExpression(iss); ValidateKeyword(keywordType, expression); break; } case WordType::Variable: { VariableType varType = Variable::GetVariableType(word); // Save the variable name std::string variableStr{ word }; // Make sure the assignment '=' is next in the line iss >> word; if (word != "=") ERROR("Did you forget the assignment '=' for the variable?"); // Grab the expression after the '=' std::string expression = GetExpression(iss); // Make sure it's a valid assignment ValidateAssignment(varType, expression); // Store the variable and its value MakeAssignment(varType, variableStr, expression); break; } case WordType::Operator: ERROR("'" + word + "' An is not a valid instruction!"); break; case WordType::Number: ERROR("'" + word + "' A is not a valid instruction!"); break; case WordType::String: ERROR("'" + word + "' A is not a valid instruction!"); break; case WordType::Invalid: default: ERROR("'" + word + "' is not supported!"); break; } } void Interpreter::Reset() { m_iFileStream.clear(); m_Line.clear(); m_LineNumber = 1; m_ErrorWord.clear(); m_IntValue = 0; m_RealValue = 0.0; m_StringValue.clear(); m_IsExponential = false; m_IsOperatorFound = false; m_IsEnd = false; ClearHolders(); ClearStacks(); } bool Interpreter::IsNumber(const std::string& word) { if (IsInteger(word)) return true; if (IsReal(word)) { if (IsExponential(word)) m_IsExponential = true; return true; } return false; } bool Interpreter::IsString(const std::string& word) { if (word.front() == '\"') { if (word.back() != '\"' || word.size() < 2) ERROR("String is missing ending quotation marks!"); return true; } return false; } bool Interpreter::IsInteger(std::string word) { try { size_t lastChar{ 0 }; m_IntValue = std::stoi(word, &lastChar); return lastChar == word.size(); } catch (...) { return false; } return false; } bool Interpreter::IsReal(std::string word) { for (const char& c : word) { if (c == '.') { try { size_t lastChar{ 0 }; m_RealValue = std::stod(word, &lastChar); return lastChar == word.size(); } catch (...) { return false; } } } return false; } bool Interpreter::IsExponential(std::string word) { for (const char& ch : word) if (ch == 'e' || ch == 'E') return true; return false; } void Interpreter::ValidateKeyword(KeywordType keywordType, std::string expression) { switch (keywordType) { // REM this is a comment case KeywordType::Comment: return; case KeywordType::If: { std::string tempStr{ expression }; for (char& c : tempStr) c = std::tolower(c); size_t found = tempStr.find("then"); if (found == std::string::npos) { ERROR("Did you forget the 'then' keyword?"); } else { std::istringstream iss{ expression }; std::string conditionalExpression; for (std::string tempWord; iss >> tempWord;) { if (Keyword::GetKeyword(tempWord) == KeywordType::Then) break; conditionalExpression += tempWord + ' '; } conditionalExpression.pop_back(); // Pop the last whitespace // Guard against double operators std::istringstream cond{ conditionalExpression }; for (std::string s; cond >> s;) { if (Operator::IsOperator(s)) { cond >> s; if (Operator::IsOperator(s)) ERROR("Did you write 2 operators in a row?"); } } //LOG_INFO("Conditional expression: '{0}'", conditionalExpression); std::string postfix = InfixToPostfix(conditionalExpression); //LOG_INFO("postfix: {0}", postfix); bool IsConditionTrue{ false }; std::istringstream condIss{ conditionalExpression }; std::string condStr{}; condIss >> condStr; VariableType condVarType = Variable::GetVariableType(condStr); switch (condVarType) { case VariableType::Integer: IsConditionTrue = EvaluateOperatorPostfix(postfix); break; case VariableType::Real: IsConditionTrue = EvaluateOperatorPostfix(postfix); break; case VariableType::String: IsConditionTrue = EvaluateStringOperatorPostfix(postfix); break; } if (IsConditionTrue) { std::string thenStatement{}; for (std::string tempWord; iss >> tempWord;) thenStatement += tempWord + ' '; thenStatement.pop_back(); ValidateKeyword(KeywordType::Then, thenStatement); } } break; } case KeywordType::Then: { std::istringstream iss{ expression }; std::string firstWord{}; iss >> firstWord; if (Keyword::IsKeyword(firstWord)) { KeywordType type = Keyword::GetKeyword(firstWord); if (type == KeywordType::Print) { std::string expr = GetExpression(iss); ValidateKeyword(type, expr); return; } else if (type == KeywordType::Read) { std::string expr = GetExpression(iss); ValidateKeyword(type, expr); return; } } else { std::string str{}; iss >> str; if (str != "=") ERROR("Did you forget the assignment '=' for the variable?"); // Grab the expression after the '=' std::string expr = GetExpression(iss); VariableType varType = Variable::GetVariableType(firstWord); ValidateAssignment(varType, expr); MakeAssignment(varType, firstWord, expr); } break; } case KeywordType::Read: { // Validate that expression is a variable if (Variable::IsVariable(expression)) { VariableType varType = Variable::GetVariableType(expression); std::string variableStr = expression; std::string readValue{}; std::cin >> readValue; ValidateAssignment(varType, readValue); MakeAssignment(varType, variableStr, readValue); } else ERROR("'" + expression + "' is not a valid assignment!"); break; } case KeywordType::Print: { if (!expression.empty()) { if (Variable::IsVariable(expression)) { for (char c : expression) { if (std::isdigit((char)c)) { ERROR("'" + expression + "' Variable names can not have any digits!"); return; } } if (Keyword::IsKeyword(expression)) ERROR("Invalid print statement! Can't print a keyword!"); PrintVariable(expression); return; } if (IsNumber(expression)) { std::cout << expression; return; } if (IsString(expression)) { std::string str{ expression }; str.erase(std::remove(str.begin(), str.end(), '"'), str.end()); std::cout << str; return; } } else { std::cout << '\n'; return; } break; } case KeywordType::End: { m_IsEnd = true; std::cout << '\n'; LOG_INFO("Program end"); break; } case KeywordType::Invalid: LOG_ERROR("Invalid Keyword Type"); break; default: LOG_ERROR("Unknown KeywordType!"); break; } } void Interpreter::ValidateAssignment(VariableType varType, std::string expression) { std::string word{}; std::istringstream iss{ expression }; iss >> word; // Verify that it is a valid assignment switch (varType) { case VariableType::Integer: { if (Variable::IsVariable(word)) break; if (!IsInteger(word) || IsReal(word)) ERROR("Invalid assignment to variable."); break; } case VariableType::Real: { if (Variable::IsVariable(word)) break; if (!IsReal(word) || IsInteger(word)) ERROR("Invalid assignment to variable."); break; } case VariableType::String: { if (Variable::IsVariable(word)) break; if (!IsString(expression)) ERROR("Invalid assignment to variable."); break; } } // Verify arithmetic expressions // Grab words until iss is empty while (iss >> word) { if (Operator::IsOperator(word)) { m_IsOperatorFound = true; OperatorType op = Operator::GetOperator(word); if (Operator::IsLogical(op)) ERROR(std::string("Used logical operator '" + word + "' in an assignment statement!").c_str()); if (Operator::IsRelational(op)) ERROR(std::string("Used relational operator '" + word + "' in an assignment statement!").c_str()); // Grab next word iss >> word; if (Operator::IsOperator(word)) ERROR(std::string("Was expecting a Number or Variable but found '" + word + "'.\nDid you write two operators in a row? ").c_str()); } } } void Interpreter::PrintVariable(const std::string& expression) { switch (Variable::GetVariableType(expression)) { case VariableType::Integer: if (m_IntHolder.Find(expression)) std::cout << m_IntHolder.GetValue(expression); else ERROR("'" + expression + "' is not defined!"); break; case VariableType::Real: if (m_RealHolder.Find(expression)) std::cout << std::fixed << m_RealHolder.GetValue(expression); else ERROR("'" + expression + "' is not defined!"); break; case VariableType::String: if (m_StringHolder.Find(expression)) std::cout << m_StringHolder.GetValue(expression); else ERROR("'" + expression + "' is not defined!"); break; } } void Interpreter::MakeAssignment(VariableType varType, const std::string& variable, const std::string& expression) { switch (varType) { case VariableType::Integer: { if (m_IsOperatorFound) { std::string postFix = InfixToPostfix(expression); int intValue = EvaluateArithmeticPostfix(postFix); m_IntHolder.InsertToMap(variable, intValue); } else { for (const char& ch : expression) if (!isdigit(ch) && ch != '-') ERROR("'" + expression + "' is not a valid integer number!"); int intValue = stoi(expression); m_IntHolder.InsertToMap(variable, intValue); } } break; case VariableType::Real: { if (m_IsOperatorFound) { std::string postFix = InfixToPostfix(expression); double realValue = EvaluateArithmeticPostfix(postFix); m_RealHolder.InsertToMap(variable, realValue); } else { for (const char& ch : expression) if (!isdigit(ch) && ch != '.' && ch != '-') ERROR("'" + expression + "' is not a valid real number!"); double realValue = stod(expression); m_RealHolder.InsertToMap(variable, realValue); } } break; case VariableType::String: { if (m_IsOperatorFound) { std::string stringResult = Concatenate(expression); stringResult.erase(std::remove(stringResult.begin(), stringResult.end(), '"'), stringResult.end()); m_StringHolder.InsertToMap(variable, stringResult); } else { std::string str{ expression }; str.erase(std::remove(str.begin(), str.end(), '"'), str.end()); m_StringHolder.InsertToMap(variable, str); } } break; case VariableType::Invalid: default: ERROR("Cannot assign " + expression + " to " + variable + "!"); break; } } int Interpreter::Precedence(std::string word) { if (Operator::IsOperator(word)) { OperatorType op = Operator::GetOperator(word); switch (op) { case OperatorType::Or: return 1; case OperatorType::And: return 2; case OperatorType::Not: return 3; case OperatorType::Eq: case OperatorType::Ne: return 4; case OperatorType::Lt: case OperatorType::Le: case OperatorType::Gt: case OperatorType::Ge: return 5; case OperatorType::Add: case OperatorType::Sub: return 6; case OperatorType::Mul: case OperatorType::Div: return 7; } } else return -1; } std::string Interpreter::InfixToPostfix(std::string infix) { Stack stack{}; std::string result{}; std::istringstream iss{ infix }; for (std::string word{}; iss >> word;) { // If word is an operand if (!Operator::IsOperator(word)) result += word + ' '; // If word is an operator else { while (!stack.IsEmpty() && Precedence(word) <= Precedence(stack.Peek())) { result += stack.Peek() + ' '; stack.Pop(); } stack.Push(word); } } while (!stack.IsEmpty()) { result += stack.Peek() + ' '; stack.Pop(); } result.pop_back(); return result; } bool Interpreter::OperateRelational(OperatorType op, const std::string& operand1, const std::string& operand2) { switch (op) { case OperatorType::Eq: return operand1 == operand2; case OperatorType::Ne: return operand1 != operand2; case OperatorType::Lt: return operand1 < operand2; case OperatorType::Le: return operand1 <= operand2; case OperatorType::Gt: return operand1 > operand2; case OperatorType::Ge: return operand1 >= operand2; } return false; } std::string Interpreter::EvaluateStringPostfix(std::string postfix) { Stack stack; std::string result{}; std::string word{}; std::istringstream iss{ postfix }; std::string stringValue{}; while (iss >> word) { WordType wordType{}; if (word.front() == '"') { stringValue = word; while (stringValue.back() != '"' || stringValue.size() < 2) { iss >> word; stringValue += ' ' + word; } wordType = GetWordType(stringValue); } else wordType = GetWordType(word); if (!Operator::IsOperator(word)) { switch (wordType) { case WordType::String: stack.Push(stringValue); break; case WordType::Number: stack.Push(word); break; case WordType::Variable: { VariableType varType = Variable::GetVariableType(word); switch (varType) { case VariableType::Integer: if (m_IntHolder.Find(word)) stack.Push(std::to_string(m_IntHolder.GetValue(word))); else ERROR("'" + word + "' is not defined!"); break; case VariableType::Real: if (m_RealHolder.Find(word)) stack.Push(std::to_string(m_RealHolder.GetValue(word))); else ERROR("'" + word + "' is not defined!"); break; case VariableType::String: if (m_StringHolder.Find(word)) stack.Push(m_StringHolder.GetValue(word)); else ERROR("'" + word + "' is not defined!"); break; } } break; } } else { std::string operand2 = stack.Peek(); stack.Pop(); std::string operand1 = stack.Peek(); stack.Pop(); result = operand1 + operand2; stack.Push(result); } } return result; } bool Interpreter::EvaluateStringOperatorPostfix(std::string postfix) { Stack stack; bool result{ false }; std::string word{}; std::istringstream iss{ postfix }; std::string stringValue{}; while (iss >> word) { WordType wordType{}; if (word.front() == '"') { stringValue = word; while (stringValue.back() != '"' || stringValue.size() < 2) { iss >> word; stringValue += ' ' + word; } wordType = GetWordType(stringValue); } else wordType = GetWordType(word); if (!Operator::IsOperator(word)) { switch (wordType) { case WordType::String: { std::string str{ stringValue }; str.erase(std::remove(str.begin(), str.end(), '"'), str.end()); stack.Push(str); break; } case WordType::Number: stack.Push(word); break; case WordType::Variable: { VariableType varType = Variable::GetVariableType(word); switch (varType) { case VariableType::Integer: if (m_IntHolder.Find(word)) stack.Push(std::to_string(m_IntHolder.GetValue(word))); else ERROR("'" + word + "' is not defined!"); break; case VariableType::Real: if (m_RealHolder.Find(word)) stack.Push(std::to_string(m_RealHolder.GetValue(word))); else ERROR("'" + word + "' is not defined!"); break; case VariableType::String: if (m_StringHolder.Find(word)) stack.Push(m_StringHolder.GetValue(word)); else ERROR("'" + word + "' is not defined!"); break; } } break; } } else { OperatorType op = Operator::GetOperator(word); std::string operand2 = stack.Peek(); stack.Pop(); std::string operand1 = stack.Peek(); stack.Pop(); result = OperateRelational(op, operand1, operand2); stack.Push(std::to_string(result)); } } return result; } std::string Interpreter::Concatenate(std::string expression) { std::string result{}; std::string postfix = InfixToPostfix(expression); result = EvaluateStringPostfix(postfix); return result; } void Interpreter::ClearHolders() { m_IntHolder.Clear(); m_RealHolder.Clear(); m_StringHolder.Clear(); } void Interpreter::ClearStacks() { m_IntStack.Clear(); m_RealStack.Clear(); } WordType Interpreter::GetWordType(std::string word) { if (word == "=") return WordType::Invalid; if (Keyword::IsKeyword(word)) return WordType::Keyword; if (Variable::IsVariable(word)) return WordType::Variable; if (IsNumber(word)) return WordType::Number; if (IsString(word)) return WordType::String; if (Operator::IsOperator(word)) return WordType::Operator; return WordType::Invalid; } std::string Interpreter::GetExpression(std::istringstream& iss) { std::string expression{}; std::getline(iss, expression); if (!expression.empty() && expression.front() == ' ') expression.erase(expression.begin()); // erase front whitespace return expression; } std::string Interpreter::GetLastError() { if (m_ErrorWord.front() == '.' && m_ErrorWord.back() == '.') return "'" + m_ErrorWord + "' is an invalid operator! Valid operators are: .add. .sub. .mul. .div. .or. .and. .not. .eq. .ne. .lt. .le. .gt. .ge."; for (const char& ch : m_ErrorWord) if (isdigit(ch)) return "'" + m_ErrorWord + "' is not a valid variable! Variables can only be letters a-z or A-Z."; return m_ErrorWord; } } include/ccbase/mpl/operations.hpp /* ** File Name: operations.hpp ** Author: ** Date: 08/05/2015 ** Contact: ** ** Definitions of arithmetic and logical operations. */ #ifndef Z1A37E0A0_607A_4903_8947_4A2FA4AD06BC #define Z1A37E0A0_607A_4903_8947_4A2FA4AD06BC namespace cc { namespace mpl { /* ** Arithmetic operations. */ #define mpl_define_binary_arithmetic_op(symbol, name) \ template \ using name = std::integral_constant< \ decltype(T::value symbol U::value), \ T::value symbol U::value \ >; #define mpl_make_nary_op(name) \ template \ using name = apply>, Ts...>; namespace detail { /* ** We first define the associative operations here, and then make the versions ** in the `mpl` namespace variadic. */ mpl_define_binary_arithmetic_op(+, plus) mpl_define_binary_arithmetic_op(*, multiplies) mpl_define_binary_arithmetic_op(&, bit_and) mpl_define_binary_arithmetic_op(|, bit_or) mpl_define_binary_arithmetic_op(^, bit_xor) } mpl_make_nary_op(plus) mpl_make_nary_op(multiplies) mpl_make_nary_op(bit_and) mpl_make_nary_op(bit_or) mpl_make_nary_op(bit_xor) mpl_define_binary_arithmetic_op(-, minus) mpl_define_binary_arithmetic_op(/, divides) mpl_define_binary_arithmetic_op(%, modulus) mpl_define_binary_arithmetic_op(<<, left_shift) #undef mpl_define_binary_arithmetic_op template using negate = std::integral_constant; template using bit_not = std::integral_constant; /* ** We need the help of a helper struct to implement right shift, in order to ** avoid a parsing error due to the `>>` operator being interpreted as the end ** of the template alias declaration. Let me know if you find a more elegant ** workaround. */ namespace detail { template struct right_shift_helper { static constexpr auto value = (A >> B); }; } template using right_shift = std::integral_constant< decltype(T::value >> U::value), detail::right_shift_helper< typename T::type, typename U::type, T::value, U::value >::value >; template using inc = std::integral_constant, T::value + 1>; template using dec = std::integral_constant, T::value - 1>; namespace detail { template using min = std::conditional_t; template using max = std::conditional_t= B::value, A, B>; } mpl_make_nary_op(min) mpl_make_nary_op(max) /* ** Logical operations. */ #define mpl_define_binary_logical_op(symbol, name) \ template \ using name = std::integral_constant; namespace detail { mpl_define_binary_logical_op(&&, and_) mpl_define_binary_logical_op(||, or_) } #undef mpl_define_binary_logical_op // AKA `all_of`. mpl_make_nary_op(and_) // AKA `any_of`. mpl_make_nary_op(or_) #undef mpl_make_nary_op template using and_c = and_...>; template using or_c = or_...>; #define mpl_define_binary_relational_op(symbol, name) \ template \ using name = bool_<(T::value symbol U::value)>; mpl_define_binary_relational_op(==, equal_to) mpl_define_binary_relational_op(!=, not_equal_to) mpl_define_binary_relational_op(>, greater) mpl_define_binary_relational_op(>=, greater_equal) mpl_define_binary_relational_op(<, less) mpl_define_binary_relational_op(<=, less_equal) #undef mpl_define_binary_relational_op template using all_equal = apply>, Ts...>; template using not_ = bool_; /* ** Miscellaneous boolean traits. */ template using if_c = std::conditional_t; template using if_ = if_c; namespace detail { template struct is_same_helper; template struct is_same_helper : is_same_helper::value, T, Ts...> {}; template struct is_same_helper { using type = bool_; }; } /* ** We use template specialization instead of `fold` because the latter somehow ** results in an ICE on clang 3.6. I don't have the time to make an MWE now. */ template using is_same = _t>; }} #endif liftchampion/nativejson-benchmark // test_file_config.cpp #include #include #include extern "C" { # include "file_config.gperf" } static bool setIndex(UHashMap* pthis, const char* p, uint32_t sz) { U_TRACE(5, "setIndex(%p,%.*S,%u)", pthis, sz, p, sz) pthis->index = gperf_hash(p, sz); U_RETURN(false); } static void check(UFileConfig& y) { U_TRACE(5,"check()") U_ASSERT( y[U_STRING_FROM_CONSTANT("LOG_FILE")] == U_STRING_FROM_CONSTANT("ldap_update.log") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("LDAP_SERVER_ADDRESS")] == U_STRING_FROM_CONSTANT("10.10.15.1:389") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ROOT_DN")] == U_STRING_FROM_CONSTANT("o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ADMIN_DN")] == U_STRING_FROM_CONSTANT("cn=Manager,o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("PASSWORD")] == U_STRING_FROM_CONSTANT("secret") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("LDAP_SERVER_ADDRESS_MAIL")] == U_STRING_FROM_CONSTANT("10.10.15.1:389") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ROOT_DN_MAIL")] == U_STRING_FROM_CONSTANT("ou=Utenti,ou=e-family.it,o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ADMIN_DN_MAIL")] == U_STRING_FROM_CONSTANT("cn=Manager,o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("PASSWORD_MAIL")] == U_STRING_FROM_CONSTANT("secret") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MAILHOST")] == U_STRING_FROM_CONSTANT("mailsrv.bf.bnl.it") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MAILDELIVERYOPTION")] == U_STRING_FROM_CONSTANT("mailbox") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("FILE_WRONG_MESSAGE")] == U_STRING_FROM_CONSTANT("ldap_update.wrg") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MESSAGE_QUEUE_NAME")] == U_STRING_FROM_CONSTANT("LDAP.UPDATE.QUEUE") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MESSAGE_QUEUE_SERVER")] == U_STRING_FROM_CONSTANT("JAVA.CHANNEL/TCP/lobelia(1414)") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MESSAGE_QUEUE_MANAGER")] == U_STRING_FROM_CONSTANT("frontend") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("MAX_ERROR_FOR_CONNECT")] == U_STRING_FROM_CONSTANT("2") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("TIME_SLEEP_LDAP_ERROR")] == U_STRING_FROM_CONSTANT("10") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("TIME_SLEEP_MQSERIES_ERROR")] == U_STRING_FROM_CONSTANT("60") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("CHECK_QUOTING")] == U_STRING_FROM_CONSTANT("str = \"Manager of my caz\"...") ) } static void check1(UFileConfig& y) { U_TRACE(5,"check1()") // y.table.reserve(y.table.capacity() * 2); UString value = y.erase(U_STRING_FROM_CONSTANT("LDAP_SERVER_ADDRESS")); U_ASSERT( value == U_STRING_FROM_CONSTANT("10.10.15.1:389") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("LDAP_SERVER_ADDRESS")] == U_STRING_FROM_CONSTANT("") ) U_ASSERT( y.erase(U_STRING_FROM_CONSTANT("ROOT_DN")) == U_STRING_FROM_CONSTANT("o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ROOT_DN")] == U_STRING_FROM_CONSTANT("") ) U_ASSERT( y.erase(U_STRING_FROM_CONSTANT("ADMIN_DN")) == U_STRING_FROM_CONSTANT("cn=Manager,o=BNL,c=IT") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("ADMIN_DN")] == U_STRING_FROM_CONSTANT("") ) y.table.clear(); U_ASSERT( y.empty() == true ) U_ASSERT( y[U_STRING_FROM_CONSTANT("TIME_SLEEP_MQSERIES_ERROR")] == U_STRING_FROM_CONSTANT("") ) } static void check2(UFileConfig& y) { U_TRACE(5,"check2()") U_ASSERT( y.erase(U_STRING_FROM_CONSTANT("NOT_PRESENT")) == U_STRING_FROM_CONSTANT("") ) U_ASSERT( y[U_STRING_FROM_CONSTANT("NOT_PRESENT")] == U_STRING_FROM_CONSTANT("") ) y.table.insertAfterFind(U_STRING_FROM_CONSTANT("NOT_PRESENT"), U_STRING_FROM_CONSTANT("60M")); U_ASSERT( y[U_STRING_FROM_CONSTANT("NOT_PRESENT")] == U_STRING_FROM_CONSTANT("60M") ) UString value = y[U_STRING_FROM_CONSTANT("NOT_PRESENT")]; U_ASSERT( y.erase(U_STRING_FROM_CONSTANT("NOT_PRESENT")) == U_STRING_FROM_CONSTANT("60M") ) U_ASSERT( value == U_STRING_FROM_CONSTANT("60M") ) U_ASSERT( value.strtoul(true) == 60 * 1024 * 1024 ) U_ASSERT( value.strtoull(true) == 60LL * 1024LL * 1024LL ) } static bool print(UStringRep* key, void* value) { U_TRACE(5, "print(%V,%p)", key, value) cout << '\n'; cout.write(key->data(), key->size()); cout << " -> "; cout.write(((UStringRep*)value)->data(), ((UStringRep*)value)->size()); U_RETURN(true); } static bool cancella(UStringRep* key, void* value) { U_TRACE(5, "cancella(%V,%p)", key, value) static int cnt; if (++cnt & 1) U_RETURN(true); U_RETURN(false); } int U_EXPORT main (int argc, char* argv[], char* env[]) { U_ULIB_INIT(argv); U_TRACE(5,"main(%d)",argc) UFileConfig y; y.load(U_STRING_FROM_CONSTANT("inp/nodog.conf")); y.destroy(); y.table.setIndexFunction(setIndex); y.table.allocate(MAX_HASH_VALUE+1); y.load(U_STRING_FROM_CONSTANT("file_config.cf")); U_ASSERT( y.table.size() == TOTAL_KEYWORDS ) uint32_t n = 1; (void) y.table.first(); while (y.table.next()) ++n; U_ASSERT( n == TOTAL_KEYWORDS ) check(y); check1(y); y.table.setIgnoreCase(false); cin >> y.table; cout << y.table; UHashMap z, x; z.assign(y.table); cout << "\n" << z; x.assign(z); cout << "\n---------------------------"; z.callForAllEntrySorted(print); z.callWithDeleteForAllEntry(cancella); cout << "\n---------------------------"; z.callForAllEntrySorted(print); cout << "\n---------------------------"; z.clear(); check1(y); check2(y); y.destroy(); y.table.assign(x); x.clear(); // Time Consumed with num_iteration(10) = 543 ms n = (argc > 1 ? atoi(argv[1]) : 5); UCrono crono; crono.start(); for (int i = 0; i < (int)n; ++i) check(y); crono.stop(); check1(y); if (argc > 1) printf("\n# Time Consumed with num_iteration(%d) = %ld ms\n", n, crono.getTimeElapsed()); } EEnginE/engine /*! * \file x11/RandR/iRandR_crtc.cpp * \brief \b Classes: \a iRandR */ /* * Copyright (C) 2015 EEnginE project * * 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 "uLog.hpp" #include "iRandR.hpp" #define CODE(err) static_cast(lError->err) #define CHECK_ERROR(func, ret) \ if (lError) { \ eLOG("RandR: ", #func, " returned ", CODE(error_code), " -- ", CODE(major_code), ", ", CODE(minor_code)); \ free(lError); \ lError = nullptr; \ lNumErrors++; \ } \ if (!ret) { \ eLOG(#func, " returned a NULL pointer"); \ lNumErrors++; \ } using namespace e_engine; using namespace unix_x11; /*! * \brief Change one CRTC * * \returns -5 when the CRTC could not be found * \returns 1 when everything went fine */ int iRandR::changeCRTC(internal::_crtc _changeToThis) { xcb_randr_crtc_t lCRTC_XCB = _changeToThis.id; bool lChangedCRTC_B = false; xcb_generic_error_t *lError; bool lCRTCInfoFound = false; int lNumErrors = 0; for (int i = 0; i < vScreenResources_XCB->num_crtcs; ++i) { if (vCRTCs_XCB[i] == lCRTC_XCB) { lCRTCInfoFound = true; break; } } if (!lCRTCInfoFound) { wLOG("RandR: Cannot find CRTC ", lCRTC_XCB, " in the current CRTC --> return -5"); return -5; } auto lCrtcCookie = xcb_randr_get_crtc_info(vConnection_XCB, lCRTC_XCB, vScreenInfo_XCB->config_timestamp); auto *lCrtcInfo = xcb_randr_get_crtc_info_reply(vConnection_XCB, lCrtcCookie, &lError); CHECK_ERROR(xcb_randr_get_crtc_info, lCrtcInfo); if (lNumErrors != 0) { eLOG("RandR: Failed to get CRTC info of CRTC ", lCRTC_XCB); if (lCrtcInfo) free(lCrtcInfo); return -5; } xcb_randr_output_t *lOutputs = xcb_randr_get_crtc_info_outputs(lCrtcInfo); if (lCrtcInfo->mode != _changeToThis.mode || lCrtcInfo->num_outputs != static_cast(_changeToThis.outputs.size()) || lCrtcInfo->x != _changeToThis.posX || lCrtcInfo->y != _changeToThis.posY || lCrtcInfo->rotation != _changeToThis.rotation) { lChangedCRTC_B = true; } else { for (unsigned int i = 0; i < _changeToThis.outputs.size(); ++i) { if (lOutputs[i] != _changeToThis.outputs[i]) { lChangedCRTC_B = true; break; } } } if (lChangedCRTC_B) { if (_changeToThis.outputs.size() == 0 || _changeToThis.mode == XCB_NONE) { // Disable output auto lConfigCookie = xcb_randr_set_crtc_config(vConnection_XCB, lCRTC_XCB, XCB_CURRENT_TIME, XCB_CURRENT_TIME, 0, 0, XCB_NONE, XCB_RANDR_ROTATION_ROTATE_0, 0, nullptr); auto *lConfigResult = xcb_randr_set_crtc_config_reply(vConnection_XCB, lConfigCookie, &lError); CHECK_ERROR(xcb_randr_set_crtc_config, lConfigResult); if (lNumErrors == 0) { iLOG("RandR: Disabled CRTC ", _changeToThis.id); } else { eLOG("RandR: Failed to disable CRTC ", _changeToThis.id); } } else { xcb_randr_output_t *lTempOutputs = new xcb_randr_output_t[_changeToThis.outputs.size()]; for (unsigned int i = 0; i < _changeToThis.outputs.size(); ++i) { lTempOutputs[i] = _changeToThis.outputs[i]; } auto lConfigCookie = xcb_randr_set_crtc_config(vConnection_XCB, lCRTC_XCB, XCB_CURRENT_TIME, XCB_CURRENT_TIME, static_cast(_changeToThis.posX), static_cast(_changeToThis.posY), _changeToThis.mode, _changeToThis.rotation, static_cast(_changeToThis.outputs.size()), lTempOutputs); delete[] lTempOutputs; auto *lConfigResult = xcb_randr_set_crtc_config_reply(vConnection_XCB, lConfigCookie, &lError); CHECK_ERROR(xcb_randr_set_crtc_config, lConfigResult); if (lNumErrors == 0) { iLOG("RandR: Changed CRTC ", _changeToThis.id); } else { eLOG("RandR: Failed to change CRTC ", _changeToThis.id); } } } else { iLOG("RandR: Changed CRTC ", _changeToThis.id, " -- nothing to do"); } if (lCrtcInfo) free(lCrtcInfo); return (lNumErrors == 0) ? 1 : -10; } /* * The MIT License (MIT) * * Copyright (c) 2014-2017 by * * 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 "common.h" #include #include #include #include "Core.h" #include "Settings.h" #include "crashdump.h" int main(int argc, char *argv[]) { // dump handler registration #ifndef QT_DEBUG CrashDumpHandler dumpHandler(kInfoLevelSmall); dumpHandler.addToArchiveList(Settings::configFile().toStdWString()); #endif QApplication a(argc, argv); QApplication::setOrganizationName("Aleksei Ilin"); QApplication::setApplicationName("wwanEric"); QApplication::setWindowIcon(QIcon(":/icons/modem.png")); #ifdef QT_DEBUG a.addLibraryPath(a.applicationDirPath()); #else // this is needs to remove unnecessary QT_INSTALL path QStringList newLibraryPaths; newLibraryPaths << a.applicationDirPath(); a.setLibraryPaths(newLibraryPaths); #endif int returnValue = 0; // Core Core * core = new Core(); if (core->init()) { returnValue = a.exec(); } else { --returnValue; } core->tini(); if (returnValue) { Q_LOGEX(LOG_VERBOSE_ERROR, QString("Application return value: %1").arg(returnValue)); } delete core; return returnValue; } include/ignition/physics/DeclareJointType.hh /* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef IGNITION_PHYSICS_DECLAREJOINTTYPE_HH_ #define IGNITION_PHYSICS_DECLAREJOINTTYPE_HH_ #include #include /// \brief Given a joint type named CustomJointType, this macro creates the /// following classes: /// /// class CustomJointTypeCast /// - A Feature class that allows plain Joint objects to downcast themselves to /// CustomJointType, as long as it is truly an instance of a CustomJointType. /// This class provides the function Joint::CastToCustomJointType() when /// added to a Joint's FeatureList. /// /// template class CustomJointType /// - An Entity class that includes the API of both the plain Joint class and /// the CustomJointType, as defined by FeaturePolicy P and FeatureList F. /// /// template class CustomJointType3d /// template class CustomJointType2d /// template class CustomJointType3f /// template class CustomJointType2f /// - Similar to CustomJointType, except P is replaced with the predefined /// Feature Policies. /// /// Physics engine plugin developers must implement the virtual function /// /// \code /// ignition::physics::Identity CastToCustomJointType(const Identity &_id) const /// \endcode /// /// if their physics engine plugin wants to be able to provide CustomJointType /// features. #define IGN_PHYSICS_DECLARE_JOINT_TYPE(CustomJointType) \ DETAIL_IGN_PHYSICS_DECLARE_DERIVED_TYPE(Joint, CustomJointType) #endif 1-10 //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Implementation of CLogEvent // // $Workfile: $ // $Date: $ // //------------------------------------------------------------------------------------------------------ // $Log: $ // // $NoKeywords: $ //=============================================================================// #include #include #include #include "LogEvent.h" #include "util.h" #include "memdbg.h" //For debugging more than anything const char* CLogEvent::TypeNames[]= { {"No Type/Invalid!"}, {"Log File Initialize"}, {"Server Spawn"}, {"Server Shutdown"}, {"Log Closed"}, {"Server Misc"}, {"Server Name"}, {"Team Rename"}, {"Level Change"}, {"Cvar Assignment"}, {"Map CRC"}, {"Team Join"}, {"Connect"}, {"Enter game"}, {"Disconnect"}, {"Name Change"}, {"Frag!"}, {"Team frag!"}, {"Suicide!"}, {"Killed by world!"}, {"Build"}, {"Match Results Marker"}, {"Match Draw"}, {"Match Victor"}, {"Match Team Results"}, {"Talk"}, {"Team Talk"}, {"Cure"}, {"Named Goal Activated"}, {"Anon Goal Activated"}, {"Named Broadcast"}, {"Anon Broadcast"}, {"Change Class"}, }; //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::getArgument // Purpose: returns the iWhichArg'th argument // Input: iWhichArg - the desired argument // Output: const CLogEventArgument* //------------------------------------------------------------------------------------------------------ const CLogEventArgument* CLogEvent::getArgument(int iWhichArg) const { if (iWhichArg < m_args.size()) return m_args[iWhichArg]; else return NULL; } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::parseArgs // Purpose: extracts the arguments out of the event text. //------------------------------------------------------------------------------------------------------ void CLogEvent::parseArgs() { char temp[512]; char* write=temp; const char* read=m_EventMessage; int i=0; while (*read) { if (*read == '\"') { //parseArgument moves the read pointer to the char after the closing " parseArgument(++read); *(write++)='['; *(write++)=(char)(i++)+48; //convert int to char by adding 48 *(write++)=']'; } else *write++=*read; *read++; } *write=0; Util::str2lowercase(temp,temp); m_StrippedText=new TRACKED char[strlen(temp)+1]; strcpy(m_StrippedText,temp); } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::parseArgument // Purpose: helper function for parseArgs, this actually removes the argument // Input: raw - the string from which we want to remove the argument //------------------------------------------------------------------------------------------------------ void CLogEvent::parseArgument(const char*& raw) { char* atemp; if (!(atemp=strchr(raw,'\"'))) return; *atemp=0; //null out the closing " CLogEventArgument* newarg=new CLogEventArgument(raw); newarg->init(raw); m_args.push_back(newarg); *atemp='\"'; //restore it. raw=atemp; //advance the pointer } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::keywordsOccur // Purpose: tests to see if all of the given keywords occur in the text for this event // Input: s1 - first keyword (required) // s2 - second keyword (optional) // s3 - third keyword (optional) // Output: Returns true if the event text contains all of the keywords passed in //------------------------------------------------------------------------------------------------------ bool CLogEvent::keywordsOccur(char* s1,char* s2,char* s3) { bool result=(strstr(m_StrippedText,s1)!=NULL); if (s2) { result = result && (strstr(m_StrippedText,s2)!=NULL); if (s3) { result = result && (strstr(m_StrippedText,s3)!=NULL); } } return result; } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::determineType // Purpose: this is a big dumb if statement to determine the type of this event //------------------------------------------------------------------------------------------------------ //this is pretty cheesy void CLogEvent::determineType() { //for now just do this in a big dumb if statement if (keywordsOccur("killed","self","with")) m_EventType=SUICIDE; else if (keywordsOccur("log closed")) m_EventType=LOG_CLOSED; else if (keywordsOccur("server name is")) m_EventType=SERVER_NAME; else if (keywordsOccur("team name of")) m_EventType=TEAM_RENAME; else if (keywordsOccur("killed","by","world")) m_EventType=KILLED_BY_WORLD; else if (keywordsOccur("killed","(teammate)")) m_EventType=TEAM_FRAG; else if (keywordsOccur("killed","with")) m_EventType=FRAG; else if (keywordsOccur("say_team")) m_EventType=SAY_TEAM; else if (keywordsOccur("say")) m_EventType=SAY; else if (keywordsOccur("joined team")) m_EventType=TEAM_JOIN; else if (keywordsOccur("changed to team")) m_EventType=TEAM_JOIN; else if (keywordsOccur("log file started")) m_EventType=LOG_FILE_INIT; else if (keywordsOccur("spawning server")) m_EventType=SERVER_SPAWN; else if (keywordsOccur("connected","address")) m_EventType=CONNECT; else if (keywordsOccur("has entered the game")) m_EventType=ENTER_GAME; else if (keywordsOccur("disconnected")) m_EventType=DISCONNECT; else if (keywordsOccur("changed name to")) m_EventType=NAME_CHANGE; else if (keywordsOccur("built")) m_EventType=BUILD; else if (keywordsOccur("map crc")) m_EventType=MAP_CRC; else if (keywordsOccur("match","results","=------=")) m_EventType=MATCH_RESULTS_MARKER; else if (keywordsOccur("activated the goal")) m_EventType=NAMED_GOAL_ACTIVATE; else if (keywordsOccur("goal", "was activated")) m_EventType=ANON_GOAL_ACTIVATE; else if (keywordsOccur("named broadcast")) m_EventType=NAMED_BROADCAST; else if (keywordsOccur("broadcast")) m_EventType=ANON_BROADCAST; else if (keywordsOccur("changed class")) m_EventType=CLASS_CHANGE; else if (keywordsOccur("-> draw <-")) m_EventType=MATCH_DRAW; else if (keywordsOccur("defeated")) m_EventType=MATCH_VICTOR; else if (keywordsOccur("results")) m_EventType=MATCH_TEAM_RESULTS; else if (keywordsOccur("=")) m_EventType=CVAR_ASSIGN; else m_EventType=SERVER_MISC; } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::CLogEvent // Purpose: CLogEvent constructor //------------------------------------------------------------------------------------------------------ CLogEvent::CLogEvent() :m_EventCode('\0'),m_EventTime(0),m_Valid(false),m_Next(NULL),m_StrippedText(NULL),m_EventType(INVALID),m_EventMessage(NULL) {} //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::~CLogEvent // Purpose: CLogEvent destructor //------------------------------------------------------------------------------------------------------ CLogEvent::~CLogEvent() { //this errors?! if (m_EventMessage) delete[] m_EventMessage; if (m_StrippedText) delete[] m_StrippedText; } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::print // Purpose: debugging function, prints this event to a file // Input: f - the file to print to //------------------------------------------------------------------------------------------------------ void CLogEvent::print(FILE* f) { fprintf(f,"(%li) Event: %s\n",m_EventTime,m_EventMessage); } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::CLogEvent // Purpose: CLogEvent constructor that reads an event from the specified file // Input: f - the file to read from //------------------------------------------------------------------------------------------------------ CLogEvent::CLogEvent(FILE* f) :m_EventCode('\0'),m_EventTime(0),m_Valid(false),m_Next(NULL),m_StrippedText(NULL),m_EventType(INVALID),m_EventMessage(NULL) { readEvent(f); } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::readEvent // Purpose: reads an event by reading each part, then checking if it was successful // Input: f - the file to read from //------------------------------------------------------------------------------------------------------ void CLogEvent::readEvent(FILE* f) { m_Valid=true; if (m_Valid) readEventCode(f); if (m_Valid) readEventTime(f); if (m_Valid) readEventMessage(f); if (m_Valid) parseArgs(); if (m_Valid) determineType(); if (m_Valid) m_Valid=!feof(f); } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::readEventCode // Purpose: reads the event code, the first character on the line (should be 'L') // Input: f - the file to read from //------------------------------------------------------------------------------------------------------ void CLogEvent::readEventCode(FILE* f) { fscanf(f," %c ",&m_EventCode); if (m_EventCode!='L') m_Valid=false; if (feof(f)) m_Valid=false; } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::readEventMessage // Purpose: reads the text of the event message. // Input: f - the file to read from //------------------------------------------------------------------------------------------------------ void CLogEvent::readEventMessage(FILE* f) { char temp[512]; fgets(temp,512,f); //special case hack for broadcasts if (strncmp(temp,"Named Broadcast:",16)==0 || strncmp(temp,"Broadcast:",16)==0) { while(1) { fpos_t temp_pos; fgetpos(f,&temp_pos); CLogEvent cle(f); fseek(f,temp_pos,SEEK_SET); if (cle.isValid()) { //if the next log event is valid, then this broadcast did not span lines break; } else { temp[strlen(temp)-1]=' '; //rid ourselves of newline temp[strlen(temp)]=0; //rid ourselves of newline char buf[512]; fgets(buf,512,f); strcat(temp,buf); } } } if (feof(f)) { m_Valid=false; } else { temp[strlen(temp)-1]=0; //rid ourselves of newline m_EventMessage=new TRACKED char[strlen(temp)+1]; strcpy(m_EventMessage,temp); } } //------------------------------------------------------------------------------------------------------ // Function: CLogEvent::readEventTime // Purpose: reads and converts the time the event happened into a time_t // Input: f - the file to read from //------------------------------------------------------------------------------------------------------ void CLogEvent::readEventTime(FILE* f) { int month=-1,day=-1,year=-1; int hour=-1,minute=-1,second=-1; fscanf(f," %d/%d/%d - %d:%d:%d: ",&month,&day,&year,&hour,&minute,&second); if (month==-1 ||day==-1 ||year==-1 || hour==-1 || minute==-1 || second==-1) m_Valid=false; else if (feof(f)) m_Valid=false; else { tm t; t.tm_isdst=0; t.tm_hour=hour; t.tm_mday=day; t.tm_min=minute; t.tm_sec=second; t.tm_year=year-1900; //note no y2k prob here, so says the CRT manual //this allows values greater than 99, but it //just wants the input with 1900 subtracted. t.tm_mon=month-1; //jan = 0 m_EventTime=mktime(&t); } } #pragma once #include "armory/character.hpp" #include "armory/guild.hpp"windowsbuild/MSVC2017/mfem/4.0/include/mfem/general/version.hpp // Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License (as published by the Free // Software Foundation) version 2.1 dated February 1999. #ifndef MFEM_VERSION_HPP #define MFEM_VERSION_HPP namespace mfem { int GetVersion(); int GetVersionMajor(); int GetVersionMinor(); int GetVersionPatch(); const char *GetVersionStr(); const char *GetGitStr(); const char *GetConfigStr(); } // namespace mfem #endif #include #include using namespace::std; class Solution { public: int maxSubArray(vector& nums) { vector res; res = findMaxSubArray(nums, 0, nums.size() - 1); return res[2]; } private: vector findMaxSubArray(vector& nums, int low, int high) { if (low == high) return { low, high, nums[low] }; else { int mid = (low + high) / 2; vector left = findMaxSubArray(nums, low, mid); vector right = findMaxSubArray(nums, mid + 1, high); vector cross = findMaxCrossSubArray(nums, low, mid, high); if (left[2] >= right[2] && left[2] >= cross[2]) return left; else if (right[2] >= left[2] && right[2] >= cross[2]) return right; else return cross; } } vector findMaxCrossSubArray(vector& nums, int low, int mid, int high) { int left_sum = INT_MIN, left_index = mid; int sum = 0; for (int i = mid; i >= low; --i) { sum += nums[i]; if (sum > left_sum) { left_sum = sum; left_index = i; } } int right_sum = INT_MIN, right_index = mid + 1; sum = 0; for (int i = mid + 1; i <= high; ++i) { sum += nums[i]; if (sum > right_sum) { right_sum = sum; right_index = i; } } return { left_index, right_index, left_sum + right_sum }; } }; int main() { vector nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; Solution sol; cout << sol.maxSubArray(nums) << endl; return 0; }smacc_client_library/smacc_navigation/backward_global_planner/src/backward_global_planner.cpp /***************************************************************************************************************** * ReelRobotix Inc. - Software License Agreement Copyright (c) 2018 * Authors: , * ******************************************************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //register this planner as a BaseGlobalPlanner plugin PLUGINLIB_EXPORT_CLASS(backward_global_planner::BackwardGlobalPlanner, nav_core::BaseGlobalPlanner); namespace backward_global_planner { /** ****************************************************************************************************************** * Constructor() ****************************************************************************************************************** */ BackwardGlobalPlanner::BackwardGlobalPlanner() { skip_straight_motion_distance_=0.2; } BackwardGlobalPlanner::~BackwardGlobalPlanner() { //clear nav_msgs::Path planMsg; planMsg.header.stamp = ros::Time::now(); planPub_.publish(planMsg); } /** ****************************************************************************************************************** * initialize() ****************************************************************************************************************** */ void BackwardGlobalPlanner::initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros) { //ROS_INFO_NAMED("Backwards", "BackwardGlobalPlanner initialize"); costmap_ros_ = costmap_ros; //ROS_WARN_NAMED("Backwards", "initializating global planner, costmap address: %ld", (long)costmap_ros); forwardPathSub_ = nh_.subscribe("odom_tracker_path", 2, &BackwardGlobalPlanner::onForwardTrailMsg, this); ros::NodeHandle nh; cmd_server_ = nh.advertiseService("cmd", boost::bind(&BackwardGlobalPlanner::commandServiceCall,this,_1,_2)); planPub_ = nh.advertise("backward_planner/global_plan", 1); markersPub_ = nh.advertise("backward_planner/markers", 1); } /** ****************************************************************************************************************** * onForwardTrailMsg() ****************************************************************************************************************** */ void BackwardGlobalPlanner::onForwardTrailMsg(const nav_msgs::Path::ConstPtr& trailMessage) { lastForwardPathMsg_ = *trailMessage; } /** ****************************************************************************************************************** * publishGoalMarker() ****************************************************************************************************************** */ void BackwardGlobalPlanner::publishGoalMarker(const geometry_msgs::Pose& pose, double r, double g, double b) { double phi = tf::getYaw(pose.orientation); visualization_msgs::Marker marker; marker.header.frame_id = "/odom"; marker.header.stamp = ros::Time::now (); marker.ns = "my_namespace2"; marker.id = 0; marker.type = visualization_msgs::Marker::ARROW; marker.action = visualization_msgs::Marker::ADD; marker.scale.x=0.1; marker.scale.y=0.3; marker.scale.z=0.1; marker.color.a= 1.0; marker.color.r = r; marker.color.g = g; marker.color.b = b; geometry_msgs::Point start,end; start.x= pose.position.x; start.y =pose.position.y; end.x = pose.position.x + 0.5 * cos(phi); end.y = pose.position.y + 0.5 * sin(phi); marker.points.push_back(start); marker.points.push_back(end); visualization_msgs::MarkerArray ma; ma.markers.push_back(marker); markersPub_.publish(ma); } /** ****************************************************************************************************************** * createPureSpiningAndStragihtLineBackwardPath() ****************************************************************************************************************** */ bool BackwardGlobalPlanner::createPureSpiningAndStragihtLineBackwardPath(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector& plan) { //tf::Stamped tfpose; //ROS_WARN_NAMED("Backwards", "getting robot pose referencing costmap: %ld", (long)costmap_ros_); auto q = start.pose.orientation; double dx = start.pose.position.x - goal.pose.position.x ; double dy = start.pose.position.y - goal.pose.position.y ; double lenght = sqrt(dx*dx + dy*dy); geometry_msgs::PoseStamped prevState; if (lenght > skip_straight_motion_distance_) { // skip initial pure spinning and initial straight motion //ROS_INFO("1 - heading to goal position pure spinning"); double heading_direction = atan2(dy, dx) ; double startyaw = tf::getYaw(q); double offset = angles::shortest_angular_distance(startyaw, heading_direction); heading_direction = startyaw+offset; prevState = reel_path_tools::makePureSpinningSubPlan(start, heading_direction, plan, puresSpinningRadStep_); //ROS_INFO("2 - going forward keep orientation pure straight"); prevState = reel_path_tools::makePureStraightSubPlan(prevState, goal.pose.position, lenght, plan); } else { prevState = start; } } /** ****************************************************************************************************************** * defaultBackwardPath() ****************************************************************************************************************** */ bool BackwardGlobalPlanner::createDefaultBackwardPath(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector& plan) { auto q = start.pose.orientation; geometry_msgs::PoseStamped pose; pose = start; plan.push_back(pose); //ROS_WARN_NAMED("Backwards", "Iterating in last forward cord path"); int i=lastForwardPathMsg_.poses.size(); double mindist =std::numeric_limits::max(); int mindistindex = -1; geometry_msgs::Pose goalProjected; for (auto& p : lastForwardPathMsg_.poses | boost::adaptors::reversed) { pose = p; pose.header.frame_id = costmap_ros_->getGlobalFrameID(); pose.header.stamp = ros::Time::now(); double dx = pose.pose.position.x - goal.pose.position.x; double dy = pose.pose.position.y - goal.pose.position.y; double dist = sqrt(dx*dx + dy*dy); if(dist <= mindist) { mindistindex = i; mindist = dist; goalProjected = pose.pose; } i--; } if(mindistindex != -1) { for (int i = lastForwardPathMsg_.poses.size() -1 ; i>=mindistindex ;i--) { auto& pose = lastForwardPathMsg_.poses[i]; plan.push_back(pose); } } else { ROS_WARN_STREAM("Creating the backwards plan, it is not found any close trajectory point. Last forward path plan message size: " << lastForwardPathMsg_.poses.size()); } } /** ****************************************************************************************************************** * makePlan() ****************************************************************************************************************** */ bool BackwardGlobalPlanner::makePlan(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector& plan) { //ROS_WARN_NAMED("Backwards", "Backwards global planner: Generating global plan "); //ROS_WARN_NAMED("Backwards", "Clearing..."); plan.clear(); this->createDefaultBackwardPath(start, goal, plan); //this->createPureSpiningAndStragihtLineBackwardPath(start, goal, plan); //ROS_INFO_STREAM(" start - " << start); //ROS_INFO_STREAM(" end - " << goal.pose.position); //ROS_INFO("3 - heading to goal orientation"); //double goalOrientation = angles::normalize_angle(tf::getYaw(goal.pose.orientation)); //reel_path_tools::makePureSpinningSubPlan(prevState,goalOrientation,plan); //ROS_WARN_STREAM( "MAKE PLAN INVOKED, plan size:"<< plan.size()); publishGoalMarker(goal.pose,1.0,0,1.0); nav_msgs::Path planMsg; planMsg .poses = plan; planMsg.header.frame_id="/odom"; planPub_.publish(planMsg); // this was previously set to size() <= 1, but a plan with a single point is also a valid plan (the goal) if (plan.size() <=1) { ROS_INFO("cannot create backward plan"); return false; } else { return true; } } /** ****************************************************************************************************************** * makePlan() ****************************************************************************************************************** */ bool BackwardGlobalPlanner::makePlan(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector& plan, double& cost) { cost = 0; makePlan(start, goal, plan); return true; } /** ****************************************************************************************************************** * commandServiceCall() ****************************************************************************************************************** */ bool BackwardGlobalPlanner::commandServiceCall(backward_global_planner::command::Request &req, backward_global_planner::command::Response &res) { //ROS_INFO_NAMED("Backwards", "BackwardGlobalplanner SERVICE CALL"); std::string msg = req.cmd.data.c_str(); std::vector fields; // Create a vector of strings, called "fields" boost::split(fields, msg, boost::algorithm::is_any_of(" ")); //ROS_INFO_NAMED("Backwards", "backward planner SERVICE REQUEST"); if(fields.size() == 0 ) { res.success.data = false; return false; } std::string cmd = fields[0]; bool error = false; if(cmd == "savepath") { //ROS_INFO_NAMED("Backwards","SAVE PATH COMMAND"); if(fields.size() >1 ) { std::vector tail (fields.begin()+1, fields.end()); std::string filename = boost::algorithm::join(tail, " "); std::ofstream os; os.open(filename); os << lastForwardPathMsg_; os.close(); //ROS_INFO_STREAM("serialized path: " << lastForwardPathMsg_); } else { error = true; } } else if(cmd== "loadpath") { //ROS_INFO_NAMED("Backwards", "LOAD PATH COMMAND"); if(fields.size() >1 ) { std::vector tail (fields.begin()+1, fields.end()); std::string filename = boost::algorithm::join(tail, " "); std::ifstream ifs(filename); std::string alltext((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); nav_msgs::Path p; uint32_t serial_size = ros::serialization::serializationLength(p); boost::shared_array buffer (new uint8_t[serial_size]); ros::serialization::IStream stream(buffer.get(),serial_size); ros::serialization::deserialize(stream, p); //ROS_INFO_STREAM_NAMED("Backwards", "serialized path: " << p); lastForwardPathMsg_ = p; } else { error = true; } } else { res.success.data = false; return false; } res.success.data = error; return true; } }10-100 /* ************************************************************************************************************* */ /* */ /* GLIP-LIB */ /* OpenGL Image Processing LIBrary */ /* */ /* Author : */ /* LICENSE : MIT License */ /* Website : glip-lib.net */ /* */ /* File : LayoutLoader.hpp */ /* Original Date : December 22th 2011 */ /* */ /* Description : Layout Loader from files or strings. */ /* */ /* ************************************************************************************************************* */ /** * \file LayoutLoader.hpp * \brief Layout Loader from files or strings. * \author * \date December 22th 2011 **/ #ifndef __LAYOUT_LOADER_INCLUDE__ #define __LAYOUT_LOADER_INCLUDE__ #include #include "Core/LibTools.hpp" #include "Core/HdlTexture.hpp" #include "Core/Geometry.hpp" #include "Core/ShaderSource.hpp" #include "Core/Filter.hpp" #include "Core/Pipeline.hpp" #include "Modules/VanillaParser.hpp" #include "Modules/LayoutLoaderModules.hpp" namespace Glip { using namespace CoreGL; using namespace CorePipeline; namespace Modules { /** \enum Glip::Modules::LayoutLoaderKeyword \brief Keywords used by LayoutLoader and LayoutWriter. Use LayoutLoader::getKeyword() to get the actual string. **/ enum LayoutLoaderKeyword { KW_LL_TRUE, KW_LL_FALSE, KW_LL_FORMAT, KW_LL_SOURCE, KW_LL_FILTER_LAYOUT, KW_LL_PIPELINE_LAYOUT, KW_LL_PIPELINE_MAIN, KW_LL_INCLUDE, KW_LL_FILTER_INSTANCE, KW_LL_PIPELINE_INSTANCE, KW_LL_CONNECTION, KW_LL_INPUT_PORTS, KW_LL_OUTPUT_PORTS, KW_LL_THIS_PIPELINE, KW_LL_REQUIRED_FORMAT, KW_LL_REQUIRED_SOURCE, KW_LL_REQUIRED_GEOMETRY, KW_LL_REQUIRED_PIPELINE, KW_LL_INSERT, KW_LL_GEOMETRY, KW_LL_GRID_2D, KW_LL_GRID_3D, KW_LL_CUSTOM_MODEL, KW_LL_STANDARD_QUAD, KW_LL_VERTEX, KW_LL_ELEMENT, KW_LL_ADD_PATH, KW_LL_CALL, KW_LL_SAFE_CALL, KW_LL_UNIQUE, LL_NumKeywords, LL_UnknownKeyword }; /** \class LayoutLoader \brief Load and save pipelines layouts to file The LayoutLoader module enables you to use dynamic pipeline saved in a file or a standard string. It will create either a Glip::Core::PipelineLayout or a Glip::Core::Pipeline that you can use directly or combined with other pipeline structures. # Script Specifications ###### ## Structure
KEYWORD(argument0[, ...])
KEYWORD:name
KEYWORD
{
     body
}
KEYWORD:name
{
     body
}
KEYWORD(argument0[, ...])
{
     body
}
KEYWORD:name(argument0[, ...])
KEYWORD:name(argument0[, ...])
{
     body
}
These are the basic description structures the parser will attempt to match. ## Comments Comments are C++/C, both single line and multiple lines are valid. ## Unique
UNIQUE(identifier)
Protect a source from being loaded multiple times. Based on the identifier used.
ArgumentDescription
identifier Unique identifier for a source.
## Add path
ADD_PATH(path)
Add a specific path to the search pool.
ArgumentDescription
path Path to be added to the search pool. Separators are '/'.
## Include
INCLUDE(filename)
Include another file. All the elements declared after parsing this file becomes available. The main pipeline(s) are changed into (a) pipeline layout(s). The elements declared before this include request are available to the included pipeline script through requirements mechanism (the included have to require these elements to use them). The required elements having the same name as an element will be overwritten for the parsing of this included file.
ArgumentDescription
filename The filename of the file to be loaded. This file must also be a script file.
## Call
CALL:moduleName(argument0, argument1, [...])
{
     body
}
Enable the script to use predefined modules attached to this loader. These modules are implementing specific high-level functions. Each might request different arguments or some code in the body.
ArgumentDescription
name Name of the module to be called. This module must have been added to the current LayoutLoader.
argument0 First possible argument passed to the module.
argumentN ...
body Possible body, passed to the module.
For more information, refer to the modules documentation in Modules::LayoutLoaderModule and Modules::LayoutLoader::addModule. ## Format ### Format
TEXTURE_FORMAT:name(width, height, mode, depth)
TEXTURE_FORMAT:name(width, height, mode, depth[, minFiltering, maxFiltering, sWrapping, tWrapping, maxMipMapLevel])
Define a texture format (Core::HdlTextureFormat). The first line shows the minimum set of arguments required.
ArgumentDescription
name Name of the texture format created.
width Width in pixels of the format.
height Height in pixels of the format.
mode Mode of the format, among GL_RED, GL_LUMINANCE, GL_RGB, GL_RGBA, etc.
depth Depth of the format, among GL_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_FLOAT, etc.
minFilter = GL_NEAREST Minification filtering.
magFilter = GL_NEAREST Magnification filtering.
sWrapping = GL_CLAMP S Wrapping.
tWrapping = GL_CLAMP T Wrapping.
maxMipMapLevel = 0 Maximum MipMap level.
### Required Format
REQUIRED_FORMAT:name(requiredFormatName)
REQUIRED_FORMAT:name(requiredFormatName[, newWidth, newHeight, newMode, newDepth, newMinFilter, newMagFilter, newSWrapping, newTWrapping, newMaxMipMapLevel)
Define a texture format from a required resource. This enables the script to receive data from the program, as a dynamic specification.
ArgumentDescription
name Name of the texture format created.
requiredFormatName Name of the required format. Must be added to the LayoutLoader via LayoutLoader::addRequiredElement.
newWidth Replace the width (in pixels) of the original format. Use * to keep the original value.
newHeight Replace the height (in pixels) of the original format. Use * to keep the original value.
newMode Replace the mode of the original format. Use * to keep the original value.
newDepth Replace the depth of the original format. Use * to keep the original value.
newMinFilter Replace the minification filtering. Use * to keep the original value.
newMagFilter Replace the magnification filtering. Use * to keep the original value.
newSWrapping Replace the S Wrapping. Use * to keep the original value.
newTWrapping Replace the T Wrapping. Use * to keep the original value.
newMaxMipMapLevel = 0 Replace the Maximum MipMap level. Use * to keep the original value.
## Geometry ### Geometry
GEOMETRY:name(type[, argument0, ...])
Define a model, which can be used as the base drawing in a filter.
ArgumentDescription
name Name of the model.
type Type of the geometry. Can be GRID_2D, GRID_3D or CUSTOM_MODEL.
argument_0 Argument, depending on the choice of the geometry.
#### Grid2D
GEOMETRY:name(GRID_2D, width, height)
Create a 2D grid of dots.
ArgumentDescription
name Name of the model.
width Number of dots in the X direction.
height Number of dots in the Y direction.
#### Grid3D
GEOMETRY:name(GRID_3D, width, height, depth)
Create a 3D grid of dots.
ArgumentDescription
name Name of the model.
width Number of dots in the X direction.
height Number of dots in the Y direction.
depth Number of dots in the Z direction.
#### CustomModel
GEOMETRY:name(CUSTOM_MODEL, primitive, hasNormals, hasTexCoords)
{
     body
}
Create a custom geometry model.
ArgumentDescription
name Name of the model.
primitive Type of the primitive.
hasNormals If the VERTEX data will contain normals data. Either TRUE or FALSE.
hasTexCoords If the VERTEX data will contain the texture coordinates. Either TRUE or FALSE.
body Contains a description of the geometry, using VERTEX and ELEMENT.
##### Vertex
VERTEX(x, y[, nx, ny, u, v])
VERTEX(x, y, z[, nx, ny, nz, u, v])
Define a vertex. If the geometry was set to receive texture coordinates, the VERTEX data must have the U and V coordinates specified.
ArgumentDescription
x X Coordinate.
y Y Coordinate.
z Z Coordinate.
nx Normal X Component (must be skipped if hasNormals was FALSE).
ny Normal Y Component (must be skipped if hasNormals was FALSE).
nz Normal Z Component (must be skipped if hasNormals was FALSE).
u U Texture coordinate (must be skipped if hasTexCoords was FALSE).
v V Texture coordinate (must be skipped if hasTexCoords was FALSE).
##### Element
ELEMENT(a, [b, c, d])
Define an element. An element is the polygon structure or primitive defined for the current geometry model. Only using GL_POINT waive the requirement for defining elements. The number of elements indices needed depend on the number of vertices per element.
ArgumentDescription
a First vertex index.
b Second vertex index.
c Third vertex index.
d Fourth vertex index.
### Required Source
REQUIRED_SOURCE:name(requiredSourceName)
Define a source from a required source. This enables the script to receive data from the program, as a dynamic specification.
ArgumentDescription
name Name of the source to be created.
requiredSpourceName Name of the required source to use.
### Required Geometry
REQUIRED_GEOMETRY:name(requiredGeometryName)
Define a geometry model from a required geometry. This enables the script to receive data from the program, as a dynamic specification.
ArgumentDescription
name Name of the geometry to be created.
requiredGeometryName Name of the required geometry to use.
## Source And Inclusion ### Source
SOURCE:name
{
     code
}
SOURCE:name(filename)
Define a source code.
ArgumentDescription
name Name of the source.
code Source code.
filename Filename of the file to load the source code from. Will be checked against the search paths pool.
### Insert
INSERT(sourceName)
Insert a source inside this source. This keyword must be inside another SOURCE. This call must be on a single line, by itself (but possibly including comments).
ArgumentDescription
sourceName Name of the source segment to be inserted at the current position.
## Filter Layout ### Filter Layout
FILTER_LAYOUT:name(outputFormatName[, fragmentShaderSourceName])
FILTER_LAYOUT:name(outputFormatName[, fragmentShaderSourceName])
{
     extraOptions
}
Define a filter layout.
ArgumentDescription
name Name of the filter layout created.
outputFormatName Name of the format for the output.
fragmentShaderSourceName Name of the fragment shader source.
vertexShaderSourceName Name of the vertex shader source. Use DEFAULT_VERTEX_SHADER to get the default vertex shader.
geometryName Name of the geometry model.
extraOptions Set of shaders, among GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, GL_COMPUTE_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER. Specific Geometry model with GL_RENDER. Set of options for the filter layout : GL_CLEAR, GL_BLEND, GL_DEPTH_TEST
### Shaders
GL_VERTEX_SHADER(name)
GL_FRAGMENT_SHADER(name)
GL_COMPUTE_SHADER(name)
GL_TESS_CONTROL_SHADER(name)
GL_TESS_EVALUATION_SHADER(name)
GL_GEOMETRY_SHADER(name)
Add other shader sources to the filter.
ArgumentDescription
name Name of the ShaderSource to be used.
### Geometry Model
GL_RENDER(name)
Specify the GeometryModel to be used (default is a standard quad).
ArgumentDescription
name Name of the GeometryModel to be used.
### Clearing
GL_CLEAR(enabled)
Enable the clear operation before computing the filter.
ArgumentDescription
enabled Either TRUE or FALSE.
### Blending
GL_BLEND(sourceFactor, destinationFactor, blendingFunction)
Enable blending in the filter and setup the parameters.
ArgumentDescription
sourceFactor Blending factor for the source.
destinationFactor Blending factor for the destination.
blendingFunction Blending equation.
### Depth Test
GL_DEPTH_TEST(depthTestFunction)
ArgumentDescription
depthTestFunction Function for the depth test.
## Pipeline Layout ### Pipeline Layout
PIPELINE_LAYOUT:name
{
     elements
}
Define a pipeline layout.
ArgumentDescription
name Name of the pipeline layout.
elements List of the elements in the layout.
#### Input Ports
INPUT_PORTS(portName0 [, ...])
Define the input ports of a pipeline layout.
ArgumentDescription
portName0 Name of the first input port.
portNameN ...
#### Output Ports
OUTPUT_PORTS(portName0 [, ...])
Define the output ports of a pipeline layout.
ArgumentDescription
portName0 Name of the first output port.
portNameN ...
#### Filter Instance
FILTER_INSTANCE:name
FILTER_INSTANCE:name(filterLayoutName)
Define a filter instance within a pipeline layout.
ArgumentDescription
name Name of this instance.
filterLayoutName The name of the layout to use. If the argument is not given, it will use the name of the instance instead.
#### Pipeline Instance
PIPELINE_INSTANCE:name
PIPELINE_INSTANCE:name(pipelineLayoutName)
Define a pipeline instance within a pipeline layout.
ArgumentDescription
name Name of this instance.
pipelineLayoutName The name of the layout to use. If the argument is not given, it will use the name of the instance instead.
#### Connection
CONNECTION(elementOutName, outputPortName, elementInName, inputPortName)
Define a connection from an output port to an input port. The data will flow from the output port outputPortName of the element elementOutName to the input port inputPortName of the element elementInName. If no connections are given in pipeline layout, the loader will attempt an automatic connection with the rules of PipelineLayout::autoConnect().
ArgumentDescription
elementOutName Element name (pipeline or filter) or the keyword THIS to get from an input port of the containing layout.
outputPortName Port name.
elementInName Element name (pipeline or filter) or the keyword THIS to get from an output port of the containing layout.
inputPortName Port name.
### Required Pipeline
REQUIRED_PIPELINE:name(requiredPipelineName)
Define a pipeline layout from a required resource. This enables the script to receive data from the program, as a dynamic specification.
ArgumentDescription
name Name of the created layout.
requiredPipelineName Name of the required pipeline.
### Main Pipeline
MAIN_PIPELINE:name
{
     elements
}
MAIN_PIPELINE:name(basePipelineLayoutName)
{
     ports
}
Define the main pipeline layout defined in the script. If the script is included from another, this will be automatically changed to a pipeline layout. The higher script must contain such pipeline. In case of the layout inheritance, you must define the input and output ports names.
ArgumentDescription
name Name of the pipeline layout.
elements Elements in the layout. See PIPELINE_LAYOUT.
basePipelineLayoutName Inherit layout from the layout which has this name.
ports Names of the input and output ports. See INPUT_PORTS and OUTPUT_PORTS
# Script Example ############# ## Script #################### The following example is the a simple input to output copy with resize to 640x480 in RGB, 1 byte per component (whatever the input format is). \code // The output format (for the output texture). Note that the filtering parameters are of no use in this pipeline. They will be use in the next processing/display step : TEXTURE_FORMAT:format(640,480,GL_RGB,GL_UNSIGNED_BYTE,GL_LINEAR,GL_LINEAR) // The shader source (for more information, check the GLSL language specifications at http://www.opengl.org/documentation/glsl/) : SOURCE:SimpleCopySource { // Choose the right GLSL version : #version 130 uniform sampler2D textureInput; // input texture. out vec4 textureOutput; // output texture. void main() { // Get the input data : vec4 c = textureLod(textureInput, gl_TexCoord[0].st, 0.0); // Write the output data : textureOutput = c; } } // Declare the filter layout : FILTER_LAYOUT:SimpleCopyFilter(format, SimpleCopySource) // The filter layout will have one input port and one output port, which names are respectively textureInput and textureOutput. // This information is gathered from the shader source SimpleCopySource, by analyzing the variables declared as uniform sampler2D for inputs and out vec4 for outputs. PIPELINE_MAIN:SimpleCopyPipeline { // Declare some input and output ports for this pipeline : INPUT_PORTS(textureInput) OUTPUT_PORTS(textureOutput) // Declare one filter component : FILTER_INSTANCE:SimpleCopyFilter // Since the input and output port names we chose for the pipeline are the same as for the filter // then we don't need to do the connections (it will be made automatically). // However one can imagine replacing the previous code by : // //INPUT_PORTS(input) //OUTPUT_PORTS(output) // // In that case, we would have to declare the connections as : // //CONNECTION(THIS,input,SimpleCopyFilter,textureInput) //CONNECTION(SimpleCopyFilter,textureOutput,THIS,output) } \endcode ## Loading Code ############## The following code shows how to load a script with the API : \code try { // Load a PipelineLayout : LayoutLoader loader; PipelineLayout myLayout = loader.getPipelineLayout("./path/pipeline.ppl"); // use it : Pipeline* myPipeline1 = new Pipeline(myLayout,"Pipeline1"); Pipeline* myPipeline2 = new Pipeline(myLayout,"Pipeline2"); // For a single pipeline, the second string is the name of that particular instance : Pipeline* myPipelineU = loader.getPipeline("./path/otherPipeline.ppl", "myPipelineName"); // use them, see Glip::CorePipeline::Pipeline documentation... // Clean all : delete myPipeline1; delete myPipeline2; delete myPipelineU; } catch(Exception& e) { // If either the parsing of the script or the compilation of the shader(s) failed, you will receive a Glip::Exception. // You can probe Glip::Exception::getType() to check the type of the error (which might be Glip::Exception::ClientScriptException or Glip::Exception::ClientShaderException, possibly another). std::cout << "An exception was caught : " << std::endl; std::cout << e.what() << std::endl; } \endcode **/ class GLIP_API LayoutLoader { public : /** \struct PipelineScriptElements \brief Contains data about a script, possibly made before the load operation. WARNING : It does not explore included files which might lead to an incomplete list of requirements. **/ struct GLIP_API PipelineScriptElements { /// Unique identifier. std::string unique; /// Paths added by the script. std::vector addedPaths, /// File included by the script. includedFiles, /// Names of the formats required by the script. requiredFormats, /// Names of the sources required by the script. requiredSources, /// Names of the geometries required by the script. requiredGeometries, /// Names of the pipelines required by the script. requiredPipelines, /// Names of the modules called by the script. modulesCalls, /// Names of the formats contained in the script. formats, /// Names of the shader source code contained in the script. sources, /// Names of the geometries contained in the script. geometries, /// Names of the filter layouts contained in the script. filtersLayout, /// Names of the pipelines layout contained in the script. pipelines; /// List of the input ports for each pipeline contained in the script (same order as pipelines). std::vector< std::vector > pipelineInputs; /// List of the output ports for each pipeline contained in the script (same order as pipelines). std::vector< std::vector > pipelineOutputs; /// Name of the main pipeline contained in the script. std::string mainPipeline; /// List of the input ports for the main pipeline contained in the script. std::vector mainPipelineInputs, /// List of the output ports for the main pipeline contained in the script. mainPipelineOutputs; }; private : static const char* keywords[LL_NumKeywords]; bool isSubLoader; // Reading dynamic : std::string currentPath; std::vector dynamicPaths; std::vector associatedKeyword; std::vector uniqueList; std::map formatList; std::map sourceList; std::map geometryList; std::map filterList; std::map pipelineList; // Static : std::vector staticPaths; std::map requiredFormatList; std::map requiredSourceList; std::map requiredGeometryList; std::map requiredPipelineList; std::map modules; // Using pointers to avoid conflict between polymorphism and object slicing. // Tools : LayoutLoader(const LayoutLoader& master); LayoutLoaderKeyword getKeyword(const std::string& str); void clean(void); void classify(const std::vector& elements, std::vector& associatedKeywords); bool fileExists(const std::string& filename, std::string& source, const bool& test=false); void loadFile(const std::string& filename, std::string& content, std::string& usedPath); void preliminaryTests(const VanillaParserSpace::Element& e, const int& nameProperty, const int& minArguments, const int& maxArguments, const int& bodyProperty, const std::string& objectName); ShaderSource enhanceShaderSource(const std::string& str, const std::string& sourceName, const int& startLine=1); void append(LayoutLoader& subLoader); void appendPath(const VanillaParserSpace::Element& e); void includeFile(const VanillaParserSpace::Element& e); bool checkUnique(const VanillaParserSpace::Element& e); void buildRequiredFormat(const VanillaParserSpace::Element& e); void buildRequiredSource(const VanillaParserSpace::Element& e); void buildRequiredGeometry(const VanillaParserSpace::Element& e); void buildRequiredPipeline(const VanillaParserSpace::Element& e); void moduleCall(const VanillaParserSpace::Element& e, std::string& mainPipelineName, const bool safe=false); void buildFormat(const VanillaParserSpace::Element& e); void buildSource(const VanillaParserSpace::Element& e); void buildGeometry(const VanillaParserSpace::Element& e); void buildFilter(const VanillaParserSpace::Element& e); void buildPipeline(const VanillaParserSpace::Element& e); void process(const std::string& code, std::string& mainPipelineName, const std::string& sourceName, const int& startLine=1); void listPipelinePorts(const VanillaParserSpace::Element& e, std::vector& inputs, std::vector& outputs); public : LayoutLoader(void); virtual ~LayoutLoader(void); const std::vector& paths(void) const; void clearPaths(void); void addToPaths(std::string p); void addToPaths(const std::vector& paths); bool removeFromPaths(const std::string& p); AbstractPipelineLayout getPipelineLayout(const std::string& source, std::string sourceName="", const int& startLine=1); Pipeline* getPipeline(const std::string& source, std::string pipelineName="", std::string sourceName="", const int& startLine=1); void addRequiredElement(const std::string& name, const HdlAbstractTextureFormat& fmt, const bool& replace=true); bool hasRequiredFormat(const std::string& name) const; const HdlAbstractTextureFormat& getRequiredFormat(const std::string& name) const; int clearRequiredFormat(const std::string& name=""); int clearRequiredFormat(bool (*filter)(const std::string&)); void addRequiredElement(const std::string& name, const ShaderSource& src, const bool& replace=true); bool hasRequiredSource(const std::string& name) const; const ShaderSource& getRequiredSource(const std::string& name) const; int clearRequiredSource(const std::string& name=""); int clearRequiredSource(bool (*filter)(const std::string&)); void addRequiredElement(const std::string& name, const GeometryModel& mdl, const bool& replace=true); bool hasRequiredGeometry(const std::string& name) const; const GeometryModel& getRequiredGeometry(const std::string& name) const; int clearRequiredGeometry(const std::string& name=""); int clearRequiredGeometry(bool (*filter)(const std::string&)); void addRequiredElement(const std::string& name, AbstractPipelineLayout& layout, const bool& replace=true); bool hasRequiredPipeline(const std::string& name) const; const AbstractPipelineLayout& getRequiredPipelineLayout(const std::string& name) const; int clearRequiredPipelineLayout(const std::string& name=""); int clearRequiredPipelineLayout(bool (*filter)(const std::string&)); int clearRequiredElements(const std::string& name=""); int clearRequiredElements(bool (*filter)(const std::string&)); PipelineScriptElements listElements(const std::string& source, std::string sourceName="", const int& startLine=1); void addModule(LayoutLoaderModule* module, const bool& replace=false); bool hasModule(const LayoutLoaderModule* module) const; bool hasModule(const std::string& name) const; std::vector listModules(void) const; std::vector listModules(void); std::vector listModuleNames(void) const; const LayoutLoaderModule& module(const std::string& name) const; LayoutLoaderModule& module(const std::string& name); const LayoutLoaderModule* removeModule(const LayoutLoaderModule* module); LayoutLoaderModule* removeModule(const std::string& name); static const char* getKeyword(LayoutLoaderKeyword k); }; /** \class LayoutWriter \brief Get equivalent pipeline code from a pipeline layout. The layout writer enables you to write a pipeline to a Pipeline Script file. Note that the uniforms values might be lost at loading. In order to avoid this problem, you have to use a UniformsLoader to store and then load the correct profile (all the uniforms values). \code LayoutWriter writer; std::string code = writer(mainPipeline); // Or directly to the disk : writer.writeToFile(mainPipeline, "./myPipeline.ppl"); \endcode **/ class GLIP_API LayoutWriter { public : static VanillaParserSpace::Element write(const HdlAbstractTextureFormat& format, const std::string& name); static VanillaParserSpace::Element write(const ShaderSource& source, const std::string& name); static VanillaParserSpace::Element write(const GeometryModel& mdl, const std::string& name); private: VanillaParserSpace::Element write(const AbstractFilterLayout& fLayout); VanillaParserSpace::Element write(const AbstractPipelineLayout& pLayout, bool isMain=false); std::string code; public : LayoutWriter(void); virtual ~LayoutWriter(void); std::string getCode(const AbstractPipelineLayout& pipelineLayout); void writeToFile(const AbstractPipelineLayout& pipelineLayout, const std::string& filename); }; } } #endif KCF_TLD/KCFtld/src/opentld/main/Trajectory.cpp /* Copyright 2011 AIT Austrian Institute of Technology * * This file is part of OpenTLD. * * OpenTLD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenTLD 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 OpenTLD. If not, see . * */ #include "Trajectory.h" #include /** * @author */ using namespace std; namespace tld { Trajectory::Trajectory() : m_length(0) { } Trajectory::~Trajectory() { } void Trajectory::init(std::size_t length) { m_length = length; m_track_positions = vector(); m_track_colors = vector(); } void Trajectory::addPoint(CvPoint point, CvScalar color) { size_t length = m_track_positions.size(); // vectors aren't full if (length < m_length) { m_track_positions.push_back(point); m_track_colors.push_back(color); } else { // push element to the end m_track_positions.push_back(point); m_track_colors.push_back(color); // drop first element m_track_positions.erase(m_track_positions.begin()); m_track_colors.erase(m_track_colors.begin()); } } void Trajectory::drawTrajectory(IplImage * image) { CvPoint tempPoint; bool needSecondPoint = false; for (size_t i = 0; i < m_track_positions.size(); i++) { // try to find 1. point of the line if ((!needSecondPoint) && (m_track_positions[i].x != -1)) { tempPoint = m_track_positions[i]; needSecondPoint = true; // try to find 2. point of the line } else if (needSecondPoint && (m_track_positions[i].x != -1)) { cvLine(image, tempPoint, m_track_positions[i], m_track_colors[i], 2); tempPoint = m_track_positions[i]; } } } } #include "multibody/kinematic/world_point_evaluator.h" #include "solvers/constraint_factory.h" using drake::MatrixX; using drake::VectorX; using drake::math::RotationMatrix; using drake::multibody::Frame; using drake::multibody::MultibodyPlant; using drake::solvers::BoundingBoxConstraint; using drake::solvers::Constraint; using drake::systems::Context; using Eigen::Matrix3d; using Eigen::Vector3d; using std::shared_ptr; using std::vector; namespace dairlib { namespace multibody { template WorldPointEvaluator::WorldPointEvaluator(const MultibodyPlant& plant, Vector3d pt_A, const Frame& frame_A, const Matrix3d rotation, const Vector3d offset, std::vector active_directions) : KinematicEvaluator(plant, 3), pt_A_(pt_A), frame_A_(frame_A), offset_(offset), rotation_(rotation) { this->set_active_inds(active_directions); } template WorldPointEvaluator::WorldPointEvaluator( const MultibodyPlant& plant, Vector3d pt_A, const Frame& frame_A, const multibody::ViewFrame& view_frame, const Matrix3d rotation, const Vector3d offset, std::vector active_directions) : KinematicEvaluator(plant, 3), pt_A_(pt_A), frame_A_(frame_A), offset_(offset), rotation_(rotation), view_frame_(&view_frame) { this->set_active_inds(active_directions); } template WorldPointEvaluator::WorldPointEvaluator(const MultibodyPlant& plant, const Vector3d pt_A, const Frame& frame_A, const Vector3d normal, const Vector3d offset, bool tangent_active) : KinematicEvaluator(plant, 3), pt_A_(pt_A), frame_A_(frame_A), offset_(offset), rotation_(RotationMatrix::MakeFromOneVector(normal, 2)) { if (!tangent_active) { this->set_active_inds({2}); // only z is active } } template VectorX WorldPointEvaluator::EvalFull(const Context& context) const { VectorX pt_world(3); const drake::multibody::Frame& world = plant().world_frame(); plant().CalcPointsPositions(context, frame_A_, pt_A_.template cast(), world, &pt_world); return rotation_ * (pt_world - offset_); } template void WorldPointEvaluator::EvalFullJacobian( const Context& context, drake::EigenPtr> J) const { const drake::multibody::Frame& world = plant().world_frame(); // .template cast converts pt_A_, as a double, into type T plant().CalcJacobianTranslationalVelocity( context, drake::multibody::JacobianWrtVariable::kV, frame_A_, pt_A_.template cast(), world, world, J); if (view_frame_ == nullptr) { *J = rotation_ * (*J); } else { *J = view_frame_->CalcWorldToFrameRotation(plant(), context) * (rotation_ * (*J)); } } template VectorX WorldPointEvaluator::EvalFullJacobianDotTimesV( const Context& context) const { const drake::multibody::Frame& world = plant().world_frame(); MatrixX Jdot_times_V = plant().CalcBiasTranslationalAcceleration( context, drake::multibody::JacobianWrtVariable::kV, frame_A_, pt_A_.template cast(), world, world); if (view_frame_ == nullptr) { return rotation_ * Jdot_times_V; } else { return view_frame_->CalcWorldToFrameRotation(plant(), context) * (rotation_ * Jdot_times_V); } } template vector> WorldPointEvaluator::CreateConicFrictionConstraints() const { // The normal index is 2 vector> constraints; if (is_frictional_) { constraints.push_back( solvers::CreateConicFrictionConstraint(this->mu(), 2)); // Include redundant bounding box constraint Vector3d lb = Vector3d::Constant(-std::numeric_limits::infinity()); Vector3d ub = Vector3d::Constant(std::numeric_limits::infinity()); lb(2) = 0; constraints.push_back(std::make_shared(lb, ub)); } return constraints; } template vector> WorldPointEvaluator::CreateLinearFrictionConstraints(int num_faces) const { vector> constraints; // The normal index is 2 if (is_frictional_) { constraints.push_back( solvers::CreateLinearFrictionConstraint(this->mu(), num_faces, 2)); // Include redundant bounding box constraint Vector3d lb = Vector3d::Constant(-std::numeric_limits::infinity()); Vector3d ub = Vector3d::Constant(std::numeric_limits::infinity()); lb(2) = 0; constraints.push_back(std::make_shared(lb, ub)); } return constraints; } DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( class ::dairlib::multibody::WorldPointEvaluator) } // namespace multibody } // namespace dairlib#include using namespace std; main() { int w,h,n; cin>>w>>h>>n; int window[w]={0}; int x,a; for(int i=0;i>x>>a; for(int j=x;jw) break; else window[j]++; } int full=0,half=0; for(int i=0;iVanya112/BSUIR_Labs #pragma once #include #include "SpaceVehicle.h" const int SpaceVehicle::_engine_coefficient = 7500; const int SpaceVehicle::_mass_coefficient = 2000; SpaceVehicle::SpaceVehicle() { this->_sv_mass = 0; this->_engine_power = 0; } SpaceVehicle::SpaceVehicle(int sv_mass, int engine_power) { this->_sv_mass = sv_mass; this->_engine_power = engine_power; } SpaceVehicle::~SpaceVehicle(){ } int SpaceVehicle::get_sv_mass() { return this->_sv_mass; } int SpaceVehicle::get_engine_power() { return this->_engine_power; } int SpaceVehicle::computeCost() { return (_engine_coefficient * _engine_power) + (_sv_mass * _mass_coefficient); } void SpaceVehicle::show() { std::cout << "Mass (kg): " << this->_sv_mass << std::endl << "Engine power (Watt) : " << this->_engine_power << std::endl; }SuuyaaYeet/command-line-tetris #include #include #include #include #include #include "GameLogic/GameController.h" #include "GameLogic/Input/Keylistener.h" #include "Utilities/AnsiEscape.h" #include "GameLogic/Highscores/Highscore.h" #include "Utilities/MemoryLeakDetection.h" #include "Utilities/Utilities.h" #ifdef _WIN32 #include #endif /* Zeigt das Hauptmenü mit verschiedenen Optionen */ int ShowStartMenuSelect() { moveTo(0,0); clearScreen(); std::string selection; std::cout <<"Welcome to our Tetris project" << std::endl <<"Select what you want to do" << std::endl <<"1:\t Start a new game" << std::endl <<"2:\t View the highscores" << std::endl <<"0:\t Close the application" << std::endl; std::cin >> selection; auto res = -1; try { res = std::stoi(selection.c_str()); } catch(...) { } return res; } void AnimateString(std::string str, bool linebreak, int delay) { for (int i = 0; i < str.length(); i++) { std::cout << str[i] << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(delay)); } if (linebreak) { std::cout << std::endl; } } /* GameOver-Screen mit Informationen über das Spiel */ void ShowGameOver(const int score, const std::string name, const int level) { const auto tempScore = "Score: " + std::to_string(score); const auto tempLevel = "Level: " + std::to_string(level); const auto tempName = "Name: " + name; const auto* chName = tempName.c_str(); const auto* chScore = tempScore.c_str(); const auto* chLevel = tempLevel.c_str(); clearScreen(); moveTo(0,0); AnimateString(std::string("Game Over"), true, 200); AnimateString(std::string(chName), true, 50); AnimateString(std::string(chLevel), true, 50); AnimateString(std::string(chScore), true, 50); std::this_thread::sleep_for(std::chrono::milliseconds(4000)); } int main() { setupConsole(); restoreConsole(); #ifdef _WIN32 // Make utf8 vaible SetConsoleOutputCP(CP_UTF8); #endif while(const auto selection = ShowStartMenuSelect()) { switch (selection) { case 1:{ AnimateString(std::string("Insert your Name: "), true, 100); std::string name; std::cin >> name; replaceAll(name,",",""); replaceAll(name," ",""); auto* controller = new GameController(); auto* listener = new Keylistener(); listener->Stop(); listener->RegisterHandler(100, [controller]() {controller->RightKeyPressed();}); // d listener->RegisterHandler(-39, [controller]() {controller->RightKeyPressed();}); // right listener->RegisterHandler(97, [controller]() {controller->LeftKeyPressed();}); // a listener->RegisterHandler(-37, [controller]() {controller->LeftKeyPressed();}); // left listener->RegisterHandler(119, [controller]() {controller->UpKeyPressed();}); // w listener->RegisterHandler(-38, [controller]() {controller->UpKeyPressed();}); // up listener->RegisterHandler(98, [controller]() {controller->BKeyPressed();}); // b listener->RegisterHandler(115, [controller]() {controller->DownKeyPressed();}); // s listener->RegisterHandler(-40, [controller]() {controller->DownKeyPressed();}); // down listener->RegisterHandler(32, [controller]() {controller->SpaceKeyPressed();}); // space listener->StartMultithreaded(); std::thread game([controller, listener, name]() { controller->Start(); while (controller->IsGameRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); controller->Update(); } }); game.join(); listener->Stop(); controller->Stop(); const auto score = controller->GetScore(); const auto level = controller->GetLevel(); AddHighscore(score, name); ShowGameOver(score, name, level); showCursor(); delete controller; delete listener; break; } case 2: clearScreen(); moveTo(0,0); ShowHighscore(); std::this_thread::sleep_for(std::chrono::milliseconds(5000)); break; default: std::cout << "This is not a valid option\n"; break; } } #ifdef debug _CrtDumpMemoryLeaks(); #endif } He-Liu-ooo/Computer-Architecture-THUEE-2022-spring- /* * Copyright (c) 2012,2015,2018 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_PACKET_QUEUE_HH__ #define __MEM_PACKET_QUEUE_HH__ /** * @file * Declaration of a simple PacketQueue that is associated with * a port on which it attempts to send packets according to the time * stamp given to them at insertion. The packet queue is responsible * for the flow control of the port. */ #include #include "mem/port.hh" #include "sim/drain.hh" #include "sim/eventq.hh" /** * A packet queue is a class that holds deferred packets and later * sends them using the associated CPU-side port or memory-side port. */ class PacketQueue : public Drainable { private: /** A deferred packet, buffered to transmit later. */ class DeferredPacket { public: Tick tick; ///< The tick when the packet is ready to transmit PacketPtr pkt; ///< Pointer to the packet to transmit DeferredPacket(Tick t, PacketPtr p) : tick(t), pkt(p) {} }; typedef std::list DeferredPacketList; /** A list of outgoing packets. */ DeferredPacketList transmitList; /** The manager which is used for the event queue */ EventManager& em; /** Used to schedule sending of deferred packets. */ void processSendEvent(); /** Event used to call processSendEvent. */ EventFunctionWrapper sendEvent; /* * Optionally disable the sanity check * on the size of the transmitList. The * sanity check will be enabled by default. */ bool _disableSanityCheck; /** * if true, inserted packets have to be unconditionally scheduled * after the last packet in the queue that references the same * address */ bool forceOrder; protected: /** Label to use for print request packets label stack. */ const std::string label; /** Remember whether we're awaiting a retry. */ bool waitingOnRetry; /** Check whether we have a packet ready to go on the transmit list. */ bool deferredPacketReady() const { return !transmitList.empty() && transmitList.front().tick <= curTick(); } /** * Attempt to send a packet. Note that a subclass of the * PacketQueue can override this method and thus change the * behaviour (as done by the cache for the request queue). The * default implementation sends the head of the transmit list. The * caller must guarantee that the list is non-empty and that the * head packet is scheduled for curTick() (or earlier). */ virtual void sendDeferredPacket(); /** * Send a packet using the appropriate method for the specific * subclass (request, response or snoop response). */ virtual bool sendTiming(PacketPtr pkt) = 0; /** * Create a packet queue, linked to an event manager, and a label * that will be used for functional print request packets. * * @param _em Event manager used for scheduling this queue * @param _label Label to push on the label stack for print request packets * @param force_order Force insertion order for packets with same address * @param disable_sanity_check Flag used to disable the sanity check * on the size of the transmitList. The check is enabled by default. */ PacketQueue(EventManager& _em, const std::string& _label, const std::string& _sendEventName, bool force_order = false, bool disable_sanity_check = false); /** * Virtual desctructor since the class may be used as a base class. */ virtual ~PacketQueue(); public: /** * Provide a name to simplify debugging. * * @return A complete name, appended to module and port */ virtual const std::string name() const = 0; /** * Get the size of the queue. */ size_t size() const { return transmitList.size(); } /** * Get the next packet ready time. */ Tick deferredPacketReadyTime() const { return transmitList.empty() ? MaxTick : transmitList.front().tick; } /** * Check if a packet corresponding to the same address exists in the * queue. * * @param pkt The packet to compare against. * @param blk_size Block size in bytes. * @return Whether a corresponding packet is found. */ bool checkConflict(const PacketPtr pkt, const int blk_size) const; /** Check the list of buffered packets against the supplied * functional request. */ bool trySatisfyFunctional(PacketPtr pkt); /** * Schedule a send event if we are not already waiting for a * retry. If the requested time is before an already scheduled * send event, the event will be rescheduled. If MaxTick is * passed, no event is scheduled. Instead, if we are idle and * asked to drain then check and signal drained. * * @param when time to schedule an event */ void schedSendEvent(Tick when); /** * Add a packet to the transmit list, and schedule a send event. * * @param pkt Packet to send * @param when Absolute time (in ticks) to send packet */ void schedSendTiming(PacketPtr pkt, Tick when); /** * Retry sending a packet from the queue. Note that this is not * necessarily the same packet if something has been added with an * earlier time stamp. */ void retry(); /** * This allows a user to explicitly disable the sanity check * on the size of the transmitList, which is enabled by default. * Users must use this function to explicitly disable the sanity * check. */ void disableSanityCheck() { _disableSanityCheck = true; } DrainState drain() override; }; class ReqPacketQueue : public PacketQueue { protected: RequestPort& memSidePort; // Static definition so it can be called when constructing the parent // without us being completely initialized. static const std::string name(const RequestPort& memSidePort, const std::string& label) { return memSidePort.name() + "-" + label; } public: /** * Create a request packet queue, linked to an event manager, a * memory-side port, and a label that will be used for functional print * request packets. * * @param _em Event manager used for scheduling this queue * @param _mem_side_port Mem_side port used to send the packets * @param _label Label to push on the label stack for print request packets */ ReqPacketQueue(EventManager& _em, RequestPort& _mem_side_port, const std::string _label = "ReqPacketQueue"); virtual ~ReqPacketQueue() { } const std::string name() const { return name(memSidePort, label); } bool sendTiming(PacketPtr pkt); }; class SnoopRespPacketQueue : public PacketQueue { protected: RequestPort& memSidePort; // Static definition so it can be called when constructing the parent // without us being completely initialized. static const std::string name(const RequestPort& memSidePort, const std::string& label) { return memSidePort.name() + "-" + label; } public: /** * Create a snoop response packet queue, linked to an event * manager, a memory-side port, and a label that will be used for * functional print request packets. * * @param _em Event manager used for scheduling this queue * @param _mem_side_port memory-side port used to send the packets * @param force_order Force insertion order for packets with same address * @param _label Label to push on the label stack for print request packets */ SnoopRespPacketQueue(EventManager& _em, RequestPort& _mem_side_port, bool force_order = false, const std::string _label = "SnoopRespPacketQueue"); virtual ~SnoopRespPacketQueue() { } const std::string name() const { return name(memSidePort, label); } bool sendTiming(PacketPtr pkt); }; class RespPacketQueue : public PacketQueue { protected: ResponsePort& cpuSidePort; // Static definition so it can be called when constructing the parent // without us being completely initialized. static const std::string name(const ResponsePort& cpuSidePort, const std::string& label) { return cpuSidePort.name() + "-" + label; } public: /** * Create a response packet queue, linked to an event manager, a * CPU-side port, and a label that will be used for functional print * request packets. * * @param _em Event manager used for scheduling this queue * @param _cpu_side_port Cpu_side port used to send the packets * @param force_order Force insertion order for packets with same address * @param _label Label to push on the label stack for print request packets */ RespPacketQueue(EventManager& _em, ResponsePort& _cpu_side_port, bool force_order = false, const std::string _label = "RespPacketQueue"); virtual ~RespPacketQueue() { } const std::string name() const { return name(cpuSidePort, label); } bool sendTiming(PacketPtr pkt); }; #endif // __MEM_PACKET_QUEUE_HH__ viniciusmalloc/spoj-br /* Resolucao: Contar o numero de PAs no array. Ficar atento a restricao de que a razao e o anterior - o atual, somente. */ #include #include #include #include #include #include #include #include #include #define MAX 500 #define color 2 #define mp make_pair #define pb push_back using namespace std; typedef pair ii; typedef pair ib; typedef vector vi; typedef long long int64; const int INF = 0x3f3f3f3f; int64 a, b, n; int main() { scanf("%d", &n); int sub = INF, ant = INF, diff, cont = 0; for (int i = 0; i < n; ++i) { scanf("%d", &a); if (ant == INF) ant = a; else { diff = ant - a; ant = a; if (sub == INF) sub = diff; else if (sub != diff) { cont++; sub = INF; } } } printf("%d", cont + 1); return 0; } Support/graphics/vertexArrayObject.cpp #include #include #include static GLenum GetDataType(VertexArrayObject::DataType type) { switch (type) { case VertexArrayObject::HalfFloat: return GL_HALF_FLOAT; case VertexArrayObject::Float: return GL_FLOAT; case VertexArrayObject::Double: return GL_DOUBLE; case VertexArrayObject::Fixed: return GL_FIXED; case VertexArrayObject::Byte: return GL_BYTE; case VertexArrayObject::UByte: return GL_UNSIGNED_BYTE; case VertexArrayObject::Short: return GL_SHORT; case VertexArrayObject::UShort: return GL_UNSIGNED_SHORT; case VertexArrayObject::Int: return GL_INT; case VertexArrayObject::UInt: return GL_UNSIGNED_INT; default: throw GraphicsException(GL_INVALID_ENUM, "Invalid VertexArrayObject Type"); } } static bool IsIntegerDataType(VertexArrayObject::DataType type) { GLenum t = GetDataType(type); return t == GL_BYTE || t == GL_UNSIGNED_BYTE || t == GL_SHORT || t == GL_UNSIGNED_SHORT || t == GL_INT || t == GL_UNSIGNED_INT; } VertexArrayObject::VertexArrayObject() : _vao(0) { GL_CHECKED(glGenVertexArrays(1, &_vao)); } VertexArrayObject::~VertexArrayObject() { if (glIsVertexArray(_vao)) { glDeleteVertexArrays(1, &_vao); } } void VertexArrayObject::Begin() { GL_CHECKED(glBindVertexArray(_vao)); } void VertexArrayObject::End() { GL_CHECKED(glBindVertexArray(0)); } void VertexArrayObject::BindBuffer(int location, BufferObject &buffer, int size, DataType type, bool normalized, int stride, int offset) { GL_CHECKED(glEnableVertexAttribArray(location)); buffer.Begin(); if (IsIntegerDataType(type)) { GL_CHECKED(glVertexAttribIPointer(location, size, GetDataType(type), stride, (GLvoid *)offset)); } else { GL_CHECKED(glVertexAttribPointer(location, size, GetDataType(type), normalized ? GL_TRUE : GL_FALSE, stride, (GLvoid *)offset)); } buffer.End(); } void VertexArrayObject::DisableBuffer(int location) { GL_CHECKED(glDisableVertexAttribArray(location)); } wlin0511/Turtlebot_hockey_game #include "path_planning/path_planning.h" #include "angles/angles.h" PathPlanning::PathPlanning(){ } bool PathPlanning::init(ros::NodeHandle &nh) { // Ros node handle for the class nh_ = nh; stop_received_ = false; start_detection_ = false; start_game_ = false; localisation_ready_ = false; recognition_ready_ = false; comm_ready_ = false; angelina_connected_= false; odom_ready_ = false; scan_ready_ = false; cmd_received_= false; all_blocked_ = false; obst_avoidance_ready= false; puck_goal_is_set_= false; puck_in_front_=false; puck_grasped_=false; puck_placed_=false; puck_released_ =false; making_step_= false; work_with_blue_pucks_= false; problem_initialized_ =false; robot_blocked_=false; posts_stored_ = false; map_ready_ =false; all_nodes_ready_ =false; robot_unblocking_ =false; robot_out_out_= false; turning_done_send_ = false; puck_not_grasped_ = false; ready_sended = false; task_number_ =0; placed_puck_num_ = 0; chosen_puck_idx_ = 0; safety_ton_odom_.fromSec(-10.0); safety_ton_scan_.fromSec(-10.0); safety_ton_localisation_.fromSec(-10.0); safety_ton_recognition_.fromSec(-10.0); safety_ton_comm_.fromSec(-10.0); kc_= 0; kt_= 0; ke_= 0; kpre_= 0; cpre_= 0; map_x_lenght_ = 10.0; map_y_lenght_= 4.0; final_y_lenght_ = 5.2; final_x_lenght_= 1.5; // Initialize all subcribers, services and publishers sub_turtle_odom= nh_.subscribe("/odom", 10, &PathPlanning::getOdometry, this); sub_sim_turtle_odom = nh_.subscribe("/base_pose_ground_truth", 10, &PathPlanning::getSimOdometry, this); sub_laser_ = nh_.subscribe("/lidar_scan", 10, &PathPlanning::getScan, this); sub_stop_signal_ = nh_.subscribe("/stop_signal", 10, &PathPlanning::stopSignal, this); sub_angelina_connected_ = nh_.subscribe("/connected", 10, &PathPlanning::angelinaConnected, this); sub_objects_poses_ = nh_.subscribe("/object_recognition/objects_poses", 10, &PathPlanning::getRecognitionData, this); sub_localisation_poses_ = nh_.subscribe("/localisation/objects_poses", 10, &PathPlanning::getMapppingData, this); sub_localisation_alive_= nh_.subscribe("/localisation/localisation_alive", 10, &PathPlanning::localicsationAlive, this); srv_task_number_ = nh_.advertiseService("/path_planning/set_task_number", &PathPlanning::setTaskNumber, this); srv_des_pose_ = nh_.advertiseService("/path_planning/set_desired_pose", &PathPlanning::setDesiredPose, this); srv_send_color_= nh_.advertiseService("/path_planning/send_color", &PathPlanning::sendColor, this); srv_start_detection_= nh_.advertiseService("/path_planning/start_detection", &PathPlanning::startDetection, this); srv_start_game_= nh_.advertiseService("/path_planning/start_game", &PathPlanning::startGame, this); srv_posts_stored_ = nh_.advertiseService("/path_planning/posts_stored", &PathPlanning::postsStored, this); srv_set_map_dimensions_ = nh_.advertiseService("/path_planning/set_map_dimensions", &PathPlanning::setMapDimensions, this); client_report_goal_ = nh_.serviceClient("report_goal"); client_report_done_ = nh_.serviceClient("report_done"); client_report_ready_= nh_.serviceClient("report_ready"); client_turning_done_= nh_.serviceClient("/localisation/turning_done"); pub_report_alive_ = nh_.advertise("/path_planning/report_alive", 10); pub_puck_grasped_ = nh_.advertise("/path_planning/puck_grasped", 10); pub_cmd_vel_real_ = nh_.advertise("/mobile_base/commands/velocity", 10); pub_cmd_vel_sim_ = nh_.advertise("/cmd_vel", 10); ///SIM // SIM default transformation somewhere in the middle of the field for start pucks_frames_m_.push_back( KDL::Frame2( KDL::Rotation2(0), KDL::Vector2(1.40, 2.0))); pucks_frames_m_.push_back( KDL::Frame2( KDL::Rotation2(0), KDL::Vector2(1.40, 1.5))); pucks_frames_m_.push_back( KDL::Frame2( KDL::Rotation2(0), KDL::Vector2(1.40, 1.0))); Fmf_ = KDL::Frame2( KDL::Rotation2(0), KDL::Vector2(3.2, 1.4)); Fmp_ = KDL::Frame2( KDL::Rotation2(0), KDL::Vector2(2.0, 1.5)); ROS_INFO ("PathPlanning is initialized"); return true; } void PathPlanning::update(const ros::Time& time, const ros::Duration& period){ // Safety timers odom_ready_= ((ros::Time::now()- safety_ton_odom_).toSec()< 2.0)? true : false; if (!odom_ready_) ROS_WARN("Odometry topic is no longer available"); scan_ready_= ((ros::Time::now()- safety_ton_scan_).toSec()< 2.0)? true : false; if (!scan_ready_) ROS_WARN("Scan topic is no available"); localisation_ready_= ((ros::Time::now()- safety_ton_localisation_).toSec()< 2.0)? true : false; ///SIM if (!localisation_ready_) ROS_WARN("Localisation node is no longer available"); recognition_ready_= ((ros::Time::now()- safety_ton_recognition_).toSec()< 2.0)? true : false; if (!recognition_ready_) ROS_WARN("Recognition node is no longer available"); ///SIM comm_ready_= ((ros::Time::now()- safety_ton_comm_).toSec()< 2.0)? true : false; if (!comm_ready_) ROS_WARN("Comm node is no longer available"); ///SIM ////////////////////////////////SIM ////////////////////////////////// // recognition_ready_ = true; // localisation_ready_ = true; // comm_ready_ = true; // angelina_connected_= true; ////////////////////////////////////////////////////////////////////// all_nodes_ready_ = (odom_ready_ && scan_ready_ && localisation_ready_ && recognition_ready_ && comm_ready_); if(scan_ready_ && odom_ready_){ if (cmd_received_){ /// DEBUG std::cout << "Fmr_: x: "< (ROBOT_RADIUS + PUCK_LOWER_RADIUS + 0.10) && !puck_not_grasped_){ puck_not_grasped_ =true; puck_grasped_ton_= ros::Time::now(); } else{ puck_not_grasped_ =false; } if (puck_not_grasped_ && (ros::Time::now()- puck_grasped_ton_).toSec() > 5.0){ puck_goal_is_set_ = false; puck_in_front_ =false; puck_grasped_= false; puck_placed_= false; puck_released_= false; } inFieldCheck(); //proximityCheck(); } } if (stop_received_ || !angelina_connected_ || !all_nodes_ready_){ moveToPose(KDL::Frame2::Identity(), KDL::Frame2::Identity(), 0.2*V_MAX, 0.1*M_PI, 0.04); // Stop ROS_WARN("Robot is stoped 0"); problem_initialized_ =false; making_step_=false; } // publish grasped puck flag to locallization std_msgs::Bool msg_puck_grasped; msg_puck_grasped.data = (puck_grasped_ && !puck_placed_); pub_puck_grasped_.publish(msg_puck_grasped); // publish robot ready alive signal for angelina if (!all_nodes_ready_){ angelina_ready_ton_ = ros::Time::now(); } else if ((ros::Time::now() - angelina_ready_ton_).toSec() > 5.0){ angelina_ready_ton_ = ros::Time::now(); std_msgs::Bool msg_ready; msg_ready.data = all_nodes_ready_; pub_report_alive_.publish(msg_ready); } // Send ready bool_req_.request.data = (all_nodes_ready_ && scan_ready_ && odom_ready_); if(angelina_connected_ && bool_req_.request.data && !ready_sended){ if (client_report_ready_.call(bool_req_) ){ ready_sended =true; } else ROS_ERROR("Failed to call service report ready"); } // Publish the command velocity pub_cmd_vel_real_.publish(cmd_msg_); pub_cmd_vel_sim_.publish(cmd_msg_); } bool PathPlanning::setDesiredPose( path_planning::SetPose::Request &req ,path_planning::SetPose::Response &res){ desFmr_= KDL::Frame2( KDL::Rotation2(req.des_pose.theta), KDL::Vector2(req.des_pose.x, req.des_pose.y)); /// TEST cmd_received_ =true; res.send = true; return true; } bool PathPlanning::setTaskNumber( path_planning::SetTask::Request &req ,path_planning::SetTask::Response &res){ if ((long int)req.task_number < 5 && (long int)req.task_number >= 0){ ROS_INFO("requested task: %ld", (long int)req.task_number); task_number_ = (long int)req.task_number; if (task_number_ == 1) ROS_INFO("Do task: %ld", (long int)req.task_number); else { ROS_INFO("Do task: %ld", (long int)req.task_number); } } else{ ROS_INFO("requested task: %ld is out of range [1-4]",(long int)req.task_number); } res.send =true; return true; } bool PathPlanning::sendColor(std_srvs::SetBool::Request &req , std_srvs::SetBool::Response &res){ work_with_blue_pucks_= req.data; if (work_with_blue_pucks_) ROS_INFO("Received color: blue"); else ROS_INFO("Received color: yellow"); res.success =true; res.message = std::string("Send color service responsed"); return true; } bool PathPlanning::startDetection(std_srvs::SetBool::Request &req ,std_srvs::SetBool::Response &res){ if (req.data){ stop_received_ = false; start_game_ = false; start_detection_ = true; rotation_step_ = 0; detection_step_ =0; ROS_INFO("Start detection request received"); exploration_start_time = ros::Time::now(); Fs_exp_init_ =Fsr_; } res.success =true; res.message = std::string("Start detection service responsed"); return true; } bool PathPlanning::startGame(std_srvs::SetBool::Request &req ,std_srvs::SetBool::Response &res){ if (req.data){ stop_received_ = false; start_game_ = true; start_detection_ = false; ROS_INFO("Start game request received"); } res.success =true; res.message = std::string("Start game service responsed"); return true; } bool PathPlanning::postsStored(std_srvs::SetBool::Request &req ,std_srvs::SetBool::Response &res){ if (req.data){ posts_stored_ = true; ROS_INFO("Post stored request received"); } else{ posts_stored_ = false; } res.success =true; res.message = std::string("Post stored service responsed"); return true; } bool PathPlanning::setMapDimensions(path_planning::map_dimensions::Request &req ,path_planning::map_dimensions::Response &res){ map_x_lenght_ = req.x_lenght; map_y_lenght_ = req.y_lenght; ROS_INFO("Map dimensions request received map_x_lenght_: %lf map_y_lenght_: %lf" ,map_x_lenght_, map_y_lenght_); Fm_blue_center.p = KDL::Vector2 (map_x_lenght_/3, map_y_lenght_/2); Fm_yellow_center.p = KDL::Vector2 (map_x_lenght_*2/3, map_y_lenght_/2); res.send =true; return true; } void PathPlanning::localicsationAlive(const std_msgs::Bool &msg){ localisation_ready_ =msg.data; safety_ton_localisation_=ros::Time::now(); } void PathPlanning::stopSignal(const std_msgs::Bool &msg){ if (msg.data){ stop_received_ = true; start_game_ = false; start_detection_ = false; puck_goal_is_set_ =false; puck_in_front_ =false; puck_grasped_ =false; puck_placed_=false; puck_released_=false; ROS_INFO("Stop signal received"); } comm_ready_ = true; safety_ton_comm_ = ros::Time::now(); } void PathPlanning::angelinaConnected(const std_msgs::Bool &msg){ angelina_connected_ =msg.data; } void PathPlanning::getScan(const sensor_msgs::LaserScan::ConstPtr& scan) { // Initialize sizes at first cycle if (!scan_ready_){ min_scan_angle_ = scan->angle_min; max_scan_angle_ = scan->angle_max; // define vectors with all angles and ranges // REAL robot the lidar data laser_angles_.setLinSpaced(scan->ranges.size(), 0.0, std::abs(min_scan_angle_) + std::abs(max_scan_angle_)); ///SIM //laser_angles_.setLinSpaced(scan->ranges.size(), min_scan_angle_, max_scan_angle_); laser_ranges_ = Eigen::VectorXd::Zero(scan->ranges.size()); act_obs_ = Eigen::VectorXd::Zero(scan->ranges.size()); H_p_ = Eigen::VectorXd::Zero((round(std::abs(min_scan_angle_) + std::abs(max_scan_angle_))/HIST_ALPHA)); H_b_ = Eigen::VectorXi::Zero((round(std::abs(min_scan_angle_) + std::abs(max_scan_angle_))/HIST_ALPHA)); H_m_ = Eigen::VectorXi::Zero((round(std::abs(min_scan_angle_) + std::abs(max_scan_angle_))/HIST_ALPHA)); } // Take all ranges for (size_t i= 0; i < scan->ranges.size(); i++) laser_ranges_(i) = scan->ranges[i]; scan_ready_ =true; safety_ton_scan_ = ros::Time::now(); } void PathPlanning::getOdometry(const nav_msgs::Odometry &msg){ KDL::Rotation Rot =KDL::Rotation::Quaternion( msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w); Tsr_.vel(0) =msg.twist.twist.linear.x; Tsr_.vel(1) =msg.twist.twist.linear.y; Tsr_.vel(2) =msg.twist.twist.linear.z; Tsr_.rot(0) =msg.twist.twist.angular.x; Tsr_.rot(1) =msg.twist.twist.angular.y; Tsr_.rot(2) =msg.twist.twist.angular.z; // data for Fsr_ double alfa, beta, gama; Rot.GetEulerZYX(alfa, beta, gama); Fsr_.p= KDL::Vector2(msg.pose.pose.position.x, msg.pose.pose.position.y); Fsr_.M.SetRot(alfa); ///SIM data for Fmr_ // KDL::Frame2 Fms = KDL::Frame2(KDL::Rotation2(0), KDL::Vector2(0, 0) ); // Fmr_= Fms*Fsr_; odom_ready_ =true; safety_ton_odom_=ros::Time::now(); } void PathPlanning::getSimOdometry(const nav_msgs::Odometry &msg){ fullFmr_ =KDL::Frame(KDL::Rotation::Quaternion(msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w), KDL::Vector(msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z)); Tmr_.vel(0) =msg.twist.twist.linear.x; Tmr_.vel(1) =msg.twist.twist.linear.y; Tmr_.vel(2) =msg.twist.twist.linear.z; Tmr_.rot(0) =msg.twist.twist.angular.x; Tmr_.rot(1) =msg.twist.twist.angular.y; Tmr_.rot(2) =msg.twist.twist.angular.z; double alfa, beta, gama; fullFmr_.M.GetEulerZYX(alfa, beta, gama); ///SIM data for msrFmr_ Fmr_.p= KDL::Vector2(msg.pose.pose.position.x, msg.pose.pose.position.y); Fmr_.M.SetRot(alfa); odom_ready_ =true; safety_ton_odom_=ros::Time::now(); } void PathPlanning::getMapppingData(const path_planning::objects_poses &msg){ if (msg.robot_pose.x < 20 && msg.robot_pose.y <20 && msg.robot_pose.x > -10 && msg.robot_pose.y >-10) { Fmr_ = KDL::Frame2(KDL::Rotation2(msg.robot_pose.theta), KDL::Vector2(msg.robot_pose.x, msg.robot_pose.y)); Fmf_ = KDL::Frame2(KDL::Rotation2(msg.final_pose.theta), KDL::Vector2(msg.final_pose.x, msg.final_pose.y)); map_ready_ =true; } else { ROS_WARN ("Sended robot position is wrong"); map_ready_ =false; } pucks_frames_m_.clear(); if (work_with_blue_pucks_){ for(auto pose : msg.blue_puck_poses) pucks_frames_m_.push_back(KDL::Frame2(KDL::Rotation2(pose.theta), KDL::Vector2(pose.x, pose.y) )); } else{ for(auto pose : msg.yellow_puck_poses) pucks_frames_m_.push_back(KDL::Frame2(KDL::Rotation2(pose.theta), KDL::Vector2(pose.x, pose.y) )); } } void PathPlanning::getRecognitionData(const path_planning::objects_poses &msg){ pucks_frames_r_.clear(); if (work_with_blue_pucks_){ for(auto pose : msg.blue_puck_poses) pucks_frames_r_.push_back(KDL::Frame2(KDL::Rotation2(pose.theta), KDL::Vector2(pose.x, pose.y) )); } else{ for(auto pose : msg.yellow_puck_poses) pucks_frames_r_.push_back(KDL::Frame2(KDL::Rotation2(pose.theta), KDL::Vector2(pose.x, pose.y) )); } recognition_ready_ =true; safety_ton_recognition_=ros::Time::now(); } bool PathPlanning::moveToPose (KDL::Frame2 Fmsr, KDL::Frame2 Fdes, double max_lin_vel, double max_ang_vel, double err_eps){ const double k_rho = 0.5; const double k_beta = -3.0; const double k_alfa = 2.0; double err_x = Fdes.p.x()- Fmsr.p.x(); double err_y = Fdes.p.y()- Fmsr.p.y(); double err_theta = angles::shortest_angular_distance( Fmsr.M.GetRot(),Fdes.M.GetRot()); double rho = std::sqrt(err_x*err_x + err_y*err_y); double alpha =0.0; double delta = (std::abs(err_x)== 0.0 && std::abs(err_y)== 0.0)? Fmsr.M.GetRot(): std::atan2(err_y, err_x) ; if (max_lin_vel > 0.0) alpha = angles::shortest_angular_distance( Fmsr.M.GetRot(), delta); else alpha = angles::shortest_angular_distance( Fmsr.M.GetRot(), M_PI+delta); //reverse double beta = -delta + Fdes.M.GetRot() ; double cmd_lin_vel,cmd_ang_vel; /// base alghorithm: first translation to the goal position and then orientation if (!Equal(Fdes.p, Fmsr.p, err_eps)){ // if goal is rotated stop linear motion and only rotate if (max_lin_vel > 0.0){ if(std::abs(alpha) > 7*err_eps ) cmd_lin_vel = 0.0; else if (std::abs(alpha) < 3*err_eps ){ cmd_lin_vel = k_rho*rho; cmd_lin_vel = (cmd_lin_vel > max_lin_vel)? max_lin_vel : cmd_lin_vel; cmd_lin_vel = (cmd_lin_vel < V_MIN)? V_MIN : cmd_lin_vel; } // limit linear accelaration cmd_lin_vel = (cmd_lin_vel > 0.0 && std::abs(Tsr_.vel.x()-cmd_lin_vel) > V_MIN)? Tsr_.vel.x()+ V_MIN : cmd_lin_vel; } else{ if(std::abs(alpha) > 7*err_eps ) cmd_lin_vel = 0.0; else if (std::abs(alpha) <3*err_eps ){ cmd_lin_vel = -k_rho*rho; cmd_lin_vel = (cmd_lin_vel < max_lin_vel)? max_lin_vel : cmd_lin_vel; cmd_lin_vel = (cmd_lin_vel > -V_MIN)? -V_MIN : cmd_lin_vel; } // limit linear accelaration cmd_lin_vel = (cmd_lin_vel < 0.0 && std::abs(Tsr_.vel.x()-cmd_lin_vel) > V_MIN)? Tsr_.vel.x()- V_MIN : cmd_lin_vel; } cmd_ang_vel = k_alfa*(alpha); } else cmd_ang_vel = k_alfa*(err_theta); /// advanced alghorithm:translation + rotation simultaneously (!!! Unstable) //cmd_lin_vel = k_rho*rho; //cmd_ang_vel = k_alfa*(alpha) + k_beta*(beta); /// DEBUG // ROS_INFO("alpha: %lf", alpha); // ROS_INFO("cmd_lin_vel1: %lf, cmd_ang_vel1: %lf",cmd_lin_vel, cmd_ang_vel); // check velocities limits cmd_ang_vel = (cmd_ang_vel > 0 && cmd_ang_vel > max_ang_vel) ? max_ang_vel : cmd_ang_vel; cmd_ang_vel = (cmd_ang_vel > 0 && cmd_ang_vel < V_MIN) ? V_MIN : cmd_ang_vel; cmd_ang_vel = (cmd_ang_vel < 0 && cmd_ang_vel < -max_ang_vel)? -max_ang_vel : cmd_ang_vel; cmd_ang_vel = (cmd_ang_vel < 0 && cmd_ang_vel > -OMEGA_MIN)? -OMEGA_MIN : cmd_ang_vel; /// DEBUG //ROS_INFO("cmd_lin_vel3: %lf, cmd_ang_vel3: %lf",cmd_lin_vel, cmd_ang_vel); if (Equal(Fdes.p, Fmsr.p, err_eps) && Equal(Fdes.M, Fmsr.M, err_eps)){ cmd_msg_.linear.x = 0; cmd_msg_.angular.z = 0; return true; } else{ cmd_msg_.linear.x = cmd_lin_vel; cmd_msg_.angular.z = cmd_ang_vel; return false; } } void PathPlanning::calcObstacleCertainty(){ non_zero_obj_.clear(); // update for (size_t i= 0; i < laser_ranges_.size(); i++){ // decrement all positive values by 1 considering dynamical enviroment if(act_obs_(i) > 0) act_obs_(i) -=1; // check the boundary if (laser_ranges_(i) < ACT_CIRCLE_RAD){ // check the max_certainly and increment by 2 to neglect the the decrementing from beginning if(act_obs_(i) <= (MAX_CERTAINLY-2)) act_obs_(i) +=2; else if(act_obs_(i) == (MAX_CERTAINLY-1)) act_obs_(i) +=1; // save the non zeros indeces for reducing of the computaional effort if(act_obs_(i) > 0){ double x = laser_ranges_(i)*cos(laser_angles_(i)); double y = laser_ranges_(i)*sin(laser_angles_(i)); non_zero_obj_.push_back(Eigen::Vector3d(act_obs_(i), x, y )); } } } } void PathPlanning::projectGoalInActWindow(std::vector &non_zero_obj, const KDL::Frame2 &Frg, bool mask){ // remove the old projection std::vector idx_to_delete ; for (auto i = 0; i < non_zero_obj.size(); i++){ if (non_zero_obj[i](0) == -9) idx_to_delete .push_back(i); } for (auto i : idx_to_delete ){ non_zero_obj.erase(non_zero_obj.begin()+i); } double theta= angles::normalize_angle_positive(atan2(Frg.p.y(), Frg.p.x())); double dist = (std::abs(Frg.p.Norm())<= ACT_CIRCLE_RAD-PUCK_LOWER_RADIUS)? std::abs(Frg.p.Norm()) : ACT_CIRCLE_RAD -PUCK_LOWER_RADIUS; non_zero_obj.push_back(Eigen::Vector3d(-9, dist*cos(theta), dist*sin(theta))); // center of goal at the end of vector kt_= (round((theta)/HIST_ALPHA) dx*dx+ dy*dy && mask) non_zero_obj[i](0) =-9; // Mask the if grasped if (puck_grasped_){ dx = non_zero_obj[i](1) - Frp_.p.x(); dy = non_zero_obj[i](2) - Frp_.p.y(); if (1.5*pow(PUCK_UPPER_RADIUS, 2) > dx*dx+ dy*dy) non_zero_obj[i](0) =-9; } } // ///////////////////////////////////////////////// DEBUG//////////////////////////////////// // Eigen::MatrixXi tmp_region_grid = Eigen::MatrixXi::Zero(ACT_WIN_SIZE, ACT_WIN_SIZE); // for (auto obj : non_zero_obj){ // // find cartesian coordinates from polar. x=r*cos(theta), y=r*sin(theta) // size_t idx_col = round(0.5 * ACT_WIN_SIZE + obj(1)/CELL_SIZE); // size_t idx_row = round(0.5 * ACT_WIN_SIZE - obj(2)/CELL_SIZE); // if (idx_row > tmp_region_grid.rows()-1) // idx_row = tmp_region_grid.rows()-1; // else if (idx_row < 0 ) // idx_row=0; // if (idx_col > tmp_region_grid.cols()-1) // idx_col = tmp_region_grid.cols()-1; // else if (idx_col < 0 ) // idx_col=0; // tmp_region_grid(idx_row, idx_col) = obj(0); // } // Eigen::IOFormat OctaveFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "]"); // std::cout <<"tmp_region_grid_1\n"<< tmp_region_grid.format(OctaveFmt) << "\n\n"; // /////////////////////////////////////////////////////////////////////////////////////////// } void PathPlanning::calcPolarHistograms(const std::vector &non_zero_obj){ H_p_.setZero(); // calculate histogram alghorithm constant parameters for speed optimisation double a =1+pow(ACT_CIRCLE_RAD,2); // positive constant double b =1.0; // positive constant double r_safety= ROBOT_RADIUS + MIN_PROX_RANGE; // safety radius double dx_r = 0; // safety center x coordinates from right side double dx_l = 0; // safety center x coordinates from left side double dy_r =-SAFETY_CURVE_RADIUS; /// check for upper left corner double dy_l = SAFETY_CURVE_RADIUS; /// check for upper left corner // calculate polar histogram considering the size of the robot for (auto obj : non_zero_obj){ double theta= angles::normalize_angle_positive( std::atan2(obj(2), obj(1))); double dist = sqrt(pow(obj(1), 2) + pow(obj(2), 2)); double m = (dist <=ACT_CIRCLE_RAD)? obj(0) * a-b*dist : 0; double gamma = angles::normalize_angle_positive(std::atan2(r_safety, dist)); int range_gamma = ceil( angles::normalize_angle_positive(2*gamma)/HIST_ALPHA); for (int p = 0; p<=range_gamma; p++){ int k_ext =round((angles::normalize_angle_positive(theta- gamma + p*HIST_ALPHA))/HIST_ALPHA); k_ext = (k_ext < H_p_.size())? k_ext : 0; if ((H_p_(k_ext)>= 0 && m>0) || (H_p_(k_ext)<= 0 && m<0)) H_p_(k_ext) += m; else if (H_p_(k_ext)> 0 && m < 0) // if exist any obstacle before the goal, block this orientation H_p_(k_ext) += abs(m); } } // calculate polar and binary for (size_t k= 0; k < H_p_.size(); k++){ H_b_(k) = (H_p_(k) > HIST_TAU_MAX)? 1 : H_b_(k); H_b_(k) = (H_p_(k) < HIST_TAU_MIN)? 0 : H_b_(k); } // masked polar histogram H_m_ = H_b_; for (auto obj : non_zero_obj){ if (obj(0) > 0.5*MAX_CERTAINLY){ // Check if beta is to the right of theta double beta = angles::normalize_angle_positive( std::atan2(obj(2), obj(1))); double dr_squared = pow( dx_r - obj(1),2 ) + pow(dy_r - obj(2), 2); double dl_squared = pow( dx_l - obj(1),2 ) + pow(dy_l - obj(2), 2); if (beta> M_PI && dr_squared < pow(SAFETY_CURVE_RADIUS, 2) ){ for (int k = round(M_PI/HIST_ALPHA); k < round(2*M_PI/HIST_ALPHA) ; k++){ int k_tmp = (k kr; std::vector kl; cn_.clear(); cr_.clear(); cl_.clear(); ct_.clear(); c_best_.clear(); for (size_t k =0; k< H.size(); k++){ if (H(k) == 0){ if (kl.empty() && kr.empty()){ kr.push_back(k); kl.push_back(k); } if (k-(kl.back()) >1){ // new gap kr.push_back(k); kl.push_back(k); } if (!kr.empty() && !kl.empty()) // update the end kl[kl.size()-1] = k; } } // if there are a gaps at the begining and at the end of histogram and ranges is 2pi combine both gaps if (H(0)==0 && H(H.size()-1)==0 && kr.size()>1 && kl.size()>1 && max_scan_angle_> (M_PI-0.2)){ kr[0] =kr[kr.size()-1]; kr.pop_back(); kl.pop_back(); } if (!kr.empty() && !kl.empty()){ for (size_t i =0; i< kl.size(); i++ ){ // normal sequence if (kl[i]>kr[i] && kl[i]+1-kr[i] > S_MAX){ cn_.push_back(round(0.5*(kl[i] + kr[i]))); cr_.push_back(kr[i] + round(0.5*S_MAX)); cl_.push_back(kl[i] - round(0.5*S_MAX)); if (cr_.back()>=0 && cr_.back()=0 %d, cr_.back()=0 , cr_.back()=0 && cl_.back()=0 %d, cl_.back()=0 , cl_.back()= cr_.back() && kt_ <= cl_.back()) || (kl[i] - kr[i] == H.size()-1)){ if (kt_>=0 && kt_ S_MAX){ int avg = round(0.5*(kl[i]+ H.size()-1 - kr[i])); int cn = ((kr[i]+avg) <= H.size()-1)? kr[i]+avg : kl[i]-avg; int cr = (round(kr[i] + 0.5*S_MAX) < H.size())? round(kr[i] + 0.5*S_MAX) : round(0.5*S_MAX-1 + kr[i])-(H.size()-1); int cl = (round(kl[i]- 0.5*S_MAX) >= 0)? round(kl[i]- 0.5*S_MAX) : H.size()-1 +(round(kl[i] - 0.5*S_MAX-1)) ; cn_.push_back(cn); cr_.push_back(cr); cl_.push_back(cl); if (cr_.back()>=0 && cr_.back()=0 %d, cr_.back()=0 , cr_.back()=0 && cl_.back()=0 %d, cl_.back()=0 , cl_.back()= cr_.back() || kt_ <= cl_.back()){ if (H_b_(kt_) == 0 && kt_>=0 && kt_ PathPlanning::calcTransformedActWindow(const std::vector &non_zero_obj, const KDL::Frame2 &Fnc){ std::vector new_non_zero_obj; KDL::Frame2 Fco, Fno; for (auto obj : non_zero_obj){ Fco = KDL::Frame2 (KDL::Rotation2(0.0), KDL::Vector2(obj(1), obj(2))); Fno = Fnc * Fco; if (obj(0)>0 && std::abs(Fno.p.Norm()) <= ACT_CIRCLE_RAD) new_non_zero_obj.push_back(Eigen::Vector3d(obj(0), Fno.p.x(), Fno.p.y())); } return new_non_zero_obj; } void PathPlanning::createProblemNew(){ ROS_INFO("Problem is started"); projectGoalInActWindow(non_zero_obj_ , Frg_, false); calcPolarHistograms(non_zero_obj_); calcCandidateDirection(H_b_); KDL::Frame2 Frg =KDL::Frame2(KDL::Rotation2(goal_offset_.M.GetRot()), KDL::Vector2(goal_offset_.p.x(), goal_offset_.p.y())); Action action; double cost, heuristic; // g cost and heuristic h cost problem_.eraseProblem(); // init new problem problem_.resizeNet(NUM_STEPS); // new added by Kris 07.01 problem_.setStartState({0, 0}); // set start state (0, 0)for problem problem_.addNodeStateToLayer(0, {0,0}); // new added by Kris 07.01 std::cout <<"c_best_ in problem: "; for(auto i : c_best_){std::cout < > parent_states = problem_.getLayer(idx_layer); for (auto parent_state : parent_states){ // ROS_INFO(" _______________________________________________"); // ROS_INFO("New parent state:[ %d, %d] ", parent_state[0], parent_state[1]); // ROS_INFO(" _______________________________________________"); std::vector children_nodes; // Check if the goal was alredy reached in previus step if(problem_.goalFound()){ break; } KDL::Frame2 F0_cn = problem_.getNode(parent_state).getFrame(); KDL::Frame2 Fcn_g = F0_cn.Inverse() * Frg; // Calculate parent offset std::vector new_non_zero_obj = calcTransformedActWindow(non_zero_obj_, F0_cn.Inverse()); projectGoalInActWindow(new_non_zero_obj , Fcn_g, false); calcPolarHistograms(new_non_zero_obj); calcCandidateDirection(H_b_); // here c_best_ is updated all_blocked_ = c_best_.empty(); if (all_blocked_) c_best_.push_back(M_PI_2); // when is blocked Rotate pi/2 size_t max_num_children = (idx_layer<1)? 4 : 2; // reduce amount of successors after first layer // find chidren for (auto j= 0; j< std::min(c_best_.size(), max_num_children); j++){ if (all_blocked_){ action = Action(0, 0, M_PI_2); ROS_WARN("Problem creation all blocked"); } else if(std::abs(Fcn_g.p.Norm())<=STEP_LENGTH && c_best_[j] == kt_){ action = Action(Fcn_g.p.x(), Fcn_g.p.y(), Fcn_g.M.GetRot()); // ROS_INFO ("almost on the goal"); } else action = Action(STEP_LENGTH*cos(c_best_[j]*HIST_ALPHA), STEP_LENGTH*sin(c_best_[j]*HIST_ALPHA), c_best_[j]*HIST_ALPHA); // calculate cost and heuristic if (all_blocked_){ cost = 1000000; // calculate some large cost and heuristic for blocked node heuristic = 1000000; } else if(idx_layer==0){ cost = calcPriCost(c_best_[j], kc_, kt_, kpre_); heuristic = pow(LAMBDA_H, idx_layer)*calcHeuristic(ke_, kt_, kc_, cpre_); } else{ cost = pow(LAMBDA_C, idx_layer)*calcProCost(c_best_[j], kt_, ke_, kc_, cpre_); heuristic = pow(LAMBDA_H, idx_layer)*calcHeuristic(ke_, kt_, kc_, cpre_); } // Calculate new node transformation wrt to active window KDL::Frame2 Fcn_nn = KDL::Frame2(KDL::Rotation2(action.theta()), KDL::Vector2(action.x(), action.y())); KDL::Frame2 F0_nn = F0_cn * Fcn_nn; KDL::Frame2 Fnn_g = F0_nn.Inverse() * Frg; // // DEBUG // ROS_INFO("Fcn_g.x %lf, Fcn_g.y %lf , Fcn_g.theta %lf",Fcn_g.p.x(), Fcn_g.p.y(), Fcn_g.M.GetRot()); // ROS_INFO("F0_cn.x: %lf, F0_cn.y: %lf, F0_cn.theta: %lf", F0_cn.p.x(), F0_cn.p.y(), F0_cn.M.GetRot()); // ROS_INFO("Fcn_nn.x: %lf, Fcn_nn.y: %lf, Fcn_nn.theta: %lf", Fcn_nn.p.x(), Fcn_nn.p.y(), Fcn_nn.M.GetRot()); // ROS_INFO("F0_nn.x: %lf, F0_nn.y: %lf, F0_nn.theta: %lf", F0_nn.p.x(), F0_nn.p.y(), F0_nn.M.GetRot()); // ROS_INFO("Fnn_g.x: %lf, Fnn_g.y: %lf, Fnn_g.theta: %lf", Fnn_g.p.x(), Fnn_g.p.y(), Fnn_g.M.GetRot()); kpre_ = 0.0; ke_ = 0.0; kc_ = 0.0; std::vector child_state {idx_layer+1, unique_node_index}; children_nodes.push_back(Node(parent_state, action, cost, heuristic, F0_nn)); problem_.addNodeStateToLayer(child_state[0], child_state); // new added by Kris 07.01 problem_.setStateNodeMap(child_state, children_nodes.back()); // map state to node problem_.setParent(child_state, parent_state); unique_node_index++; if(KDL::Equal(Fnn_g, KDL::Frame2::Identity(), 0.01)){ problem_.setGoalState(child_state); problem_.setGoalFound(); break; } } problem_.setSuccessors(parent_state, children_nodes); // map the state s and its successive nodes } } ROS_INFO("Problem is initialized"); } Action PathPlanning::calcObstAvoidanceAction(){ projectGoalInActWindow(non_zero_obj_ , Frg_, false); calcPolarHistograms(non_zero_obj_); calcCandidateDirection(H_b_); double min_cost = calcPriCost(c_best_[0], kc_, kt_, kpre_); int idx_c = 0; if (!c_best_.empty()){ for (auto i= 0; i< c_best_.size(); i++){ double current_cost = calcPriCost(c_best_[i], kc_, kt_, kpre_); if (min_cost> current_cost){ min_cost = current_cost; idx_c = i; } } int r1 = rand() % 100 + 1; // r1 in the range 1 to 100 int r2 = rand() % c_best_.size(); // r2 in the range 0 to c_best_.size() if (r1 <= 50){ // explorer mode to avoid local minima situation, 60% takes the proposed action idx_c = r2; } if((std::abs(Frg_.p.Norm()) 0.2*MAX_CERTAINLY){ double dist = sqrt (pow(non_zero_obj_[i](1), 2) + pow(non_zero_obj_[i](2), 2)); if (ROBOT_RADIUS + MIN_PROX_RANGE > dist ){ problem_initialized_ =false; making_step_=false; if (!robot_blocked_){ robot_blocked_ = true; robot_ton_blocked_= ros::Time::now(); } } } } if (robot_blocked_ && (ros::Time::now()- robot_ton_blocked_).toSec()>3.0 && !robot_unblocking_){ action_ = calcObstAvoidanceAction(); desF_= Fsr_blocked_* KDL::Frame2( KDL::Rotation2(action_.theta()), KDL::Vector2(action_.x(), action_.y())); robot_unblocking_= true; } int k = round(angles::normalize_angle_positive(std::atan2(action_.y() , action_.x()))/HIST_ALPHA); k = (k < H_b_.size())? k : 0; if (robot_unblocking_ && H_b_(k)==0){ ROS_INFO("Fsr_x: %lf, Fsr_y: %lf, Fsr_theta: %lf", Fsr_.p.x(), Fsr_.p.y(), angles::to_degrees(Fsr_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); if (moveToPose(Fsr_, desF_, 0.4*V_MAX, 0.2*M_PI, 0.04)){ robot_unblocking_= false; robot_blocked_ = false; } } else{ robot_unblocking_ =false; } if (robot_blocked_ && !robot_unblocking_){ ROS_WARN("Robot is blocked"); Fsr_blocked_ =Fsr_; moveToPose(KDL::Frame2::Identity(), KDL::Frame2::Identity(), V_MAX, M_PI, 0.04); // stop } } void PathPlanning::inFieldCheck(){ if (map_x_lenght_ -SAFETY_DIST_TO_FIELD < Fmr_.p.x() || Fmr_.p.x()< SAFETY_DIST_TO_FIELD|| map_y_lenght_ -SAFETY_DIST_TO_FIELD < Fmr_.p.y()|| Fmr_.p.y()< SAFETY_DIST_TO_FIELD ){ robot_out_out_ = true; } else { robot_out_out_ = false; } if (robot_out_out_){ ROS_INFO("Robot out of field"); Fmg_ = Fmg_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2(0.5 * map_x_lenght_, 0.5 * map_y_lenght_));; Frg_ =Fmr_.Inverse()*Fmg_; if (!problem_initialized_){ ros::Time tic =ros::Time::now(); // time consumed for creating of a problem and solution of a A* createProblemNew(); if(problem_.goalFound()){ actions_ = calcActionVector(); } else{ // actions_ = calcActionVectorAStar(); actions_.clear(); actions_.push_back(calcObstAvoidanceAction()); } current_step_ = actions_.size()-1; problem_initialized_= true; ROS_INFO("toc: %lf",(ros::Time::now() - tic).toSec()); ///DEBUG for (auto action : actions_){ROS_INFO("action: x: %lf, y %lf , theta %lf", action.x(), action.y(), action.theta());} } projectGoalInActWindow(non_zero_obj_ , Frg_, false); calcPolarHistograms(non_zero_obj_); calcCandidateDirection(H_b_); if (!making_step_ && problem_initialized_){ action_ = actions_[current_step_]; desF_= Fsr_* KDL::Frame2( KDL::Rotation2(action_.theta()), KDL::Vector2(action_.x(), action_.y())); // use odomemetry for steps measurments } int k = round(angles::normalize_angle_positive(std::atan2(action_.y() , action_.x()))/HIST_ALPHA); k = (k < H_b_.size())? k : 0; ROS_INFO("k: %d , H_b_(k) %d", k, H_b_(k)); problem_initialized_= (H_b_(k)==0); making_step_= (H_b_(k)==0); if (making_step_ ){ ROS_INFO("working on step: %d",current_step_); if (moveToPose(Fsr_, desF_, 0.2*V_MAX, 0.1*M_PI, 0.04)){ making_step_= false; if(current_step_>=1) current_step_-- ; else problem_initialized_= false; } } else{ ROS_WARN("Robot is stoped from inFieldCheck"); moveToPose(KDL::Frame2::Identity(), KDL::Frame2::Identity(), V_MAX, M_PI, 0.04); } } if (robot_out_out_ && !puck_grasped_){ puck_goal_is_set_ = false; puck_in_front_ =false; } } void PathPlanning::makeExploration(){ double rot_setpoint; double time = (ros::Time::now() - exploration_start_time).toSec(); if (rotation_step_ <24){ // 24* 45 deg = 3 rotation otherwise max 70 sec rotation desF_.p = Fs_exp_init_.p; rot_setpoint = angles::normalize_angle_positive(Fs_exp_init_.M.GetRot() + (1 +rotation_step_ )*M_PI_4); desF_.M.SetRot(rot_setpoint); if(moveToPose(Fsr_, desF_, 0.01*V_MAX, 0.5*M_PI, 0.1)){; rotation_step_++; if (rotation_step_ ==24){ bool_req_.request.data = true; if(client_turning_done_.call(bool_req_)){ turning_done_send_ = true; } else{ ROS_WARN ("Turning done service do not respond"); } } } } if (time > 80.0 && !turning_done_send_){ bool_req_.request.data = true; if(client_turning_done_.call(bool_req_)){ turning_done_send_ = true; } else{ ROS_WARN ("Turning done service do not respond"); } } ROS_INFO("Fs_exp_init__x: %lf, Fs_exp_init__y: %lf,Fs_exp_init__theta: %lf", Fs_exp_init_.p.x(), Fs_exp_init_.p.y(), angles::to_degrees(Fs_exp_init_.M.GetRot())); ROS_INFO("Fsr_x: %lf, Fsr_y: %lf, Fsr_theta: %lf", Fsr_.p.x(), Fsr_.p.y(), angles::to_degrees(Fsr_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); /// Exploration mode // if (detection_step_ ==0 && (!posts_stored_ && time > 70.0)){ // Frg_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2(0.5, 0.0)); // Action action = calcObstAvoidanceAction(); // int k = round(angles::normalize_angle_positive(std::atan2(action.y() , action.x()))/HIST_ALPHA); // k = (k < H_b_.size())? k : 0; // desF_= Fsr_* KDL::Frame2( KDL::Rotation2(action.theta()), KDL::Vector2(action.x(), action.y())); // detection_step_ = (H_b_(k)==0)? 1 : 0; // } // if (detection_step_ ==0 && posts_stored_ && map_ready_){ // Fmg_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2(1.0, 1.0)); // Frg_ = Fmr_.Inverse() * Fmg_; // Action action = calcObstAvoidanceAction(); // int k = round(angles::normalize_angle_positive(std::atan2(action.y() , action.x()))/HIST_ALPHA); // k = (k < H_b_.size())? k : 0; // desF_= Fsr_* KDL::Frame2( KDL::Rotation2(action.theta()), KDL::Vector2(action.x(), action.y())); // detection_step_ = (H_b_(k)==0)? 1 : 0; // } if (detection_step_ ==1){ moveToPose(Fsr_, desF_, 0.2*V_MAX, 0.2*M_PI, 0.04); } } void PathPlanning::goToPuck(){ Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2(-SAFETY_DIST_TO_GOAL, 0.0)); Fmg_ = Fmp_*Fpuck_offset_; if (std::abs((Fmr_.p - Fmg_.p).Norm())< 3*STEP_LENGTH && std::abs(Frp_.p.Norm())< 3*STEP_LENGTH){ //TODO check Frg_ = Frp_ * Fpuck_offset_; } else { Frg_ =Fmr_.Inverse()*Fmg_; } if (!problem_initialized_){ ros::Time tic =ros::Time::now(); // time consumed for creating of a problem and solution of a A* createProblemNew(); if(problem_.goalFound()){ actions_ = calcActionVector(); } else{ // actions_ = calcActionVectorAStar(); actions_.clear(); actions_.push_back(calcObstAvoidanceAction()); } current_step_ = actions_.size()-1; problem_initialized_= true; ROS_INFO("toc: %lf",(ros::Time::now() - tic).toSec()); ///DEBUG for (auto action : actions_){ROS_INFO("action: x: %lf, y %lf , theta %lf", action.x(), action.y(), action.theta());} } projectGoalInActWindow(non_zero_obj_ , Frg_, false); calcPolarHistograms(non_zero_obj_); calcCandidateDirection(H_b_); if(std::abs(Frg_.p.Norm())>= STEP_LENGTH){ if (!making_step_ && problem_initialized_){ action_ = actions_[current_step_]; desF_= Fsr_* KDL::Frame2( KDL::Rotation2(action_.theta()), KDL::Vector2(action_.x(), action_.y())); } int k = round(angles::normalize_angle_positive(std::atan2(action_.y() , action_.x()))/HIST_ALPHA); k = (k < H_b_.size())? k : 0; ROS_INFO("k: %d , H_b_(k) %d", k, H_b_(k)); problem_initialized_= (H_b_(k)==0); making_step_= (H_b_(k)==0); if (making_step_ ){ ROS_INFO("working on step: %d",current_step_); if (moveToPose(Fsr_, desF_, 0.4*V_MAX, 0.2*M_PI, 0.04)){ making_step_= false; if(current_step_>=1) current_step_-- ; else problem_initialized_= false; } } else{ moveToPose(KDL::Frame2::Identity(), KDL::Frame2::Identity(), V_MAX, M_PI, 0.04); // stop } } else{ ROS_INFO("almost in front of the puck"); desF_ = Fsr_*Frg_; if(moveToPose(Fsr_, desF_, 0.3*V_MAX, 0.1*M_PI, 0.03)){ if (pucks_frames_r_.back().p.x() < 1.5*SAFETY_DIST_TO_GOAL && std::abs(pucks_frames_r_.back().p.y()) < 3*PUCK_LOWER_RADIUS ){ puck_in_front_ = true; ROS_INFO("Robot in front of the puck"); } else { puck_goal_is_set_ =false; // there was no puck at this position search for new goal } problem_initialized_= false; } } ROS_INFO("x_offset: %lf, y_offset: %lf, theta_offset: %lf", action_.x(), action_.y(), angles::to_degrees(action_.theta())); ROS_INFO("Frg_x: %lf, Frg_y: %lf, Frg_theta: %lf", Frg_.p.x(), Frg_.p.y(), angles::to_degrees(Frg_.M.GetRot())); ROS_INFO("Fsr_x: %lf, Fsr_y: %lf, Fsr_theta: %lf", Fsr_.p.x(), Fsr_.p.y(), angles::to_degrees(Fsr_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); } void PathPlanning::graspPuck(){ /// SIM Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2(ROBOT_RADIUS + PUCK_LOWER_RADIUS -0.02, 0.0)); ROS_INFO("Frp_.x: %lf, Frp_.y: %lf, Frp_.theta: %lf", Frp_.p.x(), Frp_.p.y(), angles::to_degrees(Frp_.M.GetRot())); Frg_ = Frp_ *Fpuck_offset_.Inverse(); desF_ = Fsr_*Frg_; if (moveToPose(Frg_.Inverse(), KDL::Frame2::Identity(), 0.2*V_MAX, 0.1*M_PI, 0.03)){ puck_grasped_ = true; ROS_INFO("Grasping finished"); } } void PathPlanning::goToFinal(){ if (placed_puck_num_ == 0) Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0), KDL::Vector2(-ROBOT_RADIUS - PUCK_LOWER_RADIUS, 0.0 )); else if (placed_puck_num_ == 1) Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0), KDL::Vector2(-ROBOT_RADIUS - PUCK_LOWER_RADIUS, 4*PUCK_LOWER_RADIUS + ROBOT_RADIUS)); else if (placed_puck_num_ == 2) Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0), KDL::Vector2(-ROBOT_RADIUS - PUCK_LOWER_RADIUS, -4*PUCK_LOWER_RADIUS - ROBOT_RADIUS )); else Fpuck_offset_ = KDL::Frame2(KDL::Rotation2(0), KDL::Vector2(-ROBOT_RADIUS - PUCK_LOWER_RADIUS + 2*PUCK_LOWER_RADIUS , 0.0)); Frg_ =Fmr_.Inverse()*Fmf_ *Fpuck_offset_; if (!problem_initialized_){ ros::Time tic =ros::Time::now(); // time consumed for creating of a problem and solution of a A* createProblemNew(); if(problem_.goalFound()){ actions_ = calcActionVector(); } else{ // actions_ = calcActionVectorAStar(); actions_.clear(); actions_.push_back(calcObstAvoidanceAction()); } current_step_ = actions_.size()-1; problem_initialized_= true; ROS_INFO("toc: %lf",(ros::Time::now() - tic).toSec()); ///DEBUG for (auto action : actions_){ROS_INFO("action: x: %lf, y %lf , theta %lf", action.x(), action.y(), action.theta());} } projectGoalInActWindow(non_zero_obj_ , Frg_, false); calcPolarHistograms(non_zero_obj_); calcCandidateDirection(H_b_); if(std::abs(Frg_.p.Norm())>= STEP_LENGTH){ if (!making_step_){ action_ = actions_[current_step_]; desF_= Fsr_* KDL::Frame2( KDL::Rotation2(action_.theta()), KDL::Vector2(action_.x(), action_.y())); // use odomemetry for steps measurments } int k = round(angles::normalize_angle_positive(std::atan2(action_.y() , action_.x()))/HIST_ALPHA); k = (k < H_b_.size())? k : 0; ROS_INFO("k: %d , H_b_(k) %d", k, H_b_(k)); problem_initialized_= (H_b_(k)==0); making_step_= (H_b_(k)==0); if (making_step_){ ROS_INFO("working on step: %d",current_step_); if (moveToPose(Fsr_, desF_, 0.4*V_MAX, 0.2*M_PI, 0.04)){ making_step_= false; if(current_step_>=1) current_step_-- ; else problem_initialized_= false;; } } else{ moveToPose(KDL::Frame2::Identity(), KDL::Frame2::Identity(), V_MAX, M_PI, 0.04); // stop } } else{ ROS_INFO("Almost on final"); desF_ = Fsr_*Frg_; if(moveToPose(Fsr_, desF_, 0.3*V_MAX, 0.1*M_PI, 0.04)){ placed_puck_num_ ++; bool_req_.request.data = true; ROS_INFO("Go to final square finished"); if (!client_report_goal_.call(bool_req_)) ROS_ERROR("Failed to call service report goal"); if (placed_puck_num_ == 3) ROS_ERROR("Failed to call service report done"); Fsr_release_ =Fsr_; puck_placed_ = true; problem_initialized_= false; } } ROS_INFO("x_offset: %lf, y_offset: %lf, theta_offset: %lf", action_.x(), action_.y(), angles::to_degrees(action_.theta())); ROS_INFO("Fsr_x: %lf, Fsr_y: %lf, Fsr_theta: %lf", Fsr_.p.x(), Fsr_.p.y(), angles::to_degrees(Fsr_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); ROS_INFO("Frg_x: %lf, Frg_y: %lf, Frg_theta: %lf", Frg_.p.x(), Frg_.p.y(), angles::to_degrees(Frg_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); } void PathPlanning::releasePuck (){ double x = 3*PUCK_LOWER_RADIUS* cos(Fsr_release_.M.GetRot() + M_PI); double y = 3*PUCK_LOWER_RADIUS* sin(Fsr_release_.M.GetRot() + M_PI); desF_ = Fsr_release_*KDL::Frame2(KDL::Rotation2(0.0),KDL::Vector2(x, y)); //desF_ = KDL::Frame2(KDL::Rotation2(0.0), KDL::Vector2((ROBOT_RADIUS + 3*PUCK_RADIUS), 0.0)); if (moveToPose(Fsr_, desF_, -0.1*V_MAX, 0.1*M_PI, 0.03)){ puck_released_ = true; ROS_INFO("Releasing of the puck finished"); } ROS_INFO("Fsr_.x: %lf, Fsr_.y: %lf, Fsr_.theta: %lf", Fsr_.p.x(), Fsr_.p.y(), angles::to_degrees(Fsr_.M.GetRot())); ROS_INFO("des_x: %lf, des_: %lf, des_theta: %lf", desF_.p.x(), desF_.p.y(), angles::to_degrees(desF_.M.GetRot())); } void PathPlanning::choicePuckGoal(){ KDL::Frame2 Fmp; if (!pucks_frames_m_.empty() && placed_puck_num_ <3){ chosen_puck_idx_ =0; double min_dist= 100.0; for (int i=0; i 0.5*final_x_lenght_) || (std::abs(diff.y()) > 0.5*final_y_lenght_ )) && std::abs((Fmp_.p-Fmp.p).Norm()) > 4*PUCK_LOWER_RADIUS ){ if (min_dist > std::abs((Fmp.p - Fmr_.p).Norm())){ min_dist= std::abs((Fmp.p - Fmr_.p).Norm()); chosen_puck_idx_ =i; } } } Fmp_= pucks_frames_m_[chosen_puck_idx_]; puck_goal_is_set_ =true; ROS_INFO("Puck goal is set"); } } /// FROM KRIS int PathPlanning::calcDeltaAngular(int c1, int c2){ double min_angle =angles::shortest_angular_distance(c1 * HIST_ALPHA ,c2 * HIST_ALPHA); return round(std::abs(min_angle) / HIST_ALPHA); } // kc is always 0, kt is sector of the goal, kpre is sector of the previous step double PathPlanning::calcPriCost(int c, int kc, int kt, int kpre){ return MU1*calcDeltaAngular(c, kt)+MU2*calcDeltaAngular(c, kc)+MU3*calcDeltaAngular(c, kpre); } double PathPlanning::calcProCost(int c, int kt, int ke, int kc, int cpre){ return MU1_PH*std::max(calcDeltaAngular(c, kt), calcDeltaAngular(ke, kt))+ MU2_PH*calcDeltaAngular(c, kc)+MU3_PH*calcDeltaAngular(c, cpre); } double PathPlanning::calcHeuristic(int ke, int kt, int kc, int cpre){ return MU1_PH*calcDeltaAngular(ke, kt)+MU2_PH*calcDeltaAngular(kt, kc)+MU3_PH*calcDeltaAngular(kt, cpre); } // if goal can be reached in NUM_STEPS, use this std::vector PathPlanning::calcActionVector(){ std::vector v_action; std::vector curr = problem_.getGoalState(); v_action.push_back(problem_.getNode(curr).getAction()); // new line // iterate till the root node while(problem_.getParent(curr)!= problem_.getStartState()){ std:: vector parent = problem_.getParent(curr); v_action.push_back(problem_.getNode(parent).getAction()); curr = parent; } return v_action; } // if goal can't be reached in NUM_STEPS, use this std::vector PathPlanning::calcActionVectorAStar(){ std::vector path_cost; // cost vector contains the total cost for each trajectory std::vector > v_action; std::vector > v_last_layer_state = problem_.getLayer(NUM_STEPS-1); for(int i=0; i s = v_last_layer_state[i]; double total_cost = 0; std::vector v_action_branch; while(s!=problem_.getStartState()){ v_action_branch.push_back(problem_.getNode(s).getAction()); // add the action to the corresponding vector total_cost+=problem_.getNode(s).getCost(); // sum the cost and heuristic total_cost+=problem_.getNode(s).getHeuristic(); s = problem_.getParent(s); } v_action.push_back(v_action_branch); path_cost.push_back(total_cost); // store the total cost for one trajectory } // return the action sequence with minimal total cost return v_action[distance(begin(path_cost), min_element(path_cost.begin(),path_cost.end()))]; } #include #include #include int main() { using shape_t = std::uint_fast8_t; std::array, 36> matrix{ {} }; dtl::shape::SimpleRogueLike(1, 2, 3, 4, 5, 2, 5, 2).draw(matrix); dtl::console::OutputNumber(",").draw(matrix); dtl::console::OutputString("//", "##", "%%").draw(matrix); return 0; }1000+ /* Copyright (c) 2005-2022 Intel Corporation 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. */ #define DOCTEST_CONFIG_IMPLEMENT #include "common/test.h" #include "common/utils.h" #include "common/utils_report.h" #include "tbb/global_control.h" #include "tbb/task_arena.h" #include "tbb/scalable_allocator.h" // Lets slow down the main thread on exit static constexpr int MAX_DELAY = 5; struct GlobalObject { ~GlobalObject() { utils::Sleep(rand( ) % MAX_DELAY); } } go; void allocatorRandomThrashing() { const int ARRAY_SIZE = 1000; const int MAX_ITER = 10000; const int MAX_ALLOC = 10 * 1024 * 1024; void *arr[ARRAY_SIZE] = {nullptr}; for (int i = 0; i < rand() % MAX_ITER; ++i) { // Random allocation size for random arrays for (int j = 0; j < rand() % ARRAY_SIZE; ++j) { arr[j] = scalable_malloc(rand() % MAX_ALLOC); } // Deallocate everything for (int j = 0; j < ARRAY_SIZE; ++j) { scalable_free(arr[j]); arr[j] = nullptr; } } } void hangOnExitReproducer() { const int P = tbb::global_control::max_allowed_parallelism; tbb::task_arena test_arena; for (int i = 0; i < P-1; i++) { test_arena.enqueue(allocatorRandomThrashing); } } #if (_WIN32 || _WIN64) && !__TBB_WIN8UI_SUPPORT #include // _spawnl void processSpawn(const char* self) { _spawnl(_P_WAIT, self, self, "1", nullptr); } #elif __unix__ || __APPLE__ #include // fork/exec #include // waitpid void processSpawn(const char* self) { pid_t pid = fork(); if (pid == -1) { REPORT("ERROR: fork failed.\n"); } else if (pid == 0) { // child execl(self, self, "1", nullptr); REPORT("ERROR: exec never returns\n"); exit(1); } else { // parent int status; waitpid(pid, &status, 0); } } #else void processSpawn(const char* /*self*/) { REPORT("Known issue: no support for process spawn on this platform.\n"); REPORT("done\n"); exit(0); } #endif #if _MSC_VER && !__INTEL_COMPILER #pragma warning (push) #pragma warning (disable: 4702) /* Unreachable code */ #endif //! \brief \ref error_guessing TEST_CASE("testing shutdown hang") { hangOnExitReproducer(); CHECK(true); // just to notify that test has assertions } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4447) int main(int argc, char* argv[]) { // Executed from child processes if (argc == 2 && strcmp(argv[1],"1") == 0) { return doctest::Context(argc, argv).run(); } // The number of executions is a tradeoff // between execution time and NBTS statistics const int EXEC_TIMES = 100; const char* self = argv[0]; for (int i = 0; i < EXEC_TIMES; i++) { processSpawn(self); } #if _MSC_VER && !__INTEL_COMPILER #pragma warning (pop) #endif } DOCTEST_MSVC_SUPPRESS_WARNING_POP #include "PatrolState.h" PatrolState::PatrolState() { } PatrolState::~PatrolState() { } void PatrolState::onUpdate(GameObject * object, float dt) { Vector2D target = m_waypoints[m_currentWaypoint]; Vector2D pos = object->getPosition(); Vector2D dist = { target.x - pos.x, target.y - pos.y }; float mag = sqrt(dist.x *dist.x + dist.y*dist.y); } /** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding #include "mongo/platform/basic.h" #include "mongo/db/s/migration_impl.h" #include "mongo/bson/util/bson_extract.h" #include "mongo/client/connpool.h" #include "mongo/db/client.h" #include "mongo/db/operation_context.h" #include "mongo/db/repl/replication_coordinator_global.h" #include "mongo/db/s/collection_metadata.h" #include "mongo/db/s/operation_shard_version.h" #include "mongo/db/s/sharding_state.h" #include "mongo/db/s/sharding_state_recovery.h" #include "mongo/logger/ramlog.h" #include "mongo/rpc/get_status_from_command_result.h" #include "mongo/s/catalog/type_chunk.h" #include "mongo/s/chunk.h" #include "mongo/s/client/shard_registry.h" #include "mongo/s/grid.h" #include "mongo/s/stale_exception.h" #include "mongo/util/exit.h" #include "mongo/util/fail_point_service.h" #include "mongo/util/log.h" #include "mongo/util/mongoutils/str.h" namespace mongo { using std::string; using str::stream; namespace { Tee* const migrateLog = RamLog::get("migrate"); const int kDefaultWriteTimeoutForMigrationMs = 60 * 1000; const WriteConcernOptions DefaultWriteConcernForMigration(2, WriteConcernOptions::SyncMode::NONE, kDefaultWriteTimeoutForMigrationMs); WriteConcernOptions getDefaultWriteConcernForMigration() { repl::ReplicationCoordinator* replCoordinator = repl::getGlobalReplicationCoordinator(); if (replCoordinator->getReplicationMode() == mongo::repl::ReplicationCoordinator::modeReplSet) { Status status = replCoordinator->checkIfWriteConcernCanBeSatisfied(DefaultWriteConcernForMigration); if (status.isOK()) { return DefaultWriteConcernForMigration; } } return WriteConcernOptions(1, WriteConcernOptions::SyncMode::NONE, 0); } BSONObj createRecvChunkCommitRequest(const MigrationSessionId& sessionId) { BSONObjBuilder builder; builder.append("_recvChunkCommit", 1); sessionId.append(&builder); return builder.obj(); } MONGO_FP_DECLARE(failMigrationCommit); MONGO_FP_DECLARE(hangBeforeLeavingCriticalSection); MONGO_FP_DECLARE(failMigrationConfigWritePrepare); } // namespace ChunkMoveWriteConcernOptions::ChunkMoveWriteConcernOptions(BSONObj secThrottleObj, WriteConcernOptions writeConcernOptions) : _secThrottleObj(std::move(secThrottleObj)), _writeConcernOptions(std::move(writeConcernOptions)) {} StatusWith ChunkMoveWriteConcernOptions::initFromCommand( const BSONObj& cmdObj) { BSONObj secThrottleObj; WriteConcernOptions writeConcernOptions; Status status = writeConcernOptions.parseSecondaryThrottle(cmdObj, &secThrottleObj); if (!status.isOK()) { if (status.code() != ErrorCodes::WriteConcernNotDefined) { return status; } writeConcernOptions = getDefaultWriteConcernForMigration(); } else { repl::ReplicationCoordinator* replCoordinator = repl::getGlobalReplicationCoordinator(); if (replCoordinator->getReplicationMode() == repl::ReplicationCoordinator::modeMasterSlave && writeConcernOptions.shouldWaitForOtherNodes()) { warning() << "moveChunk cannot check if secondary throttle setting " << writeConcernOptions.toBSON() << " can be enforced in a master slave configuration"; } Status status = replCoordinator->checkIfWriteConcernCanBeSatisfied(writeConcernOptions); if (!status.isOK() && status != ErrorCodes::NoReplicationEnabled) { return status; } } if (writeConcernOptions.shouldWaitForOtherNodes() && writeConcernOptions.wTimeout == WriteConcernOptions::kNoTimeout) { // Don't allow no timeout writeConcernOptions.wTimeout = kDefaultWriteTimeoutForMigrationMs; } return ChunkMoveWriteConcernOptions(secThrottleObj, writeConcernOptions); } ChunkMoveOperationState::ChunkMoveOperationState(OperationContext* txn, NamespaceString ns) : _txn(txn), _nss(std::move(ns)) {} ChunkMoveOperationState::~ChunkMoveOperationState() { if (!_isRunning) { return; } auto migrationSourceManager = ShardingState::get(_txn)->migrationSourceManager(); invariant(migrationSourceManager); migrationSourceManager->done(_txn); } Status ChunkMoveOperationState::initialize(const BSONObj& cmdObj) { // Make sure we're as up-to-date as possible with shard information. This catches the case where // we might have changed a shard's host by removing/adding a shard with the same name. grid.shardRegistry()->reload(_txn); _fromShard = cmdObj["fromShard"].str(); if (_fromShard.empty()) { return {ErrorCodes::InvalidOptions, "need to specify shard to move chunk from"}; } _toShard = cmdObj["toShard"].str(); if (_toShard.empty()) { return {ErrorCodes::InvalidOptions, "need to specify shard to move chunk to"}; } Status epochStatus = bsonExtractOIDField(cmdObj, "epoch", &_collectionEpoch); if (!epochStatus.isOK()) { return epochStatus; } _minKey = cmdObj["min"].Obj(); if (_minKey.isEmpty()) { return {ErrorCodes::InvalidOptions, "need to specify a min"}; } _maxKey = cmdObj["max"].Obj(); if (_maxKey.isEmpty()) { return {ErrorCodes::InvalidOptions, "need to specify a max"}; } { std::shared_ptr fromShard = grid.shardRegistry()->getShard(_txn, _fromShard); if (!fromShard) { return {ErrorCodes::ShardNotFound, stream() << "Source shard " << _fromShard << " is missing. This indicates metadata corruption."}; } _fromShardCS = fromShard->getConnString(); } { std::shared_ptr toShard = grid.shardRegistry()->getShard(_txn, _toShard); if (!toShard) { return {ErrorCodes::ShardNotFound, stream() << "Destination shard " << _toShard << " is missing. This indicates metadata corruption."}; } _toShardCS = toShard->getConnString(); } return Status::OK(); } StatusWith ChunkMoveOperationState::acquireMoveMetadata() { // Get the distributed lock const string whyMessage(stream() << "migrating chunk [" << _minKey << ", " << _maxKey << ") in " << _nss.ns()); _distLockStatus = grid.forwardingCatalogManager()->distLock(_txn, _nss.ns(), whyMessage); if (!_distLockStatus->isOK()) { const string msg = stream() << "could not acquire collection lock for " << _nss.ns() << " to migrate chunk [" << _minKey << "," << _maxKey << ")" << causedBy(_distLockStatus->getStatus()); warning() << msg; return Status(_distLockStatus->getStatus().code(), msg); } ShardingState* const shardingState = ShardingState::get(_txn); // Snapshot the metadata Status refreshStatus = shardingState->refreshMetadataNow(_txn, _nss.ns(), &_shardVersion); if (!refreshStatus.isOK()) { const string msg = stream() << "moveChunk cannot start migrate of chunk " << "[" << _minKey << "," << _maxKey << ")" << causedBy(refreshStatus.reason()); warning() << msg; return Status(refreshStatus.code(), msg); } if (_shardVersion.majorVersion() == 0) { // It makes no sense to migrate if our version is zero and we have no chunks const string msg = stream() << "moveChunk cannot start migrate of chunk " << "[" << _minKey << "," << _maxKey << ")" << " with zero shard version"; warning() << msg; return Status(ErrorCodes::IncompatibleShardingMetadata, msg); } { // Mongos >= v3.2 sends the full version, v3.0 only sends the epoch. // TODO(SERVER-20742): Stop parsing epoch separately after 3.2. auto& operationVersion = OperationShardVersion::get(_txn); if (operationVersion.hasShardVersion()) { _collectionVersion = operationVersion.getShardVersion(_nss); _collectionEpoch = _collectionVersion.epoch(); } // else the epoch will already be set from the parsing of the ChunkMoveOperationState if (_collectionEpoch != _shardVersion.epoch()) { const string msg = stream() << "moveChunk cannot move chunk " << "[" << _minKey << "," << _maxKey << "), " << "collection may have been dropped. " << "current epoch: " << _shardVersion.epoch() << ", cmd epoch: " << _collectionEpoch; warning() << msg; throw SendStaleConfigException(_nss.toString(), msg, _collectionVersion, _shardVersion); } } _collMetadata = shardingState->getCollectionMetadata(_nss.ns()); // With nonzero shard version, we must have a coll version >= our shard version invariant(_collMetadata->getCollVersion() >= _shardVersion); // With nonzero shard version, we must have a shard key invariant(!_collMetadata->getKeyPattern().isEmpty()); ChunkType origChunk; if (!_collMetadata->getNextChunk(_minKey, &origChunk) || origChunk.getMin().woCompare(_minKey) || origChunk.getMax().woCompare(_maxKey)) { // Our boundaries are different from those passed in const string msg = stream() << "moveChunk cannot find chunk " << "[" << _minKey << "," << _maxKey << ")" << " to migrate, the chunk boundaries may be stale"; warning() << msg; throw SendStaleConfigException(_nss.toString(), msg, _collectionVersion, _shardVersion); } return &_distLockStatus->getValue(); } Status ChunkMoveOperationState::commitMigration(const MigrationSessionId& sessionId) { invariant(_distLockStatus.is_initialized()); invariant(_distLockStatus->isOK()); log() << "About to enter migrate critical section"; // We're under the collection distributed lock here, so no other migrate can change maxVersion // or CollectionMetadata state. ShardingState* const shardingState = ShardingState::get(_txn); Status startStatus = ShardingStateRecovery::startMetadataOp(_txn); if (!startStatus.isOK()) { warning() << "Failed to write sharding state recovery document" << causedBy(startStatus); return startStatus; } shardingState->migrationSourceManager()->setInCriticalSection(true); const ChunkVersion originalCollVersion = getCollMetadata()->getCollVersion(); ChunkVersion myVersion = originalCollVersion; myVersion.incMajor(); { ScopedTransaction transaction(_txn, MODE_IX); Lock::DBLock lk(_txn->lockState(), _nss.db(), MODE_IX); Lock::CollectionLock collLock(_txn->lockState(), _nss.ns(), MODE_X); invariant(myVersion > shardingState->getVersion(_nss.ns())); // Bump the metadata's version up and "forget" about the chunk being moved. This is // not the commit point, but in practice the state in this shard won't change until // the commit it done. shardingState->donateChunk(_txn, _nss.ns(), _minKey, _maxKey, myVersion); } log() << "moveChunk setting version to: " << myVersion << migrateLog; // We're under the collection lock here, too, so we can undo the chunk donation because // no other state change could be ongoing BSONObj res; Status recvChunkCommitStatus{ErrorCodes::InternalError, "status not set"}; try { ScopedDbConnection connTo(_toShardCS, 35.0); connTo->runCommand("admin", createRecvChunkCommitRequest(sessionId), res); connTo.done(); recvChunkCommitStatus = getStatusFromCommandResult(res); } catch (const DBException& e) { const string msg = stream() << "moveChunk could not contact to shard " << _toShard << " to commit transfer" << causedBy(e); warning() << msg; recvChunkCommitStatus = Status(e.toStatus().code(), msg); } if (MONGO_FAIL_POINT(failMigrationCommit) && recvChunkCommitStatus.isOK()) { recvChunkCommitStatus = Status(ErrorCodes::InternalError, "Failing _recvChunkCommit due to failpoint."); } if (!recvChunkCommitStatus.isOK()) { log() << "moveChunk migrate commit not accepted by TO-shard: " << res << " resetting shard version to: " << getShardVersion() << migrateLog; { ScopedTransaction transaction(_txn, MODE_IX); Lock::DBLock dbLock(_txn->lockState(), _nss.db(), MODE_IX); Lock::CollectionLock collLock(_txn->lockState(), _nss.ns(), MODE_X); log() << "moveChunk collection lock acquired to reset shard version from " "failed migration"; // Revert the chunk manager back to the state before "forgetting" about the chunk shardingState->undoDonateChunk(_txn, _nss.ns(), getCollMetadata()); } log() << "Shard version successfully reset to clean up failed migration"; return Status(recvChunkCommitStatus.code(), stream() << "_recvChunkCommit failed: " << causedBy(recvChunkCommitStatus)); } log() << "moveChunk migrate commit accepted by TO-shard: " << res << migrateLog; BSONArrayBuilder updates; { // Update for the chunk being moved BSONObjBuilder op; op.append("op", "u"); op.appendBool("b", false); // No upserting op.append("ns", ChunkType::ConfigNS); BSONObjBuilder n(op.subobjStart("o")); n.append(ChunkType::name(), Chunk::genID(_nss.ns(), _minKey)); myVersion.addToBSON(n, ChunkType::DEPRECATED_lastmod()); n.append(ChunkType::ns(), _nss.ns()); n.append(ChunkType::min(), _minKey); n.append(ChunkType::max(), _maxKey); n.append(ChunkType::shard(), _toShard); n.done(); BSONObjBuilder q(op.subobjStart("o2")); q.append(ChunkType::name(), Chunk::genID(_nss.ns(), _minKey)); q.done(); updates.append(op.obj()); } // Version at which the next highest lastmod will be set. If the chunk being moved is the last // in the shard, nextVersion is that chunk's lastmod otherwise the highest version is from the // chunk being bumped on the FROM-shard. ChunkVersion nextVersion = myVersion; // If we have chunks left on the FROM shard, update the version of one of them as well. We can // figure that out by grabbing the metadata as it has been changed. const std::shared_ptr bumpedCollMetadata( shardingState->getCollectionMetadata(_nss.ns())); if (bumpedCollMetadata->getNumChunks() > 0) { // get another chunk on that shard ChunkType bumpChunk; invariant(bumpedCollMetadata->getNextChunk(bumpedCollMetadata->getMinKey(), &bumpChunk)); BSONObj bumpMin = bumpChunk.getMin(); BSONObj bumpMax = bumpChunk.getMax(); dassert(bumpMin.woCompare(_minKey) != 0); BSONObjBuilder op; op.append("op", "u"); op.appendBool("b", false); op.append("ns", ChunkType::ConfigNS); nextVersion.incMinor(); // same as used on donateChunk BSONObjBuilder n(op.subobjStart("o")); n.append(ChunkType::name(), Chunk::genID(_nss.ns(), bumpMin)); nextVersion.addToBSON(n, ChunkType::DEPRECATED_lastmod()); n.append(ChunkType::ns(), _nss.ns()); n.append(ChunkType::min(), bumpMin); n.append(ChunkType::max(), bumpMax); n.append(ChunkType::shard(), _fromShard); n.done(); BSONObjBuilder q(op.subobjStart("o2")); q.append(ChunkType::name(), Chunk::genID(_nss.ns(), bumpMin)); q.done(); updates.append(op.obj()); log() << "moveChunk updating self version to: " << nextVersion << " through " << bumpMin << " -> " << bumpMax << " for collection '" << _nss.ns() << "'" << migrateLog; } else { log() << "moveChunk moved last chunk out for collection '" << _nss.ns() << "'" << migrateLog; } BSONArrayBuilder preCond; { BSONObjBuilder b; b.append("ns", ChunkType::ConfigNS); b.append("q", BSON("query" << BSON(ChunkType::ns(_nss.ns())) << "orderby" << BSON(ChunkType::DEPRECATED_lastmod() << -1))); { BSONObjBuilder bb(b.subobjStart("res")); // TODO: For backwards compatibility, we can't yet require an epoch here bb.appendTimestamp(ChunkType::DEPRECATED_lastmod(), originalCollVersion.toLong()); bb.done(); } preCond.append(b.obj()); } Status applyOpsStatus{Status::OK()}; try { // For testing migration failures if (MONGO_FAIL_POINT(failMigrationConfigWritePrepare)) { throw DBException("mock migration failure before config write", ErrorCodes::PrepareConfigsFailed); } applyOpsStatus = grid.catalogManager(_txn)->applyChunkOpsDeprecated( _txn, updates.arr(), preCond.arr(), _nss.ns(), nextVersion); } catch (const DBException& ex) { applyOpsStatus = ex.toStatus(); } if (applyOpsStatus == ErrorCodes::PrepareConfigsFailed) { // In the process of issuing the migrate commit, the SyncClusterConnection checks that // the config servers are reachable. If they are not, we are sure that the applyOps // command was not sent to any of the configs, so we can safely back out of the // migration here, by resetting the shard version that we bumped up to in the // donateChunk() call above. log() << "About to acquire moveChunk coll lock to reset shard version from " << "failed migration"; { ScopedTransaction transaction(_txn, MODE_IX); Lock::DBLock dbLock(_txn->lockState(), _nss.db(), MODE_IX); Lock::CollectionLock collLock(_txn->lockState(), _nss.ns(), MODE_X); // Revert the metadata back to the state before "forgetting" about the chunk shardingState->undoDonateChunk(_txn, _nss.ns(), getCollMetadata()); } log() << "Shard version successfully reset to clean up failed migration"; const string msg = stream() << "Failed to send migrate commit to configs " << causedBy(applyOpsStatus); return Status(applyOpsStatus.code(), msg); } else if (!applyOpsStatus.isOK()) { fassertStatusOK(34431, applyOpsStatus); } MONGO_FAIL_POINT_PAUSE_WHILE_SET(hangBeforeLeavingCriticalSection); shardingState->migrationSourceManager()->setInCriticalSection(false); ShardingStateRecovery::endMetadataOp(_txn); // Migration is done, just log some diagnostics information BSONObj chunkInfo = BSON("min" << _minKey << "max" << _maxKey << "from" << _fromShard << "to" << _toShard); BSONObjBuilder commitInfo; commitInfo.appendElements(chunkInfo); if (res["counts"].type() == Object) { commitInfo.appendElements(res["counts"].Obj()); } grid.catalogManager(_txn)->logChange(_txn, "moveChunk.commit", _nss.ns(), commitInfo.obj()); shardingState->migrationSourceManager()->done(_txn); _isRunning = false; return Status::OK(); } ChunkVersion ChunkMoveOperationState::getShardVersion() const { invariant(_distLockStatus.is_initialized()); invariant(_distLockStatus->isOK()); return _shardVersion; } std::shared_ptr ChunkMoveOperationState::getCollMetadata() const { invariant(_distLockStatus.is_initialized()); invariant(_distLockStatus->isOK()); return _collMetadata; } Status ChunkMoveOperationState::start(const MigrationSessionId& sessionId, const BSONObj& shardKeyPattern) { auto migrationSourceManager = ShardingState::get(_txn)->migrationSourceManager(); if (!migrationSourceManager->start( _txn, sessionId, _nss.ns(), _minKey, _maxKey, shardKeyPattern)) { return {ErrorCodes::ConflictingOperationInProgress, "Not starting chunk migration because another migration is already in progress " "from this shard"}; } _isRunning = true; return Status::OK(); } } // namespace mongo 0 /** * COPYRIGHT (C) 2020 ALL RIGHTS RESERVED. * * @brief HTTP and WEBSOCKET controller. * @author * @date Oct 04, 2020 */ #ifndef CAGE_CONTROLLER_HPP_ #define CAGE_CONTROLLER_HPP_ #include #include #include #include #include #include #include "cage/http_view.hpp" #include "cage/router.hpp" #include "cage/websock_view.hpp" namespace cage { class Controller { public: using SelfPtr = std::shared_ptr; using RouterPtr = Router::SelfPtr; using HttpViewPtr = HttpView::SelfPtr; using WebsockViewPtr = WebsockView::SelfPtr; using SenderType = WebsockView::SenderType; using CloserType = WebsockView::CloserType; public: virtual ~Controller() = default; Controller() = default; virtual void RegisterRouter(RouterPtr p_router); virtual HttpViewPtr GetHttpView(std::string const& target); virtual WebsockViewPtr MakeWebsockView(HttpRequest request, SenderType sender, CloserType closer); virtual std::string ServerName(); virtual std::size_t WebsockMsgQueCap(); virtual std::chrono::seconds SocketTimeout(); virtual std::size_t HttpHeadLimit(); virtual std::size_t HttpBodyLimit(); protected: std::string ParseUrl(std::string_view target); private: std::vector router_vec_; }; } // namespace cage #endif // CAGE_CONTROLLER_HPP_ /* * Copyright 2009-2017 Alibaba Cloud 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 #include using namespace AlibabaCloud::Dataworks_public; using namespace AlibabaCloud::Dataworks_public::Model; GetManualDagInstancesResult::GetManualDagInstancesResult() : ServiceResult() {} GetManualDagInstancesResult::GetManualDagInstancesResult(const std::string &payload) : ServiceResult() { parse(payload); } GetManualDagInstancesResult::~GetManualDagInstancesResult() {} void GetManualDagInstancesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allInstancesNode = value["Instances"]["InstancesItem"]; for (auto valueInstancesInstancesItem : allInstancesNode) { InstancesItem instancesObject; if(!valueInstancesInstancesItem["NodeId"].isNull()) instancesObject.nodeId = std::stol(valueInstancesInstancesItem["NodeId"].asString()); if(!valueInstancesInstancesItem["InstanceId"].isNull()) instancesObject.instanceId = std::stol(valueInstancesInstancesItem["InstanceId"].asString()); if(!valueInstancesInstancesItem["DagId"].isNull()) instancesObject.dagId = std::stol(valueInstancesInstancesItem["DagId"].asString()); if(!valueInstancesInstancesItem["DagType"].isNull()) instancesObject.dagType = valueInstancesInstancesItem["DagType"].asString(); if(!valueInstancesInstancesItem["Status"].isNull()) instancesObject.status = valueInstancesInstancesItem["Status"].asString(); if(!valueInstancesInstancesItem["BizDate"].isNull()) instancesObject.bizDate = std::stol(valueInstancesInstancesItem["BizDate"].asString()); if(!valueInstancesInstancesItem["CycTime"].isNull()) instancesObject.cycTime = std::stol(valueInstancesInstancesItem["CycTime"].asString()); if(!valueInstancesInstancesItem["CreateTime"].isNull()) instancesObject.createTime = std::stol(valueInstancesInstancesItem["CreateTime"].asString()); if(!valueInstancesInstancesItem["ModifyTime"].isNull()) instancesObject.modifyTime = std::stol(valueInstancesInstancesItem["ModifyTime"].asString()); if(!valueInstancesInstancesItem["NodeName"].isNull()) instancesObject.nodeName = valueInstancesInstancesItem["NodeName"].asString(); if(!valueInstancesInstancesItem["BeginWaitTimeTime"].isNull()) instancesObject.beginWaitTimeTime = std::stol(valueInstancesInstancesItem["BeginWaitTimeTime"].asString()); if(!valueInstancesInstancesItem["BeginWaitResTime"].isNull()) instancesObject.beginWaitResTime = std::stol(valueInstancesInstancesItem["BeginWaitResTime"].asString()); if(!valueInstancesInstancesItem["BeginRunningTime"].isNull()) instancesObject.beginRunningTime = std::stol(valueInstancesInstancesItem["BeginRunningTime"].asString()); if(!valueInstancesInstancesItem["ParamValues"].isNull()) instancesObject.paramValues = valueInstancesInstancesItem["ParamValues"].asString(); if(!valueInstancesInstancesItem["FinishTime"].isNull()) instancesObject.finishTime = std::stol(valueInstancesInstancesItem["FinishTime"].asString()); if(!valueInstancesInstancesItem["TaskType"].isNull()) instancesObject.taskType = valueInstancesInstancesItem["TaskType"].asString(); instances_.push_back(instancesObject); } } std::vector GetManualDagInstancesResult::getInstances()const { return instances_; } GalaxyHunters/Vivid #include "cell_updater_2d.hpp" CellUpdater::~CellUpdater(void) {} sock-merchant/test_sock_merchant.cpp #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch2/catch.hpp" #include "sock_merchant.hpp" TEST_CASE("Sock Merchant from HackerRank") { SECTION("Case 1") { std::vector case_1{ 1 }; REQUIRE( sockMerchant(case_1.size(), case_1) == 0); } SECTION("Case 2") { std::vector case_2{ 1, 1 }; REQUIRE( sockMerchant(case_2.size(), case_2) == 1); } SECTION("Case 3") { std::vector case_3{}; REQUIRE( sockMerchant(case_3.size(), case_3) == 0); } SECTION("Case 4") { std::vector case_4{ 1, 2, 1 }; REQUIRE( sockMerchant(case_4.size(), case_4) == 1); } SECTION("Case 5") { std::vector case_5{ 1, 2, 1, 2 }; REQUIRE( sockMerchant(case_5.size(), case_5) == 2); } } npocmaka/Windows-Server-2003 #include "precomp.h" static BOOL importLDAPBitmapHelper(LPCTSTR pcszIns, LPCTSTR pcszWorkDir, BOOL fImport); static BOOL importOEInfoHelper(LPCTSTR pcszIns, LPCTSTR pcszWorkDir, BOOL fImport); static BOOL encodeSignatureHelper(LPCTSTR pcszFrom, LPTSTR pszTo, BOOL fEncode); static void decodeSig(LPCTSTR pcszFrom, LPTSTR pszTo); static void encodeSig(LPCTSTR pcszFrom, LPTSTR pszTo); BOOL WINAPI ImportLDAPBitmapA(LPCSTR pcszIns, LPCSTR pcszWorkDir, BOOL fImport) { USES_CONVERSION; return importLDAPBitmapHelper(A2CT(pcszIns), A2CT(pcszWorkDir), fImport); } BOOL WINAPI ImportLDAPBitmapW(LPCWSTR pcwszIns, LPCWSTR pcwszWorkDir, BOOL fImport) { USES_CONVERSION; return importLDAPBitmapHelper(W2CT(pcwszIns), W2CT(pcwszWorkDir), fImport); } BOOL WINAPI ImportOEInfoA(LPCSTR pcszIns, LPCSTR pcszWorkDir, BOOL fImport) { USES_CONVERSION; return importOEInfoHelper(A2CT(pcszIns), A2CT(pcszWorkDir), fImport); } BOOL WINAPI ImportOEInfoW(LPCWSTR pcwszIns, LPCWSTR pcwszWorkDir, BOOL fImport) { USES_CONVERSION; return importOEInfoHelper(W2CT(pcwszIns), W2CT(pcwszWorkDir), fImport); } BOOL WINAPI EncodeSignatureA(LPCSTR pcszFrom, LPSTR pszTo, BOOL fEncode) { LPTSTR pszBuf = (LPTSTR)LocalAlloc(LPTR, 1024 * sizeof(TCHAR)); BOOL fRet = FALSE; USES_CONVERSION; if (pszBuf != NULL) { fRet = encodeSignatureHelper(A2CT(pcszFrom), pszBuf, fEncode); T2Abux(pszBuf, pszTo); } return fRet; } BOOL WINAPI EncodeSignatureW(LPCWSTR pcwszFrom, LPWSTR pwszTo, BOOL fEncode) { LPTSTR pszBuf = (LPTSTR)LocalAlloc(LPTR, 1024 * sizeof(TCHAR)); BOOL fRet = FALSE; USES_CONVERSION; if (pszBuf != NULL) { fRet = encodeSignatureHelper(W2CT(pcwszFrom), pszBuf, fEncode); T2Wbux(pszBuf, pwszTo); } LocalFree(pszBuf); //bug 14001, forgot to free temp buffer return fRet; } static BOOL importLDAPBitmapHelper(LPCTSTR pcszIns, LPCTSTR pcszWorkDir, BOOL fImport) { TCHAR szLDAPBitmap[MAX_PATH]; BOOL fSuccess = TRUE; if (pcszIns == NULL || pcszWorkDir == NULL) return FALSE; if (fImport) PathRemovePath(pcszWorkDir); GetPrivateProfileString(IS_LDAP, IK_BITMAP, TEXT(""), szLDAPBitmap, countof(szLDAPBitmap), pcszIns); if (szLDAPBitmap[0] != TEXT('\0')) { if (fImport) { ASSERT(PathFileExists(szLDAPBitmap)); fSuccess = CopyFileToDir(szLDAPBitmap, pcszWorkDir); } else { DeleteFileInDir(szLDAPBitmap, pcszWorkDir); WritePrivateProfileString(IS_LDAP, IK_BITMAP, NULL, pcszIns); } } return fSuccess; } static BOOL importOEInfoHelper(LPCTSTR pcszIns, LPCTSTR pcszWorkDir, BOOL fImport) { TCHAR szInfopane[INTERNET_MAX_URL_LENGTH], szInfopaneBmp[MAX_PATH], szHTMLPath[MAX_PATH]; BOOL fSuccess; if (pcszIns == NULL || pcszWorkDir == NULL) return FALSE; if (fImport) PathRemovePath(pcszWorkDir); fSuccess = TRUE; GetPrivateProfileString(IS_INTERNETMAIL, IK_INFOPANE, TEXT(""), szInfopane, countof(szInfopane), pcszIns); if (szInfopane[0] != TEXT('\0') && !PathIsURL(szInfopane)) { if (fImport) { ASSERT(PathFileExists(szInfopane)); if (CopyFileToDir(szInfopane, pcszWorkDir)) CopyHtmlImgs(szInfopane, pcszWorkDir, NULL, NULL); else fSuccess = FALSE; } else { TCHAR szTemp[MAX_PATH]; PathCombine(szTemp, pcszWorkDir, PathFindFileName(szInfopane)); if (PathFileExists(szTemp)) { DeleteHtmlImgs(szTemp, pcszWorkDir, NULL, NULL); DeleteFileInDir(szTemp, pcszWorkDir); } } } GetPrivateProfileString(IS_INTERNETMAIL, IK_INFOPANEBMP, TEXT(""), szInfopaneBmp, countof(szInfopaneBmp), pcszIns); if (szInfopaneBmp[0] != TEXT('\0')) { if (fImport) { ASSERT(PathFileExists(szInfopaneBmp)); fSuccess = CopyFileToDir(szInfopaneBmp, pcszWorkDir) && fSuccess; } else DeleteFileInDir(szInfopaneBmp, pcszWorkDir); } GetPrivateProfileString(IS_INTERNETMAIL, IK_WELCOMEMESSAGE, TEXT(""), szHTMLPath, countof(szHTMLPath), pcszIns); if (szHTMLPath[0] != TEXT('\0')) { if (fImport) { ASSERT(PathFileExists(szHTMLPath)); if (CopyFileToDir(szHTMLPath, pcszWorkDir)) CopyHtmlImgs(szHTMLPath, pcszWorkDir, NULL, NULL); else fSuccess = FALSE; } else { TCHAR szTemp[MAX_PATH]; PathCombine(szTemp, pcszWorkDir, PathFindFileName(szHTMLPath)); if (PathFileExists(szTemp)) { DeleteHtmlImgs(szTemp, pcszWorkDir, NULL, NULL); DeleteFileInDir(szTemp, pcszWorkDir); } } } if (!fImport) { WritePrivateProfileString(IS_INTERNETMAIL, IK_INFOPANE, NULL, pcszIns); WritePrivateProfileString(IS_INTERNETMAIL, IK_INFOPANEBMP, NULL, pcszIns); WritePrivateProfileString(IS_INTERNETMAIL, IK_WELCOMEMESSAGE, NULL, pcszIns); } return fSuccess; } static BOOL encodeSignatureHelper(LPCTSTR pcszFrom, LPTSTR pszTo, BOOL fEncode) { if (fEncode) encodeSig(pcszFrom, pszTo); else decodeSig(pcszFrom, pszTo); return TRUE; } static void decodeSig(LPCTSTR pszFrom, LPTSTR pszTo) { if (pszFrom == NULL || pszTo == NULL) return; while (*pszFrom != TEXT('\0')) #ifndef UNICODE if (IsDBCSLeadByte(*pszFrom)) { *pszTo++ = *pszFrom++; *pszTo++ = *pszFrom++; } else #endif if (*pszFrom != TEXT('\\')) *(pszTo++) = *(pszFrom++); else { pszFrom++; if (*pszFrom == TEXT('n')) { *pszTo++ = (TCHAR)0x0D; *pszTo++ = (TCHAR)0x0A; pszFrom++; } else if (*pszFrom == TEXT('\\')) { *pszTo++ = TEXT('\\'); pszFrom++; } else *pszTo++ = *pszFrom++; } *pszTo = TEXT('\0'); } static void encodeSig(LPCTSTR pszFrom, LPTSTR pszTo) { if (pszFrom == NULL || pszTo == NULL) return; while (*pszFrom != TEXT('\0')) #ifndef UNICODE if (IsDBCSLeadByte(*pszFrom)) { *pszTo++ = *pszFrom++; *pszTo++ = *pszFrom++; } else #endif if ((*pszFrom == TEXT('\r')) || (*pszFrom == TEXT('\n'))) { *pszTo++ = TEXT('\\'); *pszTo++ = TEXT('n'); pszFrom++; if ((*pszFrom == TEXT('\r')) || (*pszFrom == TEXT('\n'))) pszFrom++; } else { if (*pszFrom == TEXT('\\')) *pszTo++ = TEXT('\\'); *pszTo++ = *pszFrom++; } *pszTo = TEXT('\0'); } #include "stdafx.h" #include "Spinner.h" Vector2D Spinner::GetPosition(time_t tick) { float dTime = (tick - m_LastTime); m_LastTime = tick; float radius = 50.0f + cos(m_Rotation) * sin(1.1 * m_Rotation) * 20.0f; Vector2D point = m_Point + Vector2D(cos(m_Rotation), sin(m_Rotation)) * radius; m_Rotation += dTime * Random(1.0f, 1.1f) / 20.0f; return point; }ffteja/cgalGenerator/examples/Generator/random_convex_hull_2.cpp1000+ #include #include #include #include #include #include using namespace CGAL; typedef Exact_predicates_inexact_constructions_kernel K; typedef K::Point_2 Point; typedef K::FT FT; const double RADIUS=1.0; int main( ) { int N=10000; std::vector v; boost::mt19937 gen; gen.seed(0u); random_convex_hull_in_disc_2(N,RADIUS,gen,std::back_inserter(v),K()); size_t size = v.size(); FT area=polygon_area_2(v.begin(),v.end(),K()); std::cout<<"A random convex polygon inscribed in a disc with "< using namespace std; Explorer::Explorer() { x = 0; y = 0; } Explorer::Explorer(int xnew, int ynew) { x = xnew; y = ynew; } int Explorer::getterx() { return x; } bool Explorer::GotBlocked() { return Blocked; } int Explorer::gettery() { return y; } char Explorer::ReturnName() { return Name; } bool Explorer::ReturnFoundTreasure() { return FoundTreasure; } void Explorer::move(map &Map) { //going right if (y + 1 <= Map.GetCols() - 1) if (Map.Getxy(x, y + 1) == '-' || Map.Getxy(x, y + 1) == 'T') { if (Map.Getxy(x, y + 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x, y + 1, this); if (FoundTreasure) { Map.Setxy(x, y + 1); cout << Name << " has found a treasure!!!" << endl; } y++; return; } // going left if (y - 1 > 0) if (Map.Getxy(x, y - 1) == '-' || Map.Getxy(x, y - 1) == 'T') { if (Map.Getxy(x, y - 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x, y - 1, this); if (FoundTreasure) { Map.Setxy(x, y - 1); cout << Name << " has found a treasure!!!" << endl; } y--; return; } //going down if (x + 1 <= Map.GetRows() - 1) if (Map.Getxy(x + 1, y) == '-' || Map.Getxy(x + 1, y) == 'T') { if (Map.Getxy(x + 1, y) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x + 1, y, this); if (FoundTreasure) { Map.Setxy(x + 1, y); cout << Name << " has found a treasure!!!" << endl; } x++; return; } //going up-right if (x - 1 > 0 && y + 1 <= Map.GetCols() - 1) if (Map.Getxy(x - 1, y + 1) == '-' || Map.Getxy(x - 1, y + 1) == 'T') { if (Map.Getxy(x - 1, y + 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x - 1, y + 1, this); if (FoundTreasure) { Map.Setxy(x - 1, y + 1); cout << Name << " has found a treasure!!!" << endl; } x--; y++; return; } //Going up if (x - 1 > 0) if (Map.Getxy(x - 1, y) == '-' || Map.Getxy(x - 1, y) == 'T') { if (Map.Getxy(x - 1, y) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x - 1, y, this); if (FoundTreasure) { Map.Setxy(x - 1, y); cout << Name << " has found a treasure!!!" << endl; } x--; return; } //going right if (y + 1 <= Map.GetCols() - 1) if (Map.Getxy(x, y + 1) == '-' || Map.Getxy(x, y + 1) == 'T') { if (Map.Getxy(x, y + 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x, y + 1, this); if (FoundTreasure) { Map.Setxy(x, y + 1); cout << Name << " has found a treasure!!!" << endl; } y++; return; } //going down-right if (x + 1 <= Map.GetRows() - 1 && y + 1 <= Map.GetCols() - 1) if (Map.Getxy(x + 1, y + 1) == '-' || Map.Getxy(x + 1, y + 1) == 'T') { if (Map.Getxy(x + 1, y + 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x + 1, y + 1, this); if (FoundTreasure) { Map.Setxy(x + 1, y + 1); cout << Name << " has found a treasure!!!" << endl; } x++; y++; return; } //going down-left if (x + 1 <= Map.GetRows() - 1 && y - 1 > 0) if (Map.Getxy(x + 1, y - 1) == '-' || Map.Getxy(x + 1, y - 1) == 'T') { if (Map.Getxy(x + 1, y - 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x + 1, y - 1, this); if (FoundTreasure) { Map.Setxy(x + 1, y - 1); cout << Name << " has found a treasure!!!" << endl; } x++; y--; return; } //going up-left if (x - 1 > 0 && y - 1 > 0) if (Map.Getxy(x - 1, y - 1) == '-' || Map.Getxy(x - 1, y - 1) == 'T') { if (Map.Getxy(x - 1, y - 1) == 'T') { FoundTreasure = true; } Map.SetAgentsPositions(x, y, x - 1, y - 1, this); if (FoundTreasure) { Map.Setxy(x - 1, y - 1); cout << Name << " has found a treasure!!!" << endl; } x--; y--; return; } Blocked = true; cout << Name << " HAS DIED " << endl; } //********************************************************* // Read_Node.cpp - read the node file //********************************************************* #include "Network_Service.hpp" #include "Node_File.hpp" //--------------------------------------------------------- // Read_Node //--------------------------------------------------------- void Network_Service::Read_Node (void) { Db_File *file = Network_Db_File (NODE); //---- store the node data ---- Show_Message ("Reading %s -- Record", file->File_Type ()); Set_Progress (); file->Num_Records (); First_Record (true); while (file->Read ()) { Show_Progress (); if (Node_Processing (file)) { if (!node_data.Add ()) { Error ("Adding Record to the Node Data List"); } } First_Record (false); } End_Progress (); file->Close (); Print (2, "Number of %s Records = %d", file->File_Type (), Progress_Count ()); int num = node_data.Num_Records (); if (num && num != Progress_Count ()) { Print (1, "Number of Node Data Records = %d", num); } node_data.Optimize (); if (num > 0) Network_Data_True (NODE); } //--------------------------------------------------------- // Node_Processing //--------------------------------------------------------- bool Network_Service::Node_Processing (Db_File *fh) { double x, y; Node_Data *node_ptr; Node_File *file = (Node_File *) fh; //---- reserve memory ---- if (node_data.Max_Records () == 0) { if (!node_data.Max_Records (file->Num_Records ())) goto mem_error; } //---- read and save the data ---- node_ptr = node_data.New_Record (); if (node_ptr == NULL) goto mem_error; node_ptr->Node (file->Node ()); if (node_ptr->Node () == 0) return (false); x = file->X (); y = file->Y (); if (Projection_Flag ()) { if (!(Get_Projection ()->Convert (&x, &y))) { return (Check_Message ("Converting Coordinate %lf, %lf", x, y)); } } node_ptr->X (Round (x)); node_ptr->Y (Round (y)); node_ptr->Z (Round (file->Z ())); return (true); mem_error: Error ("Insufficient Memory for Node Data"); return (false); } 1-10 /****************************************************************************** * @file: CAmPersistenceDefault.cpp * * This file contains the definition of Persistence default class * (member functions and data members) used to implement the logic of * reading and writing data for last main connection and last volume * from the file system (RFS) * * @component: AudioManager Generic Controller * * @author: <> * , <> * * @copyright (c) 2015 Advanced Driver Information Technology. * This code is developed by Advanced Driver Information Technology. * Copyright of Advanced Driver Information Technology, Bosch, and DENSO. * All rights reserved. * *****************************************************************************/ #include "CAmPersistenceDefault.h" #include "CAmLogger.h" #include #include #include #include "CAmCommonUtility.h" #include namespace am { namespace gc { class CAmConnectionNode : public CAmComplexNode { public: CAmConnectionNode(const char *tagname, gc_persistence_connectionData_s &pConnection, void *data = NULL) : CAmComplexNode(tagname) , mpConnection(pConnection) , mSourceNameAttribute(ATTRIBUTE_SOURCE, mpConnection.sourceName) , mVolumeAttribute(ATTRIBUTE_VOLUME, mpConnection.volume) , mOrderAttribute(ATTRIBUTE_ORDER, mpConnection.order) , mLastConValidAttribute(ATTRIBUTE_LASTCON_VALID, mpConnection.lastConnectionValid) { (void)data; } virtual void expand(void) { addAttribute(&mSourceNameAttribute); addAttribute(&mVolumeAttribute); addAttribute(&mOrderAttribute); addAttribute(&mLastConValidAttribute); } void push_back(std::vector &listConnection, gc_persistence_connectionData_s &connection) { listConnection.push_back(connection); } private: gc_persistence_connectionData_s &mpConnection; CAmStringAttribute mSourceNameAttribute; CAmint16Attribute mVolumeAttribute; CAmint16Attribute mOrderAttribute; CAmint16Attribute mLastConValidAttribute; }; class CAmStackNode : public CAmComplexNode { public: CAmStackNode(const char *tagname, gc_persistence_stackData_s &stack, void *data = NULL) : CAmComplexNode(tagname) , mpStack(stack) , mConnectionListNode(TAG_CONNECTION, mpStack.listConnection) , mSinkNameAttribute(ATTRIBUTE_SINK, mpStack.sinkName) , mVolumeAttribute(ATTRIBUTE_VOLUME, mpStack.volume) { (void)data; } virtual void expand(void) { addChildNode(&mConnectionListNode); addAttribute(&mSinkNameAttribute); addAttribute(&mVolumeAttribute); } void push_back(std::vector &listStack, gc_persistence_stackData_s &stack) { listStack.push_back(stack); } private: gc_persistence_stackData_s &mpStack; CAmListNode< gc_persistence_connectionData_s, CAmConnectionNode> mConnectionListNode; CAmStringAttribute mSinkNameAttribute; CAmint16Attribute mVolumeAttribute; }; class CAmPersistenceMainSoundPropertyNode : public CAmComplexNode { public: CAmPersistenceMainSoundPropertyNode(const char *tagname, gc_persistence_mainSoundPropertyData_s &iMainSoundProperty, void *data = NULL) : CAmComplexNode(tagname) , mpMainSoundProperty(iMainSoundProperty) , mTypeAttribute(ATTRIBUTE_VALUE, mpMainSoundProperty.value) , mValueAttribute(ATTRIBUTE_TYPE, mpMainSoundProperty.type) { (void)data; } virtual void expand(void) { addAttribute(&mTypeAttribute); addAttribute(&mValueAttribute); } void push_back(std::vector &listMainSoundProperty, gc_persistence_mainSoundPropertyData_s &rMainSoundProperty) { listMainSoundProperty.push_back(rMainSoundProperty); } private: gc_persistence_mainSoundPropertyData_s &mpMainSoundProperty; CAmStringAttribute mTypeAttribute; CAmStringAttribute mValueAttribute; }; class CAmMainSoundPropertiesNode : public CAmComplexNode { public: CAmMainSoundPropertiesNode(const char *tagname, gc_persistence_mainSoundProData_s &iMainSoundProperties, void *data = NULL) : CAmComplexNode(tagname) , mpMainSoundPro(iMainSoundProperties) , mMainSoundPropertyListNode(TAG_MAIN_SOUND_PROPERTY, mpMainSoundPro.listMainSoundProperty) , mSinkAttribute(ATTRIBUTE_SINK, mpMainSoundPro.sinkName) , mSourceAttribute(ATTRIBUTE_SOURCE, mpMainSoundPro.sourceName) { (void)data; } virtual void expand(void) { addChildNode(&mMainSoundPropertyListNode); addAttribute(&mSinkAttribute); addAttribute(&mSourceAttribute); } void push_back(std::vector &listMainSoundPro, gc_persistence_mainSoundProData_s &mMainSoundProperties) { listMainSoundPro.push_back(mMainSoundProperties); } private: gc_persistence_mainSoundProData_s &mpMainSoundPro; CAmListNode mMainSoundPropertyListNode; CAmStringAttribute mSinkAttribute; CAmStringAttribute mSourceAttribute; }; class CAmClasNode : public CAmComplexNode { public: CAmClasNode(const char *tagname, gc_persistence_classData_s &classData, void *data = NULL) : CAmComplexNode(tagname) , mpClassData(classData) , mListStackNode(TAG_STACK, mpClassData.listConnections) , mListMainSoundProNode(TAG_MAIN_SOUND_PROPERTIES, mpClassData.listMainSoundProperties) , mClassNameAttribute(ATTRIBUTE_NAME, mpClassData.name) , mVolumeAttribute(ATTRIBUTE_VOLUME, mpClassData.volume) { (void)data; } virtual void expand(void) { addChildNode(&mListStackNode); addChildNode(&mListMainSoundProNode); addAttribute(&mClassNameAttribute); addAttribute(&mVolumeAttribute); } void push_back(std::vector &listClass, gc_persistence_classData_s &clas) { listClass.push_back(clas); } private: gc_persistence_classData_s &mpClassData; CAmListNode< gc_persistence_stackData_s, CAmStackNode > mListStackNode; CAmListNode< gc_persistence_mainSoundProData_s, CAmMainSoundPropertiesNode > mListMainSoundProNode; CAmStringAttribute mClassNameAttribute; CAmint16Attribute mVolumeAttribute; }; class CAmSystemPropertyPersistenceNode : public CAmSimpleNode { public: CAmSystemPropertyPersistenceNode(const char *tagname, gc_persistence_systemProperty_s &systemPro, void *data = NULL) : CAmSimpleNode(tagname) , mptrSystemProperty(systemPro) , mTypeAttribute(ATTRIBUTE_TYPE, mptrSystemProperty.type) , mValueAttribute(ATTRIBUTE_VALUE, mptrSystemProperty.value) { LOG_FN_DEBUG(__FILENAME__, __func__, "is called", tagname, systemPro.type, systemPro.value); addAttribute(&mTypeAttribute); addAttribute(&mValueAttribute); (void)data; } void push_back(std::vector &listSystemProperty, gc_persistence_systemProperty_s &isystemProperty) { listSystemProperty.push_back(isystemProperty); } private: gc_persistence_systemProperty_s &mptrSystemProperty; CAmStringAttribute mTypeAttribute; CAmStringAttribute mValueAttribute; }; class CAmPersistenceNode : public CAmComplexNode { public: CAmPersistenceNode(const char *tagName, std::vector &persistence, std::vector &rSystemPro) : CAmComplexNode(tagName) , mPersistence(persistence) , mListClassNode(TAG_CLASS, mPersistence) , mPersistence1(rSystemPro) , mListSystemPropertyNode(TAG_SYSTEM_PROPERTY, mPersistence1) { } virtual void expand(void) { addChildNode(&mListSystemPropertyNode); addChildNode(&mListClassNode); } private: std::vector< gc_persistence_classData_s > &mPersistence; std::vector< gc_persistence_systemProperty_s > &mPersistence1; CAmListNode< gc_persistence_classData_s, CAmClasNode > mListClassNode; CAmListNode< gc_persistence_systemProperty_s, CAmSystemPropertyPersistenceNode > mListSystemPropertyNode; }; CAmPersistenceDefault::CAmPersistenceDefault() : mFileName(GENERIC_CONTROLLER_PERSISTENCE_FILE) { LOG_FN_DEBUG(__FILENAME__, __func__, "is Called"); return; } CAmPersistenceDefault::~CAmPersistenceDefault() { _createSubDirectories(); if (_writeTOXML()) { LOG_FN_DEBUG(__FILENAME__, __func__, "is called & Write data in the XML file is Fine & filename is ", mFileName); } else { LOG_FN_WARN(__FILENAME__, __func__, "is called & Write data in the XML file is Failed & filename is ", mFileName); } } am_Error_e CAmPersistenceDefault::open(const std::string &/*appName*/) { am_Error_e resRead = _readFromXML(); if (E_OK != resRead) { LOG_FN_WARN(__FILENAME__, __func__, "& _readFromXML is FAILED & file name is ", mFileName); return E_NON_EXISTENT; } return E_OK; } am_Error_e CAmPersistenceDefault::read(const std::string &keyName, std::string &readData, int dataSize) { MapData::iterator itFileData; itFileData = mFileData.find(keyName); if (itFileData != mFileData.end()) { readData = itFileData->second; LOG_FN_INFO(__FILENAME__, __func__, "is called & data read from Map for keyName = ", keyName, " is =", readData); return E_OK; } else { LOG_FN_WARN(__FILENAME__, __func__, "is called & data read from Map is Failed for keyName = ", keyName); return E_DATABASE_ERROR; } return E_OK; } am_Error_e CAmPersistenceDefault::write(const std::string &keyName, const std::string &writeData, int dataSize) { LOG_FN_DEBUG(__FILENAME__, __func__, "keyName=", keyName, "Value=", writeData); mFileData[keyName] = writeData; return E_OK; } void CAmPersistenceDefault::_updateMainConnectionVolume(std::string className, std::string sourceName, std::string sinkName, int16_t volume, std::vector &outVClassDataS) { bool classFound = false; gc_persistence_classData_s classData; gc_persistence_stackData_s stackData; gc_persistence_connectionData_s connData; connData.sourceName = sourceName; connData.volume = volume; stackData.sinkName = sinkName; stackData.listConnection.push_back(connData); classData.name = className; classData.listConnections.push_back(stackData); for (auto &itClassData : outVClassDataS) { if (itClassData.name == className) { classFound = true; bool sinkFound = false; for ( auto &itStackData : itClassData.listConnections) { if (sinkName == itStackData.sinkName) { sinkFound = true; bool sourceFound = false; for (auto &itSourceData : itStackData.listConnection) { if (sourceName == itSourceData.sourceName) { sourceFound = true; itSourceData.volume = volume; } } if (sourceFound == false) { itStackData.listConnection.push_back(connData); } } } if (sinkFound == false) { stackData.listConnection.push_back(connData); itClassData.listConnections.push_back(stackData); } } } if (classFound == false) { outVClassDataS.push_back(classData); } } bool CAmPersistenceDefault::_lastMainConnectionVolumeStruct(std::string inputStr, std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { LOG_FN_INFO(__FILENAME__, __func__, "Input String=", inputStr); std::vector listClassesStr; /* E.g. Input String for last main connection volume as below * {BASE,[source1:sink1=20][source2:sink2=30]}{PHONE,[source3:sink3=40][source4:sink4=50]}*/ std::string delimiter = "{"; if (E_OK != CAmCommonUtility::parseString(delimiter, inputStr, listClassesStr)) { LOG_FN_ERROR(__FILENAME__, __func__, "not possible to parse last main connection volume"); return false; } for (auto itlistClassesStr : listClassesStr) { std::vector listClassStr; delimiter = ","; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistClassesStr, listClassStr)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter , not found"); continue; } if ( listClassStr.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter , wrong format"); continue; } std::string className; className = listClassStr[0]; std::vector listConVolumeStr; delimiter = "["; if (E_OK != CAmCommonUtility::parseString(delimiter, listClassStr[1], listConVolumeStr)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter [ not found"); continue; } for (auto itConnVolumeStr : listConVolumeStr) { std::vector connVolumeStr; std::string sourceName; std::string sinkName; std::string tempVol; std::vector sinkVolume; delimiter = ":"; if (E_OK != CAmCommonUtility::parseString(delimiter, itConnVolumeStr, connVolumeStr)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not found"); continue; } if (connVolumeStr.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : wrong format"); continue; } sourceName = connVolumeStr[0]; delimiter = "="; if (E_OK != CAmCommonUtility::parseString(delimiter, connVolumeStr[1], sinkVolume)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter = not found"); continue; } if (sinkVolume.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter = wrong format"); continue; } sinkName = sinkVolume[0]; tempVol = sinkVolume[1]; if (!sinkVolume.empty()) { _updateMainConnectionVolume(className, sourceName, sinkName, atoi(tempVol.c_str()), outVClassDataS); } } } return true; } void CAmPersistenceDefault::_updateClassVolume(gc_persistence_classData_s classData, std::vector &outVClassDataS) { bool classFound = false; for (auto &itClassData : outVClassDataS) { if (itClassData.name == classData.name) { classFound = true; for (auto itInputStackData : classData.listConnections) { bool sinkFound = false; for ( auto &itStackData : itClassData.listConnections) { if (itInputStackData.sinkName == itStackData.sinkName) { sinkFound = true; itStackData.volume = itInputStackData.volume; } } if (sinkFound == false) { itClassData.listConnections.push_back(itInputStackData); } } } } if (classFound == false) { outVClassDataS.push_back(classData); } } bool CAmPersistenceDefault::_lastClassVolumeStruct(std::string inputStr, std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { LOG_FN_INFO(__FILENAME__, __func__, "Input String=", inputStr); /*E.g. Input string for last class volume as below * {BASE,[ExclusiveSink1:50][ExclusiveSink2:60]}*/ std::vector< std::string > listClassesStr; std::string delimiter = "{"; if (E_OK != CAmCommonUtility::parseString(delimiter, inputStr, listClassesStr)) { LOG_FN_ERROR(__FILENAME__, __func__, "Not possible to parse the last class volume"); return false; } for (auto itlistClassVolumesStr : listClassesStr) { gc_persistence_classData_s classData; std::vector listClassVolumes; delimiter = ","; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistClassVolumesStr, listClassVolumes)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter , not found"); continue; } if (listClassVolumes.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter , not correctly formatted"); continue; } classData.name = listClassVolumes[0]; std::vector listVolumeStr; delimiter = "["; if (E_OK != CAmCommonUtility::parseString(delimiter, listClassVolumes[1], listVolumeStr)) { continue; } for (auto itSinkVolume : listVolumeStr) { gc_persistence_stackData_s sinkData; std::vector listSinkVolume; delimiter = ":"; if (E_OK != CAmCommonUtility::parseString(delimiter, itSinkVolume, listSinkVolume)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not found"); continue; } if ( listSinkVolume.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not correclty formatted"); continue; } sinkData.sinkName = listSinkVolume[0]; sinkData.volume = atoi(listSinkVolume[1].c_str()); if (sinkData.sinkName == "*") { classData.volume = sinkData.volume; continue; } if (!listSinkVolume.empty()) { classData.listConnections.push_back(sinkData); } } _updateClassVolume(classData, outVClassDataS); } return true; } void CAmPersistenceDefault::_updateMainConnection(gc_persistence_classData_s classData, std::vector &outVClassDataS) { bool classFound = false; for (auto &itClassData : outVClassDataS) { if (itClassData.name == classData.name) { classFound = true; for (auto itInputStackData : classData.listConnections) { bool sinkFound = false; for ( auto &itStackData : itClassData.listConnections) { if (itInputStackData.sinkName == itStackData.sinkName) { sinkFound = true; for (auto itInputSourceData : itInputStackData.listConnection) { bool sourceFound = false; for (auto &itSourceData : itStackData.listConnection) { if (itInputSourceData.sourceName == itSourceData.sourceName) { sourceFound = true; itSourceData.lastConnectionValid = 1; } } if (sourceFound == false) { itStackData.listConnection.push_back(itInputSourceData); } } } } if (sinkFound == false) { itClassData.listConnections.push_back(itInputStackData); } } } } if (classFound == false) { outVClassDataS.push_back(classData); } } bool CAmPersistenceDefault::_lastMainConnectionStruct(std::string inputStr, std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { LOG_FN_INFO(__FILENAME__, __func__, "Input String=", inputStr); std::vector< std::string> listClassesStr; /*E.g. Input string for the last main connection as below * {BASE,BaseSource1:ExclusiveSink1;BaseSource2:ExclusiveSink2;}*/ std::string delimiter = "{"; if (E_OK != CAmCommonUtility::parseString(delimiter, inputStr, listClassesStr)) { LOG_FN_ERROR(__FILENAME__, __func__, "cannot parse last main Connection string"); return false; } for (auto itlistClassData : listClassesStr) { gc_persistence_classData_s classData; std::vector listClassConnectionStr; delimiter = ","; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistClassData, listClassConnectionStr)) { LOG_FN_WARN(__FILENAME__, __func__, "parsing of class not successful still continuing"); continue; } if (listClassConnectionStr.size() != 2) { continue; } classData.name = listClassConnectionStr[0]; // Start internal stack/conn tags, first conn std::vector listConnectionStr; delimiter = ";"; if (E_OK != CAmCommonUtility::parseString(delimiter, listClassConnectionStr[1], listConnectionStr)) { continue; } for (auto itListMainCon : listConnectionStr) { std::vector listNames; delimiter = ":"; if (E_OK != CAmCommonUtility::parseString(delimiter, itListMainCon, listNames)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not found"); continue; } if (listNames.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "wrong formatted last main connection"); continue; } if (!itListMainCon.empty()) { gc_persistence_connectionData_s connData; struct gc_persistence_stackData_s stackData; connData.sourceName = listNames[0]; connData.lastConnectionValid = 1; stackData.sinkName = listNames[1]; stackData.listConnection.push_back(connData); classData.listConnections.clear(); classData.listConnections.push_back(stackData); _updateMainConnection(classData, outVClassDataS); } } } return true; } void CAmPersistenceDefault::_updateMainSoundProperty(gc_persistence_classData_s classData, std::vector &outVClassDataS) { bool updated = false; for (auto &it : outVClassDataS) { if (it.name == classData.name) { it.listMainSoundProperties = classData.listMainSoundProperties; updated = true; } } if (updated == false) { outVClassDataS.push_back(classData); } } bool CAmPersistenceDefault::_lastMainSoundPropertyStruct(std::string inputStr, std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { LOG_FN_INFO(__FILENAME__, __func__, "Input String=", inputStr); /*E.g. Input string for the last main sound properties * {BASE,[ET_SOURCE_BaseSource=(1:3)(2:4)(3:5)]} */ std::vector< std::string > listClasses; std::string delimiter = "{"; if (E_OK != CAmCommonUtility::parseString(delimiter, inputStr, listClasses)) { LOG_FN_ERROR(__FILENAME__, __func__, "delimiter { not found"); return false; } for (auto itlistClasses : listClasses) { gc_persistence_classData_s classData; std::vector listClass; delimiter = ","; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistClasses, listClass)) { continue; } if (listClass.size() != 2 ) { LOG_FN_WARN(__FILENAME__, __func__, "Invalid formatted class level string"); continue; } classData.name = listClass[0]; // Start internal stack/conn tags, first conn std::vector listElementProp; gc_SinkVolume_s sinkInfo; delimiter = "["; if (E_OK != CAmCommonUtility::parseString(delimiter, listClass[1], listElementProp)) { LOG_FN_WARN(__FILENAME__, __func__, "Delimiter [ not found"); continue; } for (auto itListElememntProp : listElementProp) { gc_persistence_mainSoundProData_s listMainSoundProperties {}; std::vector listPropertyListStr; delimiter = "="; if (E_OK != CAmCommonUtility::parseString(delimiter, itListElememntProp, listPropertyListStr)) { continue; } if (listPropertyListStr.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "Invalid format found property"); continue; } std::string elementName, tType, tValue; elementName = listPropertyListStr[0]; if ("ET_SOURCE" == elementName.substr(0, 9)) { listMainSoundProperties.sourceName = elementName.substr(10, std::string::npos); listMainSoundProperties.sinkName = ""; } else { listMainSoundProperties.sinkName = elementName.substr(8, std::string::npos); listMainSoundProperties.sourceName = ""; } delimiter = "("; std::vector listMainSoundPropertiesStr; if (E_OK != CAmCommonUtility::parseString(delimiter, listPropertyListStr[1], listMainSoundPropertiesStr)) { LOG_FN_WARN(__FILENAME__, __func__, "wrong class level data format in the persistence database"); } for (auto itlistMainSoundPropertyStr : listMainSoundPropertiesStr) { delimiter = ":"; gc_persistence_mainSoundPropertyData_s mainSoundProperty; std::vector typeValPair; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistMainSoundPropertyStr, typeValPair)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not found"); continue; } if (typeValPair.size() != 2) { LOG_FN_WARN(__FILENAME__, __func__, "Invaid formatted type value pair"); continue; } tType = typeValPair[0]; mainSoundProperty.type = tType; tValue = typeValPair.at(1); mainSoundProperty.value = tValue.substr(0, 1); if (!typeValPair.empty()) { listMainSoundProperties.listMainSoundProperty.push_back(mainSoundProperty); } } if (!listPropertyListStr.empty()) { classData.listMainSoundProperties.push_back(listMainSoundProperties); } } _updateMainSoundProperty(classData, outVClassDataS); } return true; } bool CAmPersistenceDefault::_lastSystemPropertyStruct(std::string inputStr, std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { std::vector listSystemPropertyStr; gc_persistence_systemProperty_s soundProperty {}; LOG_FN_INFO(__FILENAME__, __func__, "Input String=", inputStr); /*E.g. Input string for the last system property as below * {(61440:4)(61569:100)} */ std::string delimiter = "("; if (E_OK != CAmCommonUtility::parseString(delimiter, inputStr, listSystemPropertyStr)) { LOG_FN_ERROR(__FILENAME__, __func__, "wrong class level data format in the persistence database"); return false; } for (auto itlistSystemProperty : listSystemPropertyStr) { delimiter = ":"; std::vector typeValPair; if (E_OK != CAmCommonUtility::parseString(delimiter, itlistSystemProperty, typeValPair)) { LOG_FN_WARN(__FILENAME__, __func__, "delimiter : not found"); continue; } if (typeValPair.size() != 2 ) { LOG_FN_WARN(__FILENAME__, __func__, "wrong formatted string"); continue; } soundProperty.type = typeValPair[0]; soundProperty.value = typeValPair[1]; std::size_t found = soundProperty.value.find(")"); soundProperty.value = soundProperty.value.substr(0, found); outVSystemPropertyS.push_back(soundProperty); } return true; } bool CAmPersistenceDefault::_stringToStruct(std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { typedef bool (CAmPersistenceDefault::*toStruct)(std::string, std::vector &, std::vector< gc_persistence_systemProperty_s > &); std::map keyMap; keyMap["lastMainConnectionVolume"] = &CAmPersistenceDefault::_lastMainConnectionVolumeStruct; keyMap["lastClassVolume"] = &CAmPersistenceDefault::_lastClassVolumeStruct; keyMap["lastMainConnection"] = &CAmPersistenceDefault::_lastMainConnectionStruct; keyMap["lastMainSoundProperty"] = &CAmPersistenceDefault::_lastMainSoundPropertyStruct; keyMap["lastSystemProperty"] = &CAmPersistenceDefault::_lastSystemPropertyStruct; for ( auto it = keyMap.begin(); it != keyMap.end(); it++) { if (!mFileData[it->first].empty()) { (this->*(it->second))(mFileData[it->first], outVClassDataS, outVSystemPropertyS); } } return true; } am_Error_e CAmPersistenceDefault::_structTostring(std::vector &outVClassDataS, std::vector &outVSystemPropertyS) { std::string outputString; std::string outputStringInside; std::string outputStringSystem; std::string outputStringMainSoundProTypeValue; std::string outputStringLMCV; std::string outputStringLCV; std::string outputStringLMC; std::string outputStringLMSP; std::string tvolSink; std::string tSinkName; std::string tSourceName; std::string tType; std::string tValue; am_Error_e result = E_WRONG_FORMAT; if(!outVClassDataS.empty()) { for ( auto itClasses : outVClassDataS) { outputString = "{"; outputString += (itClasses).name; outputString += ","; if (!itClasses.name.empty()) { // For loop required // Sink Name and Volume and order also is required. for (auto itStacks : itClasses.listConnections) { for (auto itConnection : itStacks.listConnection) { if (!itConnection.sourceName.empty() && !itStacks.sinkName.empty() && ((std::to_string(itConnection.volume) != std::to_string(MAX_NEG_VOL)))) { outputStringInside += "[" + itConnection.sourceName + ":" + itStacks.sinkName + "=" + std::to_string(itConnection.volume) + "]"; } } } } outputString += outputStringInside + "}"; outputStringInside.clear(); outputStringLMCV += outputString; outputString.clear(); } LOG_FN_INFO(__FILENAME__, __func__, "is called & inserted lastMainConnectionVolume OutputString:", outputStringLMCV); // Insert key and string details in the map which is read from Xml file via common structure. mFileData.insert(std::pair("lastMainConnectionVolume", outputStringLMCV)); outputStringInside.clear(); outputString.clear(); outputStringLMCV.clear(); // ---------------LastClassVolume---start----------- /* E.g. Output String for last class volume as below * {BASE,[ExclusiveSink1:50][ExclusiveSink2:60]}*/ for (auto itClasses : outVClassDataS) { outputString = "{"; outputString += itClasses.name; outputString += ","; if (!itClasses.name.empty()) { // Sink Name and Volume and order also is required. for (auto itStacks : itClasses.listConnections) { if (!itStacks.sinkName.empty()) { tvolSink = std::to_string(itStacks.volume); if (std::to_string(itStacks.volume) != std::to_string(MAX_NEG_VOL)) { outputStringInside += "[" + itStacks.sinkName + ":" + std::to_string(itStacks.volume) + "]"; // new } } } tvolSink = std::to_string(itClasses.volume); if (std::to_string(itClasses.volume) != std::to_string(MAX_NEG_VOL)) { outputStringInside += "[*:" + std::to_string(itClasses.volume) + "]"; // new } } outputString += outputStringInside + "}"; outputStringLCV += outputString; outputStringInside.clear(); outputString.clear(); } LOG_FN_INFO(__FILENAME__, __func__, "is called & inserted lastClassVolume OutputString:", outputStringLCV); mFileData.insert(std::pair("lastClassVolume", outputStringLCV)); outputStringInside.clear(); outputString.clear(); outputStringLCV.clear(); // ------------- LastMainConnection--start---------------- /* E.g. Output String for last main connection as below * {BASE,BaseSource1:ExclusiveSink1;BaseSource2:ExclusiveSink2;}*/ for (auto itClasses : outVClassDataS) { outputString = "{"; outputString += itClasses.name; outputString += ","; if (!itClasses.name.empty()) { // Sink Name and Volume and order also is required. for (auto itStacks : itClasses.listConnections) { for (auto itConnections : itStacks.listConnection) { if (!itConnections.sourceName.empty() && (itConnections.lastConnectionValid == 1)) { if (!itStacks.sinkName.empty()) { tvolSink = std::to_string(itStacks.volume); outputStringInside += itConnections.sourceName + ":" + itStacks.sinkName + ";"; } } } } } outputString += outputStringInside + "}"; outputStringInside.clear(); outputStringLMC += outputString; outputStringInside.clear(); } LOG_FN_INFO(__FILENAME__, __func__, "is called ok & inserted lastMainConnection OutputString:", outputStringLMC); mFileData.insert(std::pair("lastMainConnection", outputStringLMC)); outputStringInside.clear(); outputString.clear(); // ----------Last Main sound properties-start----------------------- /* E.g. Output String for last main connection properties as below * {BASE,[ET_SOURCE_BaseSource=(1:3)(2:4)(3:5)]} */ for (auto itClasses : outVClassDataS) { outputString = "{"; outputString += (itClasses).name; outputString += ","; if (!itClasses.name.empty()) { // For loop required // Sink Name and Volume and order also is required. for (auto itElementProperties : itClasses.listMainSoundProperties) { for (auto itListMainProperties : itElementProperties.listMainSoundProperty) { if (!itListMainProperties.type.empty()) { outputStringMainSoundProTypeValue += "(" + itListMainProperties.type + ":" + itListMainProperties.value + ")"; } } if (!(itElementProperties).sourceName.empty()) { outputStringInside += "[ET_SOURCE_" + itElementProperties.sourceName + "=" + outputStringMainSoundProTypeValue + "]"; // new } else { outputStringInside += "[ET_SINK_" + itElementProperties.sinkName + "=" + outputStringMainSoundProTypeValue + "]"; // new } } } outputString += outputStringInside + "}"; outputStringInside.clear(); outputStringLMSP += outputString; } LOG_FN_INFO(__FILENAME__, __func__, "is called & inserted lastMainSoundProperties OutputString:", outputStringLMSP); // Insert key and string details in the map which is read from Xml file via common structure. mFileData.insert(std::pair("lastMainSoundProperty", outputStringLMSP)); outputString.clear(); result = E_OK; } // ---------------LastSystemProperties---start---------------- /* E.g. Output String for last system properties as below * {(61440:4)(61569:100)} */ if(!outVSystemPropertyS.empty()) { for (auto itListSYstemProperties : outVSystemPropertyS) { outputString = "{"; if (!itListSYstemProperties.type.empty()) { if (!itListSYstemProperties.value.empty()) { tValue = itListSYstemProperties.value; outputStringSystem += "(" + itListSYstemProperties.type + ":" + itListSYstemProperties.value + ")"; // new } } outputString += outputStringSystem + "}"; } LOG_FN_INFO(__FILENAME__, __func__, "is called & inserted LastSystemProperty OutputString:", outputString); mFileData.insert(std::pair("lastSystemProperty", outputString)); outputStringSystem.clear(); outputString.clear(); result = E_OK; } return result; } bool CAmPersistenceDefault::_writeTOXML() { vector mvClassDataS; vector mvSystemPropertyS; bool resData = _stringToStruct(mvClassDataS, mvSystemPropertyS); if (resData == false) { LOG_FN_WARN(__FILENAME__, __func__, "is called & Write data in the XML file is Failed"); } xmlDocPtr pDocument = xmlNewDoc((const xmlChar *)"1.0"); if (pDocument == NULL) { LOG_FN_ERROR(__FILENAME__, __func__, "is called & pDocument is NULL"); return false; } CAmPersistenceNode(TAG_ROOT_PERSISTENCE, mvClassDataS, mvSystemPropertyS).write(pDocument, NULL); xmlSaveFormatFileEnc(mFileName.c_str(), pDocument, "UTF-8", 1); xmlFreeDoc(pDocument); return true; } am_Error_e CAmPersistenceDefault::_readFromXML() { vector outVClassDataS; vector outVSystemPropertyS; char *persistencePath = (char *)getenv(PERISTENCE_FILE_PATH_ENV_VAR_NAME); if (persistencePath != NULL) { mFileName = persistencePath; LOG_FN_INFO(__FILENAME__, __func__, "is called & Input mFileName is", mFileName.c_str()); } if (!mFileName.empty()) { xmlDocPtr pDocument = xmlParseFile(mFileName.c_str()); if (pDocument == NULL) { LOG_FN_WARN("failed to parse the persistence xml file & Input mFileName is", mFileName); return E_NON_EXISTENT; } xmlNodePtr pCurrent = xmlDocGetRootElement(pDocument); if (pCurrent == NULL) { LOG_FN_ERROR("failed to get persistence xml file root node"); return E_NON_EXISTENT; } CAmPersistenceNode(TAG_ROOT_PERSISTENCE, outVClassDataS, outVSystemPropertyS).parse(pDocument, &pCurrent); xmlFreeDoc(pDocument); } else { LOG_FN_WARN(__FILENAME__, __func__, "is called and File name is Empty, not able to read persistence xml file ", mFileName); return E_NON_EXISTENT; } am_Error_e resultStructToStringToMap = _structTostring(outVClassDataS, outVSystemPropertyS); if (E_OK != resultStructToStringToMap) { LOG_FN_WARN("failed to get persistence xml file in structure and map details"); return E_WRONG_FORMAT; } LOG_FN_INFO("Peristence xml parsed successfully & Xml file data insert in map successfully"); return E_OK; } am_Error_e CAmPersistenceDefault::close() { LOG_FN_INFO(__FILENAME__, __func__, "is called !!!"); return E_OK; } am_Error_e CAmPersistenceDefault::_createDirectory(const std::string &path, mode_t mode) { struct stat st; if (path.empty() || (stat(path.c_str(), &st) == 0)) { return E_OK; } if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST) { LOG_FN_ERROR(__FILENAME__, __func__, "failed to create directory", path); return E_NOT_POSSIBLE; } return E_OK; } void CAmPersistenceDefault::_createSubDirectories() { if (mFileName.empty()) { return; } for (size_t pos = 0; (pos = mFileName.find("/", pos)) != std::string::npos; ++pos) { std::string dirName = mFileName.substr(0, pos); (void)_createDirectory(dirName, FILE_ACCESS_MODE); } } } /* namespace gc */ } /* namespace am */ celix/framework/private/test/filter_test.cpp /** *Licensed to the Apache Software Foundation (ASF) under one *or more contributor license agreements. See the NOTICE file *distributed with this work for additional information *regarding copyright ownership. The ASF licenses this file *to you 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. */ /* * filter_test.cpp * * \date Feb 11, 2013 * \author Apache Celix Project Team * \copyright Apache License, Version 2.0 */ #include #include #include "CppUTest/TestHarness.h" #include "CppUTest/TestHarness_c.h" #include "CppUTest/CommandLineTestRunner.h" #include "CppUTestExt/MockSupport.h" extern "C" { #include "filter_private.h" #include "celix_log.h" framework_logger_pt logger; } int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); } TEST_GROUP(filter) { void setup(void) { logger = (framework_logger_pt) malloc(sizeof(*logger)); logger->logFunction = frameworkLogger_log; } void teardown() { mock().checkExpectations(); mock().clear(); } }; TEST(filter, create) { char filterStr[] = "(key=value)"; filter_pt filter = filter_create(filterStr); STRCMP_EQUAL(filterStr, filter->filterStr); } eegeo/cardboard-vr-integration // Copyright eeGeo Ltd (2012-2016), All Rights Reserved #include "../UIQuad/UIQuadFactory.h" #include "UIGazeView.h" namespace Eegeo { namespace UIGaze { UIGazeView::UIGazeView(Eegeo::UI::IUIQuadFactory& quadFactory, UI::IUIRenderableFilter& uiRenderableFilter, const std::string& gazePointerAsset) { Init(quadFactory, uiRenderableFilter, gazePointerAsset); } void UIGazeView::Init(Eegeo::UI::IUIQuadFactory& quadFactory, UI::IUIRenderableFilter& uiRenderableFilter, const std::string& gazePointerAsset) { Eegeo::v2 dimension = Eegeo::v2(0.075f,0.075f)*3.f; m_pPointer = Eegeo_NEW(Eegeo::UI::UISprite)(uiRenderableFilter, quadFactory.CreateUIQuad(gazePointerAsset, dimension, Eegeo::v2::Zero(), Eegeo::v2::One(), Eegeo::Rendering::LayerIds::Values::AfterAll), dimension); } UIGazeView::~UIGazeView() { Eegeo_DELETE m_pPointer; } void UIGazeView::Update(float dt) { m_pPointer->Update(dt); } void UIGazeView::SetEcefPosition(const dv3& position) { m_pPointer->SetEcefPosition(position); } void UIGazeView::ShowView() { } void UIGazeView::HideView() { } void UIGazeView::ResetProgress() { } } } // osrtest.cpp : Defines the entry point for the console application. // #include "Precomp.h" #include #include #include #include using namespace wtl; multi_sz get_device_interfaces() { return as_hr(cm::get_device_interface_list(GUID_DEVINTERFACE_OSR_FX2)).value(); } file get_dip_switches_file() { for (auto devIf : get_device_interfaces()) { auto filePath = std::wstring(devIf) + L"\\" DIP_SWITCHES_FILE; auto file = file::create(filePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED); if (!file) continue; return std::move(file.get()); } throw result_exception(E_NOINTERFACE); } void listen() { static auto signalInterrupt = event::create().value(); signal(SIGINT, [](int signal) { signalInterrupt.set(); }); auto file = get_dip_switches_file(); auto readEvent = event::create().value(); while (true) { std::array dips; overlapped overlapped(readEvent.get()); // start an asynchronous I/O operation auto readResult = file.read(dips.begin(), dips.end(), overlapped.get()); if (readResult.get_result() != ERROR_IO_PENDING) as_hr(readResult).throw_if_failed(); if (wait_for_any_object(signalInterrupt, readEvent).value() == signalInterrupt.get()) { file.cancel(overlapped.get()); return; } auto bytesRead = overlapped.get_num_bytes_read(file.get(), dword_milliseconds(0)).value(); std::for_each(dips.begin(), dips.begin() + bytesRead, [](BYTE const & value) { wprintf_s(L"%02X\n", value); _flushall(); }); } } void PrintUsage(PCWSTR executable) { std::wcout << std::endl << L"usage: " << executable << L" " << std::endl << std::endl << L"Commands:" << std::endl << L"\tlisten - output all dip switch changes" << std::endl; } void osrtest(PCWSTR executable, PWSTR * argsBegin, PWSTR * argsEnd) { if (argsBegin == argsEnd) { PrintUsage(executable); throw hresult_exception(E_FAIL); } if (0 == _wcsicmp(*argsBegin, L"listen")) { listen(); return; } PrintUsage(executable); throw hresult_exception(E_FAIL); } int wmain(int argc, wchar_t ** argv) { auto executable = argv; auto argBegin = argv + 1; auto argEnd = argv + argc; try { osrtest(*executable, argBegin, argEnd); } catch (hresult_exception const & hre) { wprintf_s(L"Error: Failed with 0x%08X\n", hre.error()); return 1; } return 0; } /********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 * * 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 "protocol.h" #include #include #include #include #include #include "account.h" #include "accregfirstpage.h" namespace LeechCraft { namespace Azoth { namespace VelvetBird { Protocol::Protocol (PurplePlugin *plug, ICoreProxy_ptr proxy, QObject *parent) : QObject (parent) , Proxy_ (proxy) , PPlug_ (plug) { } void Protocol::Release () { for (auto acc : Accounts_) { acc->Release (); emit accountRemoved (acc); } } QObject* Protocol::GetQObject() { return this; } IProtocol::ProtocolFeatures Protocol::GetFeatures () const { return PFNone; } QList Protocol::GetRegisteredAccounts () { QList result; for (auto acc : Accounts_) result << acc; return result; } QObject* Protocol::GetParentProtocolPlugin () const { return parent (); } QString Protocol::GetProtocolName () const { return QString::fromUtf8 (purple_plugin_get_name (PPlug_)) + " (by libpurple)"; } QIcon Protocol::GetProtocolIcon () const { auto id = GetPurpleID (); if (id.startsWith ("prpl-")) id.remove (0, 5); QIcon result = QIcon::fromTheme (QString::fromUtf8 ("im-" + id)); if (result.isNull ()) result = QIcon ("lcicons:/azoth/velvetbird/resources/images/velvetbird.svg"); return result; } QByteArray Protocol::GetProtocolID () const { return "VelvetBird." + GetPurpleID (); } QList Protocol::GetAccountRegistrationWidgets (IProtocol::AccountAddOptions) { auto nameWidget = new AccRegFirstPage (); return { nameWidget }; } void Protocol::RegisterAccount (const QString& name, const QList& widgets) { auto nameWidget = dynamic_cast (widgets.value (0)); if (!nameWidget) { qWarning () << Q_FUNC_INFO << "incorrect widgets" << widgets; return; } auto pacc = purple_account_new (nameWidget->GetName ().toUtf8 ().constData (), GetPurpleID ().constData ()); purple_account_set_alias (pacc, nameWidget->GetNick ().toUtf8 ().constData ()); purple_account_set_string (pacc, "AccountName", name.toUtf8 ().constData ()); purple_accounts_add (pacc); PushAccount (pacc); } void Protocol::RemoveAccount (QObject *accObj) { auto acc = qobject_cast (accObj); emit accountRemoved (accObj); purple_accounts_delete (acc->GetPurpleAcc ()); delete acc; } QByteArray Protocol::GetPurpleID () const { return purple_plugin_get_id (PPlug_); } void Protocol::PushAccount (PurpleAccount *pacc) { auto account = new Account (pacc, this); Accounts_ << account; emit accountAdded (account); pacc->ui_data = account; } ICoreProxy_ptr Protocol::GetCoreProxy () const { return Proxy_; } } } } alekseykondus/LabGeneralAlgebra0 #include "Number.h" #include #include #include namespace LongArithmetic { Number::Number(const std::string& str) { FromString(str); } Number::Number(const Number& another) : m_Sign(another.m_Sign), m_Digits(another.m_Digits) {} Number::Number(Sign sign, const std::vector& digits) : m_Sign(sign), m_Digits(digits) {} Number Number::operator-() const { return Number(m_Sign == Sign::Plus ? Sign::Minus : Sign::Plus, m_Digits);; } Number::Sign Number::GetSign() const { return m_Sign; } const std::vector& Number::GetDigits() const { return m_Digits; } void Number::FromString(const std::string& str) { try { m_Digits.clear(); if (str.length() == 0) { m_Sign = Sign::Plus; m_Digits = { 0 }; return; } if (str[0] == '-') { m_Sign = Sign::Minus; } else { m_Sign = Sign::Plus; } int power = 0; auto end = m_Sign == Sign::Plus ? str.rend() : --str.rend(); m_Digits.push_back(0); for (auto i = str.rbegin(); i != end; i++) { if (*i < '0' || *i > '9') { //throw std::exception(""); } m_Digits.back() += static_cast(*i - '0') * powl(10, power); if (++power == 9) { power = 0; m_Digits.push_back(0); } } RemoveLeadingZeros(); } catch (const std::exception&) { m_Sign = Sign::Plus; m_Digits = { 0 }; } } std::ostream& operator <<(std::ostream& os, const Number& number) { if (number.GetDigits().empty()) { os << 0; return os; } if (number.GetSign() == Number::Sign::Minus) { os << '-'; } os << number.GetDigits().back(); char old_fill = os.fill('0'); for (auto it = ++number.GetDigits().rbegin(); it != number.GetDigits().rend(); it++) { os << std::setw(9) << *it; } os.fill(old_fill); return os; } std::string Number::ToString() const { std::ostringstream oss; oss << *this; return oss.str(); } bool Number::operator==(const Number& another) const { return m_Digits == another.GetDigits() && m_Sign == another.GetSign(); } void Number::RemoveLeadingZeros() { while (this->m_Digits.size() > 1 && this->m_Digits.back() == 0) { this->m_Digits.pop_back(); } if (this->m_Digits.size() == 1 && this->m_Digits[0] == 0) { m_Sign = Sign::Plus; } } void Number::ShiftRight() { if (this->m_Digits.size() == 0) { this->m_Digits.push_back(0); return; } this->m_Digits.push_back(this->m_Digits[this->m_Digits.size() - 1]); for (size_t i = this->m_Digits.size() - 2; i > 0; --i) this->m_Digits[i] = this->m_Digits[i - 1]; this->m_Digits[0] = 0; } bool Number::operator<(const Number& right) const { if (m_Digits == right.GetDigits() && m_Sign == right.GetSign()) return false; else if (m_Sign == Number::Sign::Minus && right.GetSign() == Number::Sign::Plus) return true; else { if (m_Digits.size() != right.GetDigits().size()) { return m_Digits.size() < right.GetDigits().size(); } else { for (long long i = m_Digits.size() - 1; i >= 0; --i) { if (m_Digits[i] != right.GetDigits()[i]) return m_Digits[i] < right.GetDigits()[i]; } return false; } } } void Number::SetSign(Sign sing){ m_Sign = sing; } bool Number::operator<=(const Number& right) const { return (*this < right || *this == right); } bool Number::operator>(const Number& right) const { return !(*this <= right); } /*Number Number::operator+(const Number& right) const { Number answer(*this); if (GetSign() == Number::Sign::Minus) { if (right.GetSign() == Number::Sign::Minus) return -((-*this) + (-right)); else return right - (-*this); } else if (right.GetSign() == Number::Sign::Minus) return *this - (-right); bool carry = false; for (size_t i = 0; i < answer.GetDigits().size() || carry; i++) { if (i == answer.GetDigits().size()) { answer.m_Digits.push_back(0); } answer.m_Digits[i] += carry + right.GetDigits()[i]; carry = answer.GetDigits()[i] >= Number::Base; if (carry) { answer.m_Digits[i] -= Number::Base; } } /*if (m_Modulus < answer) { answer = Minus(answer, m_Modulus); }//// return answer; }*/ int my_div(int num, int diver) { if ((num < 0) && (num % diver)) return num / diver - 1; else return num / diver; } int my_mod(int num, int diver) { if ((num < 0) && (num % diver)) return num % diver + diver; else return num % diver; } Number Number::operator + (const Number& num) const { Number res("0"); std::vector reschunks; //a+b Number a = *this; Number b = num; if (a.GetDigits().size() > b.GetDigits().size()) { b.m_Digits.resize(a.GetDigits().size()); } else { a.m_Digits.resize(b.m_Digits.size()); } if (m_Sign == b.GetSign()) { res.SetSign(a.GetSign()); int over = 0; for (int i = 0; i < a.m_Digits.size(); i++) { reschunks.push_back(a.m_Digits[i] + b.m_Digits[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } if (over != 0) { reschunks.push_back(over); } } else { res.SetSign(a.GetSign()); int over = 0; a.SetSign(static_cast((int)a.GetSign() * (-1))); if (a >= b) { for (int i = 0; i < a.m_Digits.size(); i++) { reschunks.push_back(a.m_Digits[i] - b.m_Digits[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } } else { res.SetSign(static_cast((int)res.GetSign() * (-1))); for (int i = 0; i < a.m_Digits.size(); i++) { reschunks.push_back(b.m_Digits[i] - a.m_Digits[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } } a.SetSign(static_cast((int)a.GetSign() * (-1))); } res.SetDigits(reschunks); res.RemoveLeadingZeros(); return res; } /*Number Number::operator-(const Number& right) const { if (right.ToString() == "0") return *this; //TODO Number answer(*this); if (right.GetSign() == Number::Sign::Minus) return *this + (-right); else if (GetSign() == Number::Sign::Minus) return -((-*this) + right); else if (*this < right) { answer = -(right - *this); answer.RemoveLeadingZeros(); return answer; } bool carry = false; for (size_t i = 0; i < right.GetDigits().size() || carry != 0; ++i) { answer.m_Digits[i] -= carry + right.GetDigits()[i]; carry = GetDigits()[i] < 0; if (carry) { answer.m_Digits[i] += Number::Base; } } answer.RemoveLeadingZeros(); return answer; }*/ Number Number::operator - (const Number& num) const { Number res("0"); std::vector reschunks; //a-b Number a = *this; Number b = num; if (a.GetDigits().size() > b.GetDigits().size()) { b.m_Digits.resize(a.GetDigits().size()); } else { a.m_Digits.resize(b.m_Digits.size()); } if (m_Sign != b.GetSign()) { res.SetSign(a.GetSign()); int over = 0; for (int i = 0; i < a.GetDigits().size(); i++) { reschunks.push_back(a.GetDigits()[i] + b.GetDigits()[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } if (over != 0) { reschunks.push_back(over); } } else { res.SetSign(a.GetSign()); int over = 0; if (a >= b) { for (int i = 0; i < a.GetDigits().size(); i++) { reschunks.push_back(a.GetDigits()[i] - b.GetDigits()[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } } else { res.SetSign(static_cast((int)res.GetSign() * (-1))); for (int i = 0; i < a.GetDigits().size(); i++) { reschunks.push_back(b.GetDigits()[i] - a.GetDigits()[i]); reschunks[i] += over; over = my_div(reschunks[i], Base); reschunks[i] = my_mod(reschunks[i], Base); } } } res.SetDigits(reschunks); res.RemoveLeadingZeros(); return res; } Number Number::operator*(const Number& right) const { Number answer(""); if (GetSign() == Number::Sign::Minus && right.GetSign() == Number::Sign::Minus) answer.SetSign(Number::Sign::Plus); else if (GetSign() == Number::Sign::Plus && right.GetSign() == Number::Sign::Plus) answer.SetSign(Number::Sign::Plus); else answer.SetSign(Number::Sign::Minus); answer.m_Digits.resize(GetDigits().size() + right.GetDigits().size()); for (size_t i = 0; i < GetDigits().size(); ++i) { uint64_t carry = 0; for (size_t j = 0; j < right.GetDigits().size() || carry != 0; ++j) { uint64_t cur = answer.GetDigits()[i + j] + GetDigits()[i] * 1LL * (j < right.GetDigits().size() ? right.GetDigits()[j] : 0) + carry; answer.m_Digits[i + j] = static_cast(cur % Number::Base); carry = static_cast(cur / Number::Base); } } answer.RemoveLeadingZeros(); return answer; } Number Number::operator/(const Number& right) const { //if (right.ToString() == "0") throw std::exception{ "Divide By Zero" }; Number b(right.ToString()); b.SetSign(Number::Sign::Plus); Number result(""), current(""); result.m_Digits.resize(GetDigits().size()); for (long long i = static_cast(GetDigits().size()) - 1; i >= 0; --i) { current.ShiftRight(); current.m_Digits[0] = GetDigits()[i]; current.RemoveLeadingZeros(); int x = 0, l = 0, r = Number::Base; while (l <= r) { int m = (l + r) / 2; Number _m(std::to_string(m)); Number t(b * _m); if (t <= current) { x = m; l = m + 1; } else r = m - 1; } Number _x(std::to_string(x)); result.m_Digits[i] = x; current = current - (b * _x); } if (GetSign() == Number::Sign::Minus && right.GetSign() == Number::Sign::Minus) result.SetSign(Number::Sign::Plus); else if (GetSign() == Number::Sign::Plus && right.GetSign() == Number::Sign::Plus) result.SetSign(Number::Sign::Plus); else result.SetSign(Number::Sign::Minus); result.RemoveLeadingZeros(); return result; } Number& Number::operator++() { *this = *this + Number("1"); return *this; } Number& Number::operator--() { *this = *this - Number("1"); return *this; } Number Number::operator++(int) { Number temp = *this; ++*this; return temp; } Number Number::operator--(int) { Number temp = *this; --*this; return temp; } Number Number::operator%(const Number& right) const { Number result(*this - ((*this / right) * right)); if (result.GetSign() == Number::Sign::Minus) result = result + right; return result; } bool Number::operator>=(const Number& right) const { return (*this > right || *this == right) ? true : false; } }Libs/Mesh/ReconstructSurface.cxx /*========================================================================= Program: ShapeWorks: Particle-based Shape Correspondence & Visualization Date: $Date: 2019/08/30 17:10:25 $ Version: $Revision: 1.1 $ Author: $Author: elhabian $ Purpose: particle-based subject-specific dense surface reconstruction, (use output of ReconstructMeanSurface) warp the mean dense shape (mesh) constructed from WarpToMeanSpace to each individual subject space using the sparse correspondence model from ShapeWorksRun Copyright (c) 2009 Scientific Computing and Imaging Institute. See ShapeWorksLicense.txt 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 notices for more information. =========================================================================*/ #include #include #include #include "ParticleBasedSurfaceReconstruction_InputParams.h" #include "Vis.h" #include "Reconstruction.h" #include "itkNrrdImageIOFactory.h" #include "itkMetaImageIOFactory.h" template < template < typename TCoordRep, unsigned > class TTransformType, template < typename ImageType, typename TCoordRep > class TInterpolatorType, typename TCoordRep, typename PixelType, typename ImageType> int DoIt(InputParams params) { typedef Reconstruction < TTransformType, TInterpolatorType, TCoordRep, PixelType, ImageType> ReconstructionType; typedef typename ReconstructionType::PointArrayType PointArrayType; double maxAngleDegrees = params.normalAngle *(180.0 / params.pi); ReconstructionType reconstructor; std::string denseFilename ; std::string sparseFilename ; std::string goodPointsFilename ; if(params.use_template_mesh) { denseFilename = params.template_dense_mesh; sparseFilename = params.template_sparse_points; goodPointsFilename = ""; // assume that all are good points if (!params.template_good_indices.empty()) goodPointsFilename = params.template_good_indices; } else { denseFilename = params.mean_prefix + "_dense.vtk"; sparseFilename = params.mean_prefix + "_sparse.particles"; goodPointsFilename = params.mean_prefix + "_goodPoints.txt"; } std::cout << "denseFilename: " << denseFilename << std::endl; std::cout << "sparseFilename: " << sparseFilename << std::endl; std::cout << "goodPointsFilename: " << goodPointsFilename << std::endl; reconstructor.readMeanInfo(denseFilename, sparseFilename, goodPointsFilename); if(params.display) { vtkSmartPointer denseMean = reconstructor.DenseMean(); vtkSmartPointer sparseMean = reconstructor.SparseMean(); Vis::visParticles(sparseMean,params.glyph_radius,std::string("mean sparse shape")); Vis::visMesh(denseMean, "mean dense shape"); } for (unsigned int shapeNo = 0; shapeNo < params.localPointsFilenames.size(); shapeNo++) { std::string basename = Utils::getFilename(params.localPointsFilenames[shapeNo]); std::cout << "Processing: " << params.localPointsFilenames[shapeNo].c_str() << std::endl; PointArrayType curSparse; Utils::readSparseShape(curSparse, const_cast (params.localPointsFilenames[shapeNo].c_str())); vtkSmartPointer curDense = reconstructor.getMesh(curSparse); std::string outfilename = params.out_path + '/'+ Utils::removeExtension(Utils::getFilename(params.localPointsFilenames[shapeNo])) + "_dense.vtk"; std::cout << "Writing: " << outfilename << std::endl; vtkSmartPointer writer = vtkPolyDataWriter::New(); writer->SetFileName(outfilename.c_str()); writer->SetInputData(curDense); writer->Update(); vtkSmartPointer vertices = vtkSmartPointer::New(); vertices->DeepCopy( curDense->GetPoints() ); std::string ptsfilename = params.out_path + '/'+ Utils::removeExtension(Utils::getFilename(params.localPointsFilenames[shapeNo])) + "_dense.particles"; Utils::writeSparseShape((char*) ptsfilename.c_str(), vertices); vtkSmartPointer curSparse_ = vtkSmartPointer::New(); Utils::readSparseShape(curSparse_, const_cast (params.localPointsFilenames[shapeNo].c_str())); ptsfilename = params.out_path + '/'+ Utils::removeExtension(Utils::getFilename(params.localPointsFilenames[shapeNo])) + "_sparse.particles"; Utils::writeSparseShape((char*) ptsfilename.c_str(), curSparse_); if(params.display) { Vis::visMeshWithParticles(curDense, curSparse_, params.glyph_radius, std::string(basename + ": dense shape in red and subject sparse shape in white")); } } return 0; } int main( int argc , char* argv[] ) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " paramfile " << std::endl; return EXIT_FAILURE; } InputParams params; params.readParams(argv[1], 1); // 1 - WarpToSubjectSpace std::cout << "Number of input sparse shapes: " << params.localPointsFilenames.size() << std::endl; //------------- typedefs --------------- const int Dimension = 3; typedef float PixelType; typedef double CoordinateRepType; typedef itk::Image< PixelType, Dimension > ImageType; //------------- end typedefs --------------- int status; if(params.use_tps_transform){ if(params.use_bspline_interpolation){ status = DoIt(params); } else{ status = DoIt(params); } } else { if(params.use_bspline_interpolation){ status = DoIt(params); } else{ status = DoIt(params); } } return 0; } src/ofxGrabScene/Nodes/Grid.cpp // // Grid.cpp // ofxGrabScene // #include "Grid.h" namespace GrabScene { namespace Nodes { //---------- Grid::Grid() { this->parameters.add(this->scale); this->parameters.add(this->ticks); this->parameters.add(this->labels); this->parameters.add(this->showX); this->parameters.add(this->showY); this->parameters.add(this->showZ); this->scale.set("Scale log10", 1.0f, -2.0f, 4.0f); this->ticks.set("Ticks", 2, 1, 100); this->labels.set("Show labels", true); this->showX.set("X", false); this->showY.set("Y", true); this->showZ.set("Z", false); this->setName("Grid"); } //---------- void Grid::draw() { shader("noLight").begin(); this->transformGL(); float scale = pow(10.0f, this->scale); ofDrawGrid(scale, this->ticks, this->labels, this->showX, this->showY, this->showZ); this->restoreTransformGL(); shader("noLight").end(); } //---------- void Grid::drawStencil() { this->transformGL(); float scale = pow(10.0f, float(this->scale)); ofDrawGrid(scale, this->ticks, false, this->showX, this->showY, this->showZ); this->restoreTransformGL(); } } }#include #include easy2d::RotateBy::RotateBy(float duration, float rotation) : FiniteTimeAction(duration) { _deltaVal = rotation; } void easy2d::RotateBy::_init() { FiniteTimeAction::_init(); if (_target) { _startVal = _target->getRotation(); } } void easy2d::RotateBy::_update() { FiniteTimeAction::_update(); if (_target) { _target->setRotation(_startVal + _deltaVal * _delta); } } easy2d::RotateBy * easy2d::RotateBy::clone() const { return gcnew RotateBy(_duration, _deltaVal); } easy2d::RotateBy * easy2d::RotateBy::reverse() const { return gcnew RotateBy(_duration, -_deltaVal); }src/vglOpencv.cpp /********************************************************************* *** *** *** Source file iplImage *** *** *** *********************************************************************/ #ifndef __OPENCV__ #include #include void cvReleaseImage(IplImage** p_ipl) { iplReleaseImage(p_ipl); } IplImage* cvCreateImage(CvSize size, int depth, int channels) { return iplCreateImage(size, depth, channels); } IplImage* cvCopy(IplImage* src, IplImage* dst) { return iplCopy(src, dst); } void cvCvtColor(IplImage* src, IplImage* dst, int code) { iplCvtColor(src, dst, code); } IplImage* cvLoadImage(char* filename, int iscolor /*= CV_LOAD_IMAGE_UNCHANGED*/) { return iplLoadImage(filename, iscolor); } int cvSaveImage(char* filename, IplImage* image, int* params /*= 0*/) { return iplSaveImage(filename, image, params); } #endif lukasz50018/SnakeGame #include "draw_snake.h" draw_snake::draw_snake( QWidget *parent ) : QWidget(parent) { } draw_snake::draw_snake( int width, int height, Options *options_w, int theme_id, QWidget *parent) : QWidget(parent) { snake = new snake_algorithm ( options_w->getColumns(), options_w->getRows(), options_w->isCollision(), options_w->isEgg(), options_w->getFruit1Value(), options_w->getFruit2Value(), options_w->getFruit3Value(), options_w->getFruitsToGrow() ); this->theme_id = theme_id; int xCellSize = width / snake->getX(); int yCellSize = height / snake->getY(); if(xCellSize > yCellSize) CellSize = yCellSize; else CellSize = xCellSize; pixToHorizontalCentre = (width - ( snake->getX() * CellSize )) / 2; pixToVerticalCentre = (height - (snake->getY() * CellSize)) / 2; timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(gameLoop())); } void draw_snake::setSpeed(int speed) { this->speed = speed; timer->setInterval(this->speed); } void draw_snake::gameLoop() { if( snake->isGameOver() == false ) { snake->move(); update(); } else { timer->stop(); isGameStarted = false; } } void draw_snake::startGame() { timer->start(speed); isGameStarted = true; } void draw_snake::pauseGame() { timer->stop(); isGameStarted = false; } void draw_snake::paintEvent(QPaintEvent *) { painter = new QPainter(this); Wall_Brush = new QBrush(Qt::SolidPattern); switch (theme_id) { case 0: Snake = new QPixmap (":/themes/themes/Default/snakeSegment.jpg"); Null = new QPixmap (":/themes/themes/Default/gameBackground.jpg"); Fruit_1 = new QPixmap (":/themes/themes/Default/appleTexture.jpg"); Fruit_2 = new QPixmap (":/themes/themes/Default/bananaTexture.jpg"); Fruit_3 = new QPixmap (":/themes/themes/Default/pineappleTexture.jpg"); Eggs = new QPixmap (":/themes/themes/Default/rockTexture.jpg"); Wall_Brush->setColor(Qt::white); break; case 1: Snake = new QPixmap (":/themes/themes/Flat/snakeSegment.jpg"); Null = new QPixmap (":/themes/themes/Flat/gameBackground.jpg"); Fruit_1 = new QPixmap (":/themes/themes/Flat/appleTexture.jpg"); Fruit_2 = new QPixmap (":/themes/themes/Flat/bananaTexture.jpg"); Fruit_3 = new QPixmap (":/themes/themes/Flat/pineappleTexture.jpg"); Eggs = new QPixmap (":/themes/themes/Flat/rockTexture.jpg"); Wall_Brush->setColor(Qt::white); break; case 2: Snake = new QPixmap (":/themes/themes/Draft/snakeSegment.jpg"); Null = new QPixmap (":/themes/themes/Draft/gameBackground.jpg"); Fruit_1 = new QPixmap (":/themes/themes/Draft/appleTexture.jpg"); Fruit_2 = new QPixmap (":/themes/themes/Draft/bananaTexture.jpg"); Fruit_3 = new QPixmap (":/themes/themes/Draft/pineappleTexture.jpg"); Eggs = new QPixmap (":/themes/themes/Draft/rockTexture.jpg"); Wall_Brush->setColor(Qt::black); break; case 3: Snake = new QPixmap (":/themes/themes/Win95/snakeSegment.jpg"); Null = new QPixmap (":/themes/themes/Win95/gameBackground.jpg"); Fruit_1 = new QPixmap (":/themes/themes/Win95/appleTexture.jpg"); Fruit_2 = new QPixmap (":/themes/themes/Win95/bananaTexture.jpg"); Fruit_3 = new QPixmap (":/themes/themes/Win95/pineappleTexture.jpg"); Eggs = new QPixmap (":/themes/themes/Win95/rockTexture.jpg"); Wall_Brush->setColor(Qt::white); break; } painter->setPen(Qt::NoPen); for( int i = 0; i < (snake->getY()) ; i++ ) { for( int j = 0; j < (snake->getX()) ; j++ ) { switch(snake->board[i][j]) { case content::Wall: painter->setBrush( *Wall_Brush); painter->drawRect(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize); break; case content::Null: painter->setBrush( *Null); painter->drawRect(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize); break; case content::Snake: painter->drawPixmap(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize, *Snake); break; case content::Egg: painter->drawPixmap(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize, *Eggs); break; case content::Fruit_1: painter->drawPixmap(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize, *Fruit_1); break; case content::Fruit_2: painter->drawPixmap(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize, *Fruit_2); break; case content::Fruit_3: painter->drawPixmap(j*CellSize + pixToHorizontalCentre, i*CellSize + pixToVerticalCentre, CellSize, CellSize, *Fruit_3); break; } } } } draw_snake::~draw_snake() { timer->~QTimer(); snake->~snake_algorithm(); } leeyangjie/quiche-10 // Copyright (c) 2018 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 "quic/core/crypto/transport_parameters.h" #include #include #include #include #include #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "third_party/boringssl/src/include/openssl/digest.h" #include "third_party/boringssl/src/include/openssl/sha.h" #include "quic/core/quic_connection_id.h" #include "quic/core/quic_data_reader.h" #include "quic/core/quic_data_writer.h" #include "quic/core/quic_types.h" #include "quic/core/quic_utils.h" #include "quic/core/quic_versions.h" #include "quic/platform/api/quic_bug_tracker.h" #include "quic/platform/api/quic_flag_utils.h" #include "quic/platform/api/quic_ip_address.h" namespace quic { // Values of the TransportParameterId enum as defined in the // "Transport Parameter Encoding" section of draft-ietf-quic-transport. // When parameters are encoded, one of these enum values is used to indicate // which parameter is encoded. The supported draft version is noted in // transport_parameters.h. enum TransportParameters::TransportParameterId : uint64_t { kOriginalDestinationConnectionId = 0, kMaxIdleTimeout = 1, kStatelessResetToken = 2, kMaxPacketSize = 3, kInitialMaxData = 4, kInitialMaxStreamDataBidiLocal = 5, kInitialMaxStreamDataBidiRemote = 6, kInitialMaxStreamDataUni = 7, kInitialMaxStreamsBidi = 8, kInitialMaxStreamsUni = 9, kAckDelayExponent = 0xa, kMaxAckDelay = 0xb, kDisableActiveMigration = 0xc, kPreferredAddress = 0xd, kActiveConnectionIdLimit = 0xe, kInitialSourceConnectionId = 0xf, kRetrySourceConnectionId = 0x10, kMaxDatagramFrameSize = 0x20, kInitialRoundTripTime = 0x3127, kGoogleConnectionOptions = 0x3128, // 0x3129 was used to convey the user agent string. // 0x312A was used only in T050 to indicate support for HANDSHAKE_DONE. // 0x312B was used to indicate that QUIC+TLS key updates were not supported. // 0x4751 was used for non-standard Google-specific parameters encoded as a // Google QUIC_CRYPTO CHLO, it has been replaced by individual parameters. kGoogleQuicVersion = 0x4752, // Used to transmit version and supported_versions. kMinAckDelay = 0xDE1A, // draft-iyengar-quic-delayed-ack. kVersionInformation = 0xFF73DB, // draft-ietf-quic-version-negotiation. }; namespace { // The following constants define minimum and maximum allowed values for some of // the parameters. These come from the "Transport Parameter Definitions" // section of draft-ietf-quic-transport. constexpr uint64_t kMinMaxPacketSizeTransportParam = 1200; constexpr uint64_t kMaxAckDelayExponentTransportParam = 20; constexpr uint64_t kDefaultAckDelayExponentTransportParam = 3; constexpr uint64_t kMaxMaxAckDelayTransportParam = 16383; constexpr uint64_t kDefaultMaxAckDelayTransportParam = 25; constexpr uint64_t kMinActiveConnectionIdLimitTransportParam = 2; constexpr uint64_t kDefaultActiveConnectionIdLimitTransportParam = 2; std::string TransportParameterIdToString( TransportParameters::TransportParameterId param_id) { switch (param_id) { case TransportParameters::kOriginalDestinationConnectionId: return "original_destination_connection_id"; case TransportParameters::kMaxIdleTimeout: return "max_idle_timeout"; case TransportParameters::kStatelessResetToken: return "stateless_reset_token"; case TransportParameters::kMaxPacketSize: return "max_udp_payload_size"; case TransportParameters::kInitialMaxData: return "initial_max_data"; case TransportParameters::kInitialMaxStreamDataBidiLocal: return "initial_max_stream_data_bidi_local"; case TransportParameters::kInitialMaxStreamDataBidiRemote: return "initial_max_stream_data_bidi_remote"; case TransportParameters::kInitialMaxStreamDataUni: return "initial_max_stream_data_uni"; case TransportParameters::kInitialMaxStreamsBidi: return "initial_max_streams_bidi"; case TransportParameters::kInitialMaxStreamsUni: return "initial_max_streams_uni"; case TransportParameters::kAckDelayExponent: return "ack_delay_exponent"; case TransportParameters::kMaxAckDelay: return "max_ack_delay"; case TransportParameters::kDisableActiveMigration: return "disable_active_migration"; case TransportParameters::kPreferredAddress: return "preferred_address"; case TransportParameters::kActiveConnectionIdLimit: return "active_connection_id_limit"; case TransportParameters::kInitialSourceConnectionId: return "initial_source_connection_id"; case TransportParameters::kRetrySourceConnectionId: return "retry_source_connection_id"; case TransportParameters::kMaxDatagramFrameSize: return "max_datagram_frame_size"; case TransportParameters::kInitialRoundTripTime: return "initial_round_trip_time"; case TransportParameters::kGoogleConnectionOptions: return "google_connection_options"; case TransportParameters::kGoogleQuicVersion: return "google-version"; case TransportParameters::kMinAckDelay: return "min_ack_delay_us"; case TransportParameters::kVersionInformation: return "version_information"; } return absl::StrCat("Unknown(", param_id, ")"); } bool TransportParameterIdIsKnown( TransportParameters::TransportParameterId param_id) { switch (param_id) { case TransportParameters::kOriginalDestinationConnectionId: case TransportParameters::kMaxIdleTimeout: case TransportParameters::kStatelessResetToken: case TransportParameters::kMaxPacketSize: case TransportParameters::kInitialMaxData: case TransportParameters::kInitialMaxStreamDataBidiLocal: case TransportParameters::kInitialMaxStreamDataBidiRemote: case TransportParameters::kInitialMaxStreamDataUni: case TransportParameters::kInitialMaxStreamsBidi: case TransportParameters::kInitialMaxStreamsUni: case TransportParameters::kAckDelayExponent: case TransportParameters::kMaxAckDelay: case TransportParameters::kDisableActiveMigration: case TransportParameters::kPreferredAddress: case TransportParameters::kActiveConnectionIdLimit: case TransportParameters::kInitialSourceConnectionId: case TransportParameters::kRetrySourceConnectionId: case TransportParameters::kMaxDatagramFrameSize: case TransportParameters::kInitialRoundTripTime: case TransportParameters::kGoogleConnectionOptions: case TransportParameters::kGoogleQuicVersion: case TransportParameters::kMinAckDelay: case TransportParameters::kVersionInformation: return true; } return false; } } // namespace TransportParameters::IntegerParameter::IntegerParameter( TransportParameters::TransportParameterId param_id, uint64_t default_value, uint64_t min_value, uint64_t max_value) : param_id_(param_id), value_(default_value), default_value_(default_value), min_value_(min_value), max_value_(max_value), has_been_read_(false) { QUICHE_DCHECK_LE(min_value, default_value); QUICHE_DCHECK_LE(default_value, max_value); QUICHE_DCHECK_LE(max_value, kVarInt62MaxValue); } TransportParameters::IntegerParameter::IntegerParameter( TransportParameters::TransportParameterId param_id) : TransportParameters::IntegerParameter::IntegerParameter( param_id, 0, 0, kVarInt62MaxValue) {} void TransportParameters::IntegerParameter::set_value(uint64_t value) { value_ = value; } uint64_t TransportParameters::IntegerParameter::value() const { return value_; } bool TransportParameters::IntegerParameter::IsValid() const { return min_value_ <= value_ && value_ <= max_value_; } bool TransportParameters::IntegerParameter::Write( QuicDataWriter* writer) const { QUICHE_DCHECK(IsValid()); if (value_ == default_value_) { // Do not write if the value is default. return true; } if (!writer->WriteVarInt62(param_id_)) { QUIC_BUG(quic_bug_10743_1) << "Failed to write param_id for " << *this; return false; } const QuicVariableLengthIntegerLength value_length = QuicDataWriter::GetVarInt62Len(value_); if (!writer->WriteVarInt62(value_length)) { QUIC_BUG(quic_bug_10743_2) << "Failed to write value_length for " << *this; return false; } if (!writer->WriteVarInt62(value_, value_length)) { QUIC_BUG(quic_bug_10743_3) << "Failed to write value for " << *this; return false; } return true; } bool TransportParameters::IntegerParameter::Read(QuicDataReader* reader, std::string* error_details) { if (has_been_read_) { *error_details = "Received a second " + TransportParameterIdToString(param_id_); return false; } has_been_read_ = true; if (!reader->ReadVarInt62(&value_)) { *error_details = "Failed to parse value for " + TransportParameterIdToString(param_id_); return false; } if (!reader->IsDoneReading()) { *error_details = absl::StrCat("Received unexpected ", reader->BytesRemaining(), " bytes after parsing ", this->ToString(false)); return false; } return true; } std::string TransportParameters::IntegerParameter::ToString( bool for_use_in_list) const { if (for_use_in_list && value_ == default_value_) { return ""; } std::string rv = for_use_in_list ? " " : ""; absl::StrAppend(&rv, TransportParameterIdToString(param_id_), " ", value_); if (!IsValid()) { rv += " (Invalid)"; } return rv; } std::ostream& operator<<(std::ostream& os, const TransportParameters::IntegerParameter& param) { os << param.ToString(/*for_use_in_list=*/false); return os; } TransportParameters::PreferredAddress::PreferredAddress() : ipv4_socket_address(QuicIpAddress::Any4(), 0), ipv6_socket_address(QuicIpAddress::Any6(), 0), connection_id(EmptyQuicConnectionId()), stateless_reset_token(kStatelessResetTokenLength, 0) {} TransportParameters::PreferredAddress::~PreferredAddress() {} bool TransportParameters::PreferredAddress::operator==( const PreferredAddress& rhs) const { return ipv4_socket_address == rhs.ipv4_socket_address && ipv6_socket_address == rhs.ipv6_socket_address && connection_id == rhs.connection_id && stateless_reset_token == rhs.stateless_reset_token; } bool TransportParameters::PreferredAddress::operator!=( const PreferredAddress& rhs) const { return !(*this == rhs); } std::ostream& operator<<( std::ostream& os, const TransportParameters::PreferredAddress& preferred_address) { os << preferred_address.ToString(); return os; } std::string TransportParameters::PreferredAddress::ToString() const { return "[" + ipv4_socket_address.ToString() + " " + ipv6_socket_address.ToString() + " connection_id " + connection_id.ToString() + " stateless_reset_token " + absl::BytesToHexString(absl::string_view( reinterpret_cast(stateless_reset_token.data()), stateless_reset_token.size())) + "]"; } TransportParameters::LegacyVersionInformation::LegacyVersionInformation() : version(0) {} bool TransportParameters::LegacyVersionInformation::operator==( const LegacyVersionInformation& rhs) const { return version == rhs.version && supported_versions == rhs.supported_versions; } bool TransportParameters::LegacyVersionInformation::operator!=( const LegacyVersionInformation& rhs) const { return !(*this == rhs); } std::string TransportParameters::LegacyVersionInformation::ToString() const { std::string rv = absl::StrCat("legacy[version ", QuicVersionLabelToString(version)); if (!supported_versions.empty()) { absl::StrAppend(&rv, " supported_versions " + QuicVersionLabelVectorToString(supported_versions)); } absl::StrAppend(&rv, "]"); return rv; } std::ostream& operator<<(std::ostream& os, const TransportParameters::LegacyVersionInformation& legacy_version_information) { os << legacy_version_information.ToString(); return os; } TransportParameters::VersionInformation::VersionInformation() : chosen_version(0) {} bool TransportParameters::VersionInformation::operator==( const VersionInformation& rhs) const { return chosen_version == rhs.chosen_version && other_versions == rhs.other_versions; } bool TransportParameters::VersionInformation::operator!=( const VersionInformation& rhs) const { return !(*this == rhs); } std::string TransportParameters::VersionInformation::ToString() const { std::string rv = absl::StrCat("[chosen_version ", QuicVersionLabelToString(chosen_version)); if (!other_versions.empty()) { absl::StrAppend(&rv, " other_versions " + QuicVersionLabelVectorToString(other_versions)); } absl::StrAppend(&rv, "]"); return rv; } std::ostream& operator<<( std::ostream& os, const TransportParameters::VersionInformation& version_information) { os << version_information.ToString(); return os; } std::ostream& operator<<(std::ostream& os, const TransportParameters& params) { os << params.ToString(); return os; } std::string TransportParameters::ToString() const { std::string rv = "["; if (perspective == Perspective::IS_SERVER) { rv += "Server"; } else { rv += "Client"; } if (legacy_version_information.has_value()) { rv += " " + legacy_version_information.value().ToString(); } if (version_information.has_value()) { rv += " " + version_information.value().ToString(); } if (original_destination_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kOriginalDestinationConnectionId) + " " + original_destination_connection_id.value().ToString(); } rv += max_idle_timeout_ms.ToString(/*for_use_in_list=*/true); if (!stateless_reset_token.empty()) { rv += " " + TransportParameterIdToString(kStatelessResetToken) + " " + absl::BytesToHexString(absl::string_view( reinterpret_cast(stateless_reset_token.data()), stateless_reset_token.size())); } rv += max_udp_payload_size.ToString(/*for_use_in_list=*/true); rv += initial_max_data.ToString(/*for_use_in_list=*/true); rv += initial_max_stream_data_bidi_local.ToString(/*for_use_in_list=*/true); rv += initial_max_stream_data_bidi_remote.ToString(/*for_use_in_list=*/true); rv += initial_max_stream_data_uni.ToString(/*for_use_in_list=*/true); rv += initial_max_streams_bidi.ToString(/*for_use_in_list=*/true); rv += initial_max_streams_uni.ToString(/*for_use_in_list=*/true); rv += ack_delay_exponent.ToString(/*for_use_in_list=*/true); rv += max_ack_delay.ToString(/*for_use_in_list=*/true); rv += min_ack_delay_us.ToString(/*for_use_in_list=*/true); if (disable_active_migration) { rv += " " + TransportParameterIdToString(kDisableActiveMigration); } if (preferred_address) { rv += " " + TransportParameterIdToString(kPreferredAddress) + " " + preferred_address->ToString(); } rv += active_connection_id_limit.ToString(/*for_use_in_list=*/true); if (initial_source_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kInitialSourceConnectionId) + " " + initial_source_connection_id.value().ToString(); } if (retry_source_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kRetrySourceConnectionId) + " " + retry_source_connection_id.value().ToString(); } rv += max_datagram_frame_size.ToString(/*for_use_in_list=*/true); rv += initial_round_trip_time_us.ToString(/*for_use_in_list=*/true); if (google_connection_options.has_value()) { rv += " " + TransportParameterIdToString(kGoogleConnectionOptions) + " "; bool first = true; for (const QuicTag& connection_option : google_connection_options.value()) { if (first) { first = false; } else { rv += ","; } rv += QuicTagToString(connection_option); } } for (const auto& kv : custom_parameters) { absl::StrAppend(&rv, " 0x", absl::Hex(static_cast(kv.first)), "="); static constexpr size_t kMaxPrintableLength = 32; if (kv.second.length() <= kMaxPrintableLength) { rv += absl::BytesToHexString(kv.second); } else { absl::string_view truncated(kv.second.data(), kMaxPrintableLength); rv += absl::StrCat(absl::BytesToHexString(truncated), "...(length ", kv.second.length(), ")"); } } rv += "]"; return rv; } TransportParameters::TransportParameters() : max_idle_timeout_ms(kMaxIdleTimeout), max_udp_payload_size(kMaxPacketSize, kDefaultMaxPacketSizeTransportParam, kMinMaxPacketSizeTransportParam, kVarInt62MaxValue), initial_max_data(kInitialMaxData), initial_max_stream_data_bidi_local(kInitialMaxStreamDataBidiLocal), initial_max_stream_data_bidi_remote(kInitialMaxStreamDataBidiRemote), initial_max_stream_data_uni(kInitialMaxStreamDataUni), initial_max_streams_bidi(kInitialMaxStreamsBidi), initial_max_streams_uni(kInitialMaxStreamsUni), ack_delay_exponent(kAckDelayExponent, kDefaultAckDelayExponentTransportParam, 0, kMaxAckDelayExponentTransportParam), max_ack_delay(kMaxAckDelay, kDefaultMaxAckDelayTransportParam, 0, kMaxMaxAckDelayTransportParam), min_ack_delay_us(kMinAckDelay, 0, 0, kMaxMaxAckDelayTransportParam * kNumMicrosPerMilli), disable_active_migration(false), active_connection_id_limit(kActiveConnectionIdLimit, kDefaultActiveConnectionIdLimitTransportParam, kMinActiveConnectionIdLimitTransportParam, kVarInt62MaxValue), max_datagram_frame_size(kMaxDatagramFrameSize), initial_round_trip_time_us(kInitialRoundTripTime) // Important note: any new transport parameters must be added // to TransportParameters::AreValid, SerializeTransportParameters and // ParseTransportParameters, TransportParameters's custom copy constructor, the // operator==, and TransportParametersTest.Comparator. {} TransportParameters::TransportParameters(const TransportParameters& other) : perspective(other.perspective), legacy_version_information(other.legacy_version_information), version_information(other.version_information), original_destination_connection_id( other.original_destination_connection_id), max_idle_timeout_ms(other.max_idle_timeout_ms), stateless_reset_token(other.stateless_reset_token), max_udp_payload_size(other.max_udp_payload_size), initial_max_data(other.initial_max_data), initial_max_stream_data_bidi_local( other.initial_max_stream_data_bidi_local), initial_max_stream_data_bidi_remote( other.initial_max_stream_data_bidi_remote), initial_max_stream_data_uni(other.initial_max_stream_data_uni), initial_max_streams_bidi(other.initial_max_streams_bidi), initial_max_streams_uni(other.initial_max_streams_uni), ack_delay_exponent(other.ack_delay_exponent), max_ack_delay(other.max_ack_delay), min_ack_delay_us(other.min_ack_delay_us), disable_active_migration(other.disable_active_migration), active_connection_id_limit(other.active_connection_id_limit), initial_source_connection_id(other.initial_source_connection_id), retry_source_connection_id(other.retry_source_connection_id), max_datagram_frame_size(other.max_datagram_frame_size), initial_round_trip_time_us(other.initial_round_trip_time_us), google_connection_options(other.google_connection_options), custom_parameters(other.custom_parameters) { if (other.preferred_address) { preferred_address = std::make_unique( *other.preferred_address); } } bool TransportParameters::operator==(const TransportParameters& rhs) const { if (!(perspective == rhs.perspective && legacy_version_information == rhs.legacy_version_information && version_information == rhs.version_information && original_destination_connection_id == rhs.original_destination_connection_id && max_idle_timeout_ms.value() == rhs.max_idle_timeout_ms.value() && stateless_reset_token == rhs.stateless_reset_token && max_udp_payload_size.value() == rhs.max_udp_payload_size.value() && initial_max_data.value() == rhs.initial_max_data.value() && initial_max_stream_data_bidi_local.value() == rhs.initial_max_stream_data_bidi_local.value() && initial_max_stream_data_bidi_remote.value() == rhs.initial_max_stream_data_bidi_remote.value() && initial_max_stream_data_uni.value() == rhs.initial_max_stream_data_uni.value() && initial_max_streams_bidi.value() == rhs.initial_max_streams_bidi.value() && initial_max_streams_uni.value() == rhs.initial_max_streams_uni.value() && ack_delay_exponent.value() == rhs.ack_delay_exponent.value() && max_ack_delay.value() == rhs.max_ack_delay.value() && min_ack_delay_us.value() == rhs.min_ack_delay_us.value() && disable_active_migration == rhs.disable_active_migration && active_connection_id_limit.value() == rhs.active_connection_id_limit.value() && initial_source_connection_id == rhs.initial_source_connection_id && retry_source_connection_id == rhs.retry_source_connection_id && max_datagram_frame_size.value() == rhs.max_datagram_frame_size.value() && initial_round_trip_time_us.value() == rhs.initial_round_trip_time_us.value() && google_connection_options == rhs.google_connection_options && custom_parameters == rhs.custom_parameters)) { return false; } if ((!preferred_address && rhs.preferred_address) || (preferred_address && !rhs.preferred_address)) { return false; } if (preferred_address && rhs.preferred_address && *preferred_address != *rhs.preferred_address) { return false; } return true; } bool TransportParameters::operator!=(const TransportParameters& rhs) const { return !(*this == rhs); } bool TransportParameters::AreValid(std::string* error_details) const { QUICHE_DCHECK(perspective == Perspective::IS_CLIENT || perspective == Perspective::IS_SERVER); if (perspective == Perspective::IS_CLIENT && !stateless_reset_token.empty()) { *error_details = "Client cannot send stateless reset token"; return false; } if (perspective == Perspective::IS_CLIENT && original_destination_connection_id.has_value()) { *error_details = "Client cannot send original_destination_connection_id"; return false; } if (!stateless_reset_token.empty() && stateless_reset_token.size() != kStatelessResetTokenLength) { *error_details = absl::StrCat("Stateless reset token has bad length ", stateless_reset_token.size()); return false; } if (perspective == Perspective::IS_CLIENT && preferred_address) { *error_details = "Client cannot send preferred address"; return false; } if (preferred_address && preferred_address->stateless_reset_token.size() != kStatelessResetTokenLength) { *error_details = absl::StrCat("Preferred address stateless reset token has bad length ", preferred_address->stateless_reset_token.size()); return false; } if (preferred_address && (!preferred_address->ipv4_socket_address.host().IsIPv4() || !preferred_address->ipv6_socket_address.host().IsIPv6())) { QUIC_BUG(quic_bug_10743_4) << "Preferred address family failure"; *error_details = "Internal preferred address family failure"; return false; } if (perspective == Perspective::IS_CLIENT && retry_source_connection_id.has_value()) { *error_details = "Client cannot send retry_source_connection_id"; return false; } for (const auto& kv : custom_parameters) { if (TransportParameterIdIsKnown(kv.first)) { *error_details = absl::StrCat("Using custom_parameters with known ID ", TransportParameterIdToString(kv.first), " is not allowed"); return false; } } if (perspective == Perspective::IS_SERVER && initial_round_trip_time_us.value() > 0) { *error_details = "Server cannot send initial round trip time"; return false; } if (version_information.has_value()) { const QuicVersionLabel& chosen_version = version_information.value().chosen_version; const QuicVersionLabelVector& other_versions = version_information.value().other_versions; if (chosen_version == 0) { *error_details = "Invalid chosen version"; return false; } if (perspective == Perspective::IS_CLIENT && std::find(other_versions.begin(), other_versions.end(), chosen_version) == other_versions.end()) { // When sent by the client, chosen_version needs to be present in // other_versions because other_versions lists the compatible versions and // the chosen version is part of that list. When sent by the server, // other_version contains the list of fully-deployed versions which is // generally equal to the list of supported versions but can slightly // differ during removal of versions across a server fleet. See // draft-ietf-quic-version-negotiation for details. *error_details = "Client chosen version not in other versions"; return false; } } const bool ok = max_idle_timeout_ms.IsValid() && max_udp_payload_size.IsValid() && initial_max_data.IsValid() && initial_max_stream_data_bidi_local.IsValid() && initial_max_stream_data_bidi_remote.IsValid() && initial_max_stream_data_uni.IsValid() && initial_max_streams_bidi.IsValid() && initial_max_streams_uni.IsValid() && ack_delay_exponent.IsValid() && max_ack_delay.IsValid() && min_ack_delay_us.IsValid() && active_connection_id_limit.IsValid() && max_datagram_frame_size.IsValid() && initial_round_trip_time_us.IsValid(); if (!ok) { *error_details = "Invalid transport parameters " + this->ToString(); } return ok; } TransportParameters::~TransportParameters() = default; bool SerializeTransportParameters(ParsedQuicVersion /*version*/, const TransportParameters& in, std::vector* out) { std::string error_details; if (!in.AreValid(&error_details)) { QUIC_BUG(invalid transport parameters) << "Not serializing invalid transport parameters: " << error_details; return false; } if (!in.legacy_version_information.has_value() || in.legacy_version_information.value().version == 0 || (in.perspective == Perspective::IS_SERVER && in.legacy_version_information.value().supported_versions.empty())) { QUIC_BUG(missing versions) << "Refusing to serialize without versions"; return false; } TransportParameters::ParameterMap custom_parameters = in.custom_parameters; for (const auto& kv : custom_parameters) { if (kv.first % 31 == 27) { // See the "Reserved Transport Parameters" section of RFC 9000. QUIC_BUG(custom_parameters with GREASE) << "Serializing custom_parameters with GREASE ID " << kv.first << " is not allowed"; return false; } } // Maximum length of the GREASE transport parameter (see below). static constexpr size_t kMaxGreaseLength = 16; // Empirically transport parameters generally fit within 128 bytes, but we // need to allocate the size up front. Integer transport parameters // have a maximum encoded length of 24 bytes (3 variable length integers), // other transport parameters have a length of 16 + the maximum value length. static constexpr size_t kTypeAndValueLength = 2 * sizeof(uint64_t); static constexpr size_t kIntegerParameterLength = kTypeAndValueLength + sizeof(uint64_t); static constexpr size_t kStatelessResetParameterLength = kTypeAndValueLength + 16 /* stateless reset token length */; static constexpr size_t kConnectionIdParameterLength = kTypeAndValueLength + 255 /* maximum connection ID length */; static constexpr size_t kPreferredAddressParameterLength = kTypeAndValueLength + 4 /*IPv4 address */ + 2 /* IPv4 port */ + 16 /* IPv6 address */ + 1 /* Connection ID length */ + 255 /* maximum connection ID length */ + 16 /* stateless reset token */; static constexpr size_t kKnownTransportParamLength = kConnectionIdParameterLength + // original_destination_connection_id kIntegerParameterLength + // max_idle_timeout kStatelessResetParameterLength + // stateless_reset_token kIntegerParameterLength + // max_udp_payload_size kIntegerParameterLength + // initial_max_data kIntegerParameterLength + // initial_max_stream_data_bidi_local kIntegerParameterLength + // initial_max_stream_data_bidi_remote kIntegerParameterLength + // initial_max_stream_data_uni kIntegerParameterLength + // initial_max_streams_bidi kIntegerParameterLength + // initial_max_streams_uni kIntegerParameterLength + // ack_delay_exponent kIntegerParameterLength + // max_ack_delay kIntegerParameterLength + // min_ack_delay_us kTypeAndValueLength + // disable_active_migration kPreferredAddressParameterLength + // preferred_address kIntegerParameterLength + // active_connection_id_limit kConnectionIdParameterLength + // initial_source_connection_id kConnectionIdParameterLength + // retry_source_connection_id kIntegerParameterLength + // max_datagram_frame_size kIntegerParameterLength + // initial_round_trip_time_us kTypeAndValueLength + // google_connection_options kTypeAndValueLength; // google-version std::vector parameter_ids = { TransportParameters::kOriginalDestinationConnectionId, TransportParameters::kMaxIdleTimeout, TransportParameters::kStatelessResetToken, TransportParameters::kMaxPacketSize, TransportParameters::kInitialMaxData, TransportParameters::kInitialMaxStreamDataBidiLocal, TransportParameters::kInitialMaxStreamDataBidiRemote, TransportParameters::kInitialMaxStreamDataUni, TransportParameters::kInitialMaxStreamsBidi, TransportParameters::kInitialMaxStreamsUni, TransportParameters::kAckDelayExponent, TransportParameters::kMaxAckDelay, TransportParameters::kMinAckDelay, TransportParameters::kActiveConnectionIdLimit, TransportParameters::kMaxDatagramFrameSize, TransportParameters::kInitialRoundTripTime, TransportParameters::kDisableActiveMigration, TransportParameters::kPreferredAddress, TransportParameters::kInitialSourceConnectionId, TransportParameters::kRetrySourceConnectionId, TransportParameters::kGoogleConnectionOptions, TransportParameters::kGoogleQuicVersion, TransportParameters::kVersionInformation, }; size_t max_transport_param_length = kKnownTransportParamLength; // google_connection_options. if (in.google_connection_options.has_value()) { max_transport_param_length += in.google_connection_options.value().size() * sizeof(QuicTag); } // Google-specific version extension. if (in.legacy_version_information.has_value()) { max_transport_param_length += sizeof(in.legacy_version_information.value().version) + 1 /* versions length */ + in.legacy_version_information.value().supported_versions.size() * sizeof(QuicVersionLabel); } // version_information. if (in.version_information.has_value()) { max_transport_param_length += sizeof(in.version_information.value().chosen_version) + // Add one for the added GREASE version. (in.version_information.value().other_versions.size() + 1) * sizeof(QuicVersionLabel); } // Add a random GREASE transport parameter, as defined in the // "Reserved Transport Parameters" section of RFC 9000. // This forces receivers to support unexpected input. QuicRandom* random = QuicRandom::GetInstance(); // Transport parameter identifiers are 62 bits long so we need to // ensure that the output of the computation below fits in 62 bits. uint64_t grease_id64 = random->RandUint64() % ((1ULL << 62) - 31); // Make sure grease_id % 31 == 27. Note that this is not uniformely // distributed but is acceptable since no security depends on this // randomness. grease_id64 = (grease_id64 / 31) * 31 + 27; TransportParameters::TransportParameterId grease_id = static_cast(grease_id64); const size_t grease_length = random->RandUint64() % kMaxGreaseLength; QUICHE_DCHECK_GE(kMaxGreaseLength, grease_length); char grease_contents[kMaxGreaseLength]; random->RandBytes(grease_contents, grease_length); custom_parameters[grease_id] = std::string(grease_contents, grease_length); // Custom parameters. for (const auto& kv : custom_parameters) { max_transport_param_length += kTypeAndValueLength + kv.second.length(); parameter_ids.push_back(kv.first); } // Randomize order of sent transport parameters by walking the array // backwards and swapping each element with a random earlier one. for (size_t i = parameter_ids.size() - 1; i > 0; i--) { std::swap(parameter_ids[i], parameter_ids[random->InsecureRandUint64() % (i + 1)]); } out->resize(max_transport_param_length); QuicDataWriter writer(out->size(), reinterpret_cast(out->data())); for (TransportParameters::TransportParameterId parameter_id : parameter_ids) { switch (parameter_id) { // original_destination_connection_id case TransportParameters::kOriginalDestinationConnectionId: { if (in.original_destination_connection_id.has_value()) { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective); QuicConnectionId original_destination_connection_id = in.original_destination_connection_id.value(); if (!writer.WriteVarInt62( TransportParameters::kOriginalDestinationConnectionId) || !writer.WriteStringPieceVarInt62(absl::string_view( original_destination_connection_id.data(), original_destination_connection_id.length()))) { QUIC_BUG(Failed to write original_destination_connection_id) << "Failed to write original_destination_connection_id " << original_destination_connection_id << " for " << in; return false; } } } break; // max_idle_timeout case TransportParameters::kMaxIdleTimeout: { if (!in.max_idle_timeout_ms.Write(&writer)) { QUIC_BUG(Failed to write idle_timeout) << "Failed to write idle_timeout for " << in; return false; } } break; // stateless_reset_token case TransportParameters::kStatelessResetToken: { if (!in.stateless_reset_token.empty()) { QUICHE_DCHECK_EQ(kStatelessResetTokenLength, in.stateless_reset_token.size()); QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective); if (!writer.WriteVarInt62( TransportParameters::kStatelessResetToken) || !writer.WriteStringPieceVarInt62( absl::string_view(reinterpret_cast( in.stateless_reset_token.data()), in.stateless_reset_token.size()))) { QUIC_BUG(Failed to write stateless_reset_token) << "Failed to write stateless_reset_token of length " << in.stateless_reset_token.size() << " for " << in; return false; } } } break; // max_udp_payload_size case TransportParameters::kMaxPacketSize: { if (!in.max_udp_payload_size.Write(&writer)) { QUIC_BUG(Failed to write max_udp_payload_size) << "Failed to write max_udp_payload_size for " << in; return false; } } break; // initial_max_data case TransportParameters::kInitialMaxData: { if (!in.initial_max_data.Write(&writer)) { QUIC_BUG(Failed to write initial_max_data) << "Failed to write initial_max_data for " << in; return false; } } break; // initial_max_stream_data_bidi_local case TransportParameters::kInitialMaxStreamDataBidiLocal: { if (!in.initial_max_stream_data_bidi_local.Write(&writer)) { QUIC_BUG(Failed to write initial_max_stream_data_bidi_local) << "Failed to write initial_max_stream_data_bidi_local for " << in; return false; } } break; // initial_max_stream_data_bidi_remote case TransportParameters::kInitialMaxStreamDataBidiRemote: { if (!in.initial_max_stream_data_bidi_remote.Write(&writer)) { QUIC_BUG(Failed to write initial_max_stream_data_bidi_remote) << "Failed to write initial_max_stream_data_bidi_remote for " << in; return false; } } break; // initial_max_stream_data_uni case TransportParameters::kInitialMaxStreamDataUni: { if (!in.initial_max_stream_data_uni.Write(&writer)) { QUIC_BUG(Failed to write initial_max_stream_data_uni) << "Failed to write initial_max_stream_data_uni for " << in; return false; } } break; // initial_max_streams_bidi case TransportParameters::kInitialMaxStreamsBidi: { if (!in.initial_max_streams_bidi.Write(&writer)) { QUIC_BUG(Failed to write initial_max_streams_bidi) << "Failed to write initial_max_streams_bidi for " << in; return false; } } break; // initial_max_streams_uni case TransportParameters::kInitialMaxStreamsUni: { if (!in.initial_max_streams_uni.Write(&writer)) { QUIC_BUG(Failed to write initial_max_streams_uni) << "Failed to write initial_max_streams_uni for " << in; return false; } } break; // ack_delay_exponent case TransportParameters::kAckDelayExponent: { if (!in.ack_delay_exponent.Write(&writer)) { QUIC_BUG(Failed to write ack_delay_exponent) << "Failed to write ack_delay_exponent for " << in; return false; } } break; // max_ack_delay case TransportParameters::kMaxAckDelay: { if (!in.max_ack_delay.Write(&writer)) { QUIC_BUG(Failed to write max_ack_delay) << "Failed to write max_ack_delay for " << in; return false; } } break; // min_ack_delay_us case TransportParameters::kMinAckDelay: { if (!in.min_ack_delay_us.Write(&writer)) { QUIC_BUG(Failed to write min_ack_delay_us) << "Failed to write min_ack_delay_us for " << in; return false; } } break; // active_connection_id_limit case TransportParameters::kActiveConnectionIdLimit: { if (!in.active_connection_id_limit.Write(&writer)) { QUIC_BUG(Failed to write active_connection_id_limit) << "Failed to write active_connection_id_limit for " << in; return false; } } break; // max_datagram_frame_size case TransportParameters::kMaxDatagramFrameSize: { if (!in.max_datagram_frame_size.Write(&writer)) { QUIC_BUG(Failed to write max_datagram_frame_size) << "Failed to write max_datagram_frame_size for " << in; return false; } } break; // initial_round_trip_time_us case TransportParameters::kInitialRoundTripTime: { if (!in.initial_round_trip_time_us.Write(&writer)) { QUIC_BUG(Failed to write initial_round_trip_time_us) << "Failed to write initial_round_trip_time_us for " << in; return false; } } break; // disable_active_migration case TransportParameters::kDisableActiveMigration: { if (in.disable_active_migration) { if (!writer.WriteVarInt62( TransportParameters::kDisableActiveMigration) || !writer.WriteVarInt62(/* transport parameter length */ 0)) { QUIC_BUG(Failed to write disable_active_migration) << "Failed to write disable_active_migration for " << in; return false; } } } break; // preferred_address case TransportParameters::kPreferredAddress: { if (in.preferred_address) { std::string v4_address_bytes = in.preferred_address->ipv4_socket_address.host().ToPackedString(); std::string v6_address_bytes = in.preferred_address->ipv6_socket_address.host().ToPackedString(); if (v4_address_bytes.length() != 4 || v6_address_bytes.length() != 16 || in.preferred_address->stateless_reset_token.size() != kStatelessResetTokenLength) { QUIC_BUG(quic_bug_10743_12) << "Bad lengths " << *in.preferred_address; return false; } const uint64_t preferred_address_length = v4_address_bytes.length() + /* IPv4 port */ sizeof(uint16_t) + v6_address_bytes.length() + /* IPv6 port */ sizeof(uint16_t) + /* connection ID length byte */ sizeof(uint8_t) + in.preferred_address->connection_id.length() + in.preferred_address->stateless_reset_token.size(); if (!writer.WriteVarInt62(TransportParameters::kPreferredAddress) || !writer.WriteVarInt62( /* transport parameter length */ preferred_address_length) || !writer.WriteStringPiece(v4_address_bytes) || !writer.WriteUInt16( in.preferred_address->ipv4_socket_address.port()) || !writer.WriteStringPiece(v6_address_bytes) || !writer.WriteUInt16( in.preferred_address->ipv6_socket_address.port()) || !writer.WriteUInt8( in.preferred_address->connection_id.length()) || !writer.WriteBytes( in.preferred_address->connection_id.data(), in.preferred_address->connection_id.length()) || !writer.WriteBytes( in.preferred_address->stateless_reset_token.data(), in.preferred_address->stateless_reset_token.size())) { QUIC_BUG(Failed to write preferred_address) << "Failed to write preferred_address for " << in; return false; } } } break; // initial_source_connection_id case TransportParameters::kInitialSourceConnectionId: { if (in.initial_source_connection_id.has_value()) { QuicConnectionId initial_source_connection_id = in.initial_source_connection_id.value(); if (!writer.WriteVarInt62( TransportParameters::kInitialSourceConnectionId) || !writer.WriteStringPieceVarInt62( absl::string_view(initial_source_connection_id.data(), initial_source_connection_id.length()))) { QUIC_BUG(Failed to write initial_source_connection_id) << "Failed to write initial_source_connection_id " << initial_source_connection_id << " for " << in; return false; } } } break; // retry_source_connection_id case TransportParameters::kRetrySourceConnectionId: { if (in.retry_source_connection_id.has_value()) { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective); QuicConnectionId retry_source_connection_id = in.retry_source_connection_id.value(); if (!writer.WriteVarInt62( TransportParameters::kRetrySourceConnectionId) || !writer.WriteStringPieceVarInt62( absl::string_view(retry_source_connection_id.data(), retry_source_connection_id.length()))) { QUIC_BUG(Failed to write retry_source_connection_id) << "Failed to write retry_source_connection_id " << retry_source_connection_id << " for " << in; return false; } } } break; // Google-specific connection options. case TransportParameters::kGoogleConnectionOptions: { if (in.google_connection_options.has_value()) { static_assert( sizeof(in.google_connection_options.value().front()) == 4, "bad size"); uint64_t connection_options_length = in.google_connection_options.value().size() * 4; if (!writer.WriteVarInt62( TransportParameters::kGoogleConnectionOptions) || !writer.WriteVarInt62( /* transport parameter length */ connection_options_length)) { QUIC_BUG(Failed to write google_connection_options) << "Failed to write google_connection_options of length " << connection_options_length << " for " << in; return false; } for (const QuicTag& connection_option : in.google_connection_options.value()) { if (!writer.WriteTag(connection_option)) { QUIC_BUG(Failed to write google_connection_option) << "Failed to write google_connection_option " << QuicTagToString(connection_option) << " for " << in; return false; } } } } break; // Google-specific version extension. case TransportParameters::kGoogleQuicVersion: { if (!in.legacy_version_information.has_value()) { break; } static_assert(sizeof(QuicVersionLabel) == sizeof(uint32_t), "bad length"); uint64_t google_version_length = sizeof(in.legacy_version_information.value().version); if (in.perspective == Perspective::IS_SERVER) { google_version_length += /* versions length */ sizeof(uint8_t) + sizeof(QuicVersionLabel) * in.legacy_version_information.value() .supported_versions.size(); } if (!writer.WriteVarInt62(TransportParameters::kGoogleQuicVersion) || !writer.WriteVarInt62( /* transport parameter length */ google_version_length) || !writer.WriteUInt32( in.legacy_version_information.value().version)) { QUIC_BUG(Failed to write Google version extension) << "Failed to write Google version extension for " << in; return false; } if (in.perspective == Perspective::IS_SERVER) { if (!writer.WriteUInt8(sizeof(QuicVersionLabel) * in.legacy_version_information.value() .supported_versions.size())) { QUIC_BUG(Failed to write versions length) << "Failed to write versions length for " << in; return false; } for (QuicVersionLabel version_label : in.legacy_version_information.value().supported_versions) { if (!writer.WriteUInt32(version_label)) { QUIC_BUG(Failed to write supported version) << "Failed to write supported version for " << in; return false; } } } } break; // version_information. case TransportParameters::kVersionInformation: { if (!in.version_information.has_value()) { break; } static_assert(sizeof(QuicVersionLabel) == sizeof(uint32_t), "bad length"); QuicVersionLabelVector other_versions = in.version_information.value().other_versions; // Insert one GREASE version at a random index. const size_t grease_index = random->InsecureRandUint64() % (other_versions.size() + 1); other_versions.insert( other_versions.begin() + grease_index, CreateQuicVersionLabel(QuicVersionReservedForNegotiation())); const uint64_t version_information_length = sizeof(in.version_information.value().chosen_version) + sizeof(QuicVersionLabel) * other_versions.size(); if (!writer.WriteVarInt62(TransportParameters::kVersionInformation) || !writer.WriteVarInt62( /* transport parameter length */ version_information_length) || !writer.WriteUInt32( in.version_information.value().chosen_version)) { QUIC_BUG(Failed to write chosen version) << "Failed to write chosen version for " << in; return false; } for (QuicVersionLabel version_label : other_versions) { if (!writer.WriteUInt32(version_label)) { QUIC_BUG(Failed to write other version) << "Failed to write other version for " << in; return false; } } } break; // Custom parameters and GREASE. default: { auto it = custom_parameters.find(parameter_id); if (it == custom_parameters.end()) { QUIC_BUG(Unknown parameter) << "Unknown parameter " << parameter_id; return false; } if (!writer.WriteVarInt62(parameter_id) || !writer.WriteStringPieceVarInt62(it->second)) { QUIC_BUG(Failed to write custom parameter) << "Failed to write custom parameter " << parameter_id; return false; } } break; } } out->resize(writer.length()); QUIC_DLOG(INFO) << "Serialized " << in << " as " << writer.length() << " bytes"; return true; } bool ParseTransportParameters(ParsedQuicVersion version, Perspective perspective, const uint8_t* in, size_t in_len, TransportParameters* out, std::string* error_details) { out->perspective = perspective; QuicDataReader reader(reinterpret_cast(in), in_len); while (!reader.IsDoneReading()) { uint64_t param_id64; if (!reader.ReadVarInt62(¶m_id64)) { *error_details = "Failed to parse transport parameter ID"; return false; } TransportParameters::TransportParameterId param_id = static_cast(param_id64); absl::string_view value; if (!reader.ReadStringPieceVarInt62(&value)) { *error_details = "Failed to read length and value of transport parameter " + TransportParameterIdToString(param_id); return false; } QuicDataReader value_reader(value); bool parse_success = true; switch (param_id) { case TransportParameters::kOriginalDestinationConnectionId: { if (out->original_destination_connection_id.has_value()) { *error_details = "Received a second original_destination_connection_id"; return false; } const size_t connection_id_length = value_reader.BytesRemaining(); if (!QuicUtils::IsConnectionIdLengthValidForVersion( connection_id_length, version.transport_version)) { *error_details = absl::StrCat( "Received original_destination_connection_id of invalid length ", connection_id_length); return false; } QuicConnectionId original_destination_connection_id; if (!value_reader.ReadConnectionId(&original_destination_connection_id, connection_id_length)) { *error_details = "Failed to read original_destination_connection_id"; return false; } out->original_destination_connection_id = original_destination_connection_id; } break; case TransportParameters::kMaxIdleTimeout: parse_success = out->max_idle_timeout_ms.Read(&value_reader, error_details); break; case TransportParameters::kStatelessResetToken: { if (!out->stateless_reset_token.empty()) { *error_details = "Received a second stateless_reset_token"; return false; } absl::string_view stateless_reset_token = value_reader.ReadRemainingPayload(); if (stateless_reset_token.length() != kStatelessResetTokenLength) { *error_details = absl::StrCat("Received stateless_reset_token of invalid length ", stateless_reset_token.length()); return false; } out->stateless_reset_token.assign( stateless_reset_token.data(), stateless_reset_token.data() + stateless_reset_token.length()); } break; case TransportParameters::kMaxPacketSize: parse_success = out->max_udp_payload_size.Read(&value_reader, error_details); break; case TransportParameters::kInitialMaxData: parse_success = out->initial_max_data.Read(&value_reader, error_details); break; case TransportParameters::kInitialMaxStreamDataBidiLocal: parse_success = out->initial_max_stream_data_bidi_local.Read( &value_reader, error_details); break; case TransportParameters::kInitialMaxStreamDataBidiRemote: parse_success = out->initial_max_stream_data_bidi_remote.Read( &value_reader, error_details); break; case TransportParameters::kInitialMaxStreamDataUni: parse_success = out->initial_max_stream_data_uni.Read(&value_reader, error_details); break; case TransportParameters::kInitialMaxStreamsBidi: parse_success = out->initial_max_streams_bidi.Read(&value_reader, error_details); break; case TransportParameters::kInitialMaxStreamsUni: parse_success = out->initial_max_streams_uni.Read(&value_reader, error_details); break; case TransportParameters::kAckDelayExponent: parse_success = out->ack_delay_exponent.Read(&value_reader, error_details); break; case TransportParameters::kMaxAckDelay: parse_success = out->max_ack_delay.Read(&value_reader, error_details); break; case TransportParameters::kDisableActiveMigration: if (out->disable_active_migration) { *error_details = "Received a second disable_active_migration"; return false; } out->disable_active_migration = true; break; case TransportParameters::kPreferredAddress: { TransportParameters::PreferredAddress preferred_address; uint16_t ipv4_port, ipv6_port; in_addr ipv4_address; in6_addr ipv6_address; preferred_address.stateless_reset_token.resize( kStatelessResetTokenLength); if (!value_reader.ReadBytes(&ipv4_address, sizeof(ipv4_address)) || !value_reader.ReadUInt16(&ipv4_port) || !value_reader.ReadBytes(&ipv6_address, sizeof(ipv6_address)) || !value_reader.ReadUInt16(&ipv6_port) || !value_reader.ReadLengthPrefixedConnectionId( &preferred_address.connection_id) || !value_reader.ReadBytes(&preferred_address.stateless_reset_token[0], kStatelessResetTokenLength)) { *error_details = "Failed to read preferred_address"; return false; } preferred_address.ipv4_socket_address = QuicSocketAddress(QuicIpAddress(ipv4_address), ipv4_port); preferred_address.ipv6_socket_address = QuicSocketAddress(QuicIpAddress(ipv6_address), ipv6_port); if (!preferred_address.ipv4_socket_address.host().IsIPv4() || !preferred_address.ipv6_socket_address.host().IsIPv6()) { *error_details = "Received preferred_address of bad families " + preferred_address.ToString(); return false; } if (!QuicUtils::IsConnectionIdValidForVersion( preferred_address.connection_id, version.transport_version)) { *error_details = "Received invalid preferred_address connection ID " + preferred_address.ToString(); return false; } out->preferred_address = std::make_unique( preferred_address); } break; case TransportParameters::kActiveConnectionIdLimit: parse_success = out->active_connection_id_limit.Read(&value_reader, error_details); break; case TransportParameters::kInitialSourceConnectionId: { if (out->initial_source_connection_id.has_value()) { *error_details = "Received a second initial_source_connection_id"; return false; } const size_t connection_id_length = value_reader.BytesRemaining(); if (!QuicUtils::IsConnectionIdLengthValidForVersion( connection_id_length, version.transport_version)) { *error_details = absl::StrCat( "Received initial_source_connection_id of invalid length ", connection_id_length); return false; } QuicConnectionId initial_source_connection_id; if (!value_reader.ReadConnectionId(&initial_source_connection_id, connection_id_length)) { *error_details = "Failed to read initial_source_connection_id"; return false; } out->initial_source_connection_id = initial_source_connection_id; } break; case TransportParameters::kRetrySourceConnectionId: { if (out->retry_source_connection_id.has_value()) { *error_details = "Received a second retry_source_connection_id"; return false; } const size_t connection_id_length = value_reader.BytesRemaining(); if (!QuicUtils::IsConnectionIdLengthValidForVersion( connection_id_length, version.transport_version)) { *error_details = absl::StrCat( "Received retry_source_connection_id of invalid length ", connection_id_length); return false; } QuicConnectionId retry_source_connection_id; if (!value_reader.ReadConnectionId(&retry_source_connection_id, connection_id_length)) { *error_details = "Failed to read retry_source_connection_id"; return false; } out->retry_source_connection_id = retry_source_connection_id; } break; case TransportParameters::kMaxDatagramFrameSize: parse_success = out->max_datagram_frame_size.Read(&value_reader, error_details); break; case TransportParameters::kInitialRoundTripTime: parse_success = out->initial_round_trip_time_us.Read(&value_reader, error_details); break; case TransportParameters::kGoogleConnectionOptions: { if (out->google_connection_options.has_value()) { *error_details = "Received a second google_connection_options"; return false; } out->google_connection_options = QuicTagVector{}; while (!value_reader.IsDoneReading()) { QuicTag connection_option; if (!value_reader.ReadTag(&connection_option)) { *error_details = "Failed to read a google_connection_options"; return false; } out->google_connection_options.value().push_back(connection_option); } } break; case TransportParameters::kGoogleQuicVersion: { if (!out->legacy_version_information.has_value()) { out->legacy_version_information = TransportParameters::LegacyVersionInformation(); } if (!value_reader.ReadUInt32( &out->legacy_version_information.value().version)) { *error_details = "Failed to read Google version extension version"; return false; } if (perspective == Perspective::IS_SERVER) { uint8_t versions_length; if (!value_reader.ReadUInt8(&versions_length)) { *error_details = "Failed to parse Google supported versions length"; return false; } const uint8_t num_versions = versions_length / sizeof(uint32_t); for (uint8_t i = 0; i < num_versions; ++i) { QuicVersionLabel version; if (!value_reader.ReadUInt32(&version)) { *error_details = "Failed to parse Google supported version"; return false; } out->legacy_version_information.value() .supported_versions.push_back(version); } } } break; case TransportParameters::kVersionInformation: { if (out->version_information.has_value()) { *error_details = "Received a second version_information"; return false; } out->version_information = TransportParameters::VersionInformation(); if (!value_reader.ReadUInt32( &out->version_information.value().chosen_version)) { *error_details = "Failed to read chosen version"; return false; } while (!value_reader.IsDoneReading()) { QuicVersionLabel other_version; if (!value_reader.ReadUInt32(&other_version)) { *error_details = "Failed to parse other version"; return false; } out->version_information.value().other_versions.push_back( other_version); } } break; case TransportParameters::kMinAckDelay: parse_success = out->min_ack_delay_us.Read(&value_reader, error_details); break; default: if (out->custom_parameters.find(param_id) != out->custom_parameters.end()) { *error_details = "Received a second unknown parameter" + TransportParameterIdToString(param_id); return false; } out->custom_parameters[param_id] = std::string(value_reader.ReadRemainingPayload()); break; } if (!parse_success) { QUICHE_DCHECK(!error_details->empty()); return false; } if (!value_reader.IsDoneReading()) { *error_details = absl::StrCat( "Received unexpected ", value_reader.BytesRemaining(), " bytes after parsing ", TransportParameterIdToString(param_id)); return false; } } if (!out->AreValid(error_details)) { QUICHE_DCHECK(!error_details->empty()); return false; } QUIC_DLOG(INFO) << "Parsed transport parameters " << *out << " from " << in_len << " bytes"; return true; } namespace { bool DigestUpdateIntegerParam( EVP_MD_CTX* hash_ctx, const TransportParameters::IntegerParameter& param) { uint64_t value = param.value(); return EVP_DigestUpdate(hash_ctx, &value, sizeof(value)); } } // namespace bool SerializeTransportParametersForTicket( const TransportParameters& in, const std::vector& application_data, std::vector* out) { std::string error_details; if (!in.AreValid(&error_details)) { QUIC_BUG(quic_bug_10743_26) << "Not serializing invalid transport parameters: " << error_details; return false; } out->resize(SHA256_DIGEST_LENGTH + 1); const uint8_t serialization_version = 0; (*out)[0] = serialization_version; bssl::ScopedEVP_MD_CTX hash_ctx; // Write application data: uint64_t app_data_len = application_data.size(); const uint64_t parameter_version = 0; // The format of the input to the hash function is as follows: // - The application data, prefixed with a 64-bit length field. // - Transport parameters: // - A 64-bit version field indicating which version of encoding is used // for transport parameters. // - A list of 64-bit integers representing the relevant parameters. // // When changing which parameters are included, additional parameters can be // added to the end of the list without changing the version field. New // parameters that are variable length must be length prefixed. If // parameters are removed from the list, the version field must be // incremented. // // Integers happen to be written in host byte order, not network byte order. if (!EVP_DigestInit(hash_ctx.get(), EVP_sha256()) || !EVP_DigestUpdate(hash_ctx.get(), &app_data_len, sizeof(app_data_len)) || !EVP_DigestUpdate(hash_ctx.get(), application_data.data(), application_data.size()) || !EVP_DigestUpdate(hash_ctx.get(), ¶meter_version, sizeof(parameter_version))) { QUIC_BUG(quic_bug_10743_27) << "Unexpected failure of EVP_Digest functions when hashing " "Transport Parameters for ticket"; return false; } // Write transport parameters specified by draft-ietf-quic-transport-28, // section 7.4.1, that are remembered for 0-RTT. if (!DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_data) || !DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_stream_data_bidi_local) || !DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_stream_data_bidi_remote) || !DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_stream_data_uni) || !DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_streams_bidi) || !DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_streams_uni) || !DigestUpdateIntegerParam(hash_ctx.get(), in.active_connection_id_limit)) { QUIC_BUG(quic_bug_10743_28) << "Unexpected failure of EVP_Digest functions when hashing " "Transport Parameters for ticket"; return false; } uint8_t disable_active_migration = in.disable_active_migration ? 1 : 0; if (!EVP_DigestUpdate(hash_ctx.get(), &disable_active_migration, sizeof(disable_active_migration)) || !EVP_DigestFinal(hash_ctx.get(), out->data() + 1, nullptr)) { QUIC_BUG(quic_bug_10743_29) << "Unexpected failure of EVP_Digest functions when hashing " "Transport Parameters for ticket"; return false; } return true; } } // namespace quic /*************************************************************************** * jlp_patch_set1.cpp * * Set of subroutines used by Xdisp1 and jlp_wx_widgets for "patching" images * * Contains: * POLY_CIRC_PATCH, PROFILE_CIRC_PATCH * * Package of routines for finding and removing defects from * an image array. The position of the area to delete may * be specified manually using the cursor, or by reading a file. * The user is prompted for the diameter of a circle * of pixels to delete around this position, which are * replaced by an interpolation of a surface fitted to * an annulus of surrounding pixels. A constant, planar, * quadratic, or cubic surface may be specified (1,3,6, or 10 * terms). The interpolation is then displayed on the screen * and the user judges the quality of fit. If necessary, the * original values of the pixels may be restored and a * different interpolation attempted. * * From Fortran version of 05/04/2006 * Converted to C by JLP in August 2006 * * JLP * Version 26/01/2013 ***************************************************************************/ #include #include #include "jlp_macros.h" #include "jlp_random.h" #include "jlp_patch_set1.h" /* #define DEBUG */ /* Size of arrays used to fit the background in POLY_CIRC_PATCH */ #define NDIM_MAX 16384 /* Maximum number of polynomial terms: */ #define NTERMS 30 /* Prototypes defined in "patch_set1.h": */ /* int POLY_CIRC_PATCH(double *image1, int nx1, int ny1, int idim1, double xp, double yp, double diam, double *noise_array, int noise_dim, int poly_order, double *sigma_sky, char *err_message); int PROFILE_CIRC_PATCH(double *image1, int nx1, int ny1, int idim1, double xp, double yp, double diam, double *noise_array, int noise_dim, double *sigma_sky, char *err_message); int CREATE_NOISE_ARRAY(double **noise_array, int noise_dim); int DELETE_NOISE_ARRAY(double *noise_array); */ // Static functions static int get_profile_value(double radc, double *rad, double *mean, int nprof, double *mean_value); static int patch_neqsol(double *xx, double *yy, double *zz, double *wwork, int *ndim, int *npts, int *nterms, int *noto, int *ioor, double *dd, double *se, double *rdoe, double *sdor, char *err_message); static int patch_reject(double *xx, double *yy, double *zz, int *ndim, double *dd, int *nn, int *kk, double *tt, int *mm, int *jreject); double patch_poly(double *z1, double *z2, double *dd); /************************************************************************ * Create a noise array used by patch routines (needed for increasing speed) * * INPUT: * noise_dim: dimension of noise_array (NB: 256 is a good value...) * * OUTPUT: * noise_array: set of Gaussian random values in the range [0,1] *************************************************************************/ int CREATE_NOISE_ARRAY(double **noise_array, int noise_dim) { double ww; long int seed; register int i; *noise_array = new double[noise_dim]; seed = 1; JLP_RANDOM_INIT(&seed); for(i = 0; i < noise_dim; i++) { JLP_RANDOM_GAUSS(&ww); (*noise_array)[i] = ww; } return(0); } int DELETE_NOISE_ARRAY(double *noise_array) { delete[] noise_array; return(0); } /****************************************************************** * Subroutine to fit a polynomial to an annulus around the center * and replace input values by noised computed values * * INPUT: * poly_order: polynomial order * diam: diameter of the patch (in pixels) * noise_array: Gaussian random noise array (normalized to 1.) * sigma_noise: sigma of the noise to be used for adding noise * noise_dim: size of (monodimensional) noise_array * sigma_sky: standard deviation of the background * * INPUT/OUTPUT: * image1[nx1, ny1]: image to be processed *******************************************************************/ int POLY_CIRC_PATCH(double *image1, int nx1, int ny1, int idim1, double xp, double yp, double diam, double diam_factor, double *noise_array, int noise_dim, double sigma_noise, int poly_order, double *sigma_sky, char *err_message) { int ixp, iyp, status, italk = 0; /* NTERMS = maximum number of polynomial terms: */ double wwork[NDIM_MAX], dd[NTERMS], se[NTERMS], rdoe[NTERMS]; double xx[NDIM_MAX], yy[NDIM_MAX], zz[NDIM_MAX], xz, yz, xnoise; double test, sdor, dx, dy, radmin2, diam_max, radmax, radmax2, rad2; double xran; int kq, nr, nterms, npts, imin, imax, jmin, jmax; int noto, ioor, jreject, ndim = NDIM_MAX; register int i, j, k; *sigma_sky = 0.; /* SET UP ARRAYS FOR patch_neqsol * * diam_factor=2 => annulus of diameters DIAM (inside) and 2*DIAM (outside) * Before 2006: * diam_factor=2 * JLP2006: diam_factor=2 is bad: I reduce it to 1.5 */ diam_max = diam * diam_factor; radmax = (diam_max + 1) / 2; radmax2 = radmax * radmax; /* Center coordinates: */ ixp = NINT(xp); iyp = NINT(yp); /* Boundaries: */ imin = MAXI((int)(xp - radmax), 0); imax = MINI((int)(xp + radmax + 1), nx1); jmin = MAXI((int)(yp - radmax), 0); jmax = MINI((int)(yp + radmax + 1), ny1); /* Define normalizing factors such that the coords. of * all the points are between [-1,-1] and [1,1]. */ radmin2 = SQUARE(diam / 2.); dx = 2. / (double)(imax - imin); dy = 2. / (double)(jmax - jmin); npts = 0; for(j = jmin; j < jmax; j++) for(i = imin; i < imax; i++){ /* * Calculate radius, and check if it lies between radmin and radmax * then use this point to compute the polynomial. * JLP2006: The cursor gives (0.5,0.5) when the cursor * is centered on the pixel (0,0) in the bottom-left corner: */ rad2 = SQUARE((double)j - (yp - 0.5)) + SQUARE((double)i - (xp - 0.5)); if (rad2 > radmin2 && rad2 <= radmax2) { /* * The coords. of all the points are between (-1,-1) and (1,1). */ xx[npts] = (i - imin) * dx - 1.; /* X coordinate */ yy[npts] = (j - jmin) * dy - 1.; /* Y coordinate */ zz[npts] = image1[i + j * idim1]; npts++; if(npts >= ndim) { fprintf(stderr, "POLY_CIRC_PATCH/Error: too many points: npts=%d (maxi=%d)\n", npts, ndim); return(-1); } } } /* Number of terms according to the polynomial order: */ switch (poly_order) { case 5: nterms = 21; break; case 4: nterms = 15; break; case 3: nterms = 10; break; case 2: nterms = 6; break; case 1: nterms = 3; break; default: nterms = 1; break; } /* Check if enough points to solve the problem: */ if(npts <= nterms) { fprintf(stderr,"POLY_CIRC_PATCH/Error: too few points to fit the background\n"); fprintf(stderr,"npts = %d nterms = %d (polynomial order = %d)\n", npts, nterms, poly_order); fprintf(stderr,"xc=%.2f yc=%.2f diam=%.2f diam_fact=%.2f\n", xp, yp, diam, diam_factor); return(-1); } /* * Initialize the solution: */ for(i = 0; i < 30; i++) dd[i] = 0.; /* * Fit the polynomial with all points: */ noto = 1; ioor = 0; status = patch_neqsol(xx, yy, zz, wwork, &ndim, &npts, &nterms, ¬o, &ioor, dd, se, rdoe, &sdor, err_message); if(status) { fprintf(stderr,"POLY_CIRC_PATCH/Error (1) in patch_neqsol status=%d\n", status); return(-1); } /* Perform twice a 2 sigma rejection (test = 2 * sdor): */ for(kq = 0; kq < 2; kq++) { test = 2. * sdor; jreject = 1; patch_reject(xx, yy, zz, &ndim, dd, &npts, &nterms, &test, &nr, &jreject); /* nr: number of points after rejection */ npts = nr; if(npts <= nterms && italk) { fprintf(stderr,"POLY_CIRC_PATCH/Warning: too few points to fit the background\n"); fprintf(stderr,"After %dth rejection: npts = %d nterms = %d\n", kq+1, npts, nterms); *sigma_sky = sdor; } else /* Refit polynomial with the selected points (i.e., 2-sigma rejection): */ status = patch_neqsol(xx, yy, zz, wwork, &ndim, &npts, &nterms, ¬o, &ioor, dd, se, rdoe, &sdor, err_message); if(status) { fprintf(stderr,"POLY_CIRC_PATCH/Error (2) in patch_neqsol status=%d\n", status); return(-2); } } /* EOF loop on kq */ #ifdef DEBUG for(i = 0; i < nterms; i++) printf("solution: dd[%d]=%f\n", i, dd[i]); for(i = 0; i < 30; i++) printf("dd[%d]=%f\n", i, dd[i]); #endif /* * Evaluate polynomial at each point within circle */ for(j = jmin; j < jmax; j++) { /* * Find a random starting point in the sequence of noise points * to obtain random numbers between 0. and 1. using noise_array */ JLP_RANDOM(&xran); k = (int)(xran * (double)noise_dim); k = MAXI(0, k); k = MINI(k, noise_dim - 1); yz = (j - jmin) * dy - 1.; for(i = imin; i < imax; i++) { /* JLP2006: The cursor gives (0.5,0.5) when the cursor * is centered on the pixel (0,0) in the bottom-left corner: */ rad2 = SQUARE((double)j - (yp - 0.5)) + SQUARE((double)i - (xp - 0.5)); if (rad2 <= radmin2) { xz = (i - imin) * dx - 1.; /* Handle k index in "noise_array": */ k++; if(k >= noise_dim) k = 0; /* Noise is normalized to the standard deviation obtained in the fit: */ xnoise = sigma_noise * noise_array[k] * sdor; /* Calling patch_poly function: */ #ifdef DEBUG if(yz < -0.2) printf("xz=%f yz=%f, image1=%f poly_value=%f\n", xz, yz, image1[i + j * idim1], patch_poly(&xz, &yz, dd)); #endif image1[i + j * idim1] = patch_poly(&xz, &yz, dd) + xnoise; } } } *sigma_sky = sdor; return(0); } /****************************************************************** * Subroutine to compute a mean profile (centered in nx1/2, ny1/2) * and replace input values by noised computed values * inside of the circle of diameter diam centered in (xp, yp) * * INPUT: * diam: diameter of the patch (in pixels) * noise_array: Gaussian random noise array (normalized to 1.) * sigma_noise: sigma of the noise to be used for adding noise * noise_dim: size of (monodimensional) noise_array * sigma_sky: standard deviation of the background * * INPUT/OUTPUT: * image1[nx1, ny1]: image to be processed *******************************************************************/ int PROFILE_CIRC_PATCH(double *image1, int nx1, int ny1, int idim1, double xp, double yp, double diam, double diam_factor, double *noise_array, int noise_dim, double sigma_noise, double *sigma_sky, char *err_message) { int ixp, iyp, ip; double sum[NDIM_MAX], sumsq[NDIM_MAX], ssum; double mean[NDIM_MAX], sig[NDIM_MAX], rad[NDIM_MAX]; double xnoise, gain = 3, mean_value; double radmin2, diam_max, radmax, radmax2, rad2, radc, radc2, radc_min; double xran; int imin, imax, jmin, jmax; int ndim = NDIM_MAX, npts[NDIM_MAX], nprof; double xc, yc, ww; register int i, j, k; *sigma_sky = 0.; /* * diam factor=1.5 => annulus of diameters DIAM (inside) and 1.5*DIAM (outside) * factor = 1.8; */ diam_max = diam * diam_factor; radmax = (diam_max + 1) / 2; radmax2 = radmax * radmax; radmin2 = SQUARE(diam / 2.); /* Center of image: */ xc = nx1/2; yc = ny1/2; /* Check if it is reasonable to compute such a profile: */ radc2 = SQUARE(xp - (xc - 0.5)) + SQUARE(yp - (yc - 0.5)); if(radc2 < 4.) { sprintf(err_message, "PROFILE_CIRC_PATCH/error: center of patch too close from center of image"); return(-1); } radc_min = sqrt(radc2) - radmax - 1.; /* Center coordinates: */ ixp = NINT(xp); iyp = NINT(yp); /* Boundaries: */ imin = MAXI((int)(xp - radmax), 0); imax = MINI((int)(xp + radmax + 1), nx1); jmin = MAXI((int)(yp - radmax), 0); jmax = MINI((int)(yp + radmax + 1), ny1); /* Initialization of profile arrays: */ for(i = 0; i < ndim; i++) { npts[i] = 0; sum[i] = 0.; sumsq[i] = 0.; mean[i] = 0.; rad[i] = 0.; sig[i] = 0.; } /* Main loop for computing the profile: */ for(j = jmin; j < jmax; j++) for(i = imin; i < imax; i++){ /* * Calculate radius, and reject if too close to star centre * * JLP2006: The cursor gives (0.5,0.5) when the cursor * is centered on the pixel (0,0) in the bottom-left corner: */ rad2 = SQUARE((double)j - (yp - 0.5)) + SQUARE((double)i - (xp - 0.5)); if(rad2 > radmin2 && rad2 <= radmax2) { /* JLP2007: should not remove 0.5 here ! */ radc2 = SQUARE((double)j - xc) + SQUARE((double)i - yc); /* Index of profile (higher resolution since it is necessary close to the * center: */ ip = NINT(gain * (sqrt(radc2) - radc_min)); ip = MINI(ndim - 1, MAXI(0, ip)); /* Update profile values: */ ww = image1[i + j * idim1]; sum[ip] += ww; sumsq[ip] += ww * ww; npts[ip]++; } } /* Compute mean profile with significant data (i.e. more than 3 points): */ k = 0; for(i = 0; i < ndim; i++) { if(npts[i] >= 3) { mean[k] = sum[i] / (double)npts[i]; ww = sumsq[i] / (double)npts[i] - SQUARE(mean[k]); sig[k] = sqrt(ww); rad[k] = radc_min + (double)i / gain; k++; } } nprof = k; if(k < 3) { sprintf(err_message, "PROFILE_CIRC_PATCH/Error: too few points, nprof=%d", nprof); return(-1); } /* Mean sigma: */ ssum = 0.; for(k = 0; k < nprof; k++) ssum += sig[k]; *sigma_sky = ssum / (double)nprof; #ifdef DEBUG printf("Profile nprof=%d, mean sigma = %f\n", nprof, *sigma_sky); #endif /* * Affect profile value to each point within circle */ for(j = jmin; j < jmax; j++) { /* * Find a random starting point in the sequence of noise points * to obtain random numbers between 0. and 1. using noise_array */ JLP_RANDOM(&xran); k = (int)(xran * (double)noise_dim); k = MAXI(0, k); k = MINI(k, noise_dim - 1); for(i = imin; i < imax; i++) { /* JLP2006: The cursor gives (0.5,0.5) when the cursor * is centered on the pixel (0,0) in the bottom-left corner: */ rad2 = SQUARE((double)j - (yp - 0.5)) + SQUARE((double)i - (xp - 0.5)); if (rad2 <= radmin2) { /* JLP2007: should not remove 0.5 here ! */ radc2 = SQUARE((double)j - yc) + SQUARE((double)i - xc); radc = sqrt(radc2); /* Index of profile (should be the same as above): */ get_profile_value(radc, rad, mean, nprof, &mean_value); /* Handle k index in "noise_array": */ k++; if(k >= noise_dim) k = 0; /* Noise is normalized to the standard deviation of the profile: */ xnoise = sigma_noise * noise_array[k] * (*sigma_sky); /* Use the mean profile value: */ image1[i + j * idim1] = mean_value + xnoise; } } /* EOF loop on i */ } /* EOF loop on j */ return(0); } /*********************************************************************** * Look for the index of "radc" in "rad" array * * rad: array sorted in increasing order * radc: value to be looked for ************************************************************************/ static int get_profile_value(double radc, double *rad, double *mean, int nprof, double *mean_value) { register int i; int status = -1, kp; /* kp: index of closer value of radc in rad array */ kp = 0; *mean_value = mean[0]; for(i = 0; i < nprof; i++) { if(radc < rad[i]) { if(i > 0) { *mean_value = (mean[i-1] * (rad[i] - radc) + mean[i] * (radc - rad[i-1])) / (rad[i] - rad[i-1]); /* DEBUGGG printf("radc=%.2f rad[i]=%.2f rad[i-1]=%.2f (i=%d) \n", radc, rad[i], rad[i-1], i); printf("value=%.2f mean[i]=%.2f mean[i-1]=%.2f\n", *mean_value, mean[i], mean[i-1]); */ kp = i - 1; } else { *mean_value = mean[0]; kp = 0; } status = 0; break; } } return(status); } /* ************************************************************** * * SUBROUTINE patch_neqsol(X,Y,WWORK,NDIM,NPTS,NTERMS,NOTO,IOOR,D,SE,RDOE,SDOR) * * THIS SUBROUTINE COMPUTES THE COEFFICIENTS, D, WHICH DEFINE THAT LINEAR * FUNCTION, Y, OF LINEARLY INDEPENDENT FUNCTIONS WHICH BEST FITS, IN THE * LEAST SQUARES SENSE, A GIVEN SET OF DATA. OR EQUIVALENTLY, IT FINDS * THE SOLUTION TO THE SYSTEM OF NORMAL EQUATIONS WHICH IS CALLED THE * NORMAL EQUATIONS SOLUTION. * * WRITTEN AND DOCUMENTED BY: * * JONES, , OBITTS, , GALLET, , AND , * 'ASTRONOMICAL SURFACE PHOTOMETRY BY NUMERICAL MAPPING * TECHNIQUES', PUBLICATION OF THE ASTRONOMY DEPARTMENT, UNIV. * OF TEXAS, AUSTIN, SERIES II, VOL. I, NO. 8, FEB. 1967 * * MODIFIED BY , UNIV. OF SUSSEX, SEPT. 1980 * * X(NDIM), Y(NDIM) = COORDINATES OF POINTS (R*4) * Z(NPTS) = VALUE OF POINT AT X(NPTS),Y(NPTS) (R*4) * WWORK = SCRATCH ARRAY (DOUBLE PRECISION, R*8) * NDIM = FIRST DIMENSION OF X, Y AND WW (I*4) * NPTS = NO. OF POINTS IN LEAST SQUARES FIT (I*4) * NTERMS = NO. OF COEFS TO BE SOLVED FOR (I*4) * NOTO = NO. OF TOTAL ORTHOGONALIZATIONS TO PERFORM (I*4) * IOOR = POSITIVE INTEGER IF OPTIONAL OUTPUT IS REQUIRED * D(NTERMS) = COEFFICIENTS OF THE POLYNOMIAL (DOUBLE PRECISION, R*8) * Maximum: NTERMS=30 * SE(K) = RMS OF FIT USING ONLY THE FIRST K COEFFICIENTS (R*8) * RDOE(NTERMS) = INDICATES THE STATISTICAL SIGNIFICANCE OF EACH TERM (R*8) * SDOR = STANDARD DEVIATION OF RESIDUALS (R*4) * * ***************************************************************/ static int patch_neqsol(double *xx, double *yy, double *zz, double *wwork, int *ndim, int *npts, int *nterms, int *noto, int *ioor, double *dd, double *se, double *rdoe, double *sdor, char *err_message) { double aa[30], akj[30][30], aaa[30], ss[30][30], yg[30]; double ggsqt[30], gg[30][30], qq[30][30][2]; double sum, flnpts = 0, zzz, zzbar, tt, gk; int ix, jy, jul, kul, ixx, jyy; register int i, j, k, l, m; if(*nterms >= *npts) { sprintf(err_message,"NEQSOL/Error: too few points nterms=%d npts=%d", *nterms, *npts); return(-1); } if(*nterms > 30) { sprintf(err_message,"NEQSOL/Error: too many terms: nterms=%d", *nterms); return(-1); } if(*noto < 1 || *noto > 2) { sprintf(err_message,"NEQSOL/Error: noto=%d (should be 1 or 2)\n", *noto); return(-1); } if(*noto == 1) { /* COMPUTE THE SQUARE OF THE NORM OF THE VECTOR OF THE DEPENDENT VARIABLE, * COMPUTE THE MEAN OF THE DEPENDENT VARIABLE, YBAR. */ flnpts = *npts; zzz = 0.; zzbar = 0.; for(i = 0; i < *npts; i++) { zzz += zz[i] * zz[i]; zzbar += zz[i]; } zzbar /= (double)(*npts); #ifdef DEBUG printf("\n NEQSOL/nterms=%d noto=%d npts=%d\n", *nterms, *noto, *npts); printf("NEQSOL/Input data: sumsq=zzz=%f mean=zzbar=%f\n", zzz, zzbar); #endif /* COMPUTE THE MATRIX OF INNER PRODUCTS OF THE NORMALIZED FITTING FUNCTIONS */ /* Generate the X and Y exponents for the polynomial: */ /* ( X**ix * Y**jy) */ ix = 0; jy = -1; /* BOF loop on j */ for(j = 0; j < *nterms; j++) { if(ix != 0) { ix--; jy++; } else { ix = jy + 1; jy = 0; } /* #ifdef DEBUG printf("NEQSOL/Term #%d Exponents: ix=%d jy=%d \n", j, ix, jy); #endif */ tt = 0.; sum = 0.; for(i = 0; i < *npts; i++) { gk = 1.; if(ix != 0) gk = pow(xx[i], ix); if(jy != 0) gk *= pow(yy[i], jy); wwork[i] = gk; tt += gk * gk; sum += zz[i] * gk; } ggsqt[j] = sqrt(tt); yg[j] = sum / ggsqt[j]; gg[j][j] = 1.0; if(j > 0) { kul = j - 1; /* Generate the X and Y exponents for the polynomial: */ ixx = 0; jyy = -1; for(k = 0; k <= kul; k++) { if(ixx != 0) { ixx--; jyy++; } else { ixx = jyy + 1; jyy = 0; } /* */ tt = 0.; for(i = 0; i < *npts; i++) { gk = 1.; if(ixx != 0) gk = pow(xx[i], ixx); if(jyy != 0) gk *= pow(yy[i], jyy); tt += wwork[i] * gk; } gg[j][k] = tt / (ggsqt[j] * ggsqt[k]); gg[k][j] = gg[j][k]; } /* EOF look on k */ } /* EOF j > 0 */ } /* EOF loop on j */ } /* EOF noto==1 */ /* COMPUTE THE MATRIX OF COEFFICIENTS, Q, DEFINING THE ORTHOGONAL FUNCTIONS * IN TERMS OF THE FITTING FUNCTIONS. */ qq[0][0][*noto - 1] = 1.; ss[0][0] = 1.; aaa[0] = 1.; if(*noto == 1) { for(k = 1; k < *nterms; k++) { akj[k][0] = - gg[k][0]; } } else { for(k = 1; k < *nterms; k++) { sum = 0.; for(j = 0; j <= k; j++) { sum += qq[k][j][0] * gg[j][0]; } akj[k][0] = -sum; } } /* BOF loop on k */ for(k = 1; k < *nterms; k++) { qq[k][k][*noto - 1] = 1.; ss[k][k] = 1.; jul = k - 1; for(j = 0; j <= jul; j++) { if(*noto == 1) { tt = akj[k][j]; } else { tt = 0.; for(l = j; l <= jul; l++) tt += akj[k][l] * ss[l][j]; } ss[k][j] = tt; } /* */ for(j = 0; j <= jul; j++) { sum = 0.; for(l = j; l <= jul; l++) { sum += ss[k][l] * qq[l][j][0]; } if(*noto == 1) { qq[k][j][0] = sum; } else { qq[k][j][1] = sum + qq[k][j][0]; } } /* COMPUTE THE VECTOR OF THE SQUARE OF THE NORM OF THE ORTHOGONAL FUNCTIONS */ sum = 0.; for(j = 0; j <= k; j++) { tt = 0.; for(l = 0; l <= k; l++) { tt += qq[k][l][*noto - 1] * gg[l][j]; } sum += qq[k][j][*noto - 1] * tt; } aaa[k] = sum; if(k < *nterms) { for(j = k + 1; j < *nterms; j++) { sum = 0.; for(l = 0; l <= k; l++) { if(*noto == 1) { tt = gg[j][l]; } else { tt = 0.; for(m = 0; m <= j; m++) tt += qq[j][m][0] * gg[m][l]; } sum += qq[k][l][*noto - 1] * tt; } akj[j][k] = -sum / aaa[k]; } } } /* EOF loop on k */ /* COMPUTE THE LEAST SQUARES COEFFICIENTS, A, FOR THE SOLUTION IN TERMS OF * THE ORTHOGONAL FUNCTIONS. */ for(k = 0; k < *nterms; k++) { sum = 0.; for(j = 0; j <= k; j++) sum += qq[k][j][*noto - 1] * yg[j]; aa[k] = sum/aaa[k]; /* DEBUG printf("DDDD/aa[%d]=%f sum=%f\n", k, aaa[k], sum); */ } /* COMPUTE THE LEAST SQUARES COEFFICIENTS,D, FOR THE SOLUTION IN TERMS OF * THE FITTING FUNCTIONS. */ for(k = 0; k < *nterms; k++) { sum = 0.; for(j = k; j < *nterms; j++) sum += qq[j][k][*noto - 1] * aa[j]; dd[k] = sum / ggsqt[k]; /* #ifdef DEBUG printf("dd[%d]=%f sum=%f ggsqt[k]=%f\n", k, dd[k], sum, ggsqt[k]); #endif */ } /* COMPUTE THE STANDARD DEVIATION OF THE RESIDUALS, SDOR. */ *sdor = 0.; for(i = 0; i < *npts; i++) { sum = patch_poly(&xx[i], &yy[i], dd); tt = zz[i] - sum; *sdor += tt * tt; } *sdor = sqrt(*sdor/(flnpts - (double)(*nterms))); #ifdef DEBUG printf("patch_neqsol/Mean standard deviation: %f\n",*sdor); #endif return(0); } /****************************************************************** * * SUBROUTINE REJECT(X,Y,NDIM,D,N,K,TT,M,J) * * WRITTEN BY ., 1967 * MODIFIED BY , 1980 * * REJECT ANY POINT WHOSE RESIDUAL IS GREATER THAN BETA*SIGMA * FROM THE POLYNOMIAL DEFINED BY THE COEFFICIENTS D. * * X(NDIM),Y(NDIM) = INDEPENDENT VARIABLE (R*4) * Z(NDIM) = THE DEPENDENT VARIABLE (R*4) * NDIM = FIRST DIMENSION OF X AND Y (I*4) * D(30) = ARRAY CONTAINING THE POLYNOMIAL COEFFICIENTS (R*8) * N = NUMBER OF VALUES TO BE TESTED * K = THE NUMBER OF TERMS IN THE POLYNOMIAL * TT = THE TEST VALUE USED TO SPECIFY THE REJECTION LEVEL * M = THE MODIFIED NUMBER OF VALUES AFTER REJECTION * JREJECT = AN INDICATOR WHICH IS ZERO ONLY ON THE LAST CALL * ( THIS PREVENTS ANY POINTS FROM BEING REJECTED) * * In "patch2_set.for:" * TEST=2.*SDOR (2-sigma) * CALL REJECT1(XX,YY,NDIM,D,NPTS,NTERMS,TEST,NR,1,-1) * ********************************************************************/ static int patch_reject(double *xx, double *yy, double *zz, int *ndim, double *dd, int *nn, int *kk, double *tt, int *mm, int *jreject) { int indxp[21], indxn[21], npos, nneg; double avr, uu, vv; double rr, ss; register int i, j; #ifdef DEBUG printf("REJECT/Test=%f jreject=%d\n", *tt, *jreject); #endif for(i = 0; i < 21; i++) { indxn[i] = 0; indxp[i] = 0; } avr = 0.; uu = 0.; vv = 0.; npos = 0; nneg = 0; *mm = 0; /* BOF loop on i=0,nn */ for(i = 0; i < *nn; i++) { /* Compression of the arrays with the X,Y coordinates: */ xx[*mm] = xx[i]; yy[*mm] = yy[i]; zz[*mm] = zz[i]; ss = patch_poly(&xx[i], &yy[i], dd); /* * R=RESIDUAL FROM POLYNOMIAL FIT */ rr = zz[i] - ss; avr += rr; if( rr < 0) { nneg++; ss = -rr; /* DO NOT INCREMENT COUNTER M IF RESIDUAL IS GREATER THAN T LIMIT */ if((ss <= *tt) || (*jreject == 0)) (*mm)++; } else if (rr > 0) { npos++; ss = rr; if((ss <= *tt) || (*jreject == 0)) (*mm)++; } else (*mm)++; /* */ uu += rr * rr; vv += rr * rr * rr; /* Fill indxp (positive residuals) and indnp (negative residuals): */ if(rr < 0) { if(rr + 0.2 < 0) { indxn[20]++; } else { j = (int)(-100. * rr); indxn[j]++; } } else if (rr > 0) { if(rr - 0.2 > 0) { indxp[20]++; } else { j = (int)(100. * rr); indxp[j]++; } } else { indxp[0]++; } } /* EOF loop on i=0,nn */ (*mm)--; return(0); } /*********************************************************************** * Function patch_poly(X,Y,D) * * Evaluates the polynomial defined by the coefficients dd, at * the normalized coordinate (x,y). * * z1 = normalized x coordinate (R*4) * z2 = normalized y coordinate (R*4) * dd(30) = array containing the coefficients of the polynomial (R*8) * * From a Fortran version written by , Nov. 1980 * ***********************************************************************/ static double ylast_value = -123456789.000; double patch_poly(double *z1, double *z2, double *dd) { double xx, y1, y2, y3, y4, y5, y6; double c0, c1, c2, c3, c4, c5, c6, c7; double poly0; /* * First, calc 1-d polynomial in x for given y value, if * not already done */ c0 = 0.; c1 = 0.; c2 = 0.; c3 = 0.; c4 = 0.; c5 = 0.; c6 = 0.; c7 = 0.; xx = *z1; y1 = *z2; if(y1 != ylast_value){ y2 = y1 * y1; y3 = y2 * y1; y4 = y3 * y1; y5 = y4 * y1; y6 = y5 * y1; } /* (Error found here in dec 2014)... */ c0 = dd[0] + dd[2] * y1 + dd[5] * y2 + dd[9] * y3 + dd[14] * y4 + dd[20] * y5 + dd[27] * y6; c1 = dd[1] + dd[4] * y1 + dd[8] * y2 + dd[13] * y3 + dd[19] * y4 + dd[26] * y5; c2 = dd[3] + dd[7] * y1 + dd[12] * y2 + dd[18] * y3 + dd[25] * y4; c3 = dd[6] + dd[11] * y1 + dd[17] * y2 + dd[24] * y3; c4 = dd[10] + dd[16] * y1 + dd[23] * y2; c5 = dd[15] + dd[22] * y1; c6 = dd[21] + dd[29] * y1; c7 = dd[28]; /* * Evaluate polynomial in X */ poly0 = ((((((c7 * xx + c6) * xx + c5) * xx + c4) * xx + c3) * xx + c2) * xx + c1) * xx + c0; ylast_value = y1; return(poly0); } 0 #include #include int main(int argc, char *argv[]) { std::cout << "Welcome to mylang" << std::endl; std::cout << "Working directory " << std::filesystem::current_path() << std::endl; std::filesystem::path program_path = std::filesystem::path("./code/program.mlg"); //program_path += boost::filesystem::path("code"); if (std::filesystem::exists(program_path)) { program_path = std::filesystem::absolute(program_path).lexically_normal(); std::cout << "Path " << program_path; std::cout << " exists"; if (std::filesystem::is_regular_file(program_path)) { std::cout << " and is a regular file" << std::endl; } else { std::cout << " but is not a regular file" << std::endl; } } else { std::cout << "Path " << program_path; std::cout << " doesn't exists" << std::endl; } }1-10 #pragma once #include #include #include namespace core{ namespace random{ class RandomInterface{ private: static RandomWrapper good; static RandomWrapper fast; RandomInterface(); public: static RandomInterface& get(){ static RandomInterface *instance = new RandomInterface(); return *instance; } const bool seedFromDevice(); void fastReSeed(const unsigned long seedVal); void goodReSeed(const unsigned long seedVal); const unsigned long fastRand(); const unsigned long goodRand(); const bool fastBool(); const bool goodBool(); RandomWrapper getNonStaticFastGenerator() const; RandomWrapper getNonStaticGoodGenerator() const; const std::vector fastRandN(const size_t n); const std::vector goodRandN(const size_t n); const signed long fastRandRange(const int min, const int max); const signed long goodRandRange(const int min, const int max); const std::vector fastRangeRangeN(const size_t n, const int min, const int max); const std::vector goodRangeRangeN(const size_t n, const int min, const int max); const signed long fastBellCurve(const int min = 0, const int max = 100); const signed long goodBellCurve(const int min = 0, const int max = 100); const std::vector fastBellCurveN(const size_t n, const int min = 0, const int max = 100); const std::vector goodBellCurveN(const size_t n, const int min = 0, const int max = 100); }; } // namespace random } // namespace core #include "utildebug.h" #include "util.h" #ifdef __linux__ #include #include #endif #include void dump_backtrace_stderr() { #ifdef __linux__ void* trace[100]; int nptrs = backtrace(trace, 100); fprintf(stderr, "\nBacktrace dump:\n"); backtrace_symbols_fd(trace, nptrs, STDERR_FILENO); std::cerr << std::endl << "To translate addresses to symbols, start GDB (gdb ./bitcoind)\n" << "Then call 'info symbol
'\n" << "Example stacktrace:\n" << "\t./bitcoind(+0x39ae5)[0x56140c19dae5]\n" << "Example GDB output:\n" << "\t(gdb) info symbol +0x39ae5\n" << "\tAppInit(int, char**) + 2568 in section .text\n" << std::endl; #else std::cerr << "Backtrace not available on this platform" << std::endl; #endif } void throw_bad_state(const char* why, const char* func, const char* file, int line) { std::stringstream err; err << "Bad state - expectation '" << why << "' failed at " << func << " in " << file << ":" << line; LogPrintf("ERROR: %s", err.str()); throw bad_state_error(err.str()); } rhencke/engine // // Copyright 2016 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SyncNULL.cpp: // Implements the class methods for SyncNULL. // #include "libANGLE/renderer/null/SyncNULL.h" #include "common/debug.h" namespace rx { SyncNULL::SyncNULL() : SyncImpl() {} SyncNULL::~SyncNULL() {} angle::Result SyncNULL::set(const gl::Context *context, GLenum condition, GLbitfield flags) { return angle::Result::Continue; } angle::Result SyncNULL::clientWait(const gl::Context *context, GLbitfield flags, GLuint64 timeout, GLenum *outResult) { *outResult = GL_ALREADY_SIGNALED; return angle::Result::Continue; } angle::Result SyncNULL::serverWait(const gl::Context *context, GLbitfield flags, GLuint64 timeout) { return angle::Result::Continue; } angle::Result SyncNULL::getStatus(const gl::Context *context, GLint *outResult) { *outResult = GL_SIGNALED; return angle::Result::Continue; } } // namespace rx 0 //============================================================================================================= /** * @file dacqserver.cpp * @author <>; * <>; * @version 1.0 * @date July, 2012 * * @section LICENSE * * Copyright (C) 2012, and . All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief implementation of the DacqServer Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "dacqserver.h" #include "neuromag.h" #include "collectorsocket.h" #include "shmemsocket.h" #include #include //************************************************************************************************************* //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include #include #include #include //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace NeuromagPlugin; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= DacqServer::DacqServer(Neuromag* p_pNeuromag, QObject * parent) : QThread(parent) , m_pCollectorSock(NULL) , m_pShmemSock(NULL) , m_bIsRunning(false) , m_bMeasInfoRequest(true) , m_bMeasRequest(true) , m_bMeasStopRequest(false) , m_bSetBuffersizeRequest(false) , m_pNeuromag(p_pNeuromag) { } //************************************************************************************************************* DacqServer::~DacqServer() { if(m_pCollectorSock) delete m_pCollectorSock; if(m_pShmemSock) delete m_pShmemSock; } //************************************************************************************************************* bool DacqServer::getMeasInfo(FiffInfo& p_fiffInfo) { // if (p_pFiffInfo) // delete p_pFiffInfo; p_fiffInfo.clear(); #ifdef DACQ_AUTOSTART m_pCollectorSock->server_stop(); m_pCollectorSock->server_start(); #endif FiffTag::SPtr t_pTag; bool t_bReadHeader = true; while(t_bReadHeader) { if (m_pShmemSock->receive_tag(t_pTag) == -1) break; // // Projector Item // if( t_pTag->kind == FIFF_BLOCK_START && *(t_pTag->toInt()) == FIFFB_PROJ_ITEM ) { printf("\tProjector... "); int nvec = -1; int nchan = -1; QStringList defaultList; QStringList names; MatrixXd data; fiff_int_t kind; bool active; QString desc; // maybe, in some cases this has to be a struct. // while(!(t_pTag->kind == FIFF_BLOCK_END && *(t_pTag->toInt()) == FIFFB_PROJ_ITEM)) { m_pShmemSock->receive_tag(t_pTag); switch(t_pTag->kind) { case FIFF_NCHAN: nchan = *(t_pTag->toInt()); break; case FIFF_PROJ_ITEM_CH_NAME_LIST: names = FiffStream::split_name_list(t_pTag->toString()); break; case FIFF_NAME: desc = t_pTag->toString(); printf("%s... ", desc.toUtf8().constData()); break; case FIFF_PROJ_ITEM_KIND: kind = *(t_pTag->toInt()); break; // case FIFF_PROJ_ITEM_TIME: // qDebug() << "FIFF_PROJ_ITEM_TIME"; // break; case FIFF_PROJ_ITEM_NVEC: nvec == *(t_pTag->toInt()); break; case FIFF_MNE_PROJ_ITEM_ACTIVE: active == *(t_pTag->toInt()); break; case FIFF_PROJ_ITEM_VECTORS: data = t_pTag->toFloatMatrix().cast(); data.transposeInPlace(); break; } } FiffNamedMatrix t_fiffNamedMatrix(nvec, nchan, defaultList, names, data); FiffProj one(kind, active, desc, t_fiffNamedMatrix); p_fiffInfo.projs.append(one); printf("[done]\r\n"); } switch(t_pTag->kind) { case FIFF_BLOCK_START: if(*(t_pTag->toInt()) == FIFFB_MEAS_INFO) printf("Reading measurement info... \r\n"); break; case FIFFB_PROCESSED_DATA: printf("Measurement ID... "); p_fiffInfo.meas_id = t_pTag->toFiffID(); printf("[done]\r\n"); break; case FIFF_MEAS_DATE: printf("\tMeasurement date... "); p_fiffInfo.meas_date[0] = t_pTag->toInt()[0]; p_fiffInfo.meas_date[1] = t_pTag->toInt()[1]; printf("[done]\r\n"); break; case FIFF_NCHAN: printf("\tNumber of channels... "); p_fiffInfo.nchan = *(t_pTag->toInt()); printf("%d... [done]\r\n", p_fiffInfo.nchan); break; case FIFF_SFREQ: printf("\tSampling frequency... "); p_fiffInfo.sfreq = *(t_pTag->toFloat()); printf("%f... [done]\r\n", p_fiffInfo.sfreq); break; case FIFF_LOWPASS: printf("\tLowpass frequency... "); p_fiffInfo.lowpass = *(t_pTag->toFloat()); printf("%f Hz... [done]\r\n", p_fiffInfo.lowpass); break; case FIFF_HIGHPASS: printf("\tHighpass frequency... "); p_fiffInfo.highpass = *(t_pTag->toFloat()); printf("%f Hz... [done]\r\n", p_fiffInfo.highpass); break; // case FIFF_LINE_FREQ: // qDebug() << "FIFF_LINE_FREQ " << *(t_pTag->toFloat()); // break; // case FIFF_UNIT_AM: // qDebug() << "FIFF_UNIT_AM " << *(t_pTag->toInt()); // break; case FIFF_CH_INFO: // qDebug() << "Processed FIFF_CH_INFO"; p_fiffInfo.chs.append( t_pTag->toChInfo() ); break; case FIFF_BLOCK_END: switch(*(t_pTag->toInt())) { case FIFFB_MEAS_INFO: t_bReadHeader = false; break; } break; // case FIFF_HPI_NCOIL: // qDebug() << "FIFF_HPI_NCOIL " << *(t_pTag->toInt()); // break; // case FIFFV_RESP_CH: // qDebug() << "FIFFV_RESP_CH " << t_pTag->toString(); // break; // default: // qDebug() << "Unknown Tag Kind: " << t_pTag->kind << " Type: " << t_pTag->type << "Size: " << t_pTag->size(); } } printf("\tProcessing channels... "); for(qint32 i = 0; i < p_fiffInfo.chs.size(); ++i) p_fiffInfo.ch_names.append(p_fiffInfo.chs[i].ch_name); printf("[done]\r\n %d", p_fiffInfo.chs.size()); printf("measurement info read.\r\n"); #ifdef DACQ_AUTOSTART if (!m_bMeasRequest) m_pCollectorSock->server_stop(); #endif //t_bReadHeader is still true --> that means a break occured if (t_bReadHeader) return false; return true; } //************************************************************************************************************* //============================================================================================================= // run //============================================================================================================= void DacqServer::run() { m_bIsRunning = true; connect(this, &DacqServer::measInfoAvailable, m_pNeuromag, &Neuromag::releaseMeasInfo); if(m_pCollectorSock) delete m_pCollectorSock; m_pCollectorSock = new CollectorSocket(); // // Make sure the buffer size is at least as big as the minimal buffer size // if(m_pNeuromag->m_uiBufferSampleSize < MIN_BUFLEN) m_pNeuromag->m_uiBufferSampleSize = MIN_BUFLEN; int t_iOriginalMaxBuflen = 1500;// set the standard size as long as we can't get it without setting it // this doesn't work without reseting it // t_iOriginalMaxBuflen = collector_getMaxBuflen(); // if (t_iOriginalMaxBuflen < 1) { // printf("Could not query the current Neuromag buffer length\r\n");//dacq_log("Could not query the current Neuromag buffer length\n"); // collector_close(); // return; // } Q_UNUSED(t_iOriginalMaxBuflen); if (m_pNeuromag->m_uiBufferSampleSize < MIN_BUFLEN) { fprintf(stderr, "%ui: Too small Neuromag buffer length requested, should be at least %d\n", m_pNeuromag->m_uiBufferSampleSize, MIN_BUFLEN); return; } else { /* Connect to the Elekta Neuromag acquisition control server, change the buffer length and exit*/ if (!m_pCollectorSock->open()) { printf("Cannot change the Neuromag buffer length: Could not open collector connection\n");//dacq_log("Cannot change the Neuromag buffer length: Could not open collector connection\n"); return; } printf("Changing the Neuromag buffer length to %d... ", m_pNeuromag->m_uiBufferSampleSize);//dacq_log("Changing the Neuromag buffer length to %d\n", newMaxBuflen); if (m_pCollectorSock->setMaxBuflen(m_pNeuromag->m_uiBufferSampleSize)) { printf("Setting a new Neuromag buffer length failed\r\n");//dacq_log("Setting a new Neuromag buffer length failed\n"); m_pCollectorSock->close(); return; } printf("[done]\r\n"); } //// if(m_pShmemSock) delete m_pShmemSock; m_pShmemSock = new ShmemSocket(); m_pShmemSock->set_data_filter (NULL, 0); /* Connect to the Elekta Neuromag shared memory system */ if (!m_pShmemSock->connect_client()) { printf("Could not connect!\r\n");//dacq_log("Could not connect!\n"); return;//(2); } /* Mainloop */ // printf("Will scale up MEG mags by %g, grads by %g and EEG data by %g\n", // meg_mag_multiplier, meg_grad_multiplier, eeg_multiplier); printf("Waiting for the measurement to start...\n"); // // Receive shmem tags // qint32 nchan = -1; float sfreq = -1.0f; FiffTag::SPtr t_pTag; qint32 t_nSamples = 0; qint32 t_nSamplesNew = 0; // // Requesting new header info: read it every time a measurement starts or a measurement info is requested // if(m_pNeuromag->m_info.isEmpty() || m_bMeasInfoRequest) { m_pNeuromag->mutex.lock(); if(getMeasInfo(m_pNeuromag->m_info)) { if(m_bMeasInfoRequest) { emit measInfoAvailable(); m_bMeasInfoRequest = false; } // Reset Buffer Size if(m_pNeuromag->m_pRawMatrixBuffer) delete m_pNeuromag->m_pRawMatrixBuffer; m_pNeuromag->m_pRawMatrixBuffer = NULL; if(!m_pNeuromag->m_info.isEmpty()) m_pNeuromag->m_pRawMatrixBuffer = new RawMatrixBuffer(RAW_BUFFFER_SIZE, m_pNeuromag->m_info.nchan, m_pNeuromag->m_uiBufferSampleSize); } else m_bIsRunning = false; m_pNeuromag->mutex.unlock(); //Stop if only meas info is requested if(!m_pNeuromag->m_bIsRunning) this->wait(); } // // Control measurement start through Neuromag connector. ToDo: in Case Realtime measurement should be performed during normal acqusition process, change this!! // #ifdef DACQ_AUTOSTART if(m_bMeasRequest) m_pCollectorSock->server_start(); #endif while(m_bIsRunning) { if(m_bMeasRequest) { if (m_pShmemSock->receive_tag(t_pTag) == -1) break; } else { // break while loop when no measurement request break; } if (nchan < 0 && !m_pNeuromag->m_info.isEmpty()) { nchan = m_pNeuromag->m_info.nchan; sfreq = m_pNeuromag->m_info.sfreq; } switch(t_pTag->kind) { case FIFF_DATA_BUFFER: if(nchan > 0) { t_nSamplesNew = t_nSamples + m_pNeuromag->m_uiBufferSampleSize - 1; printf("Reading %d ... %d = %9.3f ... %9.3f secs...", t_nSamples, t_nSamplesNew, ((float)t_nSamples) / sfreq, ((float)t_nSamplesNew) / sfreq ); t_nSamples += m_pNeuromag->m_uiBufferSampleSize; float a; float meg_mag_multiplier = 1.0; float meg_grad_multiplier = 1.0; float eeg_multiplier = 1.0; MatrixXf* t_pMatrix = new MatrixXf(nchan, m_pNeuromag->m_uiBufferSampleSize); fiff_int_t *data32 = (fiff_int_t *)t_pTag->data(); for (qint32 ch = 0; ch < nchan; ch++) { switch(m_pNeuromag->m_info.chs[ch].kind) { case FIFFV_MAGN_CH: if (m_pNeuromag->m_info.chs[ch].unit == FIFF_UNIT_T_M) a = meg_grad_multiplier; else a = meg_mag_multiplier; break; case FIFFV_EL_CH: a = eeg_multiplier; break; default: a = 1.0; } for (qint32 ns = 0; ns < m_pNeuromag->m_uiBufferSampleSize; ns++) (*t_pMatrix)(ch,ns) = a * m_pNeuromag->m_info.chs[ch].cal * m_pNeuromag->m_info.chs[ch].range * data32[nchan*ns+ch]; } m_pNeuromag->m_pRawMatrixBuffer->push(t_pMatrix); delete t_pMatrix; /* MatrixXf* t_pMatrix = new MatrixXf( (Map( (int*) t_pTag->data(), nchan, m_pNeuromag->m_uiBufferSampleSize)).cast()); // std::cout << "Matrix Xf " << t_pMatrix->block(0,0,1,4); m_pNeuromag->m_pRawMatrixBuffer->push(t_pMatrix); delete t_pMatrix; */ printf(" [done]\r\n"); } break; case FIFF_BLOCK_START: // qDebug() << "FIFF_BLOCK_START"; switch(*(t_pTag->toInt())) { case FIFFB_RAW_DATA: printf("Processing raw data...\r\n"); break; // default: // qDebug() << " Unknown " << *(t_pTag->toInt()); } break; case FIFF_ERROR_MESSAGE: printf("Error: %s\r\n", t_pTag->data()); m_bIsRunning = false; break; case FIFF_CLOSE_FILE: printf("Measurement stopped.\r\n"); break; default: printf("Unknow tag; Kind: %d, Type: %d, Size: %d \r\n", t_pTag->kind, t_pTag->type, t_pTag->size()); } } // // Stop and clean up // #ifdef DACQ_AUTOSTART m_pCollectorSock->server_stop(); #endif m_pShmemSock->disconnect_client(); m_pCollectorSock->close(); delete m_pCollectorSock; m_pCollectorSock = NULL; printf("\r\n"); } 2Dkun/My-Quest-LogMy Project Log/Classes/Native/Bulk_UnityEngine_2.cpp #include "il2cpp-config.h" #ifndef _MSC_VER # include #else # include #endif #include #include #include #include #include #include #include #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "object-internals.h" // System.InvalidCastException struct InvalidCastException_t865352475; // System.String struct String_t; // UnityEngine.PreferBinarySerialization struct PreferBinarySerialization_t1584085608; // System.Attribute struct Attribute_t739646798; // UnityEngine.PropertyAttribute struct PropertyAttribute_t2314996045; // System.Object[] struct ObjectU5BU5D_t3885370135; // UnityEngine.RangeAttribute struct RangeAttribute_t90224693; // UnityEngine.Collider struct Collider_t3058509131; // UnityEngine.Rigidbody struct Rigidbody_t2809865642; // UnityEngine.Object struct Object_t1332387349; // UnityEngine.Transform struct Transform_t2468616896; // UnityEngine.Component struct Component_t590567089; // UnityEngine.Collider2D struct Collider2D_t2180151806; // UnityEngine.RectOffset struct RectOffset_t3582970358; // UnityEngine.RectTransform struct RectTransform_t3700156813; // UnityEngine.RectTransform/ReapplyDrivenProperties struct ReapplyDrivenProperties_t2885473943; // System.Delegate struct Delegate_t2669736448; // UnityEngine.Vector3[] struct Vector3U5BU5D_t2251457841; // System.IAsyncResult struct IAsyncResult_t2851905845; // System.AsyncCallback struct AsyncCallback_t2537533359; // UnityEngine.Camera struct Camera_t110840138; // UnityEngine.Canvas struct Canvas_t2948613984; // UnityEngine.RemoteSettings/UpdatedEventHandler struct UpdatedEventHandler_t860849547; // UnityEngine.Renderer struct Renderer_t3838459598; // UnityEngine.Material struct Material_t3939796247; // UnityEngine.RenderTexture struct RenderTexture_t3726137678; // UnityEngine.RequireComponent struct RequireComponent_t2926973319; // System.Type struct Type_t; // UnityEngine.ResourceRequest struct ResourceRequest_t718765924; // UnityEngine.AsyncOperation struct AsyncOperation_t1152358279; // UnityEngine.Object[] struct ObjectU5BU5D_t348161528; // UnityEngine.RPC struct RPC_t80633788; // UnityEngine.Events.UnityAction`2 struct UnityAction_2_t1303706228; // UnityEngine.Events.UnityAction`1 struct UnityAction_1_t2300191644; // UnityEngine.Events.UnityAction`2 struct UnityAction_2_t1173199225; // UnityEngine.ScriptableObject struct ScriptableObject_t505592390; // UnityEngine.Scripting.APIUpdating.MovedFromAttribute struct MovedFromAttribute_t4199174457; // UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute struct GeneratedByOldBindingsGeneratorAttribute_t1965560690; // UnityEngine.Scripting.RequiredByNativeCodeAttribute struct RequiredByNativeCodeAttribute_t2549902335; // UnityEngine.Scripting.UsedByNativeCodeAttribute struct UsedByNativeCodeAttribute_t542057536; // UnityEngine.ScrollViewState struct ScrollViewState_t3481701544; // UnityEngine.SelectionBaseAttribute struct SelectionBaseAttribute_t3732655813; // UnityEngine.Camera[] struct CameraU5BU5D_t2507966031; // UnityEngine.GUILayer struct GUILayer_t1356563649; // UnityEngine.GUIElement struct GUIElement_t316128140; // UnityEngine.GameObject struct GameObject_t2923855588; // UnityEngine.Serialization.FormerlySerializedAsAttribute struct FormerlySerializedAsAttribute_t2004262931; // UnityEngine.SerializeField struct SerializeField_t2526071389; // UnityEngine.SerializePrivateVariables struct SerializePrivateVariables_t3415835997; // System.Collections.IEnumerator struct IEnumerator_t2002634998; // System.ArgumentException struct ArgumentException_t270170821; // UnityEngine.Shader struct Shader_t610183752; // UnityEngine.SharedBetweenAnimatorsAttribute struct SharedBetweenAnimatorsAttribute_t1365952581; // UnityEngine.SliderState struct SliderState_t1582857496; // UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform struct GameCenterPlatform_t1308980868; // UnityEngine.SocialPlatforms.Impl.AchievementDescription struct AchievementDescription_t991053089; // UnityEngine.Texture2D struct Texture2D_t1384570725; // System.Action`1 struct Action_1_t4096934434; // UnityEngine.SocialPlatforms.IAchievementDescription[] struct IAchievementDescriptionU5BU5D_t3064410227; // System.Action`1 struct Action_1_t3641405393; // UnityEngine.SocialPlatforms.IAchievementDescription struct IAchievementDescription_t725989110; // System.Action`2 struct Action_2_t3787810730; // System.Action`2 struct Action_2_t2127932065; // UnityEngine.SocialPlatforms.Impl.UserProfile[] struct UserProfileU5BU5D_t3377267652; // UnityEngine.SocialPlatforms.Impl.UserProfile struct UserProfile_t2942407481; // System.Action`1 struct Action_1_t2674754663; // UnityEngine.SocialPlatforms.Impl.LocalUser struct LocalUser_t2155741069; // UnityEngine.SocialPlatforms.IUserProfile[] struct IUserProfileU5BU5D_t3867243727; // UnityEngine.SocialPlatforms.IUserProfile struct IUserProfile_t1540824266; // System.Action`1 struct Action_1_t2897662423; // UnityEngine.SocialPlatforms.GameCenter.GcAchievementData[] struct GcAchievementDataU5BU5D_t1247845579; // UnityEngine.SocialPlatforms.Impl.Achievement struct Achievement_t2468443294; // UnityEngine.SocialPlatforms.IAchievement[] struct IAchievementU5BU5D_t1865138216; // UnityEngine.SocialPlatforms.IAchievement struct IAchievement_t78785445; // System.Action`1 struct Action_1_t1552255288; // UnityEngine.SocialPlatforms.GameCenter.GcScoreData[] struct GcScoreDataU5BU5D_t859946003; // UnityEngine.SocialPlatforms.Impl.Score struct Score_t671349143; // UnityEngine.SocialPlatforms.IScore[] struct IScoreU5BU5D_t519731081; // UnityEngine.SocialPlatforms.IScore struct IScore_t3241969944; // UnityEngine.SocialPlatforms.ILocalUser struct ILocalUser_t1088443743; // UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0 struct U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699; // UnityEngine.SocialPlatforms.ILeaderboard struct ILeaderboard_t2637439402; // UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard struct GcLeaderboard_t1761920286; // UnityEngine.SocialPlatforms.Impl.Leaderboard struct Leaderboard_t3315266811; // System.Collections.Generic.List`1 struct List_1_t984806126; // System.Collections.Generic.List`1 struct List_1_t1831767026; // System.String[] struct StringU5BU5D_t3608572874; // System.Action`1 struct Action_1_t604800638; // UnityEngine.SpaceAttribute struct SpaceAttribute_t1419322499; // UnityEngine.SphereCollider struct SphereCollider_t2896221692; // UnityEngine.Sprite struct Sprite_t3419621700; // UnityEngine.SpriteRenderer struct SpriteRenderer_t1459332486; // System.Diagnostics.StackTrace struct StackTrace_t798888381; // System.Text.StringBuilder struct StringBuilder_t313129557; // System.Exception struct Exception_t3285241636; // System.Char[] struct CharU5BU5D_t1522321484; // System.Reflection.ParameterInfo struct ParameterInfo_t1917333745; // UnityEngine.StateMachineBehaviour struct StateMachineBehaviour_t2091767483; // UnityEngine.Animator struct Animator_t3669487027; // UnityEngine.TextAreaAttribute struct TextAreaAttribute_t2984524453; // UnityEngine.TextAsset struct TextAsset_t2643108631; // UnityEngine.TextEditor struct TextEditor_t876577383; // UnityEngine.GUIStyle struct GUIStyle_t4033995491; // UnityEngine.GUIContent struct GUIContent_t3165057865; // UnityEngine.TextGenerationSettings struct TextGenerationSettings_t2955391441; // UnityEngine.TextGenerator struct TextGenerator_t1838611233; // System.Collections.Generic.List`1 struct List_1_t2359577098; // System.Collections.Generic.List`1 struct List_1_t369525373; // System.Collections.Generic.List`1 struct List_1_t1470875743; // UnityEngine.Font struct Font_t1580130639; // System.Collections.Generic.IList`1 struct IList_1_t2868756015; // System.Collections.Generic.IList`1 struct IList_1_t878704290; // System.Collections.Generic.IList`1 struct IList_1_t1980054660; // UnityEngine.TextMesh struct TextMesh_t2729623642; // UnityEngine.Texture struct Texture_t2354860603; // UnityEngine.ThreadAndSerializationSafeAttribute struct ThreadAndSerializationSafeAttribute_t669741721; // System.Diagnostics.StackFrame[] struct StackFrameU5BU5D_t688495400; // System.IntPtr[] struct IntPtrU5BU5D_t3630972082; // System.Collections.IDictionary struct IDictionary_t2631696802; // UnityEngine.SocialPlatforms.Impl.AchievementDescription[] struct AchievementDescriptionU5BU5D_t916063548; // System.Globalization.CultureInfo struct CultureInfo_t703400772; // System.Globalization.NumberFormatInfo struct NumberFormatInfo_t3630505389; // System.Globalization.DateTimeFormatInfo struct DateTimeFormatInfo_t825146048; // System.Globalization.TextInfo struct TextInfo_t1445196420; // System.Globalization.CompareInfo struct CompareInfo_t3595197132; // System.Globalization.Calendar[] struct CalendarU5BU5D_t3771720741; // System.Globalization.Calendar struct Calendar_t1732656044; // System.Byte[] struct ByteU5BU5D_t1185793865; // System.Collections.Hashtable struct Hashtable_t3901241470; // System.Collections.Generic.Dictionary`2 struct Dictionary_2_t543570752; // System.Int32 struct Int32_t2185247404; // System.Void struct Void_t1901624353; // UnityEngine.SendMouseEvents/HitInfo[] struct HitInfoU5BU5D_t4176695186; // UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard[] struct GcLeaderboardU5BU5D_t2736626859; // UnityEngine.UICharInfo[] struct UICharInfoU5BU5D_t4195871232; // UnityEngine.UIVertex[] struct UIVertexU5BU5D_t2534070687; // UnityEngine.UILineInfo[] struct UILineInfoU5BU5D_t2942809686; // System.Reflection.MethodBase struct MethodBase_t710954372; // System.Byte struct Byte_t3448579160; // System.Double struct Double_t2492335957; // System.UInt16 struct UInt16_t3344081709; // System.Boolean[] struct BooleanU5BU5D_t822121321; // System.Reflection.MethodInfo struct MethodInfo_t; // System.DelegateData struct DelegateData_t3352901259; // System.Action`1 struct Action_1_t2612654846; // UnityEngine.Font/FontTextureRebuildCallback struct FontTextureRebuildCallback_t156596975; // System.Reflection.MemberInfo struct MemberInfo_t; // System.Reflection.Emit.UnmanagedMarshal struct UnmanagedMarshal_t600271334; // UnityEngine.TouchScreenKeyboard struct TouchScreenKeyboard_t1595360201; // System.Type[] struct TypeU5BU5D_t1493067982; // System.Reflection.MemberFilter struct MemberFilter_t3326885857; // System.Int32[] struct Int32U5BU5D_t772475173; // UnityEngine.GUIStyleState struct GUIStyleState_t2009209206; // UnityEngine.Camera/CameraCallback struct CameraCallback_t2976156859; // UnityEngine.Canvas/WillRenderCanvases struct WillRenderCanvases_t1008191882; extern RuntimeClass* InvalidCastException_t865352475_il2cpp_TypeInfo_var; extern const RuntimeMethod* PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539_RuntimeMethod_var; extern Il2CppCodeGenString* _stringLiteral3498337307; extern const uint32_t ScriptPlayableOutput__ctor_m1887120702_MetadataUsageId; extern RuntimeClass* Vector3_t67624592_il2cpp_TypeInfo_var; extern RuntimeClass* Quaternion_t4184531171_il2cpp_TypeInfo_var; extern const uint32_t Quaternion_LookRotation_m474565940_MetadataUsageId; extern const uint32_t Quaternion_Lerp_m2375651230_MetadataUsageId; extern const uint32_t Quaternion_Inverse_m390778767_MetadataUsageId; extern const uint32_t Quaternion_get_eulerAngles_m2921540577_MetadataUsageId; extern const uint32_t Quaternion_Euler_m2408383635_MetadataUsageId; extern const uint32_t Quaternion_Euler_m725079561_MetadataUsageId; extern const uint32_t Quaternion_Internal_ToEulerRad_m298111895_MetadataUsageId; extern const uint32_t Quaternion_Internal_FromEulerRad_m2729453363_MetadataUsageId; extern const uint32_t Quaternion_get_identity_m647656586_MetadataUsageId; extern const uint32_t Quaternion_op_Equality_m3282458924_MetadataUsageId; extern const uint32_t Quaternion_op_Inequality_m1705400273_MetadataUsageId; extern const uint32_t Quaternion_Equals_m3924578426_MetadataUsageId; extern RuntimeClass* ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var; extern RuntimeClass* Single_t3320337292_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1867442433; extern const uint32_t Quaternion_ToString_m4223730163_MetadataUsageId; extern const uint32_t Quaternion__cctor_m1783079664_MetadataUsageId; extern const uint32_t Ray_GetPoint_m1809995955_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral2014213472; extern const uint32_t Ray_ToString_m4189095882_MetadataUsageId; extern RuntimeClass* Object_t1332387349_il2cpp_TypeInfo_var; extern const uint32_t RaycastHit_get_rigidbody_m507930372_MetadataUsageId; extern const uint32_t RaycastHit_get_transform_m3831275417_MetadataUsageId; extern RuntimeClass* Rect_t3345319094_il2cpp_TypeInfo_var; extern const uint32_t Rect_Equals_m2118345215_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral2888673510; extern const uint32_t Rect_ToString_m3090827388_MetadataUsageId; extern RuntimeClass* Il2CppComObject_il2cpp_TypeInfo_var; extern const uint32_t RectOffset_t3582970358_pinvoke_FromNativeMethodDefinition_MetadataUsageId; extern const uint32_t RectOffset_t3582970358_com_FromNativeMethodDefinition_MetadataUsageId; extern RuntimeClass* Int32_t2185247404_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral389894490; extern const uint32_t RectOffset_ToString_m1410907684_MetadataUsageId; extern RuntimeClass* RectTransform_t3700156813_il2cpp_TypeInfo_var; extern RuntimeClass* ReapplyDrivenProperties_t2885473943_il2cpp_TypeInfo_var; extern const uint32_t RectTransform_add_reapplyDrivenProperties_m1640178877_MetadataUsageId; extern const uint32_t RectTransform_remove_reapplyDrivenProperties_m2994591780_MetadataUsageId; extern const uint32_t RectTransform_SendReapplyDrivenProperties_m815986292_MetadataUsageId; extern RuntimeClass* Debug_t2324836986_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1042552891; extern const uint32_t RectTransform_GetLocalCorners_m702431553_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral2700877699; extern const uint32_t RectTransform_GetWorldCorners_m1981831296_MetadataUsageId; extern RuntimeClass* Vector2_t3854014517_il2cpp_TypeInfo_var; extern const uint32_t RectTransform_set_offsetMin_m1964412094_MetadataUsageId; extern const uint32_t RectTransform_set_offsetMax_m3548632212_MetadataUsageId; extern const uint32_t RectTransform_GetParentSize_m101662412_MetadataUsageId; extern RuntimeClass* RectTransformUtility_t1869061041_il2cpp_TypeInfo_var; extern const uint32_t RectTransformUtility_ScreenPointToWorldPointInRectangle_m949791734_MetadataUsageId; extern const uint32_t RectTransformUtility_ScreenPointToLocalPointInRectangle_m2140708364_MetadataUsageId; extern const uint32_t RectTransformUtility_ScreenPointToRay_m768706565_MetadataUsageId; extern const uint32_t RectTransformUtility_FlipLayoutOnAxis_m932564554_MetadataUsageId; extern const uint32_t RectTransformUtility_FlipLayoutAxes_m4222183317_MetadataUsageId; extern const uint32_t RectTransformUtility_RectangleContainsScreenPoint_m3537473567_MetadataUsageId; extern const uint32_t RectTransformUtility_PixelAdjustPoint_m216690555_MetadataUsageId; extern const uint32_t RectTransformUtility_PixelAdjustRect_m3656622349_MetadataUsageId; extern RuntimeClass* Vector3U5BU5D_t2251457841_il2cpp_TypeInfo_var; extern const uint32_t RectTransformUtility__cctor_m698144985_MetadataUsageId; extern RuntimeClass* RemoteSettings_t1084722070_il2cpp_TypeInfo_var; extern const uint32_t RemoteSettings_CallOnUpdate_m1065707692_MetadataUsageId; extern const RuntimeType* Object_t1332387349_0_0_0_var; extern RuntimeClass* Type_t_il2cpp_TypeInfo_var; extern const uint32_t Resources_Load_m1443494906_MetadataUsageId; extern RuntimeClass* Scene_t886992912_il2cpp_TypeInfo_var; extern const uint32_t Scene_Equals_m2736381267_MetadataUsageId; extern RuntimeClass* SceneManager_t2619984172_il2cpp_TypeInfo_var; extern const RuntimeMethod* UnityAction_2_Invoke_m142841862_RuntimeMethod_var; extern const uint32_t SceneManager_Internal_SceneLoaded_m3767349395_MetadataUsageId; extern const RuntimeMethod* UnityAction_1_Invoke_m3288951857_RuntimeMethod_var; extern const uint32_t SceneManager_Internal_SceneUnloaded_m3153820635_MetadataUsageId; extern const RuntimeMethod* UnityAction_2_Invoke_m1774221970_RuntimeMethod_var; extern const uint32_t SceneManager_Internal_ActiveSceneChanged_m1881093419_MetadataUsageId; extern const uint32_t ScriptableObject__ctor_m3935827375_MetadataUsageId; extern RuntimeClass* SendMouseEvents_t955851818_il2cpp_TypeInfo_var; extern const uint32_t SendMouseEvents_SetMouseMoved_m2459912751_MetadataUsageId; extern RuntimeClass* Input_t560450644_il2cpp_TypeInfo_var; extern RuntimeClass* CameraU5BU5D_t2507966031_il2cpp_TypeInfo_var; extern RuntimeClass* HitInfo_t2268685571_il2cpp_TypeInfo_var; extern RuntimeClass* Mathf_t2756327229_il2cpp_TypeInfo_var; extern const RuntimeMethod* Component_GetComponent_TisGUILayer_t1356563649_m427859813_RuntimeMethod_var; extern const uint32_t SendMouseEvents_DoSendMouseEvents_m384073153_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral2558053113; extern Il2CppCodeGenString* _stringLiteral2906149351; extern Il2CppCodeGenString* _stringLiteral3147111904; extern Il2CppCodeGenString* _stringLiteral417825151; extern Il2CppCodeGenString* _stringLiteral3932688994; extern Il2CppCodeGenString* _stringLiteral3422424824; extern Il2CppCodeGenString* _stringLiteral3662012992; extern const uint32_t SendMouseEvents_SendEvents_m1146913201_MetadataUsageId; extern RuntimeClass* HitInfoU5BU5D_t4176695186_il2cpp_TypeInfo_var; extern const uint32_t SendMouseEvents__cctor_m4110553720_MetadataUsageId; extern const uint32_t HitInfo_op_Implicit_m3724497342_MetadataUsageId; extern const uint32_t HitInfo_Compare_m3962420595_MetadataUsageId; extern RuntimeClass* IntPtr_t_il2cpp_TypeInfo_var; extern RuntimeClass* ArgumentException_t270170821_il2cpp_TypeInfo_var; extern RuntimeClass* IEnumerator_t2002634998_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral866912693; extern Il2CppCodeGenString* _stringLiteral1457260809; extern const uint32_t SetupCoroutine_InvokeMoveNext_m3883473951_MetadataUsageId; extern const uint32_t SetupCoroutine_InvokeMember_m817333955_MetadataUsageId; extern RuntimeClass* GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var; extern RuntimeClass* AchievementDescriptionU5BU5D_t916063548_il2cpp_TypeInfo_var; extern const uint32_t GameCenterPlatform_ClearAchievementDescriptions_m3061750857_MetadataUsageId; extern const uint32_t GameCenterPlatform_SetAchievementDescription_m1606698321_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral800264308; extern const uint32_t GameCenterPlatform_SetAchievementDescriptionImage_m1171918828_MetadataUsageId; extern const RuntimeMethod* Action_1_Invoke_m534614836_RuntimeMethod_var; extern Il2CppCodeGenString* _stringLiteral1515164757; extern const uint32_t GameCenterPlatform_TriggerAchievementDescriptionCallback_m512691905_MetadataUsageId; extern const RuntimeMethod* Action_2_Invoke_m641279976_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_AuthenticateCallbackWrapper_m2263980947_MetadataUsageId; extern const uint32_t GameCenterPlatform_ClearFriends_m613985707_MetadataUsageId; extern const uint32_t GameCenterPlatform_SetFriends_m133258073_MetadataUsageId; extern const uint32_t GameCenterPlatform_SetFriendImage_m3088999821_MetadataUsageId; extern const RuntimeMethod* Action_1_Invoke_m3062505204_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_TriggerFriendsCallbackWrapper_m3241103450_MetadataUsageId; extern RuntimeClass* AchievementU5BU5D_t867614507_il2cpp_TypeInfo_var; extern const RuntimeMethod* Action_1_Invoke_m4016068893_RuntimeMethod_var; extern Il2CppCodeGenString* _stringLiteral1000174466; extern const uint32_t GameCenterPlatform_AchievementCallbackWrapper_m3148814100_MetadataUsageId; extern const uint32_t GameCenterPlatform_ProgressCallbackWrapper_m1646544226_MetadataUsageId; extern const uint32_t GameCenterPlatform_ScoreCallbackWrapper_m2822221228_MetadataUsageId; extern RuntimeClass* ScoreU5BU5D_t13505070_il2cpp_TypeInfo_var; extern const RuntimeMethod* Action_1_Invoke_m2262809151_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_ScoreLoaderCallbackWrapper_m2682991831_MetadataUsageId; extern const uint32_t GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_LoadFriends_m328693879_MetadataUsageId; extern RuntimeClass* U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699_il2cpp_TypeInfo_var; extern RuntimeClass* Action_2_t3787810730_il2cpp_TypeInfo_var; extern RuntimeClass* ISocialPlatform_t2229370286_il2cpp_TypeInfo_var; extern const RuntimeMethod* U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_U3CU3Em__0_m2206341105_RuntimeMethod_var; extern const RuntimeMethod* Action_2__ctor_m3476159000_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1866259755_MetadataUsageId; extern const uint32_t GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1627378436_MetadataUsageId; extern RuntimeClass* LocalUser_t2155741069_il2cpp_TypeInfo_var; extern RuntimeClass* String_t_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1666647875; extern const uint32_t GameCenterPlatform_get_localUser_m3939861769_MetadataUsageId; extern const uint32_t GameCenterPlatform_PopulateLocalUser_m2400765263_MetadataUsageId; extern const uint32_t GameCenterPlatform_LoadAchievementDescriptions_m69720184_MetadataUsageId; extern const uint32_t GameCenterPlatform_ReportProgress_m3320181035_MetadataUsageId; extern const uint32_t GameCenterPlatform_LoadAchievements_m3779334338_MetadataUsageId; extern const uint32_t GameCenterPlatform_ReportScore_m2179106046_MetadataUsageId; extern const uint32_t GameCenterPlatform_LoadScores_m1004090045_MetadataUsageId; extern RuntimeClass* Leaderboard_t3315266811_il2cpp_TypeInfo_var; extern RuntimeClass* GcLeaderboard_t1761920286_il2cpp_TypeInfo_var; extern RuntimeClass* ILeaderboard_t2637439402_il2cpp_TypeInfo_var; extern const RuntimeMethod* List_1_Add_m4129652933_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_LoadScores_m3163647240_MetadataUsageId; extern const uint32_t GameCenterPlatform_LeaderboardCallbackWrapper_m2805116717_MetadataUsageId; extern const RuntimeMethod* List_1_GetEnumerator_m2419316156_RuntimeMethod_var; extern const RuntimeMethod* Enumerator_get_Current_m1279669161_RuntimeMethod_var; extern const RuntimeMethod* Enumerator_MoveNext_m1938626111_RuntimeMethod_var; extern const RuntimeMethod* Enumerator_Dispose_m3354874370_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_GetLoading_m2822327733_MetadataUsageId; extern RuntimeClass* ILocalUser_t1088443743_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral376256666; extern const uint32_t GameCenterPlatform_VerifyAuthentication_m2885445492_MetadataUsageId; extern const uint32_t GameCenterPlatform_ShowAchievementsUI_m4196866121_MetadataUsageId; extern const uint32_t GameCenterPlatform_ShowLeaderboardUI_m2825835288_MetadataUsageId; extern const uint32_t GameCenterPlatform_ClearUsers_m1938413165_MetadataUsageId; extern const uint32_t GameCenterPlatform_SetUser_m4141801796_MetadataUsageId; extern const uint32_t GameCenterPlatform_SetUserImage_m603143526_MetadataUsageId; extern const RuntimeMethod* Action_1_Invoke_m4080665887_RuntimeMethod_var; extern const uint32_t GameCenterPlatform_TriggerUsersCallbackWrapper_m3826154348_MetadataUsageId; extern RuntimeClass* UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var; extern const uint32_t GameCenterPlatform_LoadUsers_m136435526_MetadataUsageId; extern RuntimeClass* Texture2D_t1384570725_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral2464944457; extern Il2CppCodeGenString* _stringLiteral3953696827; extern const uint32_t GameCenterPlatform_SafeSetUserImage_m1317299489_MetadataUsageId; extern const uint32_t GameCenterPlatform_SafeClearArray_m307863322_MetadataUsageId; extern const uint32_t GameCenterPlatform_CreateLeaderboard_m2624606266_MetadataUsageId; extern RuntimeClass* Achievement_t2468443294_il2cpp_TypeInfo_var; extern const uint32_t GameCenterPlatform_CreateAchievement_m2311892317_MetadataUsageId; extern const uint32_t GameCenterPlatform_TriggerResetAchievementCallback_m456631406_MetadataUsageId; extern const uint32_t GameCenterPlatform_ResetAllAchievements_m2467887278_MetadataUsageId; extern const uint32_t GameCenterPlatform_ShowDefaultAchievementCompletionBanner_m1663095311_MetadataUsageId; extern const uint32_t GameCenterPlatform_ShowLeaderboardUI_m194791289_MetadataUsageId; extern RuntimeClass* List_1_t984806126_il2cpp_TypeInfo_var; extern const RuntimeMethod* List_1__ctor_m2431882546_RuntimeMethod_var; extern const uint32_t GameCenterPlatform__cctor_m2051892260_MetadataUsageId; extern const uint32_t U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_U3CU3Em__0_m2206341105_MetadataUsageId; extern const uint32_t GcAchievementData_ToAchievement_m3236287768_MetadataUsageId; extern RuntimeClass* AchievementDescription_t991053089_il2cpp_TypeInfo_var; extern const uint32_t GcAchievementDescriptionData_ToAchievementDescription_m3634773672_MetadataUsageId; extern const uint32_t GcLeaderboard_SetScores_m865112260_MetadataUsageId; extern RuntimeClass* Score_t671349143_il2cpp_TypeInfo_var; extern const uint32_t GcScoreData_ToScore_m3944565042_MetadataUsageId; extern RuntimeClass* UserProfile_t2942407481_il2cpp_TypeInfo_var; extern const uint32_t GcUserProfileData_ToUserProfile_m1615912729_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral3922184876; extern const uint32_t GcUserProfileData_AddToArray_m2882040847_MetadataUsageId; extern RuntimeClass* DateTime_t1205928702_il2cpp_TypeInfo_var; extern const uint32_t Achievement__ctor_m2199514267_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral3933156751; extern const uint32_t Achievement__ctor_m926077173_MetadataUsageId; extern RuntimeClass* Double_t2492335957_il2cpp_TypeInfo_var; extern RuntimeClass* Boolean_t1642230456_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral41011391; extern const uint32_t Achievement_ToString_m3086492804_MetadataUsageId; extern const uint32_t AchievementDescription_ToString_m1994678446_MetadataUsageId; extern RuntimeClass* StringU5BU5D_t3608572874_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1347337112; extern const uint32_t Leaderboard__ctor_m4039976758_MetadataUsageId; extern RuntimeClass* UInt32_t2977936117_il2cpp_TypeInfo_var; extern RuntimeClass* UserScope_t788576880_il2cpp_TypeInfo_var; extern RuntimeClass* TimeScope_t4070455592_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral3929450208; extern Il2CppCodeGenString* _stringLiteral1966556228; extern Il2CppCodeGenString* _stringLiteral2019217056; extern Il2CppCodeGenString* _stringLiteral1977467422; extern Il2CppCodeGenString* _stringLiteral3610780097; extern Il2CppCodeGenString* _stringLiteral3368200717; extern Il2CppCodeGenString* _stringLiteral1214608949; extern Il2CppCodeGenString* _stringLiteral3699080494; extern Il2CppCodeGenString* _stringLiteral3585726162; extern Il2CppCodeGenString* _stringLiteral2256614753; extern const uint32_t Leaderboard_ToString_m3275737436_MetadataUsageId; extern const uint32_t LocalUser__ctor_m928281921_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral4212843024; extern const uint32_t Score__ctor_m1838853748_MetadataUsageId; extern RuntimeClass* Int64_t3954580378_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral713862236; extern Il2CppCodeGenString* _stringLiteral2308931076; extern Il2CppCodeGenString* _stringLiteral2339561701; extern Il2CppCodeGenString* _stringLiteral753814197; extern Il2CppCodeGenString* _stringLiteral3809495824; extern const uint32_t Score_ToString_m1928919354_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral1411782842; extern const uint32_t UserProfile__ctor_m2050922054_MetadataUsageId; extern RuntimeClass* UserState_t2255672114_il2cpp_TypeInfo_var; extern const uint32_t UserProfile_ToString_m383837202_MetadataUsageId; extern RuntimeClass* StackTraceUtility_t1534026680_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral3572222939; extern Il2CppCodeGenString* _stringLiteral3343446928; extern const uint32_t StackTraceUtility_SetProjectFolder_m865009452_MetadataUsageId; extern RuntimeClass* StackTrace_t798888381_il2cpp_TypeInfo_var; extern const uint32_t StackTraceUtility_ExtractStackTrace_m2121576629_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral676969769; extern Il2CppCodeGenString* _stringLiteral155130972; extern Il2CppCodeGenString* _stringLiteral2311935814; extern Il2CppCodeGenString* _stringLiteral2930130424; extern Il2CppCodeGenString* _stringLiteral2902902247; extern Il2CppCodeGenString* _stringLiteral1845300824; extern const uint32_t StackTraceUtility_IsSystemStacktraceType_m70277135_MetadataUsageId; extern RuntimeClass* Exception_t3285241636_il2cpp_TypeInfo_var; extern RuntimeClass* StringBuilder_t313129557_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral696031758; extern Il2CppCodeGenString* _stringLiteral1197065091; extern Il2CppCodeGenString* _stringLiteral162306806; extern Il2CppCodeGenString* _stringLiteral2733268254; extern Il2CppCodeGenString* _stringLiteral1964127969; extern const uint32_t StackTraceUtility_ExtractStringFromExceptionInternal_m1435564516_MetadataUsageId; extern RuntimeClass* CharU5BU5D_t1522321484_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1537213814; extern Il2CppCodeGenString* _stringLiteral1742707595; extern Il2CppCodeGenString* _stringLiteral1361813893; extern Il2CppCodeGenString* _stringLiteral800780832; extern Il2CppCodeGenString* _stringLiteral3450408964; extern Il2CppCodeGenString* _stringLiteral1173566749; extern Il2CppCodeGenString* _stringLiteral1427619272; extern Il2CppCodeGenString* _stringLiteral1109926636; extern Il2CppCodeGenString* _stringLiteral3731977866; extern Il2CppCodeGenString* _stringLiteral3979129001; extern Il2CppCodeGenString* _stringLiteral675700299; extern Il2CppCodeGenString* _stringLiteral1328470161; extern Il2CppCodeGenString* _stringLiteral1284737963; extern Il2CppCodeGenString* _stringLiteral2696783159; extern const uint32_t StackTraceUtility_PostprocessStacktrace_m2698903637_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral257692189; extern Il2CppCodeGenString* _stringLiteral3341918290; extern Il2CppCodeGenString* _stringLiteral2063084106; extern Il2CppCodeGenString* _stringLiteral3525100246; extern Il2CppCodeGenString* _stringLiteral2622672072; extern Il2CppCodeGenString* _stringLiteral1864495309; extern Il2CppCodeGenString* _stringLiteral3096061537; extern Il2CppCodeGenString* _stringLiteral1633200396; extern Il2CppCodeGenString* _stringLiteral3230881341; extern Il2CppCodeGenString* _stringLiteral2222186932; extern Il2CppCodeGenString* _stringLiteral1917672447; extern Il2CppCodeGenString* _stringLiteral2694655422; extern const uint32_t StackTraceUtility_ExtractFormattedStackTrace_m2265662347_MetadataUsageId; extern const uint32_t StackTraceUtility__cctor_m2051063265_MetadataUsageId; extern RuntimeClass* GUIStyle_t4033995491_il2cpp_TypeInfo_var; extern RuntimeClass* GUIContent_t3165057865_il2cpp_TypeInfo_var; extern const uint32_t TextEditor__ctor_m1004933930_MetadataUsageId; extern const uint32_t TextGenerationSettings_CompareColors_m4161672168_MetadataUsageId; extern const uint32_t TextGenerationSettings_CompareVector2_m2697891872_MetadataUsageId; extern const uint32_t TextGenerationSettings_Equals_m872373524_MetadataUsageId; struct TextGenerationSettings_t2955391441_marshaled_pinvoke; struct TextGenerationSettings_t2955391441;; struct TextGenerationSettings_t2955391441_marshaled_pinvoke;; struct TextGenerationSettings_t2955391441_marshaled_com; struct TextGenerationSettings_t2955391441_marshaled_com;; extern RuntimeClass* List_1_t2359577098_il2cpp_TypeInfo_var; extern RuntimeClass* List_1_t369525373_il2cpp_TypeInfo_var; extern RuntimeClass* List_1_t1470875743_il2cpp_TypeInfo_var; extern const RuntimeMethod* List_1__ctor_m2525236808_RuntimeMethod_var; extern const RuntimeMethod* List_1__ctor_m691252865_RuntimeMethod_var; extern const RuntimeMethod* List_1__ctor_m581423473_RuntimeMethod_var; extern const uint32_t TextGenerator__ctor_m3315225751_MetadataUsageId; extern RuntimeClass* IDisposable_t971480393_il2cpp_TypeInfo_var; extern const uint32_t TextGenerator_Finalize_m3033244656_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral2266523459; extern Il2CppCodeGenString* _stringLiteral1956399547; extern const uint32_t TextGenerator_ValidatedSettings_m3744012953_MetadataUsageId; extern Il2CppCodeGenString* _stringLiteral475378281; extern Il2CppCodeGenString* _stringLiteral2537927702; extern const uint32_t TextGenerator_PopulateWithErrors_m2106001595_MetadataUsageId; extern const uint32_t TextGenerator_PopulateWithError_m1090609619_MetadataUsageId; extern const uint32_t TextGenerator_Populate_Internal_m93079026_MetadataUsageId; extern const uint32_t Texture__ctor_m3948473377_MetadataUsageId; extern const uint32_t Texture2D__ctor_m400428107_MetadataUsageId; struct GUIStyleState_t2009209206_marshaled_pinvoke; struct GUIStyleState_t2009209206_marshaled_com; struct RectOffset_t3582970358_marshaled_com; struct ObjectU5BU5D_t3885370135; struct Vector3U5BU5D_t2251457841; struct ObjectU5BU5D_t348161528; struct CameraU5BU5D_t2507966031; struct HitInfoU5BU5D_t4176695186; struct ParameterModifierU5BU5D_t730609508; struct StringU5BU5D_t3608572874; struct AchievementDescriptionU5BU5D_t916063548; struct IAchievementDescriptionU5BU5D_t3064410227; struct UserProfileU5BU5D_t3377267652; struct IUserProfileU5BU5D_t3867243727; struct GcAchievementDataU5BU5D_t1247845579; struct AchievementU5BU5D_t867614507; struct IAchievementU5BU5D_t1865138216; struct GcScoreDataU5BU5D_t859946003; struct ScoreU5BU5D_t13505070; struct IScoreU5BU5D_t519731081; struct CharU5BU5D_t1522321484; struct ParameterInfoU5BU5D_t2585026604; #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef STACKTRACE_T798888381_H #define STACKTRACE_T798888381_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.StackTrace struct StackTrace_t798888381 : public RuntimeObject { public: // System.Diagnostics.StackFrame[] System.Diagnostics.StackTrace::frames StackFrameU5BU5D_t688495400* ___frames_1; // System.Boolean System.Diagnostics.StackTrace::debug_info bool ___debug_info_2; public: inline static int32_t get_offset_of_frames_1() { return static_cast(offsetof(StackTrace_t798888381, ___frames_1)); } inline StackFrameU5BU5D_t688495400* get_frames_1() const { return ___frames_1; } inline StackFrameU5BU5D_t688495400** get_address_of_frames_1() { return &___frames_1; } inline void set_frames_1(StackFrameU5BU5D_t688495400* value) { ___frames_1 = value; Il2CppCodeGenWriteBarrier((&___frames_1), value); } inline static int32_t get_offset_of_debug_info_2() { return static_cast(offsetof(StackTrace_t798888381, ___debug_info_2)); } inline bool get_debug_info_2() const { return ___debug_info_2; } inline bool* get_address_of_debug_info_2() { return &___debug_info_2; } inline void set_debug_info_2(bool value) { ___debug_info_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STACKTRACE_T798888381_H #ifndef STACKTRACEUTILITY_T1534026680_H #define STACKTRACEUTILITY_T1534026680_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.StackTraceUtility struct StackTraceUtility_t1534026680 : public RuntimeObject { public: public: }; struct StackTraceUtility_t1534026680_StaticFields { public: // System.String UnityEngine.StackTraceUtility::projectFolder String_t* ___projectFolder_0; public: inline static int32_t get_offset_of_projectFolder_0() { return static_cast(offsetof(StackTraceUtility_t1534026680_StaticFields, ___projectFolder_0)); } inline String_t* get_projectFolder_0() const { return ___projectFolder_0; } inline String_t** get_address_of_projectFolder_0() { return &___projectFolder_0; } inline void set_projectFolder_0(String_t* value) { ___projectFolder_0 = value; Il2CppCodeGenWriteBarrier((&___projectFolder_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STACKTRACEUTILITY_T1534026680_H #ifndef DATAUTILITY_T3966667033_H #define DATAUTILITY_T3966667033_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Sprites.DataUtility struct DataUtility_t3966667033 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DATAUTILITY_T3966667033_H #ifndef SCENEMANAGER_T2619984172_H #define SCENEMANAGER_T2619984172_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SceneManagement.SceneManager struct SceneManager_t2619984172 : public RuntimeObject { public: public: }; struct SceneManager_t2619984172_StaticFields { public: // UnityEngine.Events.UnityAction`2 UnityEngine.SceneManagement.SceneManager::sceneLoaded UnityAction_2_t1303706228 * ___sceneLoaded_0; // UnityEngine.Events.UnityAction`1 UnityEngine.SceneManagement.SceneManager::sceneUnloaded UnityAction_1_t2300191644 * ___sceneUnloaded_1; // UnityEngine.Events.UnityAction`2 UnityEngine.SceneManagement.SceneManager::activeSceneChanged UnityAction_2_t1173199225 * ___activeSceneChanged_2; public: inline static int32_t get_offset_of_sceneLoaded_0() { return static_cast(offsetof(SceneManager_t2619984172_StaticFields, ___sceneLoaded_0)); } inline UnityAction_2_t1303706228 * get_sceneLoaded_0() const { return ___sceneLoaded_0; } inline UnityAction_2_t1303706228 ** get_address_of_sceneLoaded_0() { return &___sceneLoaded_0; } inline void set_sceneLoaded_0(UnityAction_2_t1303706228 * value) { ___sceneLoaded_0 = value; Il2CppCodeGenWriteBarrier((&___sceneLoaded_0), value); } inline static int32_t get_offset_of_sceneUnloaded_1() { return static_cast(offsetof(SceneManager_t2619984172_StaticFields, ___sceneUnloaded_1)); } inline UnityAction_1_t2300191644 * get_sceneUnloaded_1() const { return ___sceneUnloaded_1; } inline UnityAction_1_t2300191644 ** get_address_of_sceneUnloaded_1() { return &___sceneUnloaded_1; } inline void set_sceneUnloaded_1(UnityAction_1_t2300191644 * value) { ___sceneUnloaded_1 = value; Il2CppCodeGenWriteBarrier((&___sceneUnloaded_1), value); } inline static int32_t get_offset_of_activeSceneChanged_2() { return static_cast(offsetof(SceneManager_t2619984172_StaticFields, ___activeSceneChanged_2)); } inline UnityAction_2_t1173199225 * get_activeSceneChanged_2() const { return ___activeSceneChanged_2; } inline UnityAction_2_t1173199225 ** get_address_of_activeSceneChanged_2() { return &___activeSceneChanged_2; } inline void set_activeSceneChanged_2(UnityAction_2_t1173199225 * value) { ___activeSceneChanged_2 = value; Il2CppCodeGenWriteBarrier((&___activeSceneChanged_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCENEMANAGER_T2619984172_H #ifndef U3CUNITYENGINE_SOCIALPLATFORMS_ISOCIALPLATFORM_AUTHENTICATEU3EC__ANONSTOREY0_T4230897699_H #define U3CUNITYENGINE_SOCIALPLATFORMS_ISOCIALPLATFORM_AUTHENTICATEU3EC__ANONSTOREY0_T4230897699_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0 struct U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 : public RuntimeObject { public: // System.Action`1 UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0::callback Action_1_t2674754663 * ___callback_0; public: inline static int32_t get_offset_of_callback_0() { return static_cast(offsetof(U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699, ___callback_0)); } inline Action_1_t2674754663 * get_callback_0() const { return ___callback_0; } inline Action_1_t2674754663 ** get_address_of_callback_0() { return &___callback_0; } inline void set_callback_0(Action_1_t2674754663 * value) { ___callback_0 = value; Il2CppCodeGenWriteBarrier((&___callback_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CUNITYENGINE_SOCIALPLATFORMS_ISOCIALPLATFORM_AUTHENTICATEU3EC__ANONSTOREY0_T4230897699_H #ifndef RECTTRANSFORMUTILITY_T1869061041_H #define RECTTRANSFORMUTILITY_T1869061041_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectTransformUtility struct RectTransformUtility_t1869061041 : public RuntimeObject { public: public: }; struct RectTransformUtility_t1869061041_StaticFields { public: // UnityEngine.Vector3[] UnityEngine.RectTransformUtility::s_Corners Vector3U5BU5D_t2251457841* ___s_Corners_0; public: inline static int32_t get_offset_of_s_Corners_0() { return static_cast(offsetof(RectTransformUtility_t1869061041_StaticFields, ___s_Corners_0)); } inline Vector3U5BU5D_t2251457841* get_s_Corners_0() const { return ___s_Corners_0; } inline Vector3U5BU5D_t2251457841** get_address_of_s_Corners_0() { return &___s_Corners_0; } inline void set_s_Corners_0(Vector3U5BU5D_t2251457841* value) { ___s_Corners_0 = value; Il2CppCodeGenWriteBarrier((&___s_Corners_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RECTTRANSFORMUTILITY_T1869061041_H #ifndef ACHIEVEMENTDESCRIPTION_T991053089_H #define ACHIEVEMENTDESCRIPTION_T991053089_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.AchievementDescription struct AchievementDescription_t991053089 : public RuntimeObject { public: // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_Title String_t* ___m_Title_0; // UnityEngine.Texture2D UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_Image Texture2D_t1384570725 * ___m_Image_1; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_AchievedDescription String_t* ___m_AchievedDescription_2; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_UnachievedDescription String_t* ___m_UnachievedDescription_3; // System.Boolean UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_Hidden bool ___m_Hidden_4; // System.Int32 UnityEngine.SocialPlatforms.Impl.AchievementDescription::m_Points int32_t ___m_Points_5; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::k__BackingField String_t* ___U3CidU3Ek__BackingField_6; public: inline static int32_t get_offset_of_m_Title_0() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_Title_0)); } inline String_t* get_m_Title_0() const { return ___m_Title_0; } inline String_t** get_address_of_m_Title_0() { return &___m_Title_0; } inline void set_m_Title_0(String_t* value) { ___m_Title_0 = value; Il2CppCodeGenWriteBarrier((&___m_Title_0), value); } inline static int32_t get_offset_of_m_Image_1() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_Image_1)); } inline Texture2D_t1384570725 * get_m_Image_1() const { return ___m_Image_1; } inline Texture2D_t1384570725 ** get_address_of_m_Image_1() { return &___m_Image_1; } inline void set_m_Image_1(Texture2D_t1384570725 * value) { ___m_Image_1 = value; Il2CppCodeGenWriteBarrier((&___m_Image_1), value); } inline static int32_t get_offset_of_m_AchievedDescription_2() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_AchievedDescription_2)); } inline String_t* get_m_AchievedDescription_2() const { return ___m_AchievedDescription_2; } inline String_t** get_address_of_m_AchievedDescription_2() { return &___m_AchievedDescription_2; } inline void set_m_AchievedDescription_2(String_t* value) { ___m_AchievedDescription_2 = value; Il2CppCodeGenWriteBarrier((&___m_AchievedDescription_2), value); } inline static int32_t get_offset_of_m_UnachievedDescription_3() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_UnachievedDescription_3)); } inline String_t* get_m_UnachievedDescription_3() const { return ___m_UnachievedDescription_3; } inline String_t** get_address_of_m_UnachievedDescription_3() { return &___m_UnachievedDescription_3; } inline void set_m_UnachievedDescription_3(String_t* value) { ___m_UnachievedDescription_3 = value; Il2CppCodeGenWriteBarrier((&___m_UnachievedDescription_3), value); } inline static int32_t get_offset_of_m_Hidden_4() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_Hidden_4)); } inline bool get_m_Hidden_4() const { return ___m_Hidden_4; } inline bool* get_address_of_m_Hidden_4() { return &___m_Hidden_4; } inline void set_m_Hidden_4(bool value) { ___m_Hidden_4 = value; } inline static int32_t get_offset_of_m_Points_5() { return static_cast(offsetof(AchievementDescription_t991053089, ___m_Points_5)); } inline int32_t get_m_Points_5() const { return ___m_Points_5; } inline int32_t* get_address_of_m_Points_5() { return &___m_Points_5; } inline void set_m_Points_5(int32_t value) { ___m_Points_5 = value; } inline static int32_t get_offset_of_U3CidU3Ek__BackingField_6() { return static_cast(offsetof(AchievementDescription_t991053089, ___U3CidU3Ek__BackingField_6)); } inline String_t* get_U3CidU3Ek__BackingField_6() const { return ___U3CidU3Ek__BackingField_6; } inline String_t** get_address_of_U3CidU3Ek__BackingField_6() { return &___U3CidU3Ek__BackingField_6; } inline void set_U3CidU3Ek__BackingField_6(String_t* value) { ___U3CidU3Ek__BackingField_6 = value; Il2CppCodeGenWriteBarrier((&___U3CidU3Ek__BackingField_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACHIEVEMENTDESCRIPTION_T991053089_H #ifndef EXCEPTION_T3285241636_H #define EXCEPTION_T3285241636_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Exception struct Exception_t3285241636 : public RuntimeObject { public: // System.IntPtr[] System.Exception::trace_ips IntPtrU5BU5D_t3630972082* ___trace_ips_0; // System.Exception System.Exception::inner_exception Exception_t3285241636 * ___inner_exception_1; // System.String System.Exception::message String_t* ___message_2; // System.String System.Exception::help_link String_t* ___help_link_3; // System.String System.Exception::class_name String_t* ___class_name_4; // System.String System.Exception::stack_trace String_t* ___stack_trace_5; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_6; // System.Int32 System.Exception::remote_stack_index int32_t ___remote_stack_index_7; // System.Int32 System.Exception::hresult int32_t ___hresult_8; // System.String System.Exception::source String_t* ___source_9; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_10; public: inline static int32_t get_offset_of_trace_ips_0() { return static_cast(offsetof(Exception_t3285241636, ___trace_ips_0)); } inline IntPtrU5BU5D_t3630972082* get_trace_ips_0() const { return ___trace_ips_0; } inline IntPtrU5BU5D_t3630972082** get_address_of_trace_ips_0() { return &___trace_ips_0; } inline void set_trace_ips_0(IntPtrU5BU5D_t3630972082* value) { ___trace_ips_0 = value; Il2CppCodeGenWriteBarrier((&___trace_ips_0), value); } inline static int32_t get_offset_of_inner_exception_1() { return static_cast(offsetof(Exception_t3285241636, ___inner_exception_1)); } inline Exception_t3285241636 * get_inner_exception_1() const { return ___inner_exception_1; } inline Exception_t3285241636 ** get_address_of_inner_exception_1() { return &___inner_exception_1; } inline void set_inner_exception_1(Exception_t3285241636 * value) { ___inner_exception_1 = value; Il2CppCodeGenWriteBarrier((&___inner_exception_1), value); } inline static int32_t get_offset_of_message_2() { return static_cast(offsetof(Exception_t3285241636, ___message_2)); } inline String_t* get_message_2() const { return ___message_2; } inline String_t** get_address_of_message_2() { return &___message_2; } inline void set_message_2(String_t* value) { ___message_2 = value; Il2CppCodeGenWriteBarrier((&___message_2), value); } inline static int32_t get_offset_of_help_link_3() { return static_cast(offsetof(Exception_t3285241636, ___help_link_3)); } inline String_t* get_help_link_3() const { return ___help_link_3; } inline String_t** get_address_of_help_link_3() { return &___help_link_3; } inline void set_help_link_3(String_t* value) { ___help_link_3 = value; Il2CppCodeGenWriteBarrier((&___help_link_3), value); } inline static int32_t get_offset_of_class_name_4() { return static_cast(offsetof(Exception_t3285241636, ___class_name_4)); } inline String_t* get_class_name_4() const { return ___class_name_4; } inline String_t** get_address_of_class_name_4() { return &___class_name_4; } inline void set_class_name_4(String_t* value) { ___class_name_4 = value; Il2CppCodeGenWriteBarrier((&___class_name_4), value); } inline static int32_t get_offset_of_stack_trace_5() { return static_cast(offsetof(Exception_t3285241636, ___stack_trace_5)); } inline String_t* get_stack_trace_5() const { return ___stack_trace_5; } inline String_t** get_address_of_stack_trace_5() { return &___stack_trace_5; } inline void set_stack_trace_5(String_t* value) { ___stack_trace_5 = value; Il2CppCodeGenWriteBarrier((&___stack_trace_5), value); } inline static int32_t get_offset_of__remoteStackTraceString_6() { return static_cast(offsetof(Exception_t3285241636, ____remoteStackTraceString_6)); } inline String_t* get__remoteStackTraceString_6() const { return ____remoteStackTraceString_6; } inline String_t** get_address_of__remoteStackTraceString_6() { return &____remoteStackTraceString_6; } inline void set__remoteStackTraceString_6(String_t* value) { ____remoteStackTraceString_6 = value; Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_6), value); } inline static int32_t get_offset_of_remote_stack_index_7() { return static_cast(offsetof(Exception_t3285241636, ___remote_stack_index_7)); } inline int32_t get_remote_stack_index_7() const { return ___remote_stack_index_7; } inline int32_t* get_address_of_remote_stack_index_7() { return &___remote_stack_index_7; } inline void set_remote_stack_index_7(int32_t value) { ___remote_stack_index_7 = value; } inline static int32_t get_offset_of_hresult_8() { return static_cast(offsetof(Exception_t3285241636, ___hresult_8)); } inline int32_t get_hresult_8() const { return ___hresult_8; } inline int32_t* get_address_of_hresult_8() { return &___hresult_8; } inline void set_hresult_8(int32_t value) { ___hresult_8 = value; } inline static int32_t get_offset_of_source_9() { return static_cast(offsetof(Exception_t3285241636, ___source_9)); } inline String_t* get_source_9() const { return ___source_9; } inline String_t** get_address_of_source_9() { return &___source_9; } inline void set_source_9(String_t* value) { ___source_9 = value; Il2CppCodeGenWriteBarrier((&___source_9), value); } inline static int32_t get_offset_of__data_10() { return static_cast(offsetof(Exception_t3285241636, ____data_10)); } inline RuntimeObject* get__data_10() const { return ____data_10; } inline RuntimeObject** get_address_of__data_10() { return &____data_10; } inline void set__data_10(RuntimeObject* value) { ____data_10 = value; Il2CppCodeGenWriteBarrier((&____data_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXCEPTION_T3285241636_H #ifndef GAMECENTERPLATFORM_T1308980868_H #define GAMECENTERPLATFORM_T1308980868_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform struct GameCenterPlatform_t1308980868 : public RuntimeObject { public: public: }; struct GameCenterPlatform_t1308980868_StaticFields { public: // System.Action`2 UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::s_AuthenticateCallback Action_2_t3787810730 * ___s_AuthenticateCallback_0; // UnityEngine.SocialPlatforms.Impl.AchievementDescription[] UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::s_adCache AchievementDescriptionU5BU5D_t916063548* ___s_adCache_1; // UnityEngine.SocialPlatforms.Impl.UserProfile[] UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::s_friends UserProfileU5BU5D_t3377267652* ___s_friends_2; // UnityEngine.SocialPlatforms.Impl.UserProfile[] UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::s_users UserProfileU5BU5D_t3377267652* ___s_users_3; // System.Action`1 UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::s_ResetAchievements Action_1_t2674754663 * ___s_ResetAchievements_4; // UnityEngine.SocialPlatforms.Impl.LocalUser UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::m_LocalUser LocalUser_t2155741069 * ___m_LocalUser_5; // System.Collections.Generic.List`1 UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::m_GcBoards List_1_t984806126 * ___m_GcBoards_6; public: inline static int32_t get_offset_of_s_AuthenticateCallback_0() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___s_AuthenticateCallback_0)); } inline Action_2_t3787810730 * get_s_AuthenticateCallback_0() const { return ___s_AuthenticateCallback_0; } inline Action_2_t3787810730 ** get_address_of_s_AuthenticateCallback_0() { return &___s_AuthenticateCallback_0; } inline void set_s_AuthenticateCallback_0(Action_2_t3787810730 * value) { ___s_AuthenticateCallback_0 = value; Il2CppCodeGenWriteBarrier((&___s_AuthenticateCallback_0), value); } inline static int32_t get_offset_of_s_adCache_1() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___s_adCache_1)); } inline AchievementDescriptionU5BU5D_t916063548* get_s_adCache_1() const { return ___s_adCache_1; } inline AchievementDescriptionU5BU5D_t916063548** get_address_of_s_adCache_1() { return &___s_adCache_1; } inline void set_s_adCache_1(AchievementDescriptionU5BU5D_t916063548* value) { ___s_adCache_1 = value; Il2CppCodeGenWriteBarrier((&___s_adCache_1), value); } inline static int32_t get_offset_of_s_friends_2() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___s_friends_2)); } inline UserProfileU5BU5D_t3377267652* get_s_friends_2() const { return ___s_friends_2; } inline UserProfileU5BU5D_t3377267652** get_address_of_s_friends_2() { return &___s_friends_2; } inline void set_s_friends_2(UserProfileU5BU5D_t3377267652* value) { ___s_friends_2 = value; Il2CppCodeGenWriteBarrier((&___s_friends_2), value); } inline static int32_t get_offset_of_s_users_3() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___s_users_3)); } inline UserProfileU5BU5D_t3377267652* get_s_users_3() const { return ___s_users_3; } inline UserProfileU5BU5D_t3377267652** get_address_of_s_users_3() { return &___s_users_3; } inline void set_s_users_3(UserProfileU5BU5D_t3377267652* value) { ___s_users_3 = value; Il2CppCodeGenWriteBarrier((&___s_users_3), value); } inline static int32_t get_offset_of_s_ResetAchievements_4() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___s_ResetAchievements_4)); } inline Action_1_t2674754663 * get_s_ResetAchievements_4() const { return ___s_ResetAchievements_4; } inline Action_1_t2674754663 ** get_address_of_s_ResetAchievements_4() { return &___s_ResetAchievements_4; } inline void set_s_ResetAchievements_4(Action_1_t2674754663 * value) { ___s_ResetAchievements_4 = value; Il2CppCodeGenWriteBarrier((&___s_ResetAchievements_4), value); } inline static int32_t get_offset_of_m_LocalUser_5() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___m_LocalUser_5)); } inline LocalUser_t2155741069 * get_m_LocalUser_5() const { return ___m_LocalUser_5; } inline LocalUser_t2155741069 ** get_address_of_m_LocalUser_5() { return &___m_LocalUser_5; } inline void set_m_LocalUser_5(LocalUser_t2155741069 * value) { ___m_LocalUser_5 = value; Il2CppCodeGenWriteBarrier((&___m_LocalUser_5), value); } inline static int32_t get_offset_of_m_GcBoards_6() { return static_cast(offsetof(GameCenterPlatform_t1308980868_StaticFields, ___m_GcBoards_6)); } inline List_1_t984806126 * get_m_GcBoards_6() const { return ___m_GcBoards_6; } inline List_1_t984806126 ** get_address_of_m_GcBoards_6() { return &___m_GcBoards_6; } inline void set_m_GcBoards_6(List_1_t984806126 * value) { ___m_GcBoards_6 = value; Il2CppCodeGenWriteBarrier((&___m_GcBoards_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GAMECENTERPLATFORM_T1308980868_H #ifndef REMOTESETTINGS_T1084722070_H #define REMOTESETTINGS_T1084722070_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RemoteSettings struct RemoteSettings_t1084722070 : public RuntimeObject { public: public: }; struct RemoteSettings_t1084722070_StaticFields { public: // UnityEngine.RemoteSettings/UpdatedEventHandler UnityEngine.RemoteSettings::Updated UpdatedEventHandler_t860849547 * ___Updated_0; public: inline static int32_t get_offset_of_Updated_0() { return static_cast(offsetof(RemoteSettings_t1084722070_StaticFields, ___Updated_0)); } inline UpdatedEventHandler_t860849547 * get_Updated_0() const { return ___Updated_0; } inline UpdatedEventHandler_t860849547 ** get_address_of_Updated_0() { return &___Updated_0; } inline void set_Updated_0(UpdatedEventHandler_t860849547 * value) { ___Updated_0 = value; Il2CppCodeGenWriteBarrier((&___Updated_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REMOTESETTINGS_T1084722070_H #ifndef CULTUREINFO_T703400772_H #define CULTUREINFO_T703400772_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Globalization.CultureInfo struct CultureInfo_t703400772 : public RuntimeObject { public: // System.Boolean System.Globalization.CultureInfo::m_isReadOnly bool ___m_isReadOnly_7; // System.Int32 System.Globalization.CultureInfo::cultureID int32_t ___cultureID_8; // System.Int32 System.Globalization.CultureInfo::parent_lcid int32_t ___parent_lcid_9; // System.Int32 System.Globalization.CultureInfo::specific_lcid int32_t ___specific_lcid_10; // System.Int32 System.Globalization.CultureInfo::datetime_index int32_t ___datetime_index_11; // System.Int32 System.Globalization.CultureInfo::number_index int32_t ___number_index_12; // System.Boolean System.Globalization.CultureInfo::m_useUserOverride bool ___m_useUserOverride_13; // System.Globalization.NumberFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::numInfo NumberFormatInfo_t3630505389 * ___numInfo_14; // System.Globalization.DateTimeFormatInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::dateTimeInfo DateTimeFormatInfo_t825146048 * ___dateTimeInfo_15; // System.Globalization.TextInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::textInfo TextInfo_t1445196420 * ___textInfo_16; // System.String System.Globalization.CultureInfo::m_name String_t* ___m_name_17; // System.String System.Globalization.CultureInfo::displayname String_t* ___displayname_18; // System.String System.Globalization.CultureInfo::englishname String_t* ___englishname_19; // System.String System.Globalization.CultureInfo::nativename String_t* ___nativename_20; // System.String System.Globalization.CultureInfo::iso3lang String_t* ___iso3lang_21; // System.String System.Globalization.CultureInfo::iso2lang String_t* ___iso2lang_22; // System.String System.Globalization.CultureInfo::icu_name String_t* ___icu_name_23; // System.String System.Globalization.CultureInfo::win3lang String_t* ___win3lang_24; // System.String System.Globalization.CultureInfo::territory String_t* ___territory_25; // System.Globalization.CompareInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::compareInfo CompareInfo_t3595197132 * ___compareInfo_26; // System.Int32* System.Globalization.CultureInfo::calendar_data int32_t* ___calendar_data_27; // System.Void* System.Globalization.CultureInfo::textinfo_data void* ___textinfo_data_28; // System.Globalization.Calendar[] System.Globalization.CultureInfo::optional_calendars CalendarU5BU5D_t3771720741* ___optional_calendars_29; // System.Globalization.CultureInfo System.Globalization.CultureInfo::parent_culture CultureInfo_t703400772 * ___parent_culture_30; // System.Int32 System.Globalization.CultureInfo::m_dataItem int32_t ___m_dataItem_31; // System.Globalization.Calendar System.Globalization.CultureInfo::calendar Calendar_t1732656044 * ___calendar_32; // System.Boolean System.Globalization.CultureInfo::constructed bool ___constructed_33; // System.Byte[] System.Globalization.CultureInfo::cached_serialized_form ByteU5BU5D_t1185793865* ___cached_serialized_form_34; public: inline static int32_t get_offset_of_m_isReadOnly_7() { return static_cast(offsetof(CultureInfo_t703400772, ___m_isReadOnly_7)); } inline bool get_m_isReadOnly_7() const { return ___m_isReadOnly_7; } inline bool* get_address_of_m_isReadOnly_7() { return &___m_isReadOnly_7; } inline void set_m_isReadOnly_7(bool value) { ___m_isReadOnly_7 = value; } inline static int32_t get_offset_of_cultureID_8() { return static_cast(offsetof(CultureInfo_t703400772, ___cultureID_8)); } inline int32_t get_cultureID_8() const { return ___cultureID_8; } inline int32_t* get_address_of_cultureID_8() { return &___cultureID_8; } inline void set_cultureID_8(int32_t value) { ___cultureID_8 = value; } inline static int32_t get_offset_of_parent_lcid_9() { return static_cast(offsetof(CultureInfo_t703400772, ___parent_lcid_9)); } inline int32_t get_parent_lcid_9() const { return ___parent_lcid_9; } inline int32_t* get_address_of_parent_lcid_9() { return &___parent_lcid_9; } inline void set_parent_lcid_9(int32_t value) { ___parent_lcid_9 = value; } inline static int32_t get_offset_of_specific_lcid_10() { return static_cast(offsetof(CultureInfo_t703400772, ___specific_lcid_10)); } inline int32_t get_specific_lcid_10() const { return ___specific_lcid_10; } inline int32_t* get_address_of_specific_lcid_10() { return &___specific_lcid_10; } inline void set_specific_lcid_10(int32_t value) { ___specific_lcid_10 = value; } inline static int32_t get_offset_of_datetime_index_11() { return static_cast(offsetof(CultureInfo_t703400772, ___datetime_index_11)); } inline int32_t get_datetime_index_11() const { return ___datetime_index_11; } inline int32_t* get_address_of_datetime_index_11() { return &___datetime_index_11; } inline void set_datetime_index_11(int32_t value) { ___datetime_index_11 = value; } inline static int32_t get_offset_of_number_index_12() { return static_cast(offsetof(CultureInfo_t703400772, ___number_index_12)); } inline int32_t get_number_index_12() const { return ___number_index_12; } inline int32_t* get_address_of_number_index_12() { return &___number_index_12; } inline void set_number_index_12(int32_t value) { ___number_index_12 = value; } inline static int32_t get_offset_of_m_useUserOverride_13() { return static_cast(offsetof(CultureInfo_t703400772, ___m_useUserOverride_13)); } inline bool get_m_useUserOverride_13() const { return ___m_useUserOverride_13; } inline bool* get_address_of_m_useUserOverride_13() { return &___m_useUserOverride_13; } inline void set_m_useUserOverride_13(bool value) { ___m_useUserOverride_13 = value; } inline static int32_t get_offset_of_numInfo_14() { return static_cast(offsetof(CultureInfo_t703400772, ___numInfo_14)); } inline NumberFormatInfo_t3630505389 * get_numInfo_14() const { return ___numInfo_14; } inline NumberFormatInfo_t3630505389 ** get_address_of_numInfo_14() { return &___numInfo_14; } inline void set_numInfo_14(NumberFormatInfo_t3630505389 * value) { ___numInfo_14 = value; Il2CppCodeGenWriteBarrier((&___numInfo_14), value); } inline static int32_t get_offset_of_dateTimeInfo_15() { return static_cast(offsetof(CultureInfo_t703400772, ___dateTimeInfo_15)); } inline DateTimeFormatInfo_t825146048 * get_dateTimeInfo_15() const { return ___dateTimeInfo_15; } inline DateTimeFormatInfo_t825146048 ** get_address_of_dateTimeInfo_15() { return &___dateTimeInfo_15; } inline void set_dateTimeInfo_15(DateTimeFormatInfo_t825146048 * value) { ___dateTimeInfo_15 = value; Il2CppCodeGenWriteBarrier((&___dateTimeInfo_15), value); } inline static int32_t get_offset_of_textInfo_16() { return static_cast(offsetof(CultureInfo_t703400772, ___textInfo_16)); } inline TextInfo_t1445196420 * get_textInfo_16() const { return ___textInfo_16; } inline TextInfo_t1445196420 ** get_address_of_textInfo_16() { return &___textInfo_16; } inline void set_textInfo_16(TextInfo_t1445196420 * value) { ___textInfo_16 = value; Il2CppCodeGenWriteBarrier((&___textInfo_16), value); } inline static int32_t get_offset_of_m_name_17() { return static_cast(offsetof(CultureInfo_t703400772, ___m_name_17)); } inline String_t* get_m_name_17() const { return ___m_name_17; } inline String_t** get_address_of_m_name_17() { return &___m_name_17; } inline void set_m_name_17(String_t* value) { ___m_name_17 = value; Il2CppCodeGenWriteBarrier((&___m_name_17), value); } inline static int32_t get_offset_of_displayname_18() { return static_cast(offsetof(CultureInfo_t703400772, ___displayname_18)); } inline String_t* get_displayname_18() const { return ___displayname_18; } inline String_t** get_address_of_displayname_18() { return &___displayname_18; } inline void set_displayname_18(String_t* value) { ___displayname_18 = value; Il2CppCodeGenWriteBarrier((&___displayname_18), value); } inline static int32_t get_offset_of_englishname_19() { return static_cast(offsetof(CultureInfo_t703400772, ___englishname_19)); } inline String_t* get_englishname_19() const { return ___englishname_19; } inline String_t** get_address_of_englishname_19() { return &___englishname_19; } inline void set_englishname_19(String_t* value) { ___englishname_19 = value; Il2CppCodeGenWriteBarrier((&___englishname_19), value); } inline static int32_t get_offset_of_nativename_20() { return static_cast(offsetof(CultureInfo_t703400772, ___nativename_20)); } inline String_t* get_nativename_20() const { return ___nativename_20; } inline String_t** get_address_of_nativename_20() { return &___nativename_20; } inline void set_nativename_20(String_t* value) { ___nativename_20 = value; Il2CppCodeGenWriteBarrier((&___nativename_20), value); } inline static int32_t get_offset_of_iso3lang_21() { return static_cast(offsetof(CultureInfo_t703400772, ___iso3lang_21)); } inline String_t* get_iso3lang_21() const { return ___iso3lang_21; } inline String_t** get_address_of_iso3lang_21() { return &___iso3lang_21; } inline void set_iso3lang_21(String_t* value) { ___iso3lang_21 = value; Il2CppCodeGenWriteBarrier((&___iso3lang_21), value); } inline static int32_t get_offset_of_iso2lang_22() { return static_cast(offsetof(CultureInfo_t703400772, ___iso2lang_22)); } inline String_t* get_iso2lang_22() const { return ___iso2lang_22; } inline String_t** get_address_of_iso2lang_22() { return &___iso2lang_22; } inline void set_iso2lang_22(String_t* value) { ___iso2lang_22 = value; Il2CppCodeGenWriteBarrier((&___iso2lang_22), value); } inline static int32_t get_offset_of_icu_name_23() { return static_cast(offsetof(CultureInfo_t703400772, ___icu_name_23)); } inline String_t* get_icu_name_23() const { return ___icu_name_23; } inline String_t** get_address_of_icu_name_23() { return &___icu_name_23; } inline void set_icu_name_23(String_t* value) { ___icu_name_23 = value; Il2CppCodeGenWriteBarrier((&___icu_name_23), value); } inline static int32_t get_offset_of_win3lang_24() { return static_cast(offsetof(CultureInfo_t703400772, ___win3lang_24)); } inline String_t* get_win3lang_24() const { return ___win3lang_24; } inline String_t** get_address_of_win3lang_24() { return &___win3lang_24; } inline void set_win3lang_24(String_t* value) { ___win3lang_24 = value; Il2CppCodeGenWriteBarrier((&___win3lang_24), value); } inline static int32_t get_offset_of_territory_25() { return static_cast(offsetof(CultureInfo_t703400772, ___territory_25)); } inline String_t* get_territory_25() const { return ___territory_25; } inline String_t** get_address_of_territory_25() { return &___territory_25; } inline void set_territory_25(String_t* value) { ___territory_25 = value; Il2CppCodeGenWriteBarrier((&___territory_25), value); } inline static int32_t get_offset_of_compareInfo_26() { return static_cast(offsetof(CultureInfo_t703400772, ___compareInfo_26)); } inline CompareInfo_t3595197132 * get_compareInfo_26() const { return ___compareInfo_26; } inline CompareInfo_t3595197132 ** get_address_of_compareInfo_26() { return &___compareInfo_26; } inline void set_compareInfo_26(CompareInfo_t3595197132 * value) { ___compareInfo_26 = value; Il2CppCodeGenWriteBarrier((&___compareInfo_26), value); } inline static int32_t get_offset_of_calendar_data_27() { return static_cast(offsetof(CultureInfo_t703400772, ___calendar_data_27)); } inline int32_t* get_calendar_data_27() const { return ___calendar_data_27; } inline int32_t** get_address_of_calendar_data_27() { return &___calendar_data_27; } inline void set_calendar_data_27(int32_t* value) { ___calendar_data_27 = value; } inline static int32_t get_offset_of_textinfo_data_28() { return static_cast(offsetof(CultureInfo_t703400772, ___textinfo_data_28)); } inline void* get_textinfo_data_28() const { return ___textinfo_data_28; } inline void** get_address_of_textinfo_data_28() { return &___textinfo_data_28; } inline void set_textinfo_data_28(void* value) { ___textinfo_data_28 = value; } inline static int32_t get_offset_of_optional_calendars_29() { return static_cast(offsetof(CultureInfo_t703400772, ___optional_calendars_29)); } inline CalendarU5BU5D_t3771720741* get_optional_calendars_29() const { return ___optional_calendars_29; } inline CalendarU5BU5D_t3771720741** get_address_of_optional_calendars_29() { return &___optional_calendars_29; } inline void set_optional_calendars_29(CalendarU5BU5D_t3771720741* value) { ___optional_calendars_29 = value; Il2CppCodeGenWriteBarrier((&___optional_calendars_29), value); } inline static int32_t get_offset_of_parent_culture_30() { return static_cast(offsetof(CultureInfo_t703400772, ___parent_culture_30)); } inline CultureInfo_t703400772 * get_parent_culture_30() const { return ___parent_culture_30; } inline CultureInfo_t703400772 ** get_address_of_parent_culture_30() { return &___parent_culture_30; } inline void set_parent_culture_30(CultureInfo_t703400772 * value) { ___parent_culture_30 = value; Il2CppCodeGenWriteBarrier((&___parent_culture_30), value); } inline static int32_t get_offset_of_m_dataItem_31() { return static_cast(offsetof(CultureInfo_t703400772, ___m_dataItem_31)); } inline int32_t get_m_dataItem_31() const { return ___m_dataItem_31; } inline int32_t* get_address_of_m_dataItem_31() { return &___m_dataItem_31; } inline void set_m_dataItem_31(int32_t value) { ___m_dataItem_31 = value; } inline static int32_t get_offset_of_calendar_32() { return static_cast(offsetof(CultureInfo_t703400772, ___calendar_32)); } inline Calendar_t1732656044 * get_calendar_32() const { return ___calendar_32; } inline Calendar_t1732656044 ** get_address_of_calendar_32() { return &___calendar_32; } inline void set_calendar_32(Calendar_t1732656044 * value) { ___calendar_32 = value; Il2CppCodeGenWriteBarrier((&___calendar_32), value); } inline static int32_t get_offset_of_constructed_33() { return static_cast(offsetof(CultureInfo_t703400772, ___constructed_33)); } inline bool get_constructed_33() const { return ___constructed_33; } inline bool* get_address_of_constructed_33() { return &___constructed_33; } inline void set_constructed_33(bool value) { ___constructed_33 = value; } inline static int32_t get_offset_of_cached_serialized_form_34() { return static_cast(offsetof(CultureInfo_t703400772, ___cached_serialized_form_34)); } inline ByteU5BU5D_t1185793865* get_cached_serialized_form_34() const { return ___cached_serialized_form_34; } inline ByteU5BU5D_t1185793865** get_address_of_cached_serialized_form_34() { return &___cached_serialized_form_34; } inline void set_cached_serialized_form_34(ByteU5BU5D_t1185793865* value) { ___cached_serialized_form_34 = value; Il2CppCodeGenWriteBarrier((&___cached_serialized_form_34), value); } }; struct CultureInfo_t703400772_StaticFields { public: // System.Globalization.CultureInfo modreq(System.Runtime.CompilerServices.IsVolatile) System.Globalization.CultureInfo::invariant_culture_info CultureInfo_t703400772 * ___invariant_culture_info_4; // System.Object System.Globalization.CultureInfo::shared_table_lock RuntimeObject * ___shared_table_lock_5; // System.Int32 System.Globalization.CultureInfo::BootstrapCultureID int32_t ___BootstrapCultureID_6; // System.String System.Globalization.CultureInfo::MSG_READONLY String_t* ___MSG_READONLY_35; // System.Collections.Hashtable System.Globalization.CultureInfo::shared_by_number Hashtable_t3901241470 * ___shared_by_number_36; // System.Collections.Hashtable System.Globalization.CultureInfo::shared_by_name Hashtable_t3901241470 * ___shared_by_name_37; // System.Collections.Generic.Dictionary`2 System.Globalization.CultureInfo::<>f__switch$map19 Dictionary_2_t543570752 * ___U3CU3Ef__switchU24map19_38; // System.Collections.Generic.Dictionary`2 System.Globalization.CultureInfo::<>f__switch$map1A Dictionary_2_t543570752 * ___U3CU3Ef__switchU24map1A_39; public: inline static int32_t get_offset_of_invariant_culture_info_4() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___invariant_culture_info_4)); } inline CultureInfo_t703400772 * get_invariant_culture_info_4() const { return ___invariant_culture_info_4; } inline CultureInfo_t703400772 ** get_address_of_invariant_culture_info_4() { return &___invariant_culture_info_4; } inline void set_invariant_culture_info_4(CultureInfo_t703400772 * value) { ___invariant_culture_info_4 = value; Il2CppCodeGenWriteBarrier((&___invariant_culture_info_4), value); } inline static int32_t get_offset_of_shared_table_lock_5() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___shared_table_lock_5)); } inline RuntimeObject * get_shared_table_lock_5() const { return ___shared_table_lock_5; } inline RuntimeObject ** get_address_of_shared_table_lock_5() { return &___shared_table_lock_5; } inline void set_shared_table_lock_5(RuntimeObject * value) { ___shared_table_lock_5 = value; Il2CppCodeGenWriteBarrier((&___shared_table_lock_5), value); } inline static int32_t get_offset_of_BootstrapCultureID_6() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___BootstrapCultureID_6)); } inline int32_t get_BootstrapCultureID_6() const { return ___BootstrapCultureID_6; } inline int32_t* get_address_of_BootstrapCultureID_6() { return &___BootstrapCultureID_6; } inline void set_BootstrapCultureID_6(int32_t value) { ___BootstrapCultureID_6 = value; } inline static int32_t get_offset_of_MSG_READONLY_35() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___MSG_READONLY_35)); } inline String_t* get_MSG_READONLY_35() const { return ___MSG_READONLY_35; } inline String_t** get_address_of_MSG_READONLY_35() { return &___MSG_READONLY_35; } inline void set_MSG_READONLY_35(String_t* value) { ___MSG_READONLY_35 = value; Il2CppCodeGenWriteBarrier((&___MSG_READONLY_35), value); } inline static int32_t get_offset_of_shared_by_number_36() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___shared_by_number_36)); } inline Hashtable_t3901241470 * get_shared_by_number_36() const { return ___shared_by_number_36; } inline Hashtable_t3901241470 ** get_address_of_shared_by_number_36() { return &___shared_by_number_36; } inline void set_shared_by_number_36(Hashtable_t3901241470 * value) { ___shared_by_number_36 = value; Il2CppCodeGenWriteBarrier((&___shared_by_number_36), value); } inline static int32_t get_offset_of_shared_by_name_37() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___shared_by_name_37)); } inline Hashtable_t3901241470 * get_shared_by_name_37() const { return ___shared_by_name_37; } inline Hashtable_t3901241470 ** get_address_of_shared_by_name_37() { return &___shared_by_name_37; } inline void set_shared_by_name_37(Hashtable_t3901241470 * value) { ___shared_by_name_37 = value; Il2CppCodeGenWriteBarrier((&___shared_by_name_37), value); } inline static int32_t get_offset_of_U3CU3Ef__switchU24map19_38() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___U3CU3Ef__switchU24map19_38)); } inline Dictionary_2_t543570752 * get_U3CU3Ef__switchU24map19_38() const { return ___U3CU3Ef__switchU24map19_38; } inline Dictionary_2_t543570752 ** get_address_of_U3CU3Ef__switchU24map19_38() { return &___U3CU3Ef__switchU24map19_38; } inline void set_U3CU3Ef__switchU24map19_38(Dictionary_2_t543570752 * value) { ___U3CU3Ef__switchU24map19_38 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map19_38), value); } inline static int32_t get_offset_of_U3CU3Ef__switchU24map1A_39() { return static_cast(offsetof(CultureInfo_t703400772_StaticFields, ___U3CU3Ef__switchU24map1A_39)); } inline Dictionary_2_t543570752 * get_U3CU3Ef__switchU24map1A_39() const { return ___U3CU3Ef__switchU24map1A_39; } inline Dictionary_2_t543570752 ** get_address_of_U3CU3Ef__switchU24map1A_39() { return &___U3CU3Ef__switchU24map1A_39; } inline void set_U3CU3Ef__switchU24map1A_39(Dictionary_2_t543570752 * value) { ___U3CU3Ef__switchU24map1A_39 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__switchU24map1A_39), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CULTUREINFO_T703400772_H #ifndef BINDER_T530160220_H #define BINDER_T530160220_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Binder struct Binder_t530160220 : public RuntimeObject { public: public: }; struct Binder_t530160220_StaticFields { public: // System.Reflection.Binder System.Reflection.Binder::default_binder Binder_t530160220 * ___default_binder_0; public: inline static int32_t get_offset_of_default_binder_0() { return static_cast(offsetof(Binder_t530160220_StaticFields, ___default_binder_0)); } inline Binder_t530160220 * get_default_binder_0() const { return ___default_binder_0; } inline Binder_t530160220 ** get_address_of_default_binder_0() { return &___default_binder_0; } inline void set_default_binder_0(Binder_t530160220 * value) { ___default_binder_0 = value; Il2CppCodeGenWriteBarrier((&___default_binder_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINDER_T530160220_H #ifndef SETUPCOROUTINE_T2392442807_H #define SETUPCOROUTINE_T2392442807_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SetupCoroutine struct SetupCoroutine_t2392442807 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SETUPCOROUTINE_T2392442807_H #ifndef SENDMOUSEEVENTS_T955851818_H #define SENDMOUSEEVENTS_T955851818_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SendMouseEvents struct SendMouseEvents_t955851818 : public RuntimeObject { public: public: }; struct SendMouseEvents_t955851818_StaticFields { public: // System.Boolean UnityEngine.SendMouseEvents::s_MouseUsed bool ___s_MouseUsed_0; // UnityEngine.SendMouseEvents/HitInfo[] UnityEngine.SendMouseEvents::m_LastHit HitInfoU5BU5D_t4176695186* ___m_LastHit_1; // UnityEngine.SendMouseEvents/HitInfo[] UnityEngine.SendMouseEvents::m_MouseDownHit HitInfoU5BU5D_t4176695186* ___m_MouseDownHit_2; // UnityEngine.SendMouseEvents/HitInfo[] UnityEngine.SendMouseEvents::m_CurrentHit HitInfoU5BU5D_t4176695186* ___m_CurrentHit_3; // UnityEngine.Camera[] UnityEngine.SendMouseEvents::m_Cameras CameraU5BU5D_t2507966031* ___m_Cameras_4; public: inline static int32_t get_offset_of_s_MouseUsed_0() { return static_cast(offsetof(SendMouseEvents_t955851818_StaticFields, ___s_MouseUsed_0)); } inline bool get_s_MouseUsed_0() const { return ___s_MouseUsed_0; } inline bool* get_address_of_s_MouseUsed_0() { return &___s_MouseUsed_0; } inline void set_s_MouseUsed_0(bool value) { ___s_MouseUsed_0 = value; } inline static int32_t get_offset_of_m_LastHit_1() { return static_cast(offsetof(SendMouseEvents_t955851818_StaticFields, ___m_LastHit_1)); } inline HitInfoU5BU5D_t4176695186* get_m_LastHit_1() const { return ___m_LastHit_1; } inline HitInfoU5BU5D_t4176695186** get_address_of_m_LastHit_1() { return &___m_LastHit_1; } inline void set_m_LastHit_1(HitInfoU5BU5D_t4176695186* value) { ___m_LastHit_1 = value; Il2CppCodeGenWriteBarrier((&___m_LastHit_1), value); } inline static int32_t get_offset_of_m_MouseDownHit_2() { return static_cast(offsetof(SendMouseEvents_t955851818_StaticFields, ___m_MouseDownHit_2)); } inline HitInfoU5BU5D_t4176695186* get_m_MouseDownHit_2() const { return ___m_MouseDownHit_2; } inline HitInfoU5BU5D_t4176695186** get_address_of_m_MouseDownHit_2() { return &___m_MouseDownHit_2; } inline void set_m_MouseDownHit_2(HitInfoU5BU5D_t4176695186* value) { ___m_MouseDownHit_2 = value; Il2CppCodeGenWriteBarrier((&___m_MouseDownHit_2), value); } inline static int32_t get_offset_of_m_CurrentHit_3() { return static_cast(offsetof(SendMouseEvents_t955851818_StaticFields, ___m_CurrentHit_3)); } inline HitInfoU5BU5D_t4176695186* get_m_CurrentHit_3() const { return ___m_CurrentHit_3; } inline HitInfoU5BU5D_t4176695186** get_address_of_m_CurrentHit_3() { return &___m_CurrentHit_3; } inline void set_m_CurrentHit_3(HitInfoU5BU5D_t4176695186* value) { ___m_CurrentHit_3 = value; Il2CppCodeGenWriteBarrier((&___m_CurrentHit_3), value); } inline static int32_t get_offset_of_m_Cameras_4() { return static_cast(offsetof(SendMouseEvents_t955851818_StaticFields, ___m_Cameras_4)); } inline CameraU5BU5D_t2507966031* get_m_Cameras_4() const { return ___m_Cameras_4; } inline CameraU5BU5D_t2507966031** get_address_of_m_Cameras_4() { return &___m_Cameras_4; } inline void set_m_Cameras_4(CameraU5BU5D_t2507966031* value) { ___m_Cameras_4 = value; Il2CppCodeGenWriteBarrier((&___m_Cameras_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SENDMOUSEEVENTS_T955851818_H #ifndef SCROLLVIEWSTATE_T3481701544_H #define SCROLLVIEWSTATE_T3481701544_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ScrollViewState struct ScrollViewState_t3481701544 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCROLLVIEWSTATE_T3481701544_H #ifndef RESOURCES_T3251753876_H #define RESOURCES_T3251753876_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Resources struct Resources_t3251753876 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RESOURCES_T3251753876_H #ifndef SCREEN_T1803876837_H #define SCREEN_T1803876837_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Screen struct Screen_t1803876837 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCREEN_T1803876837_H #ifndef SLIDERSTATE_T1582857496_H #define SLIDERSTATE_T1582857496_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SliderState struct SliderState_t1582857496 : public RuntimeObject { public: // System.Single UnityEngine.SliderState::dragStartPos float ___dragStartPos_0; // System.Single UnityEngine.SliderState::dragStartValue float ___dragStartValue_1; // System.Boolean UnityEngine.SliderState::isDragging bool ___isDragging_2; public: inline static int32_t get_offset_of_dragStartPos_0() { return static_cast(offsetof(SliderState_t1582857496, ___dragStartPos_0)); } inline float get_dragStartPos_0() const { return ___dragStartPos_0; } inline float* get_address_of_dragStartPos_0() { return &___dragStartPos_0; } inline void set_dragStartPos_0(float value) { ___dragStartPos_0 = value; } inline static int32_t get_offset_of_dragStartValue_1() { return static_cast(offsetof(SliderState_t1582857496, ___dragStartValue_1)); } inline float get_dragStartValue_1() const { return ___dragStartValue_1; } inline float* get_address_of_dragStartValue_1() { return &___dragStartValue_1; } inline void set_dragStartValue_1(float value) { ___dragStartValue_1 = value; } inline static int32_t get_offset_of_isDragging_2() { return static_cast(offsetof(SliderState_t1582857496, ___isDragging_2)); } inline bool get_isDragging_2() const { return ___isDragging_2; } inline bool* get_address_of_isDragging_2() { return &___isDragging_2; } inline void set_isDragging_2(bool value) { ___isDragging_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SLIDERSTATE_T1582857496_H #ifndef STRINGBUILDER_T313129557_H #define STRINGBUILDER_T313129557_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.StringBuilder struct StringBuilder_t313129557 : public RuntimeObject { public: // System.Int32 System.Text.StringBuilder::_length int32_t ____length_1; // System.String System.Text.StringBuilder::_str String_t* ____str_2; // System.String System.Text.StringBuilder::_cached_str String_t* ____cached_str_3; // System.Int32 System.Text.StringBuilder::_maxCapacity int32_t ____maxCapacity_4; public: inline static int32_t get_offset_of__length_1() { return static_cast(offsetof(StringBuilder_t313129557, ____length_1)); } inline int32_t get__length_1() const { return ____length_1; } inline int32_t* get_address_of__length_1() { return &____length_1; } inline void set__length_1(int32_t value) { ____length_1 = value; } inline static int32_t get_offset_of__str_2() { return static_cast(offsetof(StringBuilder_t313129557, ____str_2)); } inline String_t* get__str_2() const { return ____str_2; } inline String_t** get_address_of__str_2() { return &____str_2; } inline void set__str_2(String_t* value) { ____str_2 = value; Il2CppCodeGenWriteBarrier((&____str_2), value); } inline static int32_t get_offset_of__cached_str_3() { return static_cast(offsetof(StringBuilder_t313129557, ____cached_str_3)); } inline String_t* get__cached_str_3() const { return ____cached_str_3; } inline String_t** get_address_of__cached_str_3() { return &____cached_str_3; } inline void set__cached_str_3(String_t* value) { ____cached_str_3 = value; Il2CppCodeGenWriteBarrier((&____cached_str_3), value); } inline static int32_t get_offset_of__maxCapacity_4() { return static_cast(offsetof(StringBuilder_t313129557, ____maxCapacity_4)); } inline int32_t get__maxCapacity_4() const { return ____maxCapacity_4; } inline int32_t* get_address_of__maxCapacity_4() { return &____maxCapacity_4; } inline void set__maxCapacity_4(int32_t value) { ____maxCapacity_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRINGBUILDER_T313129557_H #ifndef LIST_1_T984806126_H #define LIST_1_T984806126_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1 struct List_1_t984806126 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items GcLeaderboardU5BU5D_t2736626859* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_t984806126, ____items_1)); } inline GcLeaderboardU5BU5D_t2736626859* get__items_1() const { return ____items_1; } inline GcLeaderboardU5BU5D_t2736626859** get_address_of__items_1() { return &____items_1; } inline void set__items_1(GcLeaderboardU5BU5D_t2736626859* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((&____items_1), value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_t984806126, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast(offsetof(List_1_t984806126, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } }; struct List_1_t984806126_StaticFields { public: // T[] System.Collections.Generic.List`1::EmptyArray GcLeaderboardU5BU5D_t2736626859* ___EmptyArray_4; public: inline static int32_t get_offset_of_EmptyArray_4() { return static_cast(offsetof(List_1_t984806126_StaticFields, ___EmptyArray_4)); } inline GcLeaderboardU5BU5D_t2736626859* get_EmptyArray_4() const { return ___EmptyArray_4; } inline GcLeaderboardU5BU5D_t2736626859** get_address_of_EmptyArray_4() { return &___EmptyArray_4; } inline void set_EmptyArray_4(GcLeaderboardU5BU5D_t2736626859* value) { ___EmptyArray_4 = value; Il2CppCodeGenWriteBarrier((&___EmptyArray_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LIST_1_T984806126_H #ifndef ATTRIBUTE_T739646798_H #define ATTRIBUTE_T739646798_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Attribute struct Attribute_t739646798 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTE_T739646798_H #ifndef LIST_1_T369525373_H #define LIST_1_T369525373_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1 struct List_1_t369525373 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items UICharInfoU5BU5D_t4195871232* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_t369525373, ____items_1)); } inline UICharInfoU5BU5D_t4195871232* get__items_1() const { return ____items_1; } inline UICharInfoU5BU5D_t4195871232** get_address_of__items_1() { return &____items_1; } inline void set__items_1(UICharInfoU5BU5D_t4195871232* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((&____items_1), value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_t369525373, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast(offsetof(List_1_t369525373, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } }; struct List_1_t369525373_StaticFields { public: // T[] System.Collections.Generic.List`1::EmptyArray UICharInfoU5BU5D_t4195871232* ___EmptyArray_4; public: inline static int32_t get_offset_of_EmptyArray_4() { return static_cast(offsetof(List_1_t369525373_StaticFields, ___EmptyArray_4)); } inline UICharInfoU5BU5D_t4195871232* get_EmptyArray_4() const { return ___EmptyArray_4; } inline UICharInfoU5BU5D_t4195871232** get_address_of_EmptyArray_4() { return &___EmptyArray_4; } inline void set_EmptyArray_4(UICharInfoU5BU5D_t4195871232* value) { ___EmptyArray_4 = value; Il2CppCodeGenWriteBarrier((&___EmptyArray_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LIST_1_T369525373_H #ifndef MEMBERINFO_T_H #define MEMBERINFO_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.MemberInfo struct MemberInfo_t : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MEMBERINFO_T_H #ifndef LIST_1_T2359577098_H #define LIST_1_T2359577098_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1 struct List_1_t2359577098 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items UIVertexU5BU5D_t2534070687* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_t2359577098, ____items_1)); } inline UIVertexU5BU5D_t2534070687* get__items_1() const { return ____items_1; } inline UIVertexU5BU5D_t2534070687** get_address_of__items_1() { return &____items_1; } inline void set__items_1(UIVertexU5BU5D_t2534070687* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((&____items_1), value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_t2359577098, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast(offsetof(List_1_t2359577098, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } }; struct List_1_t2359577098_StaticFields { public: // T[] System.Collections.Generic.List`1::EmptyArray UIVertexU5BU5D_t2534070687* ___EmptyArray_4; public: inline static int32_t get_offset_of_EmptyArray_4() { return static_cast(offsetof(List_1_t2359577098_StaticFields, ___EmptyArray_4)); } inline UIVertexU5BU5D_t2534070687* get_EmptyArray_4() const { return ___EmptyArray_4; } inline UIVertexU5BU5D_t2534070687** get_address_of_EmptyArray_4() { return &___EmptyArray_4; } inline void set_EmptyArray_4(UIVertexU5BU5D_t2534070687* value) { ___EmptyArray_4 = value; Il2CppCodeGenWriteBarrier((&___EmptyArray_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LIST_1_T2359577098_H #ifndef VALUETYPE_T1651021560_H #define VALUETYPE_T1651021560_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t1651021560 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t1651021560_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t1651021560_marshaled_com { }; #endif // VALUETYPE_T1651021560_H #ifndef GUICONTENT_T3165057865_H #define GUICONTENT_T3165057865_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GUIContent struct GUIContent_t3165057865 : public RuntimeObject { public: // System.String UnityEngine.GUIContent::m_Text String_t* ___m_Text_0; // UnityEngine.Texture UnityEngine.GUIContent::m_Image Texture_t2354860603 * ___m_Image_1; // System.String UnityEngine.GUIContent::m_Tooltip String_t* ___m_Tooltip_2; public: inline static int32_t get_offset_of_m_Text_0() { return static_cast(offsetof(GUIContent_t3165057865, ___m_Text_0)); } inline String_t* get_m_Text_0() const { return ___m_Text_0; } inline String_t** get_address_of_m_Text_0() { return &___m_Text_0; } inline void set_m_Text_0(String_t* value) { ___m_Text_0 = value; Il2CppCodeGenWriteBarrier((&___m_Text_0), value); } inline static int32_t get_offset_of_m_Image_1() { return static_cast(offsetof(GUIContent_t3165057865, ___m_Image_1)); } inline Texture_t2354860603 * get_m_Image_1() const { return ___m_Image_1; } inline Texture_t2354860603 ** get_address_of_m_Image_1() { return &___m_Image_1; } inline void set_m_Image_1(Texture_t2354860603 * value) { ___m_Image_1 = value; Il2CppCodeGenWriteBarrier((&___m_Image_1), value); } inline static int32_t get_offset_of_m_Tooltip_2() { return static_cast(offsetof(GUIContent_t3165057865, ___m_Tooltip_2)); } inline String_t* get_m_Tooltip_2() const { return ___m_Tooltip_2; } inline String_t** get_address_of_m_Tooltip_2() { return &___m_Tooltip_2; } inline void set_m_Tooltip_2(String_t* value) { ___m_Tooltip_2 = value; Il2CppCodeGenWriteBarrier((&___m_Tooltip_2), value); } }; struct GUIContent_t3165057865_StaticFields { public: // UnityEngine.GUIContent UnityEngine.GUIContent::s_Text GUIContent_t3165057865 * ___s_Text_3; // UnityEngine.GUIContent UnityEngine.GUIContent::s_Image GUIContent_t3165057865 * ___s_Image_4; // UnityEngine.GUIContent UnityEngine.GUIContent::s_TextImage GUIContent_t3165057865 * ___s_TextImage_5; // UnityEngine.GUIContent UnityEngine.GUIContent::none GUIContent_t3165057865 * ___none_6; public: inline static int32_t get_offset_of_s_Text_3() { return static_cast(offsetof(GUIContent_t3165057865_StaticFields, ___s_Text_3)); } inline GUIContent_t3165057865 * get_s_Text_3() const { return ___s_Text_3; } inline GUIContent_t3165057865 ** get_address_of_s_Text_3() { return &___s_Text_3; } inline void set_s_Text_3(GUIContent_t3165057865 * value) { ___s_Text_3 = value; Il2CppCodeGenWriteBarrier((&___s_Text_3), value); } inline static int32_t get_offset_of_s_Image_4() { return static_cast(offsetof(GUIContent_t3165057865_StaticFields, ___s_Image_4)); } inline GUIContent_t3165057865 * get_s_Image_4() const { return ___s_Image_4; } inline GUIContent_t3165057865 ** get_address_of_s_Image_4() { return &___s_Image_4; } inline void set_s_Image_4(GUIContent_t3165057865 * value) { ___s_Image_4 = value; Il2CppCodeGenWriteBarrier((&___s_Image_4), value); } inline static int32_t get_offset_of_s_TextImage_5() { return static_cast(offsetof(GUIContent_t3165057865_StaticFields, ___s_TextImage_5)); } inline GUIContent_t3165057865 * get_s_TextImage_5() const { return ___s_TextImage_5; } inline GUIContent_t3165057865 ** get_address_of_s_TextImage_5() { return &___s_TextImage_5; } inline void set_s_TextImage_5(GUIContent_t3165057865 * value) { ___s_TextImage_5 = value; Il2CppCodeGenWriteBarrier((&___s_TextImage_5), value); } inline static int32_t get_offset_of_none_6() { return static_cast(offsetof(GUIContent_t3165057865_StaticFields, ___none_6)); } inline GUIContent_t3165057865 * get_none_6() const { return ___none_6; } inline GUIContent_t3165057865 ** get_address_of_none_6() { return &___none_6; } inline void set_none_6(GUIContent_t3165057865 * value) { ___none_6 = value; Il2CppCodeGenWriteBarrier((&___none_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.GUIContent struct GUIContent_t3165057865_marshaled_pinvoke { char* ___m_Text_0; Texture_t2354860603 * ___m_Image_1; char* ___m_Tooltip_2; }; // Native definition for COM marshalling of UnityEngine.GUIContent struct GUIContent_t3165057865_marshaled_com { Il2CppChar* ___m_Text_0; Texture_t2354860603 * ___m_Image_1; Il2CppChar* ___m_Tooltip_2; }; #endif // GUICONTENT_T3165057865_H #ifndef LIST_1_T1470875743_H #define LIST_1_T1470875743_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1 struct List_1_t1470875743 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items UILineInfoU5BU5D_t2942809686* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_t1470875743, ____items_1)); } inline UILineInfoU5BU5D_t2942809686* get__items_1() const { return ____items_1; } inline UILineInfoU5BU5D_t2942809686** get_address_of__items_1() { return &____items_1; } inline void set__items_1(UILineInfoU5BU5D_t2942809686* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((&____items_1), value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_t1470875743, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast(offsetof(List_1_t1470875743, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } }; struct List_1_t1470875743_StaticFields { public: // T[] System.Collections.Generic.List`1::EmptyArray UILineInfoU5BU5D_t2942809686* ___EmptyArray_4; public: inline static int32_t get_offset_of_EmptyArray_4() { return static_cast(offsetof(List_1_t1470875743_StaticFields, ___EmptyArray_4)); } inline UILineInfoU5BU5D_t2942809686* get_EmptyArray_4() const { return ___EmptyArray_4; } inline UILineInfoU5BU5D_t2942809686** get_address_of_EmptyArray_4() { return &___EmptyArray_4; } inline void set_EmptyArray_4(UILineInfoU5BU5D_t2942809686* value) { ___EmptyArray_4 = value; Il2CppCodeGenWriteBarrier((&___EmptyArray_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LIST_1_T1470875743_H #ifndef SYSTEMINFO_T892198491_H #define SYSTEMINFO_T892198491_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SystemInfo struct SystemInfo_t892198491 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SYSTEMINFO_T892198491_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::length int32_t ___length_0; // System.Char System.String::start_char Il2CppChar ___start_char_1; public: inline static int32_t get_offset_of_length_0() { return static_cast(offsetof(String_t, ___length_0)); } inline int32_t get_length_0() const { return ___length_0; } inline int32_t* get_address_of_length_0() { return &___length_0; } inline void set_length_0(int32_t value) { ___length_0 = value; } inline static int32_t get_offset_of_start_char_1() { return static_cast(offsetof(String_t, ___start_char_1)); } inline Il2CppChar get_start_char_1() const { return ___start_char_1; } inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; } inline void set_start_char_1(Il2CppChar value) { ___start_char_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_2; // System.Char[] System.String::WhiteChars CharU5BU5D_t1522321484* ___WhiteChars_3; public: inline static int32_t get_offset_of_Empty_2() { return static_cast(offsetof(String_t_StaticFields, ___Empty_2)); } inline String_t* get_Empty_2() const { return ___Empty_2; } inline String_t** get_address_of_Empty_2() { return &___Empty_2; } inline void set_Empty_2(String_t* value) { ___Empty_2 = value; Il2CppCodeGenWriteBarrier((&___Empty_2), value); } inline static int32_t get_offset_of_WhiteChars_3() { return static_cast(offsetof(String_t_StaticFields, ___WhiteChars_3)); } inline CharU5BU5D_t1522321484* get_WhiteChars_3() const { return ___WhiteChars_3; } inline CharU5BU5D_t1522321484** get_address_of_WhiteChars_3() { return &___WhiteChars_3; } inline void set_WhiteChars_3(CharU5BU5D_t1522321484* value) { ___WhiteChars_3 = value; Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H #ifndef YIELDINSTRUCTION_T875001183_H #define YIELDINSTRUCTION_T875001183_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.YieldInstruction struct YieldInstruction_t875001183 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t875001183_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t875001183_marshaled_com { }; #endif // YIELDINSTRUCTION_T875001183_H #ifndef STACKFRAME_T2547199141_H #define STACKFRAME_T2547199141_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.StackFrame struct StackFrame_t2547199141 : public RuntimeObject { public: // System.Int32 System.Diagnostics.StackFrame::ilOffset int32_t ___ilOffset_1; // System.Int32 System.Diagnostics.StackFrame::nativeOffset int32_t ___nativeOffset_2; // System.Reflection.MethodBase System.Diagnostics.StackFrame::methodBase MethodBase_t710954372 * ___methodBase_3; // System.String System.Diagnostics.StackFrame::fileName String_t* ___fileName_4; // System.Int32 System.Diagnostics.StackFrame::lineNumber int32_t ___lineNumber_5; // System.Int32 System.Diagnostics.StackFrame::columnNumber int32_t ___columnNumber_6; // System.String System.Diagnostics.StackFrame::internalMethodName String_t* ___internalMethodName_7; public: inline static int32_t get_offset_of_ilOffset_1() { return static_cast(offsetof(StackFrame_t2547199141, ___ilOffset_1)); } inline int32_t get_ilOffset_1() const { return ___ilOffset_1; } inline int32_t* get_address_of_ilOffset_1() { return &___ilOffset_1; } inline void set_ilOffset_1(int32_t value) { ___ilOffset_1 = value; } inline static int32_t get_offset_of_nativeOffset_2() { return static_cast(offsetof(StackFrame_t2547199141, ___nativeOffset_2)); } inline int32_t get_nativeOffset_2() const { return ___nativeOffset_2; } inline int32_t* get_address_of_nativeOffset_2() { return &___nativeOffset_2; } inline void set_nativeOffset_2(int32_t value) { ___nativeOffset_2 = value; } inline static int32_t get_offset_of_methodBase_3() { return static_cast(offsetof(StackFrame_t2547199141, ___methodBase_3)); } inline MethodBase_t710954372 * get_methodBase_3() const { return ___methodBase_3; } inline MethodBase_t710954372 ** get_address_of_methodBase_3() { return &___methodBase_3; } inline void set_methodBase_3(MethodBase_t710954372 * value) { ___methodBase_3 = value; Il2CppCodeGenWriteBarrier((&___methodBase_3), value); } inline static int32_t get_offset_of_fileName_4() { return static_cast(offsetof(StackFrame_t2547199141, ___fileName_4)); } inline String_t* get_fileName_4() const { return ___fileName_4; } inline String_t** get_address_of_fileName_4() { return &___fileName_4; } inline void set_fileName_4(String_t* value) { ___fileName_4 = value; Il2CppCodeGenWriteBarrier((&___fileName_4), value); } inline static int32_t get_offset_of_lineNumber_5() { return static_cast(offsetof(StackFrame_t2547199141, ___lineNumber_5)); } inline int32_t get_lineNumber_5() const { return ___lineNumber_5; } inline int32_t* get_address_of_lineNumber_5() { return &___lineNumber_5; } inline void set_lineNumber_5(int32_t value) { ___lineNumber_5 = value; } inline static int32_t get_offset_of_columnNumber_6() { return static_cast(offsetof(StackFrame_t2547199141, ___columnNumber_6)); } inline int32_t get_columnNumber_6() const { return ___columnNumber_6; } inline int32_t* get_address_of_columnNumber_6() { return &___columnNumber_6; } inline void set_columnNumber_6(int32_t value) { ___columnNumber_6 = value; } inline static int32_t get_offset_of_internalMethodName_7() { return static_cast(offsetof(StackFrame_t2547199141, ___internalMethodName_7)); } inline String_t* get_internalMethodName_7() const { return ___internalMethodName_7; } inline String_t** get_address_of_internalMethodName_7() { return &___internalMethodName_7; } inline void set_internalMethodName_7(String_t* value) { ___internalMethodName_7 = value; Il2CppCodeGenWriteBarrier((&___internalMethodName_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STACKFRAME_T2547199141_H #ifndef RANDOM_T1293315678_H #define RANDOM_T1293315678_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Random struct Random_t1293315678 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RANDOM_T1293315678_H #ifndef ENUM_T2506116811_H #define ENUM_T2506116811_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t2506116811 : public ValueType_t1651021560 { public: public: }; struct Enum_t2506116811_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t1522321484* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast(offsetof(Enum_t2506116811_StaticFields, ___split_char_0)); } inline CharU5BU5D_t1522321484* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t1522321484** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t1522321484* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2506116811_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2506116811_marshaled_com { }; #endif // ENUM_T2506116811_H #ifndef REQUIREDBYNATIVECODEATTRIBUTE_T2549902335_H #define REQUIREDBYNATIVECODEATTRIBUTE_T2549902335_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.RequiredByNativeCodeAttribute struct RequiredByNativeCodeAttribute_t2549902335 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REQUIREDBYNATIVECODEATTRIBUTE_T2549902335_H #ifndef SELECTIONBASEATTRIBUTE_T3732655813_H #define SELECTIONBASEATTRIBUTE_T3732655813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SelectionBaseAttribute struct SelectionBaseAttribute_t3732655813 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SELECTIONBASEATTRIBUTE_T3732655813_H #ifndef HITINFO_T2268685571_H #define HITINFO_T2268685571_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t2268685571 { public: // UnityEngine.GameObject UnityEngine.SendMouseEvents/HitInfo::target GameObject_t2923855588 * ___target_0; // UnityEngine.Camera UnityEngine.SendMouseEvents/HitInfo::camera Camera_t110840138 * ___camera_1; public: inline static int32_t get_offset_of_target_0() { return static_cast(offsetof(HitInfo_t2268685571, ___target_0)); } inline GameObject_t2923855588 * get_target_0() const { return ___target_0; } inline GameObject_t2923855588 ** get_address_of_target_0() { return &___target_0; } inline void set_target_0(GameObject_t2923855588 * value) { ___target_0 = value; Il2CppCodeGenWriteBarrier((&___target_0), value); } inline static int32_t get_offset_of_camera_1() { return static_cast(offsetof(HitInfo_t2268685571, ___camera_1)); } inline Camera_t110840138 * get_camera_1() const { return ___camera_1; } inline Camera_t110840138 ** get_address_of_camera_1() { return &___camera_1; } inline void set_camera_1(Camera_t110840138 * value) { ___camera_1 = value; Il2CppCodeGenWriteBarrier((&___camera_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t2268685571_marshaled_pinvoke { GameObject_t2923855588 * ___target_0; Camera_t110840138 * ___camera_1; }; // Native definition for COM marshalling of UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t2268685571_marshaled_com { GameObject_t2923855588 * ___target_0; Camera_t110840138 * ___camera_1; }; #endif // HITINFO_T2268685571_H #ifndef GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T1965560690_H #define GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T1965560690_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute struct GeneratedByOldBindingsGeneratorAttribute_t1965560690 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T1965560690_H #ifndef FORMERLYSERIALIZEDASATTRIBUTE_T2004262931_H #define FORMERLYSERIALIZEDASATTRIBUTE_T2004262931_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Serialization.FormerlySerializedAsAttribute struct FormerlySerializedAsAttribute_t2004262931 : public Attribute_t739646798 { public: // System.String UnityEngine.Serialization.FormerlySerializedAsAttribute::m_oldName String_t* ___m_oldName_0; public: inline static int32_t get_offset_of_m_oldName_0() { return static_cast(offsetof(FormerlySerializedAsAttribute_t2004262931, ___m_oldName_0)); } inline String_t* get_m_oldName_0() const { return ___m_oldName_0; } inline String_t** get_address_of_m_oldName_0() { return &___m_oldName_0; } inline void set_m_oldName_0(String_t* value) { ___m_oldName_0 = value; Il2CppCodeGenWriteBarrier((&___m_oldName_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FORMERLYSERIALIZEDASATTRIBUTE_T2004262931_H #ifndef SERIALIZEFIELD_T2526071389_H #define SERIALIZEFIELD_T2526071389_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SerializeField struct SerializeField_t2526071389 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERIALIZEFIELD_T2526071389_H #ifndef SERIALIZEPRIVATEVARIABLES_T3415835997_H #define SERIALIZEPRIVATEVARIABLES_T3415835997_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SerializePrivateVariables struct SerializePrivateVariables_t3415835997 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERIALIZEPRIVATEVARIABLES_T3415835997_H #ifndef SYSTEMEXCEPTION_T3352021648_H #define SYSTEMEXCEPTION_T3352021648_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SystemException struct SystemException_t3352021648 : public Exception_t3285241636 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SYSTEMEXCEPTION_T3352021648_H #ifndef MOVEDFROMATTRIBUTE_T4199174457_H #define MOVEDFROMATTRIBUTE_T4199174457_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.APIUpdating.MovedFromAttribute struct MovedFromAttribute_t4199174457 : public Attribute_t739646798 { public: // System.String UnityEngine.Scripting.APIUpdating.MovedFromAttribute::k__BackingField String_t* ___U3CNamespaceU3Ek__BackingField_0; // System.Boolean UnityEngine.Scripting.APIUpdating.MovedFromAttribute::k__BackingField bool ___U3CIsInDifferentAssemblyU3Ek__BackingField_1; public: inline static int32_t get_offset_of_U3CNamespaceU3Ek__BackingField_0() { return static_cast(offsetof(MovedFromAttribute_t4199174457, ___U3CNamespaceU3Ek__BackingField_0)); } inline String_t* get_U3CNamespaceU3Ek__BackingField_0() const { return ___U3CNamespaceU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNamespaceU3Ek__BackingField_0() { return &___U3CNamespaceU3Ek__BackingField_0; } inline void set_U3CNamespaceU3Ek__BackingField_0(String_t* value) { ___U3CNamespaceU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNamespaceU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CIsInDifferentAssemblyU3Ek__BackingField_1() { return static_cast(offsetof(MovedFromAttribute_t4199174457, ___U3CIsInDifferentAssemblyU3Ek__BackingField_1)); } inline bool get_U3CIsInDifferentAssemblyU3Ek__BackingField_1() const { return ___U3CIsInDifferentAssemblyU3Ek__BackingField_1; } inline bool* get_address_of_U3CIsInDifferentAssemblyU3Ek__BackingField_1() { return &___U3CIsInDifferentAssemblyU3Ek__BackingField_1; } inline void set_U3CIsInDifferentAssemblyU3Ek__BackingField_1(bool value) { ___U3CIsInDifferentAssemblyU3Ek__BackingField_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MOVEDFROMATTRIBUTE_T4199174457_H #ifndef TIMESPAN_T3641256953_H #define TIMESPAN_T3641256953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TimeSpan struct TimeSpan_t3641256953 { public: // System.Int64 System.TimeSpan::_ticks int64_t ____ticks_8; public: inline static int32_t get_offset_of__ticks_8() { return static_cast(offsetof(TimeSpan_t3641256953, ____ticks_8)); } inline int64_t get__ticks_8() const { return ____ticks_8; } inline int64_t* get_address_of__ticks_8() { return &____ticks_8; } inline void set__ticks_8(int64_t value) { ____ticks_8 = value; } }; struct TimeSpan_t3641256953_StaticFields { public: // System.TimeSpan System.TimeSpan::MaxValue TimeSpan_t3641256953 ___MaxValue_5; // System.TimeSpan System.TimeSpan::MinValue TimeSpan_t3641256953 ___MinValue_6; // System.TimeSpan System.TimeSpan::Zero TimeSpan_t3641256953 ___Zero_7; public: inline static int32_t get_offset_of_MaxValue_5() { return static_cast(offsetof(TimeSpan_t3641256953_StaticFields, ___MaxValue_5)); } inline TimeSpan_t3641256953 get_MaxValue_5() const { return ___MaxValue_5; } inline TimeSpan_t3641256953 * get_address_of_MaxValue_5() { return &___MaxValue_5; } inline void set_MaxValue_5(TimeSpan_t3641256953 value) { ___MaxValue_5 = value; } inline static int32_t get_offset_of_MinValue_6() { return static_cast(offsetof(TimeSpan_t3641256953_StaticFields, ___MinValue_6)); } inline TimeSpan_t3641256953 get_MinValue_6() const { return ___MinValue_6; } inline TimeSpan_t3641256953 * get_address_of_MinValue_6() { return &___MinValue_6; } inline void set_MinValue_6(TimeSpan_t3641256953 value) { ___MinValue_6 = value; } inline static int32_t get_offset_of_Zero_7() { return static_cast(offsetof(TimeSpan_t3641256953_StaticFields, ___Zero_7)); } inline TimeSpan_t3641256953 get_Zero_7() const { return ___Zero_7; } inline TimeSpan_t3641256953 * get_address_of_Zero_7() { return &___Zero_7; } inline void set_Zero_7(TimeSpan_t3641256953 value) { ___Zero_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESPAN_T3641256953_H #ifndef USEDBYNATIVECODEATTRIBUTE_T542057536_H #define USEDBYNATIVECODEATTRIBUTE_T542057536_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.UsedByNativeCodeAttribute struct UsedByNativeCodeAttribute_t542057536 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // USEDBYNATIVECODEATTRIBUTE_T542057536_H #ifndef THREADANDSERIALIZATIONSAFEATTRIBUTE_T669741721_H #define THREADANDSERIALIZATIONSAFEATTRIBUTE_T669741721_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ThreadAndSerializationSafeAttribute struct ThreadAndSerializationSafeAttribute_t669741721 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // THREADANDSERIALIZATIONSAFEATTRIBUTE_T669741721_H #ifndef CHAR_T215683921_H #define CHAR_T215683921_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Char struct Char_t215683921 { public: // System.Char System.Char::m_value Il2CppChar ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Char_t215683921, ___m_value_2)); } inline Il2CppChar get_m_value_2() const { return ___m_value_2; } inline Il2CppChar* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(Il2CppChar value) { ___m_value_2 = value; } }; struct Char_t215683921_StaticFields { public: // System.Byte* System.Char::category_data uint8_t* ___category_data_3; // System.Byte* System.Char::numeric_data uint8_t* ___numeric_data_4; // System.Double* System.Char::numeric_data_values double* ___numeric_data_values_5; // System.UInt16* System.Char::to_lower_data_low uint16_t* ___to_lower_data_low_6; // System.UInt16* System.Char::to_lower_data_high uint16_t* ___to_lower_data_high_7; // System.UInt16* System.Char::to_upper_data_low uint16_t* ___to_upper_data_low_8; // System.UInt16* System.Char::to_upper_data_high uint16_t* ___to_upper_data_high_9; public: inline static int32_t get_offset_of_category_data_3() { return static_cast(offsetof(Char_t215683921_StaticFields, ___category_data_3)); } inline uint8_t* get_category_data_3() const { return ___category_data_3; } inline uint8_t** get_address_of_category_data_3() { return &___category_data_3; } inline void set_category_data_3(uint8_t* value) { ___category_data_3 = value; } inline static int32_t get_offset_of_numeric_data_4() { return static_cast(offsetof(Char_t215683921_StaticFields, ___numeric_data_4)); } inline uint8_t* get_numeric_data_4() const { return ___numeric_data_4; } inline uint8_t** get_address_of_numeric_data_4() { return &___numeric_data_4; } inline void set_numeric_data_4(uint8_t* value) { ___numeric_data_4 = value; } inline static int32_t get_offset_of_numeric_data_values_5() { return static_cast(offsetof(Char_t215683921_StaticFields, ___numeric_data_values_5)); } inline double* get_numeric_data_values_5() const { return ___numeric_data_values_5; } inline double** get_address_of_numeric_data_values_5() { return &___numeric_data_values_5; } inline void set_numeric_data_values_5(double* value) { ___numeric_data_values_5 = value; } inline static int32_t get_offset_of_to_lower_data_low_6() { return static_cast(offsetof(Char_t215683921_StaticFields, ___to_lower_data_low_6)); } inline uint16_t* get_to_lower_data_low_6() const { return ___to_lower_data_low_6; } inline uint16_t** get_address_of_to_lower_data_low_6() { return &___to_lower_data_low_6; } inline void set_to_lower_data_low_6(uint16_t* value) { ___to_lower_data_low_6 = value; } inline static int32_t get_offset_of_to_lower_data_high_7() { return static_cast(offsetof(Char_t215683921_StaticFields, ___to_lower_data_high_7)); } inline uint16_t* get_to_lower_data_high_7() const { return ___to_lower_data_high_7; } inline uint16_t** get_address_of_to_lower_data_high_7() { return &___to_lower_data_high_7; } inline void set_to_lower_data_high_7(uint16_t* value) { ___to_lower_data_high_7 = value; } inline static int32_t get_offset_of_to_upper_data_low_8() { return static_cast(offsetof(Char_t215683921_StaticFields, ___to_upper_data_low_8)); } inline uint16_t* get_to_upper_data_low_8() const { return ___to_upper_data_low_8; } inline uint16_t** get_address_of_to_upper_data_low_8() { return &___to_upper_data_low_8; } inline void set_to_upper_data_low_8(uint16_t* value) { ___to_upper_data_low_8 = value; } inline static int32_t get_offset_of_to_upper_data_high_9() { return static_cast(offsetof(Char_t215683921_StaticFields, ___to_upper_data_high_9)); } inline uint16_t* get_to_upper_data_high_9() const { return ___to_upper_data_high_9; } inline uint16_t** get_address_of_to_upper_data_high_9() { return &___to_upper_data_high_9; } inline void set_to_upper_data_high_9(uint16_t* value) { ___to_upper_data_high_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CHAR_T215683921_H #ifndef COLOR_T267620335_H #define COLOR_T267620335_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Color struct Color_t267620335 { public: // System.Single UnityEngine.Color::r float ___r_0; // System.Single UnityEngine.Color::g float ___g_1; // System.Single UnityEngine.Color::b float ___b_2; // System.Single UnityEngine.Color::a float ___a_3; public: inline static int32_t get_offset_of_r_0() { return static_cast(offsetof(Color_t267620335, ___r_0)); } inline float get_r_0() const { return ___r_0; } inline float* get_address_of_r_0() { return &___r_0; } inline void set_r_0(float value) { ___r_0 = value; } inline static int32_t get_offset_of_g_1() { return static_cast(offsetof(Color_t267620335, ___g_1)); } inline float get_g_1() const { return ___g_1; } inline float* get_address_of_g_1() { return &___g_1; } inline void set_g_1(float value) { ___g_1 = value; } inline static int32_t get_offset_of_b_2() { return static_cast(offsetof(Color_t267620335, ___b_2)); } inline float get_b_2() const { return ___b_2; } inline float* get_address_of_b_2() { return &___b_2; } inline void set_b_2(float value) { ___b_2 = value; } inline static int32_t get_offset_of_a_3() { return static_cast(offsetof(Color_t267620335, ___a_3)); } inline float get_a_3() const { return ___a_3; } inline float* get_address_of_a_3() { return &___a_3; } inline void set_a_3(float value) { ___a_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLOR_T267620335_H #ifndef METHODBASE_T710954372_H #define METHODBASE_T710954372_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.MethodBase struct MethodBase_t710954372 : public MemberInfo_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // METHODBASE_T710954372_H #ifndef ANIMATORSTATEINFO_T3042152932_H #define ANIMATORSTATEINFO_T3042152932_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AnimatorStateInfo struct AnimatorStateInfo_t3042152932 { public: // System.Int32 UnityEngine.AnimatorStateInfo::m_Name int32_t ___m_Name_0; // System.Int32 UnityEngine.AnimatorStateInfo::m_Path int32_t ___m_Path_1; // System.Int32 UnityEngine.AnimatorStateInfo::m_FullPath int32_t ___m_FullPath_2; // System.Single UnityEngine.AnimatorStateInfo::m_NormalizedTime float ___m_NormalizedTime_3; // System.Single UnityEngine.AnimatorStateInfo::m_Length float ___m_Length_4; // System.Single UnityEngine.AnimatorStateInfo::m_Speed float ___m_Speed_5; // System.Single UnityEngine.AnimatorStateInfo::m_SpeedMultiplier float ___m_SpeedMultiplier_6; // System.Int32 UnityEngine.AnimatorStateInfo::m_Tag int32_t ___m_Tag_7; // System.Int32 UnityEngine.AnimatorStateInfo::m_Loop int32_t ___m_Loop_8; public: inline static int32_t get_offset_of_m_Name_0() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Name_0)); } inline int32_t get_m_Name_0() const { return ___m_Name_0; } inline int32_t* get_address_of_m_Name_0() { return &___m_Name_0; } inline void set_m_Name_0(int32_t value) { ___m_Name_0 = value; } inline static int32_t get_offset_of_m_Path_1() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Path_1)); } inline int32_t get_m_Path_1() const { return ___m_Path_1; } inline int32_t* get_address_of_m_Path_1() { return &___m_Path_1; } inline void set_m_Path_1(int32_t value) { ___m_Path_1 = value; } inline static int32_t get_offset_of_m_FullPath_2() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_FullPath_2)); } inline int32_t get_m_FullPath_2() const { return ___m_FullPath_2; } inline int32_t* get_address_of_m_FullPath_2() { return &___m_FullPath_2; } inline void set_m_FullPath_2(int32_t value) { ___m_FullPath_2 = value; } inline static int32_t get_offset_of_m_NormalizedTime_3() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_NormalizedTime_3)); } inline float get_m_NormalizedTime_3() const { return ___m_NormalizedTime_3; } inline float* get_address_of_m_NormalizedTime_3() { return &___m_NormalizedTime_3; } inline void set_m_NormalizedTime_3(float value) { ___m_NormalizedTime_3 = value; } inline static int32_t get_offset_of_m_Length_4() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Length_4)); } inline float get_m_Length_4() const { return ___m_Length_4; } inline float* get_address_of_m_Length_4() { return &___m_Length_4; } inline void set_m_Length_4(float value) { ___m_Length_4 = value; } inline static int32_t get_offset_of_m_Speed_5() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Speed_5)); } inline float get_m_Speed_5() const { return ___m_Speed_5; } inline float* get_address_of_m_Speed_5() { return &___m_Speed_5; } inline void set_m_Speed_5(float value) { ___m_Speed_5 = value; } inline static int32_t get_offset_of_m_SpeedMultiplier_6() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_SpeedMultiplier_6)); } inline float get_m_SpeedMultiplier_6() const { return ___m_SpeedMultiplier_6; } inline float* get_address_of_m_SpeedMultiplier_6() { return &___m_SpeedMultiplier_6; } inline void set_m_SpeedMultiplier_6(float value) { ___m_SpeedMultiplier_6 = value; } inline static int32_t get_offset_of_m_Tag_7() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Tag_7)); } inline int32_t get_m_Tag_7() const { return ___m_Tag_7; } inline int32_t* get_address_of_m_Tag_7() { return &___m_Tag_7; } inline void set_m_Tag_7(int32_t value) { ___m_Tag_7 = value; } inline static int32_t get_offset_of_m_Loop_8() { return static_cast(offsetof(AnimatorStateInfo_t3042152932, ___m_Loop_8)); } inline int32_t get_m_Loop_8() const { return ___m_Loop_8; } inline int32_t* get_address_of_m_Loop_8() { return &___m_Loop_8; } inline void set_m_Loop_8(int32_t value) { ___m_Loop_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ANIMATORSTATEINFO_T3042152932_H #ifndef VECTOR4_T4108915337_H #define VECTOR4_T4108915337_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector4 struct Vector4_t4108915337 { public: // System.Single UnityEngine.Vector4::x float ___x_1; // System.Single UnityEngine.Vector4::y float ___y_2; // System.Single UnityEngine.Vector4::z float ___z_3; // System.Single UnityEngine.Vector4::w float ___w_4; public: inline static int32_t get_offset_of_x_1() { return static_cast(offsetof(Vector4_t4108915337, ___x_1)); } inline float get_x_1() const { return ___x_1; } inline float* get_address_of_x_1() { return &___x_1; } inline void set_x_1(float value) { ___x_1 = value; } inline static int32_t get_offset_of_y_2() { return static_cast(offsetof(Vector4_t4108915337, ___y_2)); } inline float get_y_2() const { return ___y_2; } inline float* get_address_of_y_2() { return &___y_2; } inline void set_y_2(float value) { ___y_2 = value; } inline static int32_t get_offset_of_z_3() { return static_cast(offsetof(Vector4_t4108915337, ___z_3)); } inline float get_z_3() const { return ___z_3; } inline float* get_address_of_z_3() { return &___z_3; } inline void set_z_3(float value) { ___z_3 = value; } inline static int32_t get_offset_of_w_4() { return static_cast(offsetof(Vector4_t4108915337, ___w_4)); } inline float get_w_4() const { return ___w_4; } inline float* get_address_of_w_4() { return &___w_4; } inline void set_w_4(float value) { ___w_4 = value; } }; struct Vector4_t4108915337_StaticFields { public: // UnityEngine.Vector4 UnityEngine.Vector4::zeroVector Vector4_t4108915337 ___zeroVector_5; // UnityEngine.Vector4 UnityEngine.Vector4::oneVector Vector4_t4108915337 ___oneVector_6; // UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector Vector4_t4108915337 ___positiveInfinityVector_7; // UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector Vector4_t4108915337 ___negativeInfinityVector_8; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast(offsetof(Vector4_t4108915337_StaticFields, ___zeroVector_5)); } inline Vector4_t4108915337 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector4_t4108915337 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector4_t4108915337 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast(offsetof(Vector4_t4108915337_StaticFields, ___oneVector_6)); } inline Vector4_t4108915337 get_oneVector_6() const { return ___oneVector_6; } inline Vector4_t4108915337 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector4_t4108915337 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_positiveInfinityVector_7() { return static_cast(offsetof(Vector4_t4108915337_StaticFields, ___positiveInfinityVector_7)); } inline Vector4_t4108915337 get_positiveInfinityVector_7() const { return ___positiveInfinityVector_7; } inline Vector4_t4108915337 * get_address_of_positiveInfinityVector_7() { return &___positiveInfinityVector_7; } inline void set_positiveInfinityVector_7(Vector4_t4108915337 value) { ___positiveInfinityVector_7 = value; } inline static int32_t get_offset_of_negativeInfinityVector_8() { return static_cast(offsetof(Vector4_t4108915337_StaticFields, ___negativeInfinityVector_8)); } inline Vector4_t4108915337 get_negativeInfinityVector_8() const { return ___negativeInfinityVector_8; } inline Vector4_t4108915337 * get_address_of_negativeInfinityVector_8() { return &___negativeInfinityVector_8; } inline void set_negativeInfinityVector_8(Vector4_t4108915337 value) { ___negativeInfinityVector_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR4_T4108915337_H #ifndef SORTINGLAYER_T3174227707_H #define SORTINGLAYER_T3174227707_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SortingLayer struct SortingLayer_t3174227707 { public: // System.Int32 UnityEngine.SortingLayer::m_Id int32_t ___m_Id_0; public: inline static int32_t get_offset_of_m_Id_0() { return static_cast(offsetof(SortingLayer_t3174227707, ___m_Id_0)); } inline int32_t get_m_Id_0() const { return ___m_Id_0; } inline int32_t* get_address_of_m_Id_0() { return &___m_Id_0; } inline void set_m_Id_0(int32_t value) { ___m_Id_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SORTINGLAYER_T3174227707_H #ifndef UINT32_T2977936117_H #define UINT32_T2977936117_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt32 struct UInt32_t2977936117 { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(UInt32_t2977936117, ___m_value_2)); } inline uint32_t get_m_value_2() const { return ___m_value_2; } inline uint32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT32_T2977936117_H #ifndef ENUMERATOR_T3520049488_H #define ENUMERATOR_T3520049488_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1/Enumerator struct Enumerator_t3520049488 { public: // System.Collections.Generic.List`1 System.Collections.Generic.List`1/Enumerator::l List_1_t1831767026 * ___l_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::next int32_t ___next_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::ver int32_t ___ver_2; // T System.Collections.Generic.List`1/Enumerator::current RuntimeObject * ___current_3; public: inline static int32_t get_offset_of_l_0() { return static_cast(offsetof(Enumerator_t3520049488, ___l_0)); } inline List_1_t1831767026 * get_l_0() const { return ___l_0; } inline List_1_t1831767026 ** get_address_of_l_0() { return &___l_0; } inline void set_l_0(List_1_t1831767026 * value) { ___l_0 = value; Il2CppCodeGenWriteBarrier((&___l_0), value); } inline static int32_t get_offset_of_next_1() { return static_cast(offsetof(Enumerator_t3520049488, ___next_1)); } inline int32_t get_next_1() const { return ___next_1; } inline int32_t* get_address_of_next_1() { return &___next_1; } inline void set_next_1(int32_t value) { ___next_1 = value; } inline static int32_t get_offset_of_ver_2() { return static_cast(offsetof(Enumerator_t3520049488, ___ver_2)); } inline int32_t get_ver_2() const { return ___ver_2; } inline int32_t* get_address_of_ver_2() { return &___ver_2; } inline void set_ver_2(int32_t value) { ___ver_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast(offsetof(Enumerator_t3520049488, ___current_3)); } inline RuntimeObject * get_current_3() const { return ___current_3; } inline RuntimeObject ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(RuntimeObject * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((&___current_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENUMERATOR_T3520049488_H #ifndef SHAREDBETWEENANIMATORSATTRIBUTE_T1365952581_H #define SHAREDBETWEENANIMATORSATTRIBUTE_T1365952581_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SharedBetweenAnimatorsAttribute struct SharedBetweenAnimatorsAttribute_t1365952581 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SHAREDBETWEENANIMATORSATTRIBUTE_T1365952581_H #ifndef ENUMERATOR_T2673088588_H #define ENUMERATOR_T2673088588_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1/Enumerator struct Enumerator_t2673088588 { public: // System.Collections.Generic.List`1 System.Collections.Generic.List`1/Enumerator::l List_1_t984806126 * ___l_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::next int32_t ___next_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::ver int32_t ___ver_2; // T System.Collections.Generic.List`1/Enumerator::current GcLeaderboard_t1761920286 * ___current_3; public: inline static int32_t get_offset_of_l_0() { return static_cast(offsetof(Enumerator_t2673088588, ___l_0)); } inline List_1_t984806126 * get_l_0() const { return ___l_0; } inline List_1_t984806126 ** get_address_of_l_0() { return &___l_0; } inline void set_l_0(List_1_t984806126 * value) { ___l_0 = value; Il2CppCodeGenWriteBarrier((&___l_0), value); } inline static int32_t get_offset_of_next_1() { return static_cast(offsetof(Enumerator_t2673088588, ___next_1)); } inline int32_t get_next_1() const { return ___next_1; } inline int32_t* get_address_of_next_1() { return &___next_1; } inline void set_next_1(int32_t value) { ___next_1 = value; } inline static int32_t get_offset_of_ver_2() { return static_cast(offsetof(Enumerator_t2673088588, ___ver_2)); } inline int32_t get_ver_2() const { return ___ver_2; } inline int32_t* get_address_of_ver_2() { return &___ver_2; } inline void set_ver_2(int32_t value) { ___ver_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast(offsetof(Enumerator_t2673088588, ___current_3)); } inline GcLeaderboard_t1761920286 * get_current_3() const { return ___current_3; } inline GcLeaderboard_t1761920286 ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(GcLeaderboard_t1761920286 * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((&___current_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENUMERATOR_T2673088588_H #ifndef INT64_T3954580378_H #define INT64_T3954580378_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int64 struct Int64_t3954580378 { public: // System.Int64 System.Int64::m_value int64_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Int64_t3954580378, ___m_value_2)); } inline int64_t get_m_value_2() const { return ___m_value_2; } inline int64_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int64_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64_T3954580378_H #ifndef DOUBLE_T2492335957_H #define DOUBLE_T2492335957_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Double struct Double_t2492335957 { public: // System.Double System.Double::m_value double ___m_value_13; public: inline static int32_t get_offset_of_m_value_13() { return static_cast(offsetof(Double_t2492335957, ___m_value_13)); } inline double get_m_value_13() const { return ___m_value_13; } inline double* get_address_of_m_value_13() { return &___m_value_13; } inline void set_m_value_13(double value) { ___m_value_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DOUBLE_T2492335957_H #ifndef GCSCOREDATA_T1096391638_H #define GCSCOREDATA_T1096391638_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t1096391638 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Category String_t* ___m_Category_0; // System.UInt32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_ValueLow uint32_t ___m_ValueLow_1; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_ValueHigh int32_t ___m_ValueHigh_2; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Date int32_t ___m_Date_3; // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_FormattedValue String_t* ___m_FormattedValue_4; // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_PlayerID String_t* ___m_PlayerID_5; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Rank int32_t ___m_Rank_6; public: inline static int32_t get_offset_of_m_Category_0() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_Category_0)); } inline String_t* get_m_Category_0() const { return ___m_Category_0; } inline String_t** get_address_of_m_Category_0() { return &___m_Category_0; } inline void set_m_Category_0(String_t* value) { ___m_Category_0 = value; Il2CppCodeGenWriteBarrier((&___m_Category_0), value); } inline static int32_t get_offset_of_m_ValueLow_1() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_ValueLow_1)); } inline uint32_t get_m_ValueLow_1() const { return ___m_ValueLow_1; } inline uint32_t* get_address_of_m_ValueLow_1() { return &___m_ValueLow_1; } inline void set_m_ValueLow_1(uint32_t value) { ___m_ValueLow_1 = value; } inline static int32_t get_offset_of_m_ValueHigh_2() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_ValueHigh_2)); } inline int32_t get_m_ValueHigh_2() const { return ___m_ValueHigh_2; } inline int32_t* get_address_of_m_ValueHigh_2() { return &___m_ValueHigh_2; } inline void set_m_ValueHigh_2(int32_t value) { ___m_ValueHigh_2 = value; } inline static int32_t get_offset_of_m_Date_3() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_Date_3)); } inline int32_t get_m_Date_3() const { return ___m_Date_3; } inline int32_t* get_address_of_m_Date_3() { return &___m_Date_3; } inline void set_m_Date_3(int32_t value) { ___m_Date_3 = value; } inline static int32_t get_offset_of_m_FormattedValue_4() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_FormattedValue_4)); } inline String_t* get_m_FormattedValue_4() const { return ___m_FormattedValue_4; } inline String_t** get_address_of_m_FormattedValue_4() { return &___m_FormattedValue_4; } inline void set_m_FormattedValue_4(String_t* value) { ___m_FormattedValue_4 = value; Il2CppCodeGenWriteBarrier((&___m_FormattedValue_4), value); } inline static int32_t get_offset_of_m_PlayerID_5() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_PlayerID_5)); } inline String_t* get_m_PlayerID_5() const { return ___m_PlayerID_5; } inline String_t** get_address_of_m_PlayerID_5() { return &___m_PlayerID_5; } inline void set_m_PlayerID_5(String_t* value) { ___m_PlayerID_5 = value; Il2CppCodeGenWriteBarrier((&___m_PlayerID_5), value); } inline static int32_t get_offset_of_m_Rank_6() { return static_cast(offsetof(GcScoreData_t1096391638, ___m_Rank_6)); } inline int32_t get_m_Rank_6() const { return ___m_Rank_6; } inline int32_t* get_address_of_m_Rank_6() { return &___m_Rank_6; } inline void set_m_Rank_6(int32_t value) { ___m_Rank_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t1096391638_marshaled_pinvoke { char* ___m_Category_0; uint32_t ___m_ValueLow_1; int32_t ___m_ValueHigh_2; int32_t ___m_Date_3; char* ___m_FormattedValue_4; char* ___m_PlayerID_5; int32_t ___m_Rank_6; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t1096391638_marshaled_com { Il2CppChar* ___m_Category_0; uint32_t ___m_ValueLow_1; int32_t ___m_ValueHigh_2; int32_t ___m_Date_3; Il2CppChar* ___m_FormattedValue_4; Il2CppChar* ___m_PlayerID_5; int32_t ___m_Rank_6; }; #endif // GCSCOREDATA_T1096391638_H #ifndef GCACHIEVEMENTDATA_T3004100478_H #define GCACHIEVEMENTDATA_T3004100478_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t3004100478 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Identifier String_t* ___m_Identifier_0; // System.Double UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_PercentCompleted double ___m_PercentCompleted_1; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Completed int32_t ___m_Completed_2; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Hidden int32_t ___m_Hidden_3; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_LastReportedDate int32_t ___m_LastReportedDate_4; public: inline static int32_t get_offset_of_m_Identifier_0() { return static_cast(offsetof(GcAchievementData_t3004100478, ___m_Identifier_0)); } inline String_t* get_m_Identifier_0() const { return ___m_Identifier_0; } inline String_t** get_address_of_m_Identifier_0() { return &___m_Identifier_0; } inline void set_m_Identifier_0(String_t* value) { ___m_Identifier_0 = value; Il2CppCodeGenWriteBarrier((&___m_Identifier_0), value); } inline static int32_t get_offset_of_m_PercentCompleted_1() { return static_cast(offsetof(GcAchievementData_t3004100478, ___m_PercentCompleted_1)); } inline double get_m_PercentCompleted_1() const { return ___m_PercentCompleted_1; } inline double* get_address_of_m_PercentCompleted_1() { return &___m_PercentCompleted_1; } inline void set_m_PercentCompleted_1(double value) { ___m_PercentCompleted_1 = value; } inline static int32_t get_offset_of_m_Completed_2() { return static_cast(offsetof(GcAchievementData_t3004100478, ___m_Completed_2)); } inline int32_t get_m_Completed_2() const { return ___m_Completed_2; } inline int32_t* get_address_of_m_Completed_2() { return &___m_Completed_2; } inline void set_m_Completed_2(int32_t value) { ___m_Completed_2 = value; } inline static int32_t get_offset_of_m_Hidden_3() { return static_cast(offsetof(GcAchievementData_t3004100478, ___m_Hidden_3)); } inline int32_t get_m_Hidden_3() const { return ___m_Hidden_3; } inline int32_t* get_address_of_m_Hidden_3() { return &___m_Hidden_3; } inline void set_m_Hidden_3(int32_t value) { ___m_Hidden_3 = value; } inline static int32_t get_offset_of_m_LastReportedDate_4() { return static_cast(offsetof(GcAchievementData_t3004100478, ___m_LastReportedDate_4)); } inline int32_t get_m_LastReportedDate_4() const { return ___m_LastReportedDate_4; } inline int32_t* get_address_of_m_LastReportedDate_4() { return &___m_LastReportedDate_4; } inline void set_m_LastReportedDate_4(int32_t value) { ___m_LastReportedDate_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t3004100478_marshaled_pinvoke { char* ___m_Identifier_0; double ___m_PercentCompleted_1; int32_t ___m_Completed_2; int32_t ___m_Hidden_3; int32_t ___m_LastReportedDate_4; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t3004100478_marshaled_com { Il2CppChar* ___m_Identifier_0; double ___m_PercentCompleted_1; int32_t ___m_Completed_2; int32_t ___m_Hidden_3; int32_t ___m_LastReportedDate_4; }; #endif // GCACHIEVEMENTDATA_T3004100478_H #ifndef GCUSERPROFILEDATA_T265536658_H #define GCUSERPROFILEDATA_T265536658_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData struct GcUserProfileData_t265536658 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::userName String_t* ___userName_0; // System.String UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::userID String_t* ___userID_1; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::isFriend int32_t ___isFriend_2; // UnityEngine.Texture2D UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::image Texture2D_t1384570725 * ___image_3; public: inline static int32_t get_offset_of_userName_0() { return static_cast(offsetof(GcUserProfileData_t265536658, ___userName_0)); } inline String_t* get_userName_0() const { return ___userName_0; } inline String_t** get_address_of_userName_0() { return &___userName_0; } inline void set_userName_0(String_t* value) { ___userName_0 = value; Il2CppCodeGenWriteBarrier((&___userName_0), value); } inline static int32_t get_offset_of_userID_1() { return static_cast(offsetof(GcUserProfileData_t265536658, ___userID_1)); } inline String_t* get_userID_1() const { return ___userID_1; } inline String_t** get_address_of_userID_1() { return &___userID_1; } inline void set_userID_1(String_t* value) { ___userID_1 = value; Il2CppCodeGenWriteBarrier((&___userID_1), value); } inline static int32_t get_offset_of_isFriend_2() { return static_cast(offsetof(GcUserProfileData_t265536658, ___isFriend_2)); } inline int32_t get_isFriend_2() const { return ___isFriend_2; } inline int32_t* get_address_of_isFriend_2() { return &___isFriend_2; } inline void set_isFriend_2(int32_t value) { ___isFriend_2 = value; } inline static int32_t get_offset_of_image_3() { return static_cast(offsetof(GcUserProfileData_t265536658, ___image_3)); } inline Texture2D_t1384570725 * get_image_3() const { return ___image_3; } inline Texture2D_t1384570725 ** get_address_of_image_3() { return &___image_3; } inline void set_image_3(Texture2D_t1384570725 * value) { ___image_3 = value; Il2CppCodeGenWriteBarrier((&___image_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData struct GcUserProfileData_t265536658_marshaled_pinvoke { char* ___userName_0; char* ___userID_1; int32_t ___isFriend_2; Texture2D_t1384570725 * ___image_3; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData struct GcUserProfileData_t265536658_marshaled_com { Il2CppChar* ___userName_0; Il2CppChar* ___userID_1; int32_t ___isFriend_2; Texture2D_t1384570725 * ___image_3; }; #endif // GCUSERPROFILEDATA_T265536658_H #ifndef GCACHIEVEMENTDESCRIPTIONDATA_T1960457254_H #define GCACHIEVEMENTDESCRIPTIONDATA_T1960457254_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData struct GcAchievementDescriptionData_t1960457254 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_Identifier String_t* ___m_Identifier_0; // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_Title String_t* ___m_Title_1; // UnityEngine.Texture2D UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_Image Texture2D_t1384570725 * ___m_Image_2; // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_AchievedDescription String_t* ___m_AchievedDescription_3; // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_UnachievedDescription String_t* ___m_UnachievedDescription_4; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_Hidden int32_t ___m_Hidden_5; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::m_Points int32_t ___m_Points_6; public: inline static int32_t get_offset_of_m_Identifier_0() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_Identifier_0)); } inline String_t* get_m_Identifier_0() const { return ___m_Identifier_0; } inline String_t** get_address_of_m_Identifier_0() { return &___m_Identifier_0; } inline void set_m_Identifier_0(String_t* value) { ___m_Identifier_0 = value; Il2CppCodeGenWriteBarrier((&___m_Identifier_0), value); } inline static int32_t get_offset_of_m_Title_1() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_Title_1)); } inline String_t* get_m_Title_1() const { return ___m_Title_1; } inline String_t** get_address_of_m_Title_1() { return &___m_Title_1; } inline void set_m_Title_1(String_t* value) { ___m_Title_1 = value; Il2CppCodeGenWriteBarrier((&___m_Title_1), value); } inline static int32_t get_offset_of_m_Image_2() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_Image_2)); } inline Texture2D_t1384570725 * get_m_Image_2() const { return ___m_Image_2; } inline Texture2D_t1384570725 ** get_address_of_m_Image_2() { return &___m_Image_2; } inline void set_m_Image_2(Texture2D_t1384570725 * value) { ___m_Image_2 = value; Il2CppCodeGenWriteBarrier((&___m_Image_2), value); } inline static int32_t get_offset_of_m_AchievedDescription_3() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_AchievedDescription_3)); } inline String_t* get_m_AchievedDescription_3() const { return ___m_AchievedDescription_3; } inline String_t** get_address_of_m_AchievedDescription_3() { return &___m_AchievedDescription_3; } inline void set_m_AchievedDescription_3(String_t* value) { ___m_AchievedDescription_3 = value; Il2CppCodeGenWriteBarrier((&___m_AchievedDescription_3), value); } inline static int32_t get_offset_of_m_UnachievedDescription_4() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_UnachievedDescription_4)); } inline String_t* get_m_UnachievedDescription_4() const { return ___m_UnachievedDescription_4; } inline String_t** get_address_of_m_UnachievedDescription_4() { return &___m_UnachievedDescription_4; } inline void set_m_UnachievedDescription_4(String_t* value) { ___m_UnachievedDescription_4 = value; Il2CppCodeGenWriteBarrier((&___m_UnachievedDescription_4), value); } inline static int32_t get_offset_of_m_Hidden_5() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_Hidden_5)); } inline int32_t get_m_Hidden_5() const { return ___m_Hidden_5; } inline int32_t* get_address_of_m_Hidden_5() { return &___m_Hidden_5; } inline void set_m_Hidden_5(int32_t value) { ___m_Hidden_5 = value; } inline static int32_t get_offset_of_m_Points_6() { return static_cast(offsetof(GcAchievementDescriptionData_t1960457254, ___m_Points_6)); } inline int32_t get_m_Points_6() const { return ___m_Points_6; } inline int32_t* get_address_of_m_Points_6() { return &___m_Points_6; } inline void set_m_Points_6(int32_t value) { ___m_Points_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData struct GcAchievementDescriptionData_t1960457254_marshaled_pinvoke { char* ___m_Identifier_0; char* ___m_Title_1; Texture2D_t1384570725 * ___m_Image_2; char* ___m_AchievedDescription_3; char* ___m_UnachievedDescription_4; int32_t ___m_Hidden_5; int32_t ___m_Points_6; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData struct GcAchievementDescriptionData_t1960457254_marshaled_com { Il2CppChar* ___m_Identifier_0; Il2CppChar* ___m_Title_1; Texture2D_t1384570725 * ___m_Image_2; Il2CppChar* ___m_AchievedDescription_3; Il2CppChar* ___m_UnachievedDescription_4; int32_t ___m_Hidden_5; int32_t ___m_Points_6; }; #endif // GCACHIEVEMENTDESCRIPTIONDATA_T1960457254_H #ifndef RANGE_T2283206190_H #define RANGE_T2283206190_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Range struct Range_t2283206190 { public: // System.Int32 UnityEngine.SocialPlatforms.Range::from int32_t ___from_0; // System.Int32 UnityEngine.SocialPlatforms.Range::count int32_t ___count_1; public: inline static int32_t get_offset_of_from_0() { return static_cast(offsetof(Range_t2283206190, ___from_0)); } inline int32_t get_from_0() const { return ___from_0; } inline int32_t* get_address_of_from_0() { return &___from_0; } inline void set_from_0(int32_t value) { ___from_0 = value; } inline static int32_t get_offset_of_count_1() { return static_cast(offsetof(Range_t2283206190, ___count_1)); } inline int32_t get_count_1() const { return ___count_1; } inline int32_t* get_address_of_count_1() { return &___count_1; } inline void set_count_1(int32_t value) { ___count_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RANGE_T2283206190_H #ifndef SCENE_T886992912_H #define SCENE_T886992912_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SceneManagement.Scene struct Scene_t886992912 { public: // System.Int32 UnityEngine.SceneManagement.Scene::m_Handle int32_t ___m_Handle_0; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(Scene_t886992912, ___m_Handle_0)); } inline int32_t get_m_Handle_0() const { return ___m_Handle_0; } inline int32_t* get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(int32_t value) { ___m_Handle_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCENE_T886992912_H #ifndef PARAMETERMODIFIER_T2814373913_H #define PARAMETERMODIFIER_T2814373913_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.ParameterModifier struct ParameterModifier_t2814373913 { public: // System.Boolean[] System.Reflection.ParameterModifier::_byref BooleanU5BU5D_t822121321* ____byref_0; public: inline static int32_t get_offset_of__byref_0() { return static_cast(offsetof(ParameterModifier_t2814373913, ____byref_0)); } inline BooleanU5BU5D_t822121321* get__byref_0() const { return ____byref_0; } inline BooleanU5BU5D_t822121321** get_address_of__byref_0() { return &____byref_0; } inline void set__byref_0(BooleanU5BU5D_t822121321* value) { ____byref_0 = value; Il2CppCodeGenWriteBarrier((&____byref_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.ParameterModifier struct ParameterModifier_t2814373913_marshaled_pinvoke { int32_t* ____byref_0; }; // Native definition for COM marshalling of System.Reflection.ParameterModifier struct ParameterModifier_t2814373913_marshaled_com { int32_t* ____byref_0; }; #endif // PARAMETERMODIFIER_T2814373913_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero IntPtr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline IntPtr_t get_Zero_1() const { return ___Zero_1; } inline IntPtr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(IntPtr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef VECTOR3_T67624592_H #define VECTOR3_T67624592_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector3 struct Vector3_t67624592 { public: // System.Single UnityEngine.Vector3::x float ___x_1; // System.Single UnityEngine.Vector3::y float ___y_2; // System.Single UnityEngine.Vector3::z float ___z_3; public: inline static int32_t get_offset_of_x_1() { return static_cast(offsetof(Vector3_t67624592, ___x_1)); } inline float get_x_1() const { return ___x_1; } inline float* get_address_of_x_1() { return &___x_1; } inline void set_x_1(float value) { ___x_1 = value; } inline static int32_t get_offset_of_y_2() { return static_cast(offsetof(Vector3_t67624592, ___y_2)); } inline float get_y_2() const { return ___y_2; } inline float* get_address_of_y_2() { return &___y_2; } inline void set_y_2(float value) { ___y_2 = value; } inline static int32_t get_offset_of_z_3() { return static_cast(offsetof(Vector3_t67624592, ___z_3)); } inline float get_z_3() const { return ___z_3; } inline float* get_address_of_z_3() { return &___z_3; } inline void set_z_3(float value) { ___z_3 = value; } }; struct Vector3_t67624592_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_t67624592 ___zeroVector_4; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_t67624592 ___oneVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_t67624592 ___upVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_t67624592 ___downVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_t67624592 ___leftVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_t67624592 ___rightVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_t67624592 ___forwardVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_t67624592 ___backVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_t67624592 ___positiveInfinityVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_t67624592 ___negativeInfinityVector_13; public: inline static int32_t get_offset_of_zeroVector_4() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___zeroVector_4)); } inline Vector3_t67624592 get_zeroVector_4() const { return ___zeroVector_4; } inline Vector3_t67624592 * get_address_of_zeroVector_4() { return &___zeroVector_4; } inline void set_zeroVector_4(Vector3_t67624592 value) { ___zeroVector_4 = value; } inline static int32_t get_offset_of_oneVector_5() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___oneVector_5)); } inline Vector3_t67624592 get_oneVector_5() const { return ___oneVector_5; } inline Vector3_t67624592 * get_address_of_oneVector_5() { return &___oneVector_5; } inline void set_oneVector_5(Vector3_t67624592 value) { ___oneVector_5 = value; } inline static int32_t get_offset_of_upVector_6() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___upVector_6)); } inline Vector3_t67624592 get_upVector_6() const { return ___upVector_6; } inline Vector3_t67624592 * get_address_of_upVector_6() { return &___upVector_6; } inline void set_upVector_6(Vector3_t67624592 value) { ___upVector_6 = value; } inline static int32_t get_offset_of_downVector_7() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___downVector_7)); } inline Vector3_t67624592 get_downVector_7() const { return ___downVector_7; } inline Vector3_t67624592 * get_address_of_downVector_7() { return &___downVector_7; } inline void set_downVector_7(Vector3_t67624592 value) { ___downVector_7 = value; } inline static int32_t get_offset_of_leftVector_8() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___leftVector_8)); } inline Vector3_t67624592 get_leftVector_8() const { return ___leftVector_8; } inline Vector3_t67624592 * get_address_of_leftVector_8() { return &___leftVector_8; } inline void set_leftVector_8(Vector3_t67624592 value) { ___leftVector_8 = value; } inline static int32_t get_offset_of_rightVector_9() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___rightVector_9)); } inline Vector3_t67624592 get_rightVector_9() const { return ___rightVector_9; } inline Vector3_t67624592 * get_address_of_rightVector_9() { return &___rightVector_9; } inline void set_rightVector_9(Vector3_t67624592 value) { ___rightVector_9 = value; } inline static int32_t get_offset_of_forwardVector_10() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___forwardVector_10)); } inline Vector3_t67624592 get_forwardVector_10() const { return ___forwardVector_10; } inline Vector3_t67624592 * get_address_of_forwardVector_10() { return &___forwardVector_10; } inline void set_forwardVector_10(Vector3_t67624592 value) { ___forwardVector_10 = value; } inline static int32_t get_offset_of_backVector_11() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___backVector_11)); } inline Vector3_t67624592 get_backVector_11() const { return ___backVector_11; } inline Vector3_t67624592 * get_address_of_backVector_11() { return &___backVector_11; } inline void set_backVector_11(Vector3_t67624592 value) { ___backVector_11 = value; } inline static int32_t get_offset_of_positiveInfinityVector_12() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___positiveInfinityVector_12)); } inline Vector3_t67624592 get_positiveInfinityVector_12() const { return ___positiveInfinityVector_12; } inline Vector3_t67624592 * get_address_of_positiveInfinityVector_12() { return &___positiveInfinityVector_12; } inline void set_positiveInfinityVector_12(Vector3_t67624592 value) { ___positiveInfinityVector_12 = value; } inline static int32_t get_offset_of_negativeInfinityVector_13() { return static_cast(offsetof(Vector3_t67624592_StaticFields, ___negativeInfinityVector_13)); } inline Vector3_t67624592 get_negativeInfinityVector_13() const { return ___negativeInfinityVector_13; } inline Vector3_t67624592 * get_address_of_negativeInfinityVector_13() { return &___negativeInfinityVector_13; } inline void set_negativeInfinityVector_13(Vector3_t67624592 value) { ___negativeInfinityVector_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR3_T67624592_H #ifndef REQUIRECOMPONENT_T2926973319_H #define REQUIRECOMPONENT_T2926973319_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RequireComponent struct RequireComponent_t2926973319 : public Attribute_t739646798 { public: // System.Type UnityEngine.RequireComponent::m_Type0 Type_t * ___m_Type0_0; // System.Type UnityEngine.RequireComponent::m_Type1 Type_t * ___m_Type1_1; // System.Type UnityEngine.RequireComponent::m_Type2 Type_t * ___m_Type2_2; public: inline static int32_t get_offset_of_m_Type0_0() { return static_cast(offsetof(RequireComponent_t2926973319, ___m_Type0_0)); } inline Type_t * get_m_Type0_0() const { return ___m_Type0_0; } inline Type_t ** get_address_of_m_Type0_0() { return &___m_Type0_0; } inline void set_m_Type0_0(Type_t * value) { ___m_Type0_0 = value; Il2CppCodeGenWriteBarrier((&___m_Type0_0), value); } inline static int32_t get_offset_of_m_Type1_1() { return static_cast(offsetof(RequireComponent_t2926973319, ___m_Type1_1)); } inline Type_t * get_m_Type1_1() const { return ___m_Type1_1; } inline Type_t ** get_address_of_m_Type1_1() { return &___m_Type1_1; } inline void set_m_Type1_1(Type_t * value) { ___m_Type1_1 = value; Il2CppCodeGenWriteBarrier((&___m_Type1_1), value); } inline static int32_t get_offset_of_m_Type2_2() { return static_cast(offsetof(RequireComponent_t2926973319, ___m_Type2_2)); } inline Type_t * get_m_Type2_2() const { return ___m_Type2_2; } inline Type_t ** get_address_of_m_Type2_2() { return &___m_Type2_2; } inline void set_m_Type2_2(Type_t * value) { ___m_Type2_2 = value; Il2CppCodeGenWriteBarrier((&___m_Type2_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REQUIRECOMPONENT_T2926973319_H #ifndef PROPERTYATTRIBUTE_T2314996045_H #define PROPERTYATTRIBUTE_T2314996045_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.PropertyAttribute struct PropertyAttribute_t2314996045 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PROPERTYATTRIBUTE_T2314996045_H #ifndef PREFERBINARYSERIALIZATION_T1584085608_H #define PREFERBINARYSERIALIZATION_T1584085608_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.PreferBinarySerialization struct PreferBinarySerialization_t1584085608 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PREFERBINARYSERIALIZATION_T1584085608_H #ifndef VECTOR2_T3854014517_H #define VECTOR2_T3854014517_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector2 struct Vector2_t3854014517 { public: // System.Single UnityEngine.Vector2::x float ___x_0; // System.Single UnityEngine.Vector2::y float ___y_1; public: inline static int32_t get_offset_of_x_0() { return static_cast(offsetof(Vector2_t3854014517, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast(offsetof(Vector2_t3854014517, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } }; struct Vector2_t3854014517_StaticFields { public: // UnityEngine.Vector2 UnityEngine.Vector2::zeroVector Vector2_t3854014517 ___zeroVector_2; // UnityEngine.Vector2 UnityEngine.Vector2::oneVector Vector2_t3854014517 ___oneVector_3; // UnityEngine.Vector2 UnityEngine.Vector2::upVector Vector2_t3854014517 ___upVector_4; // UnityEngine.Vector2 UnityEngine.Vector2::downVector Vector2_t3854014517 ___downVector_5; // UnityEngine.Vector2 UnityEngine.Vector2::leftVector Vector2_t3854014517 ___leftVector_6; // UnityEngine.Vector2 UnityEngine.Vector2::rightVector Vector2_t3854014517 ___rightVector_7; // UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector Vector2_t3854014517 ___positiveInfinityVector_8; // UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector Vector2_t3854014517 ___negativeInfinityVector_9; public: inline static int32_t get_offset_of_zeroVector_2() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___zeroVector_2)); } inline Vector2_t3854014517 get_zeroVector_2() const { return ___zeroVector_2; } inline Vector2_t3854014517 * get_address_of_zeroVector_2() { return &___zeroVector_2; } inline void set_zeroVector_2(Vector2_t3854014517 value) { ___zeroVector_2 = value; } inline static int32_t get_offset_of_oneVector_3() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___oneVector_3)); } inline Vector2_t3854014517 get_oneVector_3() const { return ___oneVector_3; } inline Vector2_t3854014517 * get_address_of_oneVector_3() { return &___oneVector_3; } inline void set_oneVector_3(Vector2_t3854014517 value) { ___oneVector_3 = value; } inline static int32_t get_offset_of_upVector_4() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___upVector_4)); } inline Vector2_t3854014517 get_upVector_4() const { return ___upVector_4; } inline Vector2_t3854014517 * get_address_of_upVector_4() { return &___upVector_4; } inline void set_upVector_4(Vector2_t3854014517 value) { ___upVector_4 = value; } inline static int32_t get_offset_of_downVector_5() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___downVector_5)); } inline Vector2_t3854014517 get_downVector_5() const { return ___downVector_5; } inline Vector2_t3854014517 * get_address_of_downVector_5() { return &___downVector_5; } inline void set_downVector_5(Vector2_t3854014517 value) { ___downVector_5 = value; } inline static int32_t get_offset_of_leftVector_6() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___leftVector_6)); } inline Vector2_t3854014517 get_leftVector_6() const { return ___leftVector_6; } inline Vector2_t3854014517 * get_address_of_leftVector_6() { return &___leftVector_6; } inline void set_leftVector_6(Vector2_t3854014517 value) { ___leftVector_6 = value; } inline static int32_t get_offset_of_rightVector_7() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___rightVector_7)); } inline Vector2_t3854014517 get_rightVector_7() const { return ___rightVector_7; } inline Vector2_t3854014517 * get_address_of_rightVector_7() { return &___rightVector_7; } inline void set_rightVector_7(Vector2_t3854014517 value) { ___rightVector_7 = value; } inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___positiveInfinityVector_8)); } inline Vector2_t3854014517 get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; } inline Vector2_t3854014517 * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; } inline void set_positiveInfinityVector_8(Vector2_t3854014517 value) { ___positiveInfinityVector_8 = value; } inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast(offsetof(Vector2_t3854014517_StaticFields, ___negativeInfinityVector_9)); } inline Vector2_t3854014517 get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; } inline Vector2_t3854014517 * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; } inline void set_negativeInfinityVector_9(Vector2_t3854014517 value) { ___negativeInfinityVector_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR2_T3854014517_H #ifndef RANGEINT_T772515686_H #define RANGEINT_T772515686_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RangeInt struct RangeInt_t772515686 { public: // System.Int32 UnityEngine.RangeInt::start int32_t ___start_0; // System.Int32 UnityEngine.RangeInt::length int32_t ___length_1; public: inline static int32_t get_offset_of_start_0() { return static_cast(offsetof(RangeInt_t772515686, ___start_0)); } inline int32_t get_start_0() const { return ___start_0; } inline int32_t* get_address_of_start_0() { return &___start_0; } inline void set_start_0(int32_t value) { ___start_0 = value; } inline static int32_t get_offset_of_length_1() { return static_cast(offsetof(RangeInt_t772515686, ___length_1)); } inline int32_t get_length_1() const { return ___length_1; } inline int32_t* get_address_of_length_1() { return &___length_1; } inline void set_length_1(int32_t value) { ___length_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RANGEINT_T772515686_H #ifndef INT32_T2185247404_H #define INT32_T2185247404_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t2185247404 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Int32_t2185247404, ___m_value_2)); } inline int32_t get_m_value_2() const { return ___m_value_2; } inline int32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2185247404_H #ifndef RPC_T80633788_H #define RPC_T80633788_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RPC struct RPC_t80633788 : public Attribute_t739646798 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RPC_T80633788_H #ifndef BOOLEAN_T1642230456_H #define BOOLEAN_T1642230456_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_t1642230456 { public: // System.Boolean System.Boolean::m_value bool ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Boolean_t1642230456, ___m_value_2)); } inline bool get_m_value_2() const { return ___m_value_2; } inline bool* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(bool value) { ___m_value_2 = value; } }; struct Boolean_t1642230456_StaticFields { public: // System.String System.Boolean::FalseString String_t* ___FalseString_0; // System.String System.Boolean::TrueString String_t* ___TrueString_1; public: inline static int32_t get_offset_of_FalseString_0() { return static_cast(offsetof(Boolean_t1642230456_StaticFields, ___FalseString_0)); } inline String_t* get_FalseString_0() const { return ___FalseString_0; } inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; } inline void set_FalseString_0(String_t* value) { ___FalseString_0 = value; Il2CppCodeGenWriteBarrier((&___FalseString_0), value); } inline static int32_t get_offset_of_TrueString_1() { return static_cast(offsetof(Boolean_t1642230456_StaticFields, ___TrueString_1)); } inline String_t* get_TrueString_1() const { return ___TrueString_1; } inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; } inline void set_TrueString_1(String_t* value) { ___TrueString_1 = value; Il2CppCodeGenWriteBarrier((&___TrueString_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T1642230456_H #ifndef VOID_T1901624353_H #define VOID_T1901624353_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1901624353 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1901624353_H #ifndef QUATERNION_T4184531171_H #define QUATERNION_T4184531171_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Quaternion struct Quaternion_t4184531171 { public: // System.Single UnityEngine.Quaternion::x float ___x_0; // System.Single UnityEngine.Quaternion::y float ___y_1; // System.Single UnityEngine.Quaternion::z float ___z_2; // System.Single UnityEngine.Quaternion::w float ___w_3; public: inline static int32_t get_offset_of_x_0() { return static_cast(offsetof(Quaternion_t4184531171, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast(offsetof(Quaternion_t4184531171, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } inline static int32_t get_offset_of_z_2() { return static_cast(offsetof(Quaternion_t4184531171, ___z_2)); } inline float get_z_2() const { return ___z_2; } inline float* get_address_of_z_2() { return &___z_2; } inline void set_z_2(float value) { ___z_2 = value; } inline static int32_t get_offset_of_w_3() { return static_cast(offsetof(Quaternion_t4184531171, ___w_3)); } inline float get_w_3() const { return ___w_3; } inline float* get_address_of_w_3() { return &___w_3; } inline void set_w_3(float value) { ___w_3 = value; } }; struct Quaternion_t4184531171_StaticFields { public: // UnityEngine.Quaternion UnityEngine.Quaternion::identityQuaternion Quaternion_t4184531171 ___identityQuaternion_4; public: inline static int32_t get_offset_of_identityQuaternion_4() { return static_cast(offsetof(Quaternion_t4184531171_StaticFields, ___identityQuaternion_4)); } inline Quaternion_t4184531171 get_identityQuaternion_4() const { return ___identityQuaternion_4; } inline Quaternion_t4184531171 * get_address_of_identityQuaternion_4() { return &___identityQuaternion_4; } inline void set_identityQuaternion_4(Quaternion_t4184531171 value) { ___identityQuaternion_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // QUATERNION_T4184531171_H #ifndef SINGLE_T3320337292_H #define SINGLE_T3320337292_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Single struct Single_t3320337292 { public: // System.Single System.Single::m_value float ___m_value_7; public: inline static int32_t get_offset_of_m_value_7() { return static_cast(offsetof(Single_t3320337292, ___m_value_7)); } inline float get_m_value_7() const { return ___m_value_7; } inline float* get_address_of_m_value_7() { return &___m_value_7; } inline void set_m_value_7(float value) { ___m_value_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLE_T3320337292_H #ifndef RECT_T3345319094_H #define RECT_T3345319094_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rect struct Rect_t3345319094 { public: // System.Single UnityEngine.Rect::m_XMin float ___m_XMin_0; // System.Single UnityEngine.Rect::m_YMin float ___m_YMin_1; // System.Single UnityEngine.Rect::m_Width float ___m_Width_2; // System.Single UnityEngine.Rect::m_Height float ___m_Height_3; public: inline static int32_t get_offset_of_m_XMin_0() { return static_cast(offsetof(Rect_t3345319094, ___m_XMin_0)); } inline float get_m_XMin_0() const { return ___m_XMin_0; } inline float* get_address_of_m_XMin_0() { return &___m_XMin_0; } inline void set_m_XMin_0(float value) { ___m_XMin_0 = value; } inline static int32_t get_offset_of_m_YMin_1() { return static_cast(offsetof(Rect_t3345319094, ___m_YMin_1)); } inline float get_m_YMin_1() const { return ___m_YMin_1; } inline float* get_address_of_m_YMin_1() { return &___m_YMin_1; } inline void set_m_YMin_1(float value) { ___m_YMin_1 = value; } inline static int32_t get_offset_of_m_Width_2() { return static_cast(offsetof(Rect_t3345319094, ___m_Width_2)); } inline float get_m_Width_2() const { return ___m_Width_2; } inline float* get_address_of_m_Width_2() { return &___m_Width_2; } inline void set_m_Width_2(float value) { ___m_Width_2 = value; } inline static int32_t get_offset_of_m_Height_3() { return static_cast(offsetof(Rect_t3345319094, ___m_Height_3)); } inline float get_m_Height_3() const { return ___m_Height_3; } inline float* get_address_of_m_Height_3() { return &___m_Height_3; } inline void set_m_Height_3(float value) { ___m_Height_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RECT_T3345319094_H #ifndef RAY_T3058960190_H #define RAY_T3058960190_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Ray struct Ray_t3058960190 { public: // UnityEngine.Vector3 UnityEngine.Ray::m_Origin Vector3_t67624592 ___m_Origin_0; // UnityEngine.Vector3 UnityEngine.Ray::m_Direction Vector3_t67624592 ___m_Direction_1; public: inline static int32_t get_offset_of_m_Origin_0() { return static_cast(offsetof(Ray_t3058960190, ___m_Origin_0)); } inline Vector3_t67624592 get_m_Origin_0() const { return ___m_Origin_0; } inline Vector3_t67624592 * get_address_of_m_Origin_0() { return &___m_Origin_0; } inline void set_m_Origin_0(Vector3_t67624592 value) { ___m_Origin_0 = value; } inline static int32_t get_offset_of_m_Direction_1() { return static_cast(offsetof(Ray_t3058960190, ___m_Direction_1)); } inline Vector3_t67624592 get_m_Direction_1() const { return ___m_Direction_1; } inline Vector3_t67624592 * get_address_of_m_Direction_1() { return &___m_Direction_1; } inline void set_m_Direction_1(Vector3_t67624592 value) { ___m_Direction_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RAY_T3058960190_H #ifndef RAYCASTHIT_T254327561_H #define RAYCASTHIT_T254327561_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RaycastHit struct RaycastHit_t254327561 { public: // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Point Vector3_t67624592 ___m_Point_0; // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Normal Vector3_t67624592 ___m_Normal_1; // System.Int32 UnityEngine.RaycastHit::m_FaceID int32_t ___m_FaceID_2; // System.Single UnityEngine.RaycastHit::m_Distance float ___m_Distance_3; // UnityEngine.Vector2 UnityEngine.RaycastHit::m_UV Vector2_t3854014517 ___m_UV_4; // UnityEngine.Collider UnityEngine.RaycastHit::m_Collider Collider_t3058509131 * ___m_Collider_5; public: inline static int32_t get_offset_of_m_Point_0() { return static_cast(offsetof(RaycastHit_t254327561, ___m_Point_0)); } inline Vector3_t67624592 get_m_Point_0() const { return ___m_Point_0; } inline Vector3_t67624592 * get_address_of_m_Point_0() { return &___m_Point_0; } inline void set_m_Point_0(Vector3_t67624592 value) { ___m_Point_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast(offsetof(RaycastHit_t254327561, ___m_Normal_1)); } inline Vector3_t67624592 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_t67624592 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_t67624592 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_FaceID_2() { return static_cast(offsetof(RaycastHit_t254327561, ___m_FaceID_2)); } inline int32_t get_m_FaceID_2() const { return ___m_FaceID_2; } inline int32_t* get_address_of_m_FaceID_2() { return &___m_FaceID_2; } inline void set_m_FaceID_2(int32_t value) { ___m_FaceID_2 = value; } inline static int32_t get_offset_of_m_Distance_3() { return static_cast(offsetof(RaycastHit_t254327561, ___m_Distance_3)); } inline float get_m_Distance_3() const { return ___m_Distance_3; } inline float* get_address_of_m_Distance_3() { return &___m_Distance_3; } inline void set_m_Distance_3(float value) { ___m_Distance_3 = value; } inline static int32_t get_offset_of_m_UV_4() { return static_cast(offsetof(RaycastHit_t254327561, ___m_UV_4)); } inline Vector2_t3854014517 get_m_UV_4() const { return ___m_UV_4; } inline Vector2_t3854014517 * get_address_of_m_UV_4() { return &___m_UV_4; } inline void set_m_UV_4(Vector2_t3854014517 value) { ___m_UV_4 = value; } inline static int32_t get_offset_of_m_Collider_5() { return static_cast(offsetof(RaycastHit_t254327561, ___m_Collider_5)); } inline Collider_t3058509131 * get_m_Collider_5() const { return ___m_Collider_5; } inline Collider_t3058509131 ** get_address_of_m_Collider_5() { return &___m_Collider_5; } inline void set_m_Collider_5(Collider_t3058509131 * value) { ___m_Collider_5 = value; Il2CppCodeGenWriteBarrier((&___m_Collider_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.RaycastHit struct RaycastHit_t254327561_marshaled_pinvoke { Vector3_t67624592 ___m_Point_0; Vector3_t67624592 ___m_Normal_1; int32_t ___m_FaceID_2; float ___m_Distance_3; Vector2_t3854014517 ___m_UV_4; Collider_t3058509131 * ___m_Collider_5; }; // Native definition for COM marshalling of UnityEngine.RaycastHit struct RaycastHit_t254327561_marshaled_com { Vector3_t67624592 ___m_Point_0; Vector3_t67624592 ___m_Normal_1; int32_t ___m_FaceID_2; float ___m_Distance_3; Vector2_t3854014517 ___m_UV_4; Collider_t3058509131 * ___m_Collider_5; }; #endif // RAYCASTHIT_T254327561_H #ifndef RUNTIMEPLATFORM_T2755064529_H #define RUNTIMEPLATFORM_T2755064529_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RuntimePlatform struct RuntimePlatform_t2755064529 { public: // System.Int32 UnityEngine.RuntimePlatform::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(RuntimePlatform_t2755064529, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEPLATFORM_T2755064529_H #ifndef LOADSCENEMODE_T1017499915_H #define LOADSCENEMODE_T1017499915_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SceneManagement.LoadSceneMode struct LoadSceneMode_t1017499915 { public: // System.Int32 UnityEngine.SceneManagement.LoadSceneMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(LoadSceneMode_t1017499915, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOADSCENEMODE_T1017499915_H #ifndef SPACEATTRIBUTE_T1419322499_H #define SPACEATTRIBUTE_T1419322499_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SpaceAttribute struct SpaceAttribute_t1419322499 : public PropertyAttribute_t2314996045 { public: // System.Single UnityEngine.SpaceAttribute::height float ___height_0; public: inline static int32_t get_offset_of_height_0() { return static_cast(offsetof(SpaceAttribute_t1419322499, ___height_0)); } inline float get_height_0() const { return ___height_0; } inline float* get_address_of_height_0() { return &___height_0; } inline void set_height_0(float value) { ___height_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SPACEATTRIBUTE_T1419322499_H #ifndef SPACE_T2088309879_H #define SPACE_T2088309879_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Space struct Space_t2088309879 { public: // System.Int32 UnityEngine.Space::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(Space_t2088309879, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SPACE_T2088309879_H #ifndef USERSTATE_T2255672114_H #define USERSTATE_T2255672114_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.UserState struct UserState_t2255672114 { public: // System.Int32 UnityEngine.SocialPlatforms.UserState::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(UserState_t2255672114, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // USERSTATE_T2255672114_H #ifndef RAYCASTHIT2D_T3236695499_H #define RAYCASTHIT2D_T3236695499_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RaycastHit2D struct RaycastHit2D_t3236695499 { public: // UnityEngine.Vector2 UnityEngine.RaycastHit2D::m_Centroid Vector2_t3854014517 ___m_Centroid_0; // UnityEngine.Vector2 UnityEngine.RaycastHit2D::m_Point Vector2_t3854014517 ___m_Point_1; // UnityEngine.Vector2 UnityEngine.RaycastHit2D::m_Normal Vector2_t3854014517 ___m_Normal_2; // System.Single UnityEngine.RaycastHit2D::m_Distance float ___m_Distance_3; // System.Single UnityEngine.RaycastHit2D::m_Fraction float ___m_Fraction_4; // UnityEngine.Collider2D UnityEngine.RaycastHit2D::m_Collider Collider2D_t2180151806 * ___m_Collider_5; public: inline static int32_t get_offset_of_m_Centroid_0() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Centroid_0)); } inline Vector2_t3854014517 get_m_Centroid_0() const { return ___m_Centroid_0; } inline Vector2_t3854014517 * get_address_of_m_Centroid_0() { return &___m_Centroid_0; } inline void set_m_Centroid_0(Vector2_t3854014517 value) { ___m_Centroid_0 = value; } inline static int32_t get_offset_of_m_Point_1() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Point_1)); } inline Vector2_t3854014517 get_m_Point_1() const { return ___m_Point_1; } inline Vector2_t3854014517 * get_address_of_m_Point_1() { return &___m_Point_1; } inline void set_m_Point_1(Vector2_t3854014517 value) { ___m_Point_1 = value; } inline static int32_t get_offset_of_m_Normal_2() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Normal_2)); } inline Vector2_t3854014517 get_m_Normal_2() const { return ___m_Normal_2; } inline Vector2_t3854014517 * get_address_of_m_Normal_2() { return &___m_Normal_2; } inline void set_m_Normal_2(Vector2_t3854014517 value) { ___m_Normal_2 = value; } inline static int32_t get_offset_of_m_Distance_3() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Distance_3)); } inline float get_m_Distance_3() const { return ___m_Distance_3; } inline float* get_address_of_m_Distance_3() { return &___m_Distance_3; } inline void set_m_Distance_3(float value) { ___m_Distance_3 = value; } inline static int32_t get_offset_of_m_Fraction_4() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Fraction_4)); } inline float get_m_Fraction_4() const { return ___m_Fraction_4; } inline float* get_address_of_m_Fraction_4() { return &___m_Fraction_4; } inline void set_m_Fraction_4(float value) { ___m_Fraction_4 = value; } inline static int32_t get_offset_of_m_Collider_5() { return static_cast(offsetof(RaycastHit2D_t3236695499, ___m_Collider_5)); } inline Collider2D_t2180151806 * get_m_Collider_5() const { return ___m_Collider_5; } inline Collider2D_t2180151806 ** get_address_of_m_Collider_5() { return &___m_Collider_5; } inline void set_m_Collider_5(Collider2D_t2180151806 * value) { ___m_Collider_5 = value; Il2CppCodeGenWriteBarrier((&___m_Collider_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.RaycastHit2D struct RaycastHit2D_t3236695499_marshaled_pinvoke { Vector2_t3854014517 ___m_Centroid_0; Vector2_t3854014517 ___m_Point_1; Vector2_t3854014517 ___m_Normal_2; float ___m_Distance_3; float ___m_Fraction_4; Collider2D_t2180151806 * ___m_Collider_5; }; // Native definition for COM marshalling of UnityEngine.RaycastHit2D struct RaycastHit2D_t3236695499_marshaled_com { Vector2_t3854014517 ___m_Centroid_0; Vector2_t3854014517 ___m_Point_1; Vector2_t3854014517 ___m_Normal_2; float ___m_Distance_3; float ___m_Fraction_4; Collider2D_t2180151806 * ___m_Collider_5; }; #endif // RAYCASTHIT2D_T3236695499_H #ifndef TIMESCOPE_T4070455592_H #define TIMESCOPE_T4070455592_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.TimeScope struct TimeScope_t4070455592 { public: // System.Int32 UnityEngine.SocialPlatforms.TimeScope::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TimeScope_t4070455592, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESCOPE_T4070455592_H #ifndef USERSCOPE_T788576880_H #define USERSCOPE_T788576880_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.UserScope struct UserScope_t788576880 { public: // System.Int32 UnityEngine.SocialPlatforms.UserScope::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(UserScope_t788576880, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // USERSCOPE_T788576880_H #ifndef RECTOFFSET_T3582970358_H #define RECTOFFSET_T3582970358_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectOffset struct RectOffset_t3582970358 : public RuntimeObject { public: // System.IntPtr UnityEngine.RectOffset::m_Ptr IntPtr_t ___m_Ptr_0; // System.Object UnityEngine.RectOffset::m_SourceStyle RuntimeObject * ___m_SourceStyle_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(RectOffset_t3582970358, ___m_Ptr_0)); } inline IntPtr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline IntPtr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(IntPtr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_SourceStyle_1() { return static_cast(offsetof(RectOffset_t3582970358, ___m_SourceStyle_1)); } inline RuntimeObject * get_m_SourceStyle_1() const { return ___m_SourceStyle_1; } inline RuntimeObject ** get_address_of_m_SourceStyle_1() { return &___m_SourceStyle_1; } inline void set_m_SourceStyle_1(RuntimeObject * value) { ___m_SourceStyle_1 = value; Il2CppCodeGenWriteBarrier((&___m_SourceStyle_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.RectOffset struct RectOffset_t3582970358_marshaled_pinvoke { intptr_t ___m_Ptr_0; Il2CppIUnknown* ___m_SourceStyle_1; }; // Native definition for COM marshalling of UnityEngine.RectOffset struct RectOffset_t3582970358_marshaled_com { intptr_t ___m_Ptr_0; Il2CppIUnknown* ___m_SourceStyle_1; }; #endif // RECTOFFSET_T3582970358_H #ifndef GCLEADERBOARD_T1761920286_H #define GCLEADERBOARD_T1761920286_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard struct GcLeaderboard_t1761920286 : public RuntimeObject { public: // System.IntPtr UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::m_InternalLeaderboard IntPtr_t ___m_InternalLeaderboard_0; // UnityEngine.SocialPlatforms.Impl.Leaderboard UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::m_GenericLeaderboard Leaderboard_t3315266811 * ___m_GenericLeaderboard_1; public: inline static int32_t get_offset_of_m_InternalLeaderboard_0() { return static_cast(offsetof(GcLeaderboard_t1761920286, ___m_InternalLeaderboard_0)); } inline IntPtr_t get_m_InternalLeaderboard_0() const { return ___m_InternalLeaderboard_0; } inline IntPtr_t* get_address_of_m_InternalLeaderboard_0() { return &___m_InternalLeaderboard_0; } inline void set_m_InternalLeaderboard_0(IntPtr_t value) { ___m_InternalLeaderboard_0 = value; } inline static int32_t get_offset_of_m_GenericLeaderboard_1() { return static_cast(offsetof(GcLeaderboard_t1761920286, ___m_GenericLeaderboard_1)); } inline Leaderboard_t3315266811 * get_m_GenericLeaderboard_1() const { return ___m_GenericLeaderboard_1; } inline Leaderboard_t3315266811 ** get_address_of_m_GenericLeaderboard_1() { return &___m_GenericLeaderboard_1; } inline void set_m_GenericLeaderboard_1(Leaderboard_t3315266811 * value) { ___m_GenericLeaderboard_1 = value; Il2CppCodeGenWriteBarrier((&___m_GenericLeaderboard_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard struct GcLeaderboard_t1761920286_marshaled_pinvoke { intptr_t ___m_InternalLeaderboard_0; Leaderboard_t3315266811 * ___m_GenericLeaderboard_1; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard struct GcLeaderboard_t1761920286_marshaled_com { intptr_t ___m_InternalLeaderboard_0; Leaderboard_t3315266811 * ___m_GenericLeaderboard_1; }; #endif // GCLEADERBOARD_T1761920286_H #ifndef OBJECT_T1332387349_H #define OBJECT_T1332387349_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t1332387349 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr IntPtr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast(offsetof(Object_t1332387349, ___m_CachedPtr_0)); } inline IntPtr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline IntPtr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(IntPtr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t1332387349_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast(offsetof(Object_t1332387349_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t1332387349_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t1332387349_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T1332387349_H #ifndef RANGEATTRIBUTE_T90224693_H #define RANGEATTRIBUTE_T90224693_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RangeAttribute struct RangeAttribute_t90224693 : public PropertyAttribute_t2314996045 { public: // System.Single UnityEngine.RangeAttribute::min float ___min_0; // System.Single UnityEngine.RangeAttribute::max float ___max_1; public: inline static int32_t get_offset_of_min_0() { return static_cast(offsetof(RangeAttribute_t90224693, ___min_0)); } inline float get_min_0() const { return ___min_0; } inline float* get_address_of_min_0() { return &___min_0; } inline void set_min_0(float value) { ___min_0 = value; } inline static int32_t get_offset_of_max_1() { return static_cast(offsetof(RangeAttribute_t90224693, ___max_1)); } inline float get_max_1() const { return ___max_1; } inline float* get_address_of_max_1() { return &___max_1; } inline void set_max_1(float value) { ___max_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RANGEATTRIBUTE_T90224693_H #ifndef TEXTANCHOR_T517930805_H #define TEXTANCHOR_T517930805_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextAnchor struct TextAnchor_t517930805 { public: // System.Int32 UnityEngine.TextAnchor::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TextAnchor_t517930805, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTANCHOR_T517930805_H #ifndef OPERATINGSYSTEMFAMILY_T1729349672_H #define OPERATINGSYSTEMFAMILY_T1729349672_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.OperatingSystemFamily struct OperatingSystemFamily_t1729349672 { public: // System.Int32 UnityEngine.OperatingSystemFamily::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(OperatingSystemFamily_t1729349672, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OPERATINGSYSTEMFAMILY_T1729349672_H #ifndef DATETIMEKIND_T4172753671_H #define DATETIMEKIND_T4172753671_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.DateTimeKind struct DateTimeKind_t4172753671 { public: // System.Int32 System.DateTimeKind::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(DateTimeKind_t4172753671, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DATETIMEKIND_T4172753671_H #ifndef PLAYABLEOUTPUTHANDLE_T192146840_H #define PLAYABLEOUTPUTHANDLE_T192146840_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.PlayableOutputHandle struct PlayableOutputHandle_t192146840 { public: // System.IntPtr UnityEngine.Playables.PlayableOutputHandle::m_Handle IntPtr_t ___m_Handle_0; // System.Int32 UnityEngine.Playables.PlayableOutputHandle::m_Version int32_t ___m_Version_1; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(PlayableOutputHandle_t192146840, ___m_Handle_0)); } inline IntPtr_t get_m_Handle_0() const { return ___m_Handle_0; } inline IntPtr_t* get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(IntPtr_t value) { ___m_Handle_0 = value; } inline static int32_t get_offset_of_m_Version_1() { return static_cast(offsetof(PlayableOutputHandle_t192146840, ___m_Version_1)); } inline int32_t get_m_Version_1() const { return ___m_Version_1; } inline int32_t* get_address_of_m_Version_1() { return &___m_Version_1; } inline void set_m_Version_1(int32_t value) { ___m_Version_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLAYABLEOUTPUTHANDLE_T192146840_H #ifndef INVALIDCASTEXCEPTION_T865352475_H #define INVALIDCASTEXCEPTION_T865352475_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.InvalidCastException struct InvalidCastException_t865352475 : public SystemException_t3352021648 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INVALIDCASTEXCEPTION_T865352475_H #ifndef PLAYABLEGRAPH_T3648426783_H #define PLAYABLEGRAPH_T3648426783_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.PlayableGraph struct PlayableGraph_t3648426783 { public: // System.IntPtr UnityEngine.Playables.PlayableGraph::m_Handle IntPtr_t ___m_Handle_0; // System.Int32 UnityEngine.Playables.PlayableGraph::m_Version int32_t ___m_Version_1; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(PlayableGraph_t3648426783, ___m_Handle_0)); } inline IntPtr_t get_m_Handle_0() const { return ___m_Handle_0; } inline IntPtr_t* get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(IntPtr_t value) { ___m_Handle_0 = value; } inline static int32_t get_offset_of_m_Version_1() { return static_cast(offsetof(PlayableGraph_t3648426783, ___m_Version_1)); } inline int32_t get_m_Version_1() const { return ___m_Version_1; } inline int32_t* get_address_of_m_Version_1() { return &___m_Version_1; } inline void set_m_Version_1(int32_t value) { ___m_Version_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLAYABLEGRAPH_T3648426783_H #ifndef TEXTUREFORMAT_T2964362094_H #define TEXTUREFORMAT_T2964362094_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextureFormat struct TextureFormat_t2964362094 { public: // System.Int32 UnityEngine.TextureFormat::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TextureFormat_t2964362094, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTUREFORMAT_T2964362094_H #ifndef TEXTUREWRAPMODE_T1366850874_H #define TEXTUREWRAPMODE_T1366850874_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextureWrapMode struct TextureWrapMode_t1366850874 { public: // System.Int32 UnityEngine.TextureWrapMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TextureWrapMode_t1366850874, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTUREWRAPMODE_T1366850874_H #ifndef QUERYTRIGGERINTERACTION_T3632248208_H #define QUERYTRIGGERINTERACTION_T3632248208_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.QueryTriggerInteraction struct QueryTriggerInteraction_t3632248208 { public: // System.Int32 UnityEngine.QueryTriggerInteraction::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(QueryTriggerInteraction_t3632248208, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // QUERYTRIGGERINTERACTION_T3632248208_H #ifndef HORIZONTALWRAPMODE_T3529294704_H #define HORIZONTALWRAPMODE_T3529294704_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.HorizontalWrapMode struct HorizontalWrapMode_t3529294704 { public: // System.Int32 UnityEngine.HorizontalWrapMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(HorizontalWrapMode_t3529294704, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // HORIZONTALWRAPMODE_T3529294704_H #ifndef FONTSTYLE_T4273880013_H #define FONTSTYLE_T4273880013_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.FontStyle struct FontStyle_t4273880013 { public: // System.Int32 UnityEngine.FontStyle::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(FontStyle_t4273880013, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FONTSTYLE_T4273880013_H #ifndef TEXTGENERATIONERROR_T2424902167_H #define TEXTGENERATIONERROR_T2424902167_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextGenerationError struct TextGenerationError_t2424902167 { public: // System.Int32 UnityEngine.TextGenerationError::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TextGenerationError_t2424902167, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTGENERATIONERROR_T2424902167_H #ifndef DBLCLICKSNAPPING_T2356930034_H #define DBLCLICKSNAPPING_T2356930034_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextEditor/DblClickSnapping struct DblClickSnapping_t2356930034 { public: // System.Byte UnityEngine.TextEditor/DblClickSnapping::value__ uint8_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(DblClickSnapping_t2356930034, ___value___1)); } inline uint8_t get_value___1() const { return ___value___1; } inline uint8_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(uint8_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DBLCLICKSNAPPING_T2356930034_H #ifndef TOUCHSCREENKEYBOARD_T1595360201_H #define TOUCHSCREENKEYBOARD_T1595360201_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TouchScreenKeyboard struct TouchScreenKeyboard_t1595360201 : public RuntimeObject { public: // System.IntPtr UnityEngine.TouchScreenKeyboard::m_Ptr IntPtr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(TouchScreenKeyboard_t1595360201, ___m_Ptr_0)); } inline IntPtr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline IntPtr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(IntPtr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TOUCHSCREENKEYBOARD_T1595360201_H #ifndef TEXTCLIPPING_T1360164806_H #define TEXTCLIPPING_T1360164806_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextClipping struct TextClipping_t1360164806 { public: // System.Int32 UnityEngine.TextClipping::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(TextClipping_t1360164806, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTCLIPPING_T1360164806_H #ifndef TEXTAREAATTRIBUTE_T2984524453_H #define TEXTAREAATTRIBUTE_T2984524453_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextAreaAttribute struct TextAreaAttribute_t2984524453 : public PropertyAttribute_t2314996045 { public: // System.Int32 UnityEngine.TextAreaAttribute::minLines int32_t ___minLines_0; // System.Int32 UnityEngine.TextAreaAttribute::maxLines int32_t ___maxLines_1; public: inline static int32_t get_offset_of_minLines_0() { return static_cast(offsetof(TextAreaAttribute_t2984524453, ___minLines_0)); } inline int32_t get_minLines_0() const { return ___minLines_0; } inline int32_t* get_address_of_minLines_0() { return &___minLines_0; } inline void set_minLines_0(int32_t value) { ___minLines_0 = value; } inline static int32_t get_offset_of_maxLines_1() { return static_cast(offsetof(TextAreaAttribute_t2984524453, ___maxLines_1)); } inline int32_t get_maxLines_1() const { return ___maxLines_1; } inline int32_t* get_address_of_maxLines_1() { return &___maxLines_1; } inline void set_maxLines_1(int32_t value) { ___maxLines_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTAREAATTRIBUTE_T2984524453_H #ifndef VERTICALWRAPMODE_T687953371_H #define VERTICALWRAPMODE_T687953371_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.VerticalWrapMode struct VerticalWrapMode_t687953371 { public: // System.Int32 UnityEngine.VerticalWrapMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(VerticalWrapMode_t687953371, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VERTICALWRAPMODE_T687953371_H #ifndef DELEGATE_T2669736448_H #define DELEGATE_T2669736448_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t2669736448 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl IntPtr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method IntPtr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline IntPtr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code IntPtr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_t3352901259 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast(offsetof(Delegate_t2669736448, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast(offsetof(Delegate_t2669736448, ___invoke_impl_1)); } inline IntPtr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline IntPtr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(IntPtr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast(offsetof(Delegate_t2669736448, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast(offsetof(Delegate_t2669736448, ___method_3)); } inline IntPtr_t get_method_3() const { return ___method_3; } inline IntPtr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(IntPtr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast(offsetof(Delegate_t2669736448, ___delegate_trampoline_4)); } inline IntPtr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline IntPtr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(IntPtr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast(offsetof(Delegate_t2669736448, ___method_code_5)); } inline IntPtr_t get_method_code_5() const { return ___method_code_5; } inline IntPtr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(IntPtr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast(offsetof(Delegate_t2669736448, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast(offsetof(Delegate_t2669736448, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast(offsetof(Delegate_t2669736448, ___data_8)); } inline DelegateData_t3352901259 * get_data_8() const { return ___data_8; } inline DelegateData_t3352901259 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_t3352901259 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T2669736448_H #ifndef PLAYABLEHANDLE_T606199888_H #define PLAYABLEHANDLE_T606199888_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.PlayableHandle struct PlayableHandle_t606199888 { public: // System.IntPtr UnityEngine.Playables.PlayableHandle::m_Handle IntPtr_t ___m_Handle_0; // System.Int32 UnityEngine.Playables.PlayableHandle::m_Version int32_t ___m_Version_1; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(PlayableHandle_t606199888, ___m_Handle_0)); } inline IntPtr_t get_m_Handle_0() const { return ___m_Handle_0; } inline IntPtr_t* get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(IntPtr_t value) { ___m_Handle_0 = value; } inline static int32_t get_offset_of_m_Version_1() { return static_cast(offsetof(PlayableHandle_t606199888, ___m_Version_1)); } inline int32_t get_m_Version_1() const { return ___m_Version_1; } inline int32_t* get_address_of_m_Version_1() { return &___m_Version_1; } inline void set_m_Version_1(int32_t value) { ___m_Version_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLAYABLEHANDLE_T606199888_H #ifndef RENDERMODE_T272694717_H #define RENDERMODE_T272694717_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RenderMode struct RenderMode_t272694717 { public: // System.Int32 UnityEngine.RenderMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(RenderMode_t272694717, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RENDERMODE_T272694717_H #ifndef PLANE_T3179518881_H #define PLANE_T3179518881_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Plane struct Plane_t3179518881 { public: // UnityEngine.Vector3 UnityEngine.Plane::m_Normal Vector3_t67624592 ___m_Normal_0; // System.Single UnityEngine.Plane::m_Distance float ___m_Distance_1; public: inline static int32_t get_offset_of_m_Normal_0() { return static_cast(offsetof(Plane_t3179518881, ___m_Normal_0)); } inline Vector3_t67624592 get_m_Normal_0() const { return ___m_Normal_0; } inline Vector3_t67624592 * get_address_of_m_Normal_0() { return &___m_Normal_0; } inline void set_m_Normal_0(Vector3_t67624592 value) { ___m_Normal_0 = value; } inline static int32_t get_offset_of_m_Distance_1() { return static_cast(offsetof(Plane_t3179518881, ___m_Distance_1)); } inline float get_m_Distance_1() const { return ___m_Distance_1; } inline float* get_address_of_m_Distance_1() { return &___m_Distance_1; } inline void set_m_Distance_1(float value) { ___m_Distance_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLANE_T3179518881_H #ifndef CAMERACLEARFLAGS_T2050591568_H #define CAMERACLEARFLAGS_T2050591568_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CameraClearFlags struct CameraClearFlags_t2050591568 { public: // System.Int32 UnityEngine.CameraClearFlags::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(CameraClearFlags_t2050591568, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAMERACLEARFLAGS_T2050591568_H #ifndef PARAMETERATTRIBUTES_T1557681500_H #define PARAMETERATTRIBUTES_T1557681500_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.ParameterAttributes struct ParameterAttributes_t1557681500 { public: // System.Int32 System.Reflection.ParameterAttributes::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(ParameterAttributes_t1557681500, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PARAMETERATTRIBUTES_T1557681500_H #ifndef SHADOWCASTINGMODE_T3202908605_H #define SHADOWCASTINGMODE_T3202908605_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rendering.ShadowCastingMode struct ShadowCastingMode_t3202908605 { public: // System.Int32 UnityEngine.Rendering.ShadowCastingMode::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(ShadowCastingMode_t3202908605, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SHADOWCASTINGMODE_T3202908605_H #ifndef ASYNCOPERATION_T1152358279_H #define ASYNCOPERATION_T1152358279_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AsyncOperation struct AsyncOperation_t1152358279 : public YieldInstruction_t875001183 { public: // System.IntPtr UnityEngine.AsyncOperation::m_Ptr IntPtr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(AsyncOperation_t1152358279, ___m_Ptr_0)); } inline IntPtr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline IntPtr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(IntPtr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1152358279_marshaled_pinvoke : public YieldInstruction_t875001183_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1152358279_marshaled_com : public YieldInstruction_t875001183_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // ASYNCOPERATION_T1152358279_H #ifndef RUNTIMETYPEHANDLE_T1644603945_H #define RUNTIMETYPEHANDLE_T1644603945_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.RuntimeTypeHandle struct RuntimeTypeHandle_t1644603945 { public: // System.IntPtr System.RuntimeTypeHandle::value IntPtr_t ___value_0; public: inline static int32_t get_offset_of_value_0() { return static_cast(offsetof(RuntimeTypeHandle_t1644603945, ___value_0)); } inline IntPtr_t get_value_0() const { return ___value_0; } inline IntPtr_t* get_address_of_value_0() { return &___value_0; } inline void set_value_0(IntPtr_t value) { ___value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMETYPEHANDLE_T1644603945_H #ifndef SKELETONBONE_T3980876343_H #define SKELETONBONE_T3980876343_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SkeletonBone struct SkeletonBone_t3980876343 { public: // System.String UnityEngine.SkeletonBone::name String_t* ___name_0; // System.String UnityEngine.SkeletonBone::parentName String_t* ___parentName_1; // UnityEngine.Vector3 UnityEngine.SkeletonBone::position Vector3_t67624592 ___position_2; // UnityEngine.Quaternion UnityEngine.SkeletonBone::rotation Quaternion_t4184531171 ___rotation_3; // UnityEngine.Vector3 UnityEngine.SkeletonBone::scale Vector3_t67624592 ___scale_4; public: inline static int32_t get_offset_of_name_0() { return static_cast(offsetof(SkeletonBone_t3980876343, ___name_0)); } inline String_t* get_name_0() const { return ___name_0; } inline String_t** get_address_of_name_0() { return &___name_0; } inline void set_name_0(String_t* value) { ___name_0 = value; Il2CppCodeGenWriteBarrier((&___name_0), value); } inline static int32_t get_offset_of_parentName_1() { return static_cast(offsetof(SkeletonBone_t3980876343, ___parentName_1)); } inline String_t* get_parentName_1() const { return ___parentName_1; } inline String_t** get_address_of_parentName_1() { return &___parentName_1; } inline void set_parentName_1(String_t* value) { ___parentName_1 = value; Il2CppCodeGenWriteBarrier((&___parentName_1), value); } inline static int32_t get_offset_of_position_2() { return static_cast(offsetof(SkeletonBone_t3980876343, ___position_2)); } inline Vector3_t67624592 get_position_2() const { return ___position_2; } inline Vector3_t67624592 * get_address_of_position_2() { return &___position_2; } inline void set_position_2(Vector3_t67624592 value) { ___position_2 = value; } inline static int32_t get_offset_of_rotation_3() { return static_cast(offsetof(SkeletonBone_t3980876343, ___rotation_3)); } inline Quaternion_t4184531171 get_rotation_3() const { return ___rotation_3; } inline Quaternion_t4184531171 * get_address_of_rotation_3() { return &___rotation_3; } inline void set_rotation_3(Quaternion_t4184531171 value) { ___rotation_3 = value; } inline static int32_t get_offset_of_scale_4() { return static_cast(offsetof(SkeletonBone_t3980876343, ___scale_4)); } inline Vector3_t67624592 get_scale_4() const { return ___scale_4; } inline Vector3_t67624592 * get_address_of_scale_4() { return &___scale_4; } inline void set_scale_4(Vector3_t67624592 value) { ___scale_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SkeletonBone struct SkeletonBone_t3980876343_marshaled_pinvoke { char* ___name_0; char* ___parentName_1; Vector3_t67624592 ___position_2; Quaternion_t4184531171 ___rotation_3; Vector3_t67624592 ___scale_4; }; // Native definition for COM marshalling of UnityEngine.SkeletonBone struct SkeletonBone_t3980876343_marshaled_com { Il2CppChar* ___name_0; Il2CppChar* ___parentName_1; Vector3_t67624592 ___position_2; Quaternion_t4184531171 ___rotation_3; Vector3_t67624592 ___scale_4; }; #endif // SKELETONBONE_T3980876343_H #ifndef ARGUMENTEXCEPTION_T270170821_H #define ARGUMENTEXCEPTION_T270170821_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ArgumentException struct ArgumentException_t270170821 : public SystemException_t3352021648 { public: // System.String System.ArgumentException::param_name String_t* ___param_name_12; public: inline static int32_t get_offset_of_param_name_12() { return static_cast(offsetof(ArgumentException_t270170821, ___param_name_12)); } inline String_t* get_param_name_12() const { return ___param_name_12; } inline String_t** get_address_of_param_name_12() { return &___param_name_12; } inline void set_param_name_12(String_t* value) { ___param_name_12 = value; Il2CppCodeGenWriteBarrier((&___param_name_12), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARGUMENTEXCEPTION_T270170821_H #ifndef BINDINGFLAGS_T2621667298_H #define BINDINGFLAGS_T2621667298_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.BindingFlags struct BindingFlags_t2621667298 { public: // System.Int32 System.Reflection.BindingFlags::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(BindingFlags_t2621667298, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINDINGFLAGS_T2621667298_H #ifndef COLORWRITEMASK_T1030456560_H #define COLORWRITEMASK_T1030456560_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rendering.ColorWriteMask struct ColorWriteMask_t1030456560 { public: // System.Int32 UnityEngine.Rendering.ColorWriteMask::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(ColorWriteMask_t1030456560, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLORWRITEMASK_T1030456560_H #ifndef COMPAREFUNCTION_T2535906654_H #define COMPAREFUNCTION_T2535906654_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rendering.CompareFunction struct CompareFunction_t2535906654 { public: // System.Int32 UnityEngine.Rendering.CompareFunction::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(CompareFunction_t2535906654, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPAREFUNCTION_T2535906654_H #ifndef EDGE_T2904435204_H #define EDGE_T2904435204_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectTransform/Edge struct Edge_t2904435204 { public: // System.Int32 UnityEngine.RectTransform/Edge::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(Edge_t2904435204, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EDGE_T2904435204_H #ifndef STENCILOP_T1777355712_H #define STENCILOP_T1777355712_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rendering.StencilOp struct StencilOp_t1777355712 { public: // System.Int32 UnityEngine.Rendering.StencilOp::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(StencilOp_t1777355712, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STENCILOP_T1777355712_H #ifndef AXIS_T785729709_H #define AXIS_T785729709_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectTransform/Axis struct Axis_t785729709 { public: // System.Int32 UnityEngine.RectTransform/Axis::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(Axis_t785729709, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // AXIS_T785729709_H #ifndef SENDMESSAGEOPTIONS_T514890815_H #define SENDMESSAGEOPTIONS_T514890815_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SendMessageOptions struct SendMessageOptions_t514890815 { public: // System.Int32 UnityEngine.SendMessageOptions::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(SendMessageOptions_t514890815, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SENDMESSAGEOPTIONS_T514890815_H #ifndef MATERIAL_T3939796247_H #define MATERIAL_T3939796247_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Material struct Material_t3939796247 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MATERIAL_T3939796247_H #ifndef TEXTGENERATIONSETTINGS_T2955391441_H #define TEXTGENERATIONSETTINGS_T2955391441_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextGenerationSettings struct TextGenerationSettings_t2955391441 { public: // UnityEngine.Font UnityEngine.TextGenerationSettings::font Font_t1580130639 * ___font_0; // UnityEngine.Color UnityEngine.TextGenerationSettings::color Color_t267620335 ___color_1; // System.Int32 UnityEngine.TextGenerationSettings::fontSize int32_t ___fontSize_2; // System.Single UnityEngine.TextGenerationSettings::lineSpacing float ___lineSpacing_3; // System.Boolean UnityEngine.TextGenerationSettings::richText bool ___richText_4; // System.Single UnityEngine.TextGenerationSettings::scaleFactor float ___scaleFactor_5; // UnityEngine.FontStyle UnityEngine.TextGenerationSettings::fontStyle int32_t ___fontStyle_6; // UnityEngine.TextAnchor UnityEngine.TextGenerationSettings::textAnchor int32_t ___textAnchor_7; // System.Boolean UnityEngine.TextGenerationSettings::alignByGeometry bool ___alignByGeometry_8; // System.Boolean UnityEngine.TextGenerationSettings::resizeTextForBestFit bool ___resizeTextForBestFit_9; // System.Int32 UnityEngine.TextGenerationSettings::resizeTextMinSize int32_t ___resizeTextMinSize_10; // System.Int32 UnityEngine.TextGenerationSettings::resizeTextMaxSize int32_t ___resizeTextMaxSize_11; // System.Boolean UnityEngine.TextGenerationSettings::updateBounds bool ___updateBounds_12; // UnityEngine.VerticalWrapMode UnityEngine.TextGenerationSettings::verticalOverflow int32_t ___verticalOverflow_13; // UnityEngine.HorizontalWrapMode UnityEngine.TextGenerationSettings::horizontalOverflow int32_t ___horizontalOverflow_14; // UnityEngine.Vector2 UnityEngine.TextGenerationSettings::generationExtents Vector2_t3854014517 ___generationExtents_15; // UnityEngine.Vector2 UnityEngine.TextGenerationSettings::pivot Vector2_t3854014517 ___pivot_16; // System.Boolean UnityEngine.TextGenerationSettings::generateOutOfBounds bool ___generateOutOfBounds_17; public: inline static int32_t get_offset_of_font_0() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___font_0)); } inline Font_t1580130639 * get_font_0() const { return ___font_0; } inline Font_t1580130639 ** get_address_of_font_0() { return &___font_0; } inline void set_font_0(Font_t1580130639 * value) { ___font_0 = value; Il2CppCodeGenWriteBarrier((&___font_0), value); } inline static int32_t get_offset_of_color_1() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___color_1)); } inline Color_t267620335 get_color_1() const { return ___color_1; } inline Color_t267620335 * get_address_of_color_1() { return &___color_1; } inline void set_color_1(Color_t267620335 value) { ___color_1 = value; } inline static int32_t get_offset_of_fontSize_2() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___fontSize_2)); } inline int32_t get_fontSize_2() const { return ___fontSize_2; } inline int32_t* get_address_of_fontSize_2() { return &___fontSize_2; } inline void set_fontSize_2(int32_t value) { ___fontSize_2 = value; } inline static int32_t get_offset_of_lineSpacing_3() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___lineSpacing_3)); } inline float get_lineSpacing_3() const { return ___lineSpacing_3; } inline float* get_address_of_lineSpacing_3() { return &___lineSpacing_3; } inline void set_lineSpacing_3(float value) { ___lineSpacing_3 = value; } inline static int32_t get_offset_of_richText_4() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___richText_4)); } inline bool get_richText_4() const { return ___richText_4; } inline bool* get_address_of_richText_4() { return &___richText_4; } inline void set_richText_4(bool value) { ___richText_4 = value; } inline static int32_t get_offset_of_scaleFactor_5() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___scaleFactor_5)); } inline float get_scaleFactor_5() const { return ___scaleFactor_5; } inline float* get_address_of_scaleFactor_5() { return &___scaleFactor_5; } inline void set_scaleFactor_5(float value) { ___scaleFactor_5 = value; } inline static int32_t get_offset_of_fontStyle_6() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___fontStyle_6)); } inline int32_t get_fontStyle_6() const { return ___fontStyle_6; } inline int32_t* get_address_of_fontStyle_6() { return &___fontStyle_6; } inline void set_fontStyle_6(int32_t value) { ___fontStyle_6 = value; } inline static int32_t get_offset_of_textAnchor_7() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___textAnchor_7)); } inline int32_t get_textAnchor_7() const { return ___textAnchor_7; } inline int32_t* get_address_of_textAnchor_7() { return &___textAnchor_7; } inline void set_textAnchor_7(int32_t value) { ___textAnchor_7 = value; } inline static int32_t get_offset_of_alignByGeometry_8() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___alignByGeometry_8)); } inline bool get_alignByGeometry_8() const { return ___alignByGeometry_8; } inline bool* get_address_of_alignByGeometry_8() { return &___alignByGeometry_8; } inline void set_alignByGeometry_8(bool value) { ___alignByGeometry_8 = value; } inline static int32_t get_offset_of_resizeTextForBestFit_9() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___resizeTextForBestFit_9)); } inline bool get_resizeTextForBestFit_9() const { return ___resizeTextForBestFit_9; } inline bool* get_address_of_resizeTextForBestFit_9() { return &___resizeTextForBestFit_9; } inline void set_resizeTextForBestFit_9(bool value) { ___resizeTextForBestFit_9 = value; } inline static int32_t get_offset_of_resizeTextMinSize_10() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___resizeTextMinSize_10)); } inline int32_t get_resizeTextMinSize_10() const { return ___resizeTextMinSize_10; } inline int32_t* get_address_of_resizeTextMinSize_10() { return &___resizeTextMinSize_10; } inline void set_resizeTextMinSize_10(int32_t value) { ___resizeTextMinSize_10 = value; } inline static int32_t get_offset_of_resizeTextMaxSize_11() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___resizeTextMaxSize_11)); } inline int32_t get_resizeTextMaxSize_11() const { return ___resizeTextMaxSize_11; } inline int32_t* get_address_of_resizeTextMaxSize_11() { return &___resizeTextMaxSize_11; } inline void set_resizeTextMaxSize_11(int32_t value) { ___resizeTextMaxSize_11 = value; } inline static int32_t get_offset_of_updateBounds_12() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___updateBounds_12)); } inline bool get_updateBounds_12() const { return ___updateBounds_12; } inline bool* get_address_of_updateBounds_12() { return &___updateBounds_12; } inline void set_updateBounds_12(bool value) { ___updateBounds_12 = value; } inline static int32_t get_offset_of_verticalOverflow_13() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___verticalOverflow_13)); } inline int32_t get_verticalOverflow_13() const { return ___verticalOverflow_13; } inline int32_t* get_address_of_verticalOverflow_13() { return &___verticalOverflow_13; } inline void set_verticalOverflow_13(int32_t value) { ___verticalOverflow_13 = value; } inline static int32_t get_offset_of_horizontalOverflow_14() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___horizontalOverflow_14)); } inline int32_t get_horizontalOverflow_14() const { return ___horizontalOverflow_14; } inline int32_t* get_address_of_horizontalOverflow_14() { return &___horizontalOverflow_14; } inline void set_horizontalOverflow_14(int32_t value) { ___horizontalOverflow_14 = value; } inline static int32_t get_offset_of_generationExtents_15() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___generationExtents_15)); } inline Vector2_t3854014517 get_generationExtents_15() const { return ___generationExtents_15; } inline Vector2_t3854014517 * get_address_of_generationExtents_15() { return &___generationExtents_15; } inline void set_generationExtents_15(Vector2_t3854014517 value) { ___generationExtents_15 = value; } inline static int32_t get_offset_of_pivot_16() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___pivot_16)); } inline Vector2_t3854014517 get_pivot_16() const { return ___pivot_16; } inline Vector2_t3854014517 * get_address_of_pivot_16() { return &___pivot_16; } inline void set_pivot_16(Vector2_t3854014517 value) { ___pivot_16 = value; } inline static int32_t get_offset_of_generateOutOfBounds_17() { return static_cast(offsetof(TextGenerationSettings_t2955391441, ___generateOutOfBounds_17)); } inline bool get_generateOutOfBounds_17() const { return ___generateOutOfBounds_17; } inline bool* get_address_of_generateOutOfBounds_17() { return &___generateOutOfBounds_17; } inline void set_generateOutOfBounds_17(bool value) { ___generateOutOfBounds_17 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.TextGenerationSettings struct TextGenerationSettings_t2955391441_marshaled_pinvoke { Font_t1580130639 * ___font_0; Color_t267620335 ___color_1; int32_t ___fontSize_2; float ___lineSpacing_3; int32_t ___richText_4; float ___scaleFactor_5; int32_t ___fontStyle_6; int32_t ___textAnchor_7; int32_t ___alignByGeometry_8; int32_t ___resizeTextForBestFit_9; int32_t ___resizeTextMinSize_10; int32_t ___resizeTextMaxSize_11; int32_t ___updateBounds_12; int32_t ___verticalOverflow_13; int32_t ___horizontalOverflow_14; Vector2_t3854014517 ___generationExtents_15; Vector2_t3854014517 ___pivot_16; int32_t ___generateOutOfBounds_17; }; // Native definition for COM marshalling of UnityEngine.TextGenerationSettings struct TextGenerationSettings_t2955391441_marshaled_com { Font_t1580130639 * ___font_0; Color_t267620335 ___color_1; int32_t ___fontSize_2; float ___lineSpacing_3; int32_t ___richText_4; float ___scaleFactor_5; int32_t ___fontStyle_6; int32_t ___textAnchor_7; int32_t ___alignByGeometry_8; int32_t ___resizeTextForBestFit_9; int32_t ___resizeTextMinSize_10; int32_t ___resizeTextMaxSize_11; int32_t ___updateBounds_12; int32_t ___verticalOverflow_13; int32_t ___horizontalOverflow_14; Vector2_t3854014517 ___generationExtents_15; Vector2_t3854014517 ___pivot_16; int32_t ___generateOutOfBounds_17; }; #endif // TEXTGENERATIONSETTINGS_T2955391441_H #ifndef FONT_T1580130639_H #define FONT_T1580130639_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Font struct Font_t1580130639 : public Object_t1332387349 { public: // UnityEngine.Font/FontTextureRebuildCallback UnityEngine.Font::m_FontTextureRebuildCallback FontTextureRebuildCallback_t156596975 * ___m_FontTextureRebuildCallback_3; public: inline static int32_t get_offset_of_m_FontTextureRebuildCallback_3() { return static_cast(offsetof(Font_t1580130639, ___m_FontTextureRebuildCallback_3)); } inline FontTextureRebuildCallback_t156596975 * get_m_FontTextureRebuildCallback_3() const { return ___m_FontTextureRebuildCallback_3; } inline FontTextureRebuildCallback_t156596975 ** get_address_of_m_FontTextureRebuildCallback_3() { return &___m_FontTextureRebuildCallback_3; } inline void set_m_FontTextureRebuildCallback_3(FontTextureRebuildCallback_t156596975 * value) { ___m_FontTextureRebuildCallback_3 = value; Il2CppCodeGenWriteBarrier((&___m_FontTextureRebuildCallback_3), value); } }; struct Font_t1580130639_StaticFields { public: // System.Action`1 UnityEngine.Font::textureRebuilt Action_1_t2612654846 * ___textureRebuilt_2; public: inline static int32_t get_offset_of_textureRebuilt_2() { return static_cast(offsetof(Font_t1580130639_StaticFields, ___textureRebuilt_2)); } inline Action_1_t2612654846 * get_textureRebuilt_2() const { return ___textureRebuilt_2; } inline Action_1_t2612654846 ** get_address_of_textureRebuilt_2() { return &___textureRebuilt_2; } inline void set_textureRebuilt_2(Action_1_t2612654846 * value) { ___textureRebuilt_2 = value; Il2CppCodeGenWriteBarrier((&___textureRebuilt_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FONT_T1580130639_H #ifndef QUALITYSETTINGS_T2975562250_H #define QUALITYSETTINGS_T2975562250_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.QualitySettings struct QualitySettings_t2975562250 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // QUALITYSETTINGS_T2975562250_H #ifndef PARAMETERINFO_T1917333745_H #define PARAMETERINFO_T1917333745_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.ParameterInfo struct ParameterInfo_t1917333745 : public RuntimeObject { public: // System.Type System.Reflection.ParameterInfo::ClassImpl Type_t * ___ClassImpl_0; // System.Object System.Reflection.ParameterInfo::DefaultValueImpl RuntimeObject * ___DefaultValueImpl_1; // System.Reflection.MemberInfo System.Reflection.ParameterInfo::MemberImpl MemberInfo_t * ___MemberImpl_2; // System.String System.Reflection.ParameterInfo::NameImpl String_t* ___NameImpl_3; // System.Int32 System.Reflection.ParameterInfo::PositionImpl int32_t ___PositionImpl_4; // System.Reflection.ParameterAttributes System.Reflection.ParameterInfo::AttrsImpl int32_t ___AttrsImpl_5; // System.Reflection.Emit.UnmanagedMarshal System.Reflection.ParameterInfo::marshalAs UnmanagedMarshal_t600271334 * ___marshalAs_6; public: inline static int32_t get_offset_of_ClassImpl_0() { return static_cast(offsetof(ParameterInfo_t1917333745, ___ClassImpl_0)); } inline Type_t * get_ClassImpl_0() const { return ___ClassImpl_0; } inline Type_t ** get_address_of_ClassImpl_0() { return &___ClassImpl_0; } inline void set_ClassImpl_0(Type_t * value) { ___ClassImpl_0 = value; Il2CppCodeGenWriteBarrier((&___ClassImpl_0), value); } inline static int32_t get_offset_of_DefaultValueImpl_1() { return static_cast(offsetof(ParameterInfo_t1917333745, ___DefaultValueImpl_1)); } inline RuntimeObject * get_DefaultValueImpl_1() const { return ___DefaultValueImpl_1; } inline RuntimeObject ** get_address_of_DefaultValueImpl_1() { return &___DefaultValueImpl_1; } inline void set_DefaultValueImpl_1(RuntimeObject * value) { ___DefaultValueImpl_1 = value; Il2CppCodeGenWriteBarrier((&___DefaultValueImpl_1), value); } inline static int32_t get_offset_of_MemberImpl_2() { return static_cast(offsetof(ParameterInfo_t1917333745, ___MemberImpl_2)); } inline MemberInfo_t * get_MemberImpl_2() const { return ___MemberImpl_2; } inline MemberInfo_t ** get_address_of_MemberImpl_2() { return &___MemberImpl_2; } inline void set_MemberImpl_2(MemberInfo_t * value) { ___MemberImpl_2 = value; Il2CppCodeGenWriteBarrier((&___MemberImpl_2), value); } inline static int32_t get_offset_of_NameImpl_3() { return static_cast(offsetof(ParameterInfo_t1917333745, ___NameImpl_3)); } inline String_t* get_NameImpl_3() const { return ___NameImpl_3; } inline String_t** get_address_of_NameImpl_3() { return &___NameImpl_3; } inline void set_NameImpl_3(String_t* value) { ___NameImpl_3 = value; Il2CppCodeGenWriteBarrier((&___NameImpl_3), value); } inline static int32_t get_offset_of_PositionImpl_4() { return static_cast(offsetof(ParameterInfo_t1917333745, ___PositionImpl_4)); } inline int32_t get_PositionImpl_4() const { return ___PositionImpl_4; } inline int32_t* get_address_of_PositionImpl_4() { return &___PositionImpl_4; } inline void set_PositionImpl_4(int32_t value) { ___PositionImpl_4 = value; } inline static int32_t get_offset_of_AttrsImpl_5() { return static_cast(offsetof(ParameterInfo_t1917333745, ___AttrsImpl_5)); } inline int32_t get_AttrsImpl_5() const { return ___AttrsImpl_5; } inline int32_t* get_address_of_AttrsImpl_5() { return &___AttrsImpl_5; } inline void set_AttrsImpl_5(int32_t value) { ___AttrsImpl_5 = value; } inline static int32_t get_offset_of_marshalAs_6() { return static_cast(offsetof(ParameterInfo_t1917333745, ___marshalAs_6)); } inline UnmanagedMarshal_t600271334 * get_marshalAs_6() const { return ___marshalAs_6; } inline UnmanagedMarshal_t600271334 ** get_address_of_marshalAs_6() { return &___marshalAs_6; } inline void set_marshalAs_6(UnmanagedMarshal_t600271334 * value) { ___marshalAs_6 = value; Il2CppCodeGenWriteBarrier((&___marshalAs_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PARAMETERINFO_T1917333745_H #ifndef TEXTASSET_T2643108631_H #define TEXTASSET_T2643108631_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextAsset struct TextAsset_t2643108631 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTASSET_T2643108631_H #ifndef TEXTEDITOR_T876577383_H #define TEXTEDITOR_T876577383_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextEditor struct TextEditor_t876577383 : public RuntimeObject { public: // UnityEngine.TouchScreenKeyboard UnityEngine.TextEditor::keyboardOnScreen TouchScreenKeyboard_t1595360201 * ___keyboardOnScreen_0; // System.Int32 UnityEngine.TextEditor::controlID int32_t ___controlID_1; // UnityEngine.GUIStyle UnityEngine.TextEditor::style GUIStyle_t4033995491 * ___style_2; // System.Boolean UnityEngine.TextEditor::multiline bool ___multiline_3; // System.Boolean UnityEngine.TextEditor::hasHorizontalCursorPos bool ___hasHorizontalCursorPos_4; // System.Boolean UnityEngine.TextEditor::isPasswordField bool ___isPasswordField_5; // UnityEngine.Vector2 UnityEngine.TextEditor::scrollOffset Vector2_t3854014517 ___scrollOffset_6; // UnityEngine.GUIContent UnityEngine.TextEditor::m_Content GUIContent_t3165057865 * ___m_Content_7; // System.Int32 UnityEngine.TextEditor::m_CursorIndex int32_t ___m_CursorIndex_8; // System.Int32 UnityEngine.TextEditor::m_SelectIndex int32_t ___m_SelectIndex_9; // System.Boolean UnityEngine.TextEditor::m_RevealCursor bool ___m_RevealCursor_10; // System.Boolean UnityEngine.TextEditor::m_MouseDragSelectsWholeWords bool ___m_MouseDragSelectsWholeWords_11; // System.Int32 UnityEngine.TextEditor::m_DblClickInitPos int32_t ___m_DblClickInitPos_12; // UnityEngine.TextEditor/DblClickSnapping UnityEngine.TextEditor::m_DblClickSnap uint8_t ___m_DblClickSnap_13; // System.Boolean UnityEngine.TextEditor::m_bJustSelected bool ___m_bJustSelected_14; // System.Int32 UnityEngine.TextEditor::m_iAltCursorPos int32_t ___m_iAltCursorPos_15; public: inline static int32_t get_offset_of_keyboardOnScreen_0() { return static_cast(offsetof(TextEditor_t876577383, ___keyboardOnScreen_0)); } inline TouchScreenKeyboard_t1595360201 * get_keyboardOnScreen_0() const { return ___keyboardOnScreen_0; } inline TouchScreenKeyboard_t1595360201 ** get_address_of_keyboardOnScreen_0() { return &___keyboardOnScreen_0; } inline void set_keyboardOnScreen_0(TouchScreenKeyboard_t1595360201 * value) { ___keyboardOnScreen_0 = value; Il2CppCodeGenWriteBarrier((&___keyboardOnScreen_0), value); } inline static int32_t get_offset_of_controlID_1() { return static_cast(offsetof(TextEditor_t876577383, ___controlID_1)); } inline int32_t get_controlID_1() const { return ___controlID_1; } inline int32_t* get_address_of_controlID_1() { return &___controlID_1; } inline void set_controlID_1(int32_t value) { ___controlID_1 = value; } inline static int32_t get_offset_of_style_2() { return static_cast(offsetof(TextEditor_t876577383, ___style_2)); } inline GUIStyle_t4033995491 * get_style_2() const { return ___style_2; } inline GUIStyle_t4033995491 ** get_address_of_style_2() { return &___style_2; } inline void set_style_2(GUIStyle_t4033995491 * value) { ___style_2 = value; Il2CppCodeGenWriteBarrier((&___style_2), value); } inline static int32_t get_offset_of_multiline_3() { return static_cast(offsetof(TextEditor_t876577383, ___multiline_3)); } inline bool get_multiline_3() const { return ___multiline_3; } inline bool* get_address_of_multiline_3() { return &___multiline_3; } inline void set_multiline_3(bool value) { ___multiline_3 = value; } inline static int32_t get_offset_of_hasHorizontalCursorPos_4() { return static_cast(offsetof(TextEditor_t876577383, ___hasHorizontalCursorPos_4)); } inline bool get_hasHorizontalCursorPos_4() const { return ___hasHorizontalCursorPos_4; } inline bool* get_address_of_hasHorizontalCursorPos_4() { return &___hasHorizontalCursorPos_4; } inline void set_hasHorizontalCursorPos_4(bool value) { ___hasHorizontalCursorPos_4 = value; } inline static int32_t get_offset_of_isPasswordField_5() { return static_cast(offsetof(TextEditor_t876577383, ___isPasswordField_5)); } inline bool get_isPasswordField_5() const { return ___isPasswordField_5; } inline bool* get_address_of_isPasswordField_5() { return &___isPasswordField_5; } inline void set_isPasswordField_5(bool value) { ___isPasswordField_5 = value; } inline static int32_t get_offset_of_scrollOffset_6() { return static_cast(offsetof(TextEditor_t876577383, ___scrollOffset_6)); } inline Vector2_t3854014517 get_scrollOffset_6() const { return ___scrollOffset_6; } inline Vector2_t3854014517 * get_address_of_scrollOffset_6() { return &___scrollOffset_6; } inline void set_scrollOffset_6(Vector2_t3854014517 value) { ___scrollOffset_6 = value; } inline static int32_t get_offset_of_m_Content_7() { return static_cast(offsetof(TextEditor_t876577383, ___m_Content_7)); } inline GUIContent_t3165057865 * get_m_Content_7() const { return ___m_Content_7; } inline GUIContent_t3165057865 ** get_address_of_m_Content_7() { return &___m_Content_7; } inline void set_m_Content_7(GUIContent_t3165057865 * value) { ___m_Content_7 = value; Il2CppCodeGenWriteBarrier((&___m_Content_7), value); } inline static int32_t get_offset_of_m_CursorIndex_8() { return static_cast(offsetof(TextEditor_t876577383, ___m_CursorIndex_8)); } inline int32_t get_m_CursorIndex_8() const { return ___m_CursorIndex_8; } inline int32_t* get_address_of_m_CursorIndex_8() { return &___m_CursorIndex_8; } inline void set_m_CursorIndex_8(int32_t value) { ___m_CursorIndex_8 = value; } inline static int32_t get_offset_of_m_SelectIndex_9() { return static_cast(offsetof(TextEditor_t876577383, ___m_SelectIndex_9)); } inline int32_t get_m_SelectIndex_9() const { return ___m_SelectIndex_9; } inline int32_t* get_address_of_m_SelectIndex_9() { return &___m_SelectIndex_9; } inline void set_m_SelectIndex_9(int32_t value) { ___m_SelectIndex_9 = value; } inline static int32_t get_offset_of_m_RevealCursor_10() { return static_cast(offsetof(TextEditor_t876577383, ___m_RevealCursor_10)); } inline bool get_m_RevealCursor_10() const { return ___m_RevealCursor_10; } inline bool* get_address_of_m_RevealCursor_10() { return &___m_RevealCursor_10; } inline void set_m_RevealCursor_10(bool value) { ___m_RevealCursor_10 = value; } inline static int32_t get_offset_of_m_MouseDragSelectsWholeWords_11() { return static_cast(offsetof(TextEditor_t876577383, ___m_MouseDragSelectsWholeWords_11)); } inline bool get_m_MouseDragSelectsWholeWords_11() const { return ___m_MouseDragSelectsWholeWords_11; } inline bool* get_address_of_m_MouseDragSelectsWholeWords_11() { return &___m_MouseDragSelectsWholeWords_11; } inline void set_m_MouseDragSelectsWholeWords_11(bool value) { ___m_MouseDragSelectsWholeWords_11 = value; } inline static int32_t get_offset_of_m_DblClickInitPos_12() { return static_cast(offsetof(TextEditor_t876577383, ___m_DblClickInitPos_12)); } inline int32_t get_m_DblClickInitPos_12() const { return ___m_DblClickInitPos_12; } inline int32_t* get_address_of_m_DblClickInitPos_12() { return &___m_DblClickInitPos_12; } inline void set_m_DblClickInitPos_12(int32_t value) { ___m_DblClickInitPos_12 = value; } inline static int32_t get_offset_of_m_DblClickSnap_13() { return static_cast(offsetof(TextEditor_t876577383, ___m_DblClickSnap_13)); } inline uint8_t get_m_DblClickSnap_13() const { return ___m_DblClickSnap_13; } inline uint8_t* get_address_of_m_DblClickSnap_13() { return &___m_DblClickSnap_13; } inline void set_m_DblClickSnap_13(uint8_t value) { ___m_DblClickSnap_13 = value; } inline static int32_t get_offset_of_m_bJustSelected_14() { return static_cast(offsetof(TextEditor_t876577383, ___m_bJustSelected_14)); } inline bool get_m_bJustSelected_14() const { return ___m_bJustSelected_14; } inline bool* get_address_of_m_bJustSelected_14() { return &___m_bJustSelected_14; } inline void set_m_bJustSelected_14(bool value) { ___m_bJustSelected_14 = value; } inline static int32_t get_offset_of_m_iAltCursorPos_15() { return static_cast(offsetof(TextEditor_t876577383, ___m_iAltCursorPos_15)); } inline int32_t get_m_iAltCursorPos_15() const { return ___m_iAltCursorPos_15; } inline int32_t* get_address_of_m_iAltCursorPos_15() { return &___m_iAltCursorPos_15; } inline void set_m_iAltCursorPos_15(int32_t value) { ___m_iAltCursorPos_15 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTEDITOR_T876577383_H #ifndef SHADER_T610183752_H #define SHADER_T610183752_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Shader struct Shader_t610183752 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SHADER_T610183752_H #ifndef GAMEOBJECT_T2923855588_H #define GAMEOBJECT_T2923855588_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GameObject struct GameObject_t2923855588 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GAMEOBJECT_T2923855588_H #ifndef RESOURCEREQUEST_T718765924_H #define RESOURCEREQUEST_T718765924_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ResourceRequest struct ResourceRequest_t718765924 : public AsyncOperation_t1152358279 { public: // System.String UnityEngine.ResourceRequest::m_Path String_t* ___m_Path_1; // System.Type UnityEngine.ResourceRequest::m_Type Type_t * ___m_Type_2; public: inline static int32_t get_offset_of_m_Path_1() { return static_cast(offsetof(ResourceRequest_t718765924, ___m_Path_1)); } inline String_t* get_m_Path_1() const { return ___m_Path_1; } inline String_t** get_address_of_m_Path_1() { return &___m_Path_1; } inline void set_m_Path_1(String_t* value) { ___m_Path_1 = value; Il2CppCodeGenWriteBarrier((&___m_Path_1), value); } inline static int32_t get_offset_of_m_Type_2() { return static_cast(offsetof(ResourceRequest_t718765924, ___m_Type_2)); } inline Type_t * get_m_Type_2() const { return ___m_Type_2; } inline Type_t ** get_address_of_m_Type_2() { return &___m_Type_2; } inline void set_m_Type_2(Type_t * value) { ___m_Type_2 = value; Il2CppCodeGenWriteBarrier((&___m_Type_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.ResourceRequest struct ResourceRequest_t718765924_marshaled_pinvoke : public AsyncOperation_t1152358279_marshaled_pinvoke { char* ___m_Path_1; Type_t * ___m_Type_2; }; // Native definition for COM marshalling of UnityEngine.ResourceRequest struct ResourceRequest_t718765924_marshaled_com : public AsyncOperation_t1152358279_marshaled_com { Il2CppChar* ___m_Path_1; Type_t * ___m_Type_2; }; #endif // RESOURCEREQUEST_T718765924_H #ifndef TYPE_T_H #define TYPE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Type struct Type_t : public MemberInfo_t { public: // System.RuntimeTypeHandle System.Type::_impl RuntimeTypeHandle_t1644603945 ____impl_1; public: inline static int32_t get_offset_of__impl_1() { return static_cast(offsetof(Type_t, ____impl_1)); } inline RuntimeTypeHandle_t1644603945 get__impl_1() const { return ____impl_1; } inline RuntimeTypeHandle_t1644603945 * get_address_of__impl_1() { return &____impl_1; } inline void set__impl_1(RuntimeTypeHandle_t1644603945 value) { ____impl_1 = value; } }; struct Type_t_StaticFields { public: // System.Char System.Type::Delimiter Il2CppChar ___Delimiter_2; // System.Type[] System.Type::EmptyTypes TypeU5BU5D_t1493067982* ___EmptyTypes_3; // System.Reflection.MemberFilter System.Type::FilterAttribute MemberFilter_t3326885857 * ___FilterAttribute_4; // System.Reflection.MemberFilter System.Type::FilterName MemberFilter_t3326885857 * ___FilterName_5; // System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase MemberFilter_t3326885857 * ___FilterNameIgnoreCase_6; // System.Object System.Type::Missing RuntimeObject * ___Missing_7; public: inline static int32_t get_offset_of_Delimiter_2() { return static_cast(offsetof(Type_t_StaticFields, ___Delimiter_2)); } inline Il2CppChar get_Delimiter_2() const { return ___Delimiter_2; } inline Il2CppChar* get_address_of_Delimiter_2() { return &___Delimiter_2; } inline void set_Delimiter_2(Il2CppChar value) { ___Delimiter_2 = value; } inline static int32_t get_offset_of_EmptyTypes_3() { return static_cast(offsetof(Type_t_StaticFields, ___EmptyTypes_3)); } inline TypeU5BU5D_t1493067982* get_EmptyTypes_3() const { return ___EmptyTypes_3; } inline TypeU5BU5D_t1493067982** get_address_of_EmptyTypes_3() { return &___EmptyTypes_3; } inline void set_EmptyTypes_3(TypeU5BU5D_t1493067982* value) { ___EmptyTypes_3 = value; Il2CppCodeGenWriteBarrier((&___EmptyTypes_3), value); } inline static int32_t get_offset_of_FilterAttribute_4() { return static_cast(offsetof(Type_t_StaticFields, ___FilterAttribute_4)); } inline MemberFilter_t3326885857 * get_FilterAttribute_4() const { return ___FilterAttribute_4; } inline MemberFilter_t3326885857 ** get_address_of_FilterAttribute_4() { return &___FilterAttribute_4; } inline void set_FilterAttribute_4(MemberFilter_t3326885857 * value) { ___FilterAttribute_4 = value; Il2CppCodeGenWriteBarrier((&___FilterAttribute_4), value); } inline static int32_t get_offset_of_FilterName_5() { return static_cast(offsetof(Type_t_StaticFields, ___FilterName_5)); } inline MemberFilter_t3326885857 * get_FilterName_5() const { return ___FilterName_5; } inline MemberFilter_t3326885857 ** get_address_of_FilterName_5() { return &___FilterName_5; } inline void set_FilterName_5(MemberFilter_t3326885857 * value) { ___FilterName_5 = value; Il2CppCodeGenWriteBarrier((&___FilterName_5), value); } inline static int32_t get_offset_of_FilterNameIgnoreCase_6() { return static_cast(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_6)); } inline MemberFilter_t3326885857 * get_FilterNameIgnoreCase_6() const { return ___FilterNameIgnoreCase_6; } inline MemberFilter_t3326885857 ** get_address_of_FilterNameIgnoreCase_6() { return &___FilterNameIgnoreCase_6; } inline void set_FilterNameIgnoreCase_6(MemberFilter_t3326885857 * value) { ___FilterNameIgnoreCase_6 = value; Il2CppCodeGenWriteBarrier((&___FilterNameIgnoreCase_6), value); } inline static int32_t get_offset_of_Missing_7() { return static_cast(offsetof(Type_t_StaticFields, ___Missing_7)); } inline RuntimeObject * get_Missing_7() const { return ___Missing_7; } inline RuntimeObject ** get_address_of_Missing_7() { return &___Missing_7; } inline void set_Missing_7(RuntimeObject * value) { ___Missing_7 = value; Il2CppCodeGenWriteBarrier((&___Missing_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPE_T_H #ifndef RUNTIMEANIMATORCONTROLLER_T1897926676_H #define RUNTIMEANIMATORCONTROLLER_T1897926676_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RuntimeAnimatorController struct RuntimeAnimatorController_t1897926676 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEANIMATORCONTROLLER_T1897926676_H #ifndef SCRIPTPLAYABLEOUTPUT_T3853613875_H #define SCRIPTPLAYABLEOUTPUT_T3853613875_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.ScriptPlayableOutput struct ScriptPlayableOutput_t3853613875 { public: // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.ScriptPlayableOutput::m_Handle PlayableOutputHandle_t192146840 ___m_Handle_0; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(ScriptPlayableOutput_t3853613875, ___m_Handle_0)); } inline PlayableOutputHandle_t192146840 get_m_Handle_0() const { return ___m_Handle_0; } inline PlayableOutputHandle_t192146840 * get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(PlayableOutputHandle_t192146840 value) { ___m_Handle_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCRIPTPLAYABLEOUTPUT_T3853613875_H #ifndef LEADERBOARD_T3315266811_H #define LEADERBOARD_T3315266811_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.Leaderboard struct Leaderboard_t3315266811 : public RuntimeObject { public: // System.Boolean UnityEngine.SocialPlatforms.Impl.Leaderboard::m_Loading bool ___m_Loading_0; // UnityEngine.SocialPlatforms.IScore UnityEngine.SocialPlatforms.Impl.Leaderboard::m_LocalUserScore RuntimeObject* ___m_LocalUserScore_1; // System.UInt32 UnityEngine.SocialPlatforms.Impl.Leaderboard::m_MaxRange uint32_t ___m_MaxRange_2; // UnityEngine.SocialPlatforms.IScore[] UnityEngine.SocialPlatforms.Impl.Leaderboard::m_Scores IScoreU5BU5D_t519731081* ___m_Scores_3; // System.String UnityEngine.SocialPlatforms.Impl.Leaderboard::m_Title String_t* ___m_Title_4; // System.String[] UnityEngine.SocialPlatforms.Impl.Leaderboard::m_UserIDs StringU5BU5D_t3608572874* ___m_UserIDs_5; // System.String UnityEngine.SocialPlatforms.Impl.Leaderboard::k__BackingField String_t* ___U3CidU3Ek__BackingField_6; // UnityEngine.SocialPlatforms.UserScope UnityEngine.SocialPlatforms.Impl.Leaderboard::k__BackingField int32_t ___U3CuserScopeU3Ek__BackingField_7; // UnityEngine.SocialPlatforms.Range UnityEngine.SocialPlatforms.Impl.Leaderboard::k__BackingField Range_t2283206190 ___U3CrangeU3Ek__BackingField_8; // UnityEngine.SocialPlatforms.TimeScope UnityEngine.SocialPlatforms.Impl.Leaderboard::k__BackingField int32_t ___U3CtimeScopeU3Ek__BackingField_9; public: inline static int32_t get_offset_of_m_Loading_0() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_Loading_0)); } inline bool get_m_Loading_0() const { return ___m_Loading_0; } inline bool* get_address_of_m_Loading_0() { return &___m_Loading_0; } inline void set_m_Loading_0(bool value) { ___m_Loading_0 = value; } inline static int32_t get_offset_of_m_LocalUserScore_1() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_LocalUserScore_1)); } inline RuntimeObject* get_m_LocalUserScore_1() const { return ___m_LocalUserScore_1; } inline RuntimeObject** get_address_of_m_LocalUserScore_1() { return &___m_LocalUserScore_1; } inline void set_m_LocalUserScore_1(RuntimeObject* value) { ___m_LocalUserScore_1 = value; Il2CppCodeGenWriteBarrier((&___m_LocalUserScore_1), value); } inline static int32_t get_offset_of_m_MaxRange_2() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_MaxRange_2)); } inline uint32_t get_m_MaxRange_2() const { return ___m_MaxRange_2; } inline uint32_t* get_address_of_m_MaxRange_2() { return &___m_MaxRange_2; } inline void set_m_MaxRange_2(uint32_t value) { ___m_MaxRange_2 = value; } inline static int32_t get_offset_of_m_Scores_3() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_Scores_3)); } inline IScoreU5BU5D_t519731081* get_m_Scores_3() const { return ___m_Scores_3; } inline IScoreU5BU5D_t519731081** get_address_of_m_Scores_3() { return &___m_Scores_3; } inline void set_m_Scores_3(IScoreU5BU5D_t519731081* value) { ___m_Scores_3 = value; Il2CppCodeGenWriteBarrier((&___m_Scores_3), value); } inline static int32_t get_offset_of_m_Title_4() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_Title_4)); } inline String_t* get_m_Title_4() const { return ___m_Title_4; } inline String_t** get_address_of_m_Title_4() { return &___m_Title_4; } inline void set_m_Title_4(String_t* value) { ___m_Title_4 = value; Il2CppCodeGenWriteBarrier((&___m_Title_4), value); } inline static int32_t get_offset_of_m_UserIDs_5() { return static_cast(offsetof(Leaderboard_t3315266811, ___m_UserIDs_5)); } inline StringU5BU5D_t3608572874* get_m_UserIDs_5() const { return ___m_UserIDs_5; } inline StringU5BU5D_t3608572874** get_address_of_m_UserIDs_5() { return &___m_UserIDs_5; } inline void set_m_UserIDs_5(StringU5BU5D_t3608572874* value) { ___m_UserIDs_5 = value; Il2CppCodeGenWriteBarrier((&___m_UserIDs_5), value); } inline static int32_t get_offset_of_U3CidU3Ek__BackingField_6() { return static_cast(offsetof(Leaderboard_t3315266811, ___U3CidU3Ek__BackingField_6)); } inline String_t* get_U3CidU3Ek__BackingField_6() const { return ___U3CidU3Ek__BackingField_6; } inline String_t** get_address_of_U3CidU3Ek__BackingField_6() { return &___U3CidU3Ek__BackingField_6; } inline void set_U3CidU3Ek__BackingField_6(String_t* value) { ___U3CidU3Ek__BackingField_6 = value; Il2CppCodeGenWriteBarrier((&___U3CidU3Ek__BackingField_6), value); } inline static int32_t get_offset_of_U3CuserScopeU3Ek__BackingField_7() { return static_cast(offsetof(Leaderboard_t3315266811, ___U3CuserScopeU3Ek__BackingField_7)); } inline int32_t get_U3CuserScopeU3Ek__BackingField_7() const { return ___U3CuserScopeU3Ek__BackingField_7; } inline int32_t* get_address_of_U3CuserScopeU3Ek__BackingField_7() { return &___U3CuserScopeU3Ek__BackingField_7; } inline void set_U3CuserScopeU3Ek__BackingField_7(int32_t value) { ___U3CuserScopeU3Ek__BackingField_7 = value; } inline static int32_t get_offset_of_U3CrangeU3Ek__BackingField_8() { return static_cast(offsetof(Leaderboard_t3315266811, ___U3CrangeU3Ek__BackingField_8)); } inline Range_t2283206190 get_U3CrangeU3Ek__BackingField_8() const { return ___U3CrangeU3Ek__BackingField_8; } inline Range_t2283206190 * get_address_of_U3CrangeU3Ek__BackingField_8() { return &___U3CrangeU3Ek__BackingField_8; } inline void set_U3CrangeU3Ek__BackingField_8(Range_t2283206190 value) { ___U3CrangeU3Ek__BackingField_8 = value; } inline static int32_t get_offset_of_U3CtimeScopeU3Ek__BackingField_9() { return static_cast(offsetof(Leaderboard_t3315266811, ___U3CtimeScopeU3Ek__BackingField_9)); } inline int32_t get_U3CtimeScopeU3Ek__BackingField_9() const { return ___U3CtimeScopeU3Ek__BackingField_9; } inline int32_t* get_address_of_U3CtimeScopeU3Ek__BackingField_9() { return &___U3CtimeScopeU3Ek__BackingField_9; } inline void set_U3CtimeScopeU3Ek__BackingField_9(int32_t value) { ___U3CtimeScopeU3Ek__BackingField_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LEADERBOARD_T3315266811_H #ifndef MULTICASTDELEGATE_T929297072_H #define MULTICASTDELEGATE_T929297072_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t929297072 : public Delegate_t2669736448 { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t929297072 * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t929297072 * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast(offsetof(MulticastDelegate_t929297072, ___prev_9)); } inline MulticastDelegate_t929297072 * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t929297072 ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t929297072 * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast(offsetof(MulticastDelegate_t929297072, ___kpm_next_10)); } inline MulticastDelegate_t929297072 * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t929297072 ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t929297072 * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T929297072_H #ifndef USERPROFILE_T2942407481_H #define USERPROFILE_T2942407481_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.UserProfile struct UserProfile_t2942407481 : public RuntimeObject { public: // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::m_UserName String_t* ___m_UserName_0; // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::m_ID String_t* ___m_ID_1; // System.Boolean UnityEngine.SocialPlatforms.Impl.UserProfile::m_IsFriend bool ___m_IsFriend_2; // UnityEngine.SocialPlatforms.UserState UnityEngine.SocialPlatforms.Impl.UserProfile::m_State int32_t ___m_State_3; // UnityEngine.Texture2D UnityEngine.SocialPlatforms.Impl.UserProfile::m_Image Texture2D_t1384570725 * ___m_Image_4; public: inline static int32_t get_offset_of_m_UserName_0() { return static_cast(offsetof(UserProfile_t2942407481, ___m_UserName_0)); } inline String_t* get_m_UserName_0() const { return ___m_UserName_0; } inline String_t** get_address_of_m_UserName_0() { return &___m_UserName_0; } inline void set_m_UserName_0(String_t* value) { ___m_UserName_0 = value; Il2CppCodeGenWriteBarrier((&___m_UserName_0), value); } inline static int32_t get_offset_of_m_ID_1() { return static_cast(offsetof(UserProfile_t2942407481, ___m_ID_1)); } inline String_t* get_m_ID_1() const { return ___m_ID_1; } inline String_t** get_address_of_m_ID_1() { return &___m_ID_1; } inline void set_m_ID_1(String_t* value) { ___m_ID_1 = value; Il2CppCodeGenWriteBarrier((&___m_ID_1), value); } inline static int32_t get_offset_of_m_IsFriend_2() { return static_cast(offsetof(UserProfile_t2942407481, ___m_IsFriend_2)); } inline bool get_m_IsFriend_2() const { return ___m_IsFriend_2; } inline bool* get_address_of_m_IsFriend_2() { return &___m_IsFriend_2; } inline void set_m_IsFriend_2(bool value) { ___m_IsFriend_2 = value; } inline static int32_t get_offset_of_m_State_3() { return static_cast(offsetof(UserProfile_t2942407481, ___m_State_3)); } inline int32_t get_m_State_3() const { return ___m_State_3; } inline int32_t* get_address_of_m_State_3() { return &___m_State_3; } inline void set_m_State_3(int32_t value) { ___m_State_3 = value; } inline static int32_t get_offset_of_m_Image_4() { return static_cast(offsetof(UserProfile_t2942407481, ___m_Image_4)); } inline Texture2D_t1384570725 * get_m_Image_4() const { return ___m_Image_4; } inline Texture2D_t1384570725 ** get_address_of_m_Image_4() { return &___m_Image_4; } inline void set_m_Image_4(Texture2D_t1384570725 * value) { ___m_Image_4 = value; Il2CppCodeGenWriteBarrier((&___m_Image_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // USERPROFILE_T2942407481_H #ifndef DATETIME_T1205928702_H #define DATETIME_T1205928702_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.DateTime struct DateTime_t1205928702 { public: // System.TimeSpan System.DateTime::ticks TimeSpan_t3641256953 ___ticks_10; // System.DateTimeKind System.DateTime::kind int32_t ___kind_11; public: inline static int32_t get_offset_of_ticks_10() { return static_cast(offsetof(DateTime_t1205928702, ___ticks_10)); } inline TimeSpan_t3641256953 get_ticks_10() const { return ___ticks_10; } inline TimeSpan_t3641256953 * get_address_of_ticks_10() { return &___ticks_10; } inline void set_ticks_10(TimeSpan_t3641256953 value) { ___ticks_10 = value; } inline static int32_t get_offset_of_kind_11() { return static_cast(offsetof(DateTime_t1205928702, ___kind_11)); } inline int32_t get_kind_11() const { return ___kind_11; } inline int32_t* get_address_of_kind_11() { return &___kind_11; } inline void set_kind_11(int32_t value) { ___kind_11 = value; } }; struct DateTime_t1205928702_StaticFields { public: // System.DateTime System.DateTime::MaxValue DateTime_t1205928702 ___MaxValue_12; // System.DateTime System.DateTime::MinValue DateTime_t1205928702 ___MinValue_13; // System.String[] System.DateTime::ParseTimeFormats StringU5BU5D_t3608572874* ___ParseTimeFormats_14; // System.String[] System.DateTime::ParseYearDayMonthFormats StringU5BU5D_t3608572874* ___ParseYearDayMonthFormats_15; // System.String[] System.DateTime::ParseYearMonthDayFormats StringU5BU5D_t3608572874* ___ParseYearMonthDayFormats_16; // System.String[] System.DateTime::ParseDayMonthYearFormats StringU5BU5D_t3608572874* ___ParseDayMonthYearFormats_17; // System.String[] System.DateTime::ParseMonthDayYearFormats StringU5BU5D_t3608572874* ___ParseMonthDayYearFormats_18; // System.String[] System.DateTime::MonthDayShortFormats StringU5BU5D_t3608572874* ___MonthDayShortFormats_19; // System.String[] System.DateTime::DayMonthShortFormats StringU5BU5D_t3608572874* ___DayMonthShortFormats_20; // System.Int32[] System.DateTime::daysmonth Int32U5BU5D_t772475173* ___daysmonth_21; // System.Int32[] System.DateTime::daysmonthleap Int32U5BU5D_t772475173* ___daysmonthleap_22; // System.Object System.DateTime::to_local_time_span_object RuntimeObject * ___to_local_time_span_object_23; // System.Int64 System.DateTime::last_now int64_t ___last_now_24; public: inline static int32_t get_offset_of_MaxValue_12() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___MaxValue_12)); } inline DateTime_t1205928702 get_MaxValue_12() const { return ___MaxValue_12; } inline DateTime_t1205928702 * get_address_of_MaxValue_12() { return &___MaxValue_12; } inline void set_MaxValue_12(DateTime_t1205928702 value) { ___MaxValue_12 = value; } inline static int32_t get_offset_of_MinValue_13() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___MinValue_13)); } inline DateTime_t1205928702 get_MinValue_13() const { return ___MinValue_13; } inline DateTime_t1205928702 * get_address_of_MinValue_13() { return &___MinValue_13; } inline void set_MinValue_13(DateTime_t1205928702 value) { ___MinValue_13 = value; } inline static int32_t get_offset_of_ParseTimeFormats_14() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___ParseTimeFormats_14)); } inline StringU5BU5D_t3608572874* get_ParseTimeFormats_14() const { return ___ParseTimeFormats_14; } inline StringU5BU5D_t3608572874** get_address_of_ParseTimeFormats_14() { return &___ParseTimeFormats_14; } inline void set_ParseTimeFormats_14(StringU5BU5D_t3608572874* value) { ___ParseTimeFormats_14 = value; Il2CppCodeGenWriteBarrier((&___ParseTimeFormats_14), value); } inline static int32_t get_offset_of_ParseYearDayMonthFormats_15() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___ParseYearDayMonthFormats_15)); } inline StringU5BU5D_t3608572874* get_ParseYearDayMonthFormats_15() const { return ___ParseYearDayMonthFormats_15; } inline StringU5BU5D_t3608572874** get_address_of_ParseYearDayMonthFormats_15() { return &___ParseYearDayMonthFormats_15; } inline void set_ParseYearDayMonthFormats_15(StringU5BU5D_t3608572874* value) { ___ParseYearDayMonthFormats_15 = value; Il2CppCodeGenWriteBarrier((&___ParseYearDayMonthFormats_15), value); } inline static int32_t get_offset_of_ParseYearMonthDayFormats_16() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___ParseYearMonthDayFormats_16)); } inline StringU5BU5D_t3608572874* get_ParseYearMonthDayFormats_16() const { return ___ParseYearMonthDayFormats_16; } inline StringU5BU5D_t3608572874** get_address_of_ParseYearMonthDayFormats_16() { return &___ParseYearMonthDayFormats_16; } inline void set_ParseYearMonthDayFormats_16(StringU5BU5D_t3608572874* value) { ___ParseYearMonthDayFormats_16 = value; Il2CppCodeGenWriteBarrier((&___ParseYearMonthDayFormats_16), value); } inline static int32_t get_offset_of_ParseDayMonthYearFormats_17() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___ParseDayMonthYearFormats_17)); } inline StringU5BU5D_t3608572874* get_ParseDayMonthYearFormats_17() const { return ___ParseDayMonthYearFormats_17; } inline StringU5BU5D_t3608572874** get_address_of_ParseDayMonthYearFormats_17() { return &___ParseDayMonthYearFormats_17; } inline void set_ParseDayMonthYearFormats_17(StringU5BU5D_t3608572874* value) { ___ParseDayMonthYearFormats_17 = value; Il2CppCodeGenWriteBarrier((&___ParseDayMonthYearFormats_17), value); } inline static int32_t get_offset_of_ParseMonthDayYearFormats_18() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___ParseMonthDayYearFormats_18)); } inline StringU5BU5D_t3608572874* get_ParseMonthDayYearFormats_18() const { return ___ParseMonthDayYearFormats_18; } inline StringU5BU5D_t3608572874** get_address_of_ParseMonthDayYearFormats_18() { return &___ParseMonthDayYearFormats_18; } inline void set_ParseMonthDayYearFormats_18(StringU5BU5D_t3608572874* value) { ___ParseMonthDayYearFormats_18 = value; Il2CppCodeGenWriteBarrier((&___ParseMonthDayYearFormats_18), value); } inline static int32_t get_offset_of_MonthDayShortFormats_19() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___MonthDayShortFormats_19)); } inline StringU5BU5D_t3608572874* get_MonthDayShortFormats_19() const { return ___MonthDayShortFormats_19; } inline StringU5BU5D_t3608572874** get_address_of_MonthDayShortFormats_19() { return &___MonthDayShortFormats_19; } inline void set_MonthDayShortFormats_19(StringU5BU5D_t3608572874* value) { ___MonthDayShortFormats_19 = value; Il2CppCodeGenWriteBarrier((&___MonthDayShortFormats_19), value); } inline static int32_t get_offset_of_DayMonthShortFormats_20() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___DayMonthShortFormats_20)); } inline StringU5BU5D_t3608572874* get_DayMonthShortFormats_20() const { return ___DayMonthShortFormats_20; } inline StringU5BU5D_t3608572874** get_address_of_DayMonthShortFormats_20() { return &___DayMonthShortFormats_20; } inline void set_DayMonthShortFormats_20(StringU5BU5D_t3608572874* value) { ___DayMonthShortFormats_20 = value; Il2CppCodeGenWriteBarrier((&___DayMonthShortFormats_20), value); } inline static int32_t get_offset_of_daysmonth_21() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___daysmonth_21)); } inline Int32U5BU5D_t772475173* get_daysmonth_21() const { return ___daysmonth_21; } inline Int32U5BU5D_t772475173** get_address_of_daysmonth_21() { return &___daysmonth_21; } inline void set_daysmonth_21(Int32U5BU5D_t772475173* value) { ___daysmonth_21 = value; Il2CppCodeGenWriteBarrier((&___daysmonth_21), value); } inline static int32_t get_offset_of_daysmonthleap_22() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___daysmonthleap_22)); } inline Int32U5BU5D_t772475173* get_daysmonthleap_22() const { return ___daysmonthleap_22; } inline Int32U5BU5D_t772475173** get_address_of_daysmonthleap_22() { return &___daysmonthleap_22; } inline void set_daysmonthleap_22(Int32U5BU5D_t772475173* value) { ___daysmonthleap_22 = value; Il2CppCodeGenWriteBarrier((&___daysmonthleap_22), value); } inline static int32_t get_offset_of_to_local_time_span_object_23() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___to_local_time_span_object_23)); } inline RuntimeObject * get_to_local_time_span_object_23() const { return ___to_local_time_span_object_23; } inline RuntimeObject ** get_address_of_to_local_time_span_object_23() { return &___to_local_time_span_object_23; } inline void set_to_local_time_span_object_23(RuntimeObject * value) { ___to_local_time_span_object_23 = value; Il2CppCodeGenWriteBarrier((&___to_local_time_span_object_23), value); } inline static int32_t get_offset_of_last_now_24() { return static_cast(offsetof(DateTime_t1205928702_StaticFields, ___last_now_24)); } inline int64_t get_last_now_24() const { return ___last_now_24; } inline int64_t* get_address_of_last_now_24() { return &___last_now_24; } inline void set_last_now_24(int64_t value) { ___last_now_24 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DATETIME_T1205928702_H #ifndef SCRIPTABLEOBJECT_T505592390_H #define SCRIPTABLEOBJECT_T505592390_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ScriptableObject struct ScriptableObject_t505592390 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t505592390_marshaled_pinvoke : public Object_t1332387349_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t505592390_marshaled_com : public Object_t1332387349_marshaled_com { }; #endif // SCRIPTABLEOBJECT_T505592390_H #ifndef TEXTURE_T2354860603_H #define TEXTURE_T2354860603_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture struct Texture_t2354860603 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE_T2354860603_H #ifndef PLAYABLEOUTPUT_T1264890687_H #define PLAYABLEOUTPUT_T1264890687_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.PlayableOutput struct PlayableOutput_t1264890687 { public: // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.PlayableOutput::m_Handle PlayableOutputHandle_t192146840 ___m_Handle_0; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(PlayableOutput_t1264890687, ___m_Handle_0)); } inline PlayableOutputHandle_t192146840 get_m_Handle_0() const { return ___m_Handle_0; } inline PlayableOutputHandle_t192146840 * get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(PlayableOutputHandle_t192146840 value) { ___m_Handle_0 = value; } }; struct PlayableOutput_t1264890687_StaticFields { public: // UnityEngine.Playables.PlayableOutput UnityEngine.Playables.PlayableOutput::m_NullPlayableOutput PlayableOutput_t1264890687 ___m_NullPlayableOutput_1; public: inline static int32_t get_offset_of_m_NullPlayableOutput_1() { return static_cast(offsetof(PlayableOutput_t1264890687_StaticFields, ___m_NullPlayableOutput_1)); } inline PlayableOutput_t1264890687 get_m_NullPlayableOutput_1() const { return ___m_NullPlayableOutput_1; } inline PlayableOutput_t1264890687 * get_address_of_m_NullPlayableOutput_1() { return &___m_NullPlayableOutput_1; } inline void set_m_NullPlayableOutput_1(PlayableOutput_t1264890687 value) { ___m_NullPlayableOutput_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLAYABLEOUTPUT_T1264890687_H #ifndef SPRITE_T3419621700_H #define SPRITE_T3419621700_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Sprite struct Sprite_t3419621700 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SPRITE_T3419621700_H #ifndef GUISTYLE_T4033995491_H #define GUISTYLE_T4033995491_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GUIStyle struct GUIStyle_t4033995491 : public RuntimeObject { public: // System.IntPtr UnityEngine.GUIStyle::m_Ptr IntPtr_t ___m_Ptr_0; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_Normal GUIStyleState_t2009209206 * ___m_Normal_1; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_Hover GUIStyleState_t2009209206 * ___m_Hover_2; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_Active GUIStyleState_t2009209206 * ___m_Active_3; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_Focused GUIStyleState_t2009209206 * ___m_Focused_4; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_OnNormal GUIStyleState_t2009209206 * ___m_OnNormal_5; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_OnHover GUIStyleState_t2009209206 * ___m_OnHover_6; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_OnActive GUIStyleState_t2009209206 * ___m_OnActive_7; // UnityEngine.GUIStyleState UnityEngine.GUIStyle::m_OnFocused GUIStyleState_t2009209206 * ___m_OnFocused_8; // UnityEngine.RectOffset UnityEngine.GUIStyle::m_Border RectOffset_t3582970358 * ___m_Border_9; // UnityEngine.RectOffset UnityEngine.GUIStyle::m_Padding RectOffset_t3582970358 * ___m_Padding_10; // UnityEngine.RectOffset UnityEngine.GUIStyle::m_Margin RectOffset_t3582970358 * ___m_Margin_11; // UnityEngine.RectOffset UnityEngine.GUIStyle::m_Overflow RectOffset_t3582970358 * ___m_Overflow_12; // UnityEngine.Font UnityEngine.GUIStyle::m_FontInternal Font_t1580130639 * ___m_FontInternal_13; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Ptr_0)); } inline IntPtr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline IntPtr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(IntPtr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Normal_1)); } inline GUIStyleState_t2009209206 * get_m_Normal_1() const { return ___m_Normal_1; } inline GUIStyleState_t2009209206 ** get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(GUIStyleState_t2009209206 * value) { ___m_Normal_1 = value; Il2CppCodeGenWriteBarrier((&___m_Normal_1), value); } inline static int32_t get_offset_of_m_Hover_2() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Hover_2)); } inline GUIStyleState_t2009209206 * get_m_Hover_2() const { return ___m_Hover_2; } inline GUIStyleState_t2009209206 ** get_address_of_m_Hover_2() { return &___m_Hover_2; } inline void set_m_Hover_2(GUIStyleState_t2009209206 * value) { ___m_Hover_2 = value; Il2CppCodeGenWriteBarrier((&___m_Hover_2), value); } inline static int32_t get_offset_of_m_Active_3() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Active_3)); } inline GUIStyleState_t2009209206 * get_m_Active_3() const { return ___m_Active_3; } inline GUIStyleState_t2009209206 ** get_address_of_m_Active_3() { return &___m_Active_3; } inline void set_m_Active_3(GUIStyleState_t2009209206 * value) { ___m_Active_3 = value; Il2CppCodeGenWriteBarrier((&___m_Active_3), value); } inline static int32_t get_offset_of_m_Focused_4() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Focused_4)); } inline GUIStyleState_t2009209206 * get_m_Focused_4() const { return ___m_Focused_4; } inline GUIStyleState_t2009209206 ** get_address_of_m_Focused_4() { return &___m_Focused_4; } inline void set_m_Focused_4(GUIStyleState_t2009209206 * value) { ___m_Focused_4 = value; Il2CppCodeGenWriteBarrier((&___m_Focused_4), value); } inline static int32_t get_offset_of_m_OnNormal_5() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_OnNormal_5)); } inline GUIStyleState_t2009209206 * get_m_OnNormal_5() const { return ___m_OnNormal_5; } inline GUIStyleState_t2009209206 ** get_address_of_m_OnNormal_5() { return &___m_OnNormal_5; } inline void set_m_OnNormal_5(GUIStyleState_t2009209206 * value) { ___m_OnNormal_5 = value; Il2CppCodeGenWriteBarrier((&___m_OnNormal_5), value); } inline static int32_t get_offset_of_m_OnHover_6() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_OnHover_6)); } inline GUIStyleState_t2009209206 * get_m_OnHover_6() const { return ___m_OnHover_6; } inline GUIStyleState_t2009209206 ** get_address_of_m_OnHover_6() { return &___m_OnHover_6; } inline void set_m_OnHover_6(GUIStyleState_t2009209206 * value) { ___m_OnHover_6 = value; Il2CppCodeGenWriteBarrier((&___m_OnHover_6), value); } inline static int32_t get_offset_of_m_OnActive_7() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_OnActive_7)); } inline GUIStyleState_t2009209206 * get_m_OnActive_7() const { return ___m_OnActive_7; } inline GUIStyleState_t2009209206 ** get_address_of_m_OnActive_7() { return &___m_OnActive_7; } inline void set_m_OnActive_7(GUIStyleState_t2009209206 * value) { ___m_OnActive_7 = value; Il2CppCodeGenWriteBarrier((&___m_OnActive_7), value); } inline static int32_t get_offset_of_m_OnFocused_8() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_OnFocused_8)); } inline GUIStyleState_t2009209206 * get_m_OnFocused_8() const { return ___m_OnFocused_8; } inline GUIStyleState_t2009209206 ** get_address_of_m_OnFocused_8() { return &___m_OnFocused_8; } inline void set_m_OnFocused_8(GUIStyleState_t2009209206 * value) { ___m_OnFocused_8 = value; Il2CppCodeGenWriteBarrier((&___m_OnFocused_8), value); } inline static int32_t get_offset_of_m_Border_9() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Border_9)); } inline RectOffset_t3582970358 * get_m_Border_9() const { return ___m_Border_9; } inline RectOffset_t3582970358 ** get_address_of_m_Border_9() { return &___m_Border_9; } inline void set_m_Border_9(RectOffset_t3582970358 * value) { ___m_Border_9 = value; Il2CppCodeGenWriteBarrier((&___m_Border_9), value); } inline static int32_t get_offset_of_m_Padding_10() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Padding_10)); } inline RectOffset_t3582970358 * get_m_Padding_10() const { return ___m_Padding_10; } inline RectOffset_t3582970358 ** get_address_of_m_Padding_10() { return &___m_Padding_10; } inline void set_m_Padding_10(RectOffset_t3582970358 * value) { ___m_Padding_10 = value; Il2CppCodeGenWriteBarrier((&___m_Padding_10), value); } inline static int32_t get_offset_of_m_Margin_11() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Margin_11)); } inline RectOffset_t3582970358 * get_m_Margin_11() const { return ___m_Margin_11; } inline RectOffset_t3582970358 ** get_address_of_m_Margin_11() { return &___m_Margin_11; } inline void set_m_Margin_11(RectOffset_t3582970358 * value) { ___m_Margin_11 = value; Il2CppCodeGenWriteBarrier((&___m_Margin_11), value); } inline static int32_t get_offset_of_m_Overflow_12() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_Overflow_12)); } inline RectOffset_t3582970358 * get_m_Overflow_12() const { return ___m_Overflow_12; } inline RectOffset_t3582970358 ** get_address_of_m_Overflow_12() { return &___m_Overflow_12; } inline void set_m_Overflow_12(RectOffset_t3582970358 * value) { ___m_Overflow_12 = value; Il2CppCodeGenWriteBarrier((&___m_Overflow_12), value); } inline static int32_t get_offset_of_m_FontInternal_13() { return static_cast(offsetof(GUIStyle_t4033995491, ___m_FontInternal_13)); } inline Font_t1580130639 * get_m_FontInternal_13() const { return ___m_FontInternal_13; } inline Font_t1580130639 ** get_address_of_m_FontInternal_13() { return &___m_FontInternal_13; } inline void set_m_FontInternal_13(Font_t1580130639 * value) { ___m_FontInternal_13 = value; Il2CppCodeGenWriteBarrier((&___m_FontInternal_13), value); } }; struct GUIStyle_t4033995491_StaticFields { public: // System.Boolean UnityEngine.GUIStyle::showKeyboardFocus bool ___showKeyboardFocus_14; // UnityEngine.GUIStyle UnityEngine.GUIStyle::s_None GUIStyle_t4033995491 * ___s_None_15; public: inline static int32_t get_offset_of_showKeyboardFocus_14() { return static_cast(offsetof(GUIStyle_t4033995491_StaticFields, ___showKeyboardFocus_14)); } inline bool get_showKeyboardFocus_14() const { return ___showKeyboardFocus_14; } inline bool* get_address_of_showKeyboardFocus_14() { return &___showKeyboardFocus_14; } inline void set_showKeyboardFocus_14(bool value) { ___showKeyboardFocus_14 = value; } inline static int32_t get_offset_of_s_None_15() { return static_cast(offsetof(GUIStyle_t4033995491_StaticFields, ___s_None_15)); } inline GUIStyle_t4033995491 * get_s_None_15() const { return ___s_None_15; } inline GUIStyle_t4033995491 ** get_address_of_s_None_15() { return &___s_None_15; } inline void set_s_None_15(GUIStyle_t4033995491 * value) { ___s_None_15 = value; Il2CppCodeGenWriteBarrier((&___s_None_15), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.GUIStyle struct GUIStyle_t4033995491_marshaled_pinvoke { intptr_t ___m_Ptr_0; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_Normal_1; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_Hover_2; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_Active_3; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_Focused_4; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_OnNormal_5; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_OnHover_6; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_OnActive_7; GUIStyleState_t2009209206_marshaled_pinvoke* ___m_OnFocused_8; RectOffset_t3582970358_marshaled_pinvoke ___m_Border_9; RectOffset_t3582970358_marshaled_pinvoke ___m_Padding_10; RectOffset_t3582970358_marshaled_pinvoke ___m_Margin_11; RectOffset_t3582970358_marshaled_pinvoke ___m_Overflow_12; Font_t1580130639 * ___m_FontInternal_13; }; // Native definition for COM marshalling of UnityEngine.GUIStyle struct GUIStyle_t4033995491_marshaled_com { intptr_t ___m_Ptr_0; GUIStyleState_t2009209206_marshaled_com* ___m_Normal_1; GUIStyleState_t2009209206_marshaled_com* ___m_Hover_2; GUIStyleState_t2009209206_marshaled_com* ___m_Active_3; GUIStyleState_t2009209206_marshaled_com* ___m_Focused_4; GUIStyleState_t2009209206_marshaled_com* ___m_OnNormal_5; GUIStyleState_t2009209206_marshaled_com* ___m_OnHover_6; GUIStyleState_t2009209206_marshaled_com* ___m_OnActive_7; GUIStyleState_t2009209206_marshaled_com* ___m_OnFocused_8; RectOffset_t3582970358_marshaled_com* ___m_Border_9; RectOffset_t3582970358_marshaled_com* ___m_Padding_10; RectOffset_t3582970358_marshaled_com* ___m_Margin_11; RectOffset_t3582970358_marshaled_com* ___m_Overflow_12; Font_t1580130639 * ___m_FontInternal_13; }; #endif // GUISTYLE_T4033995491_H #ifndef COMPONENT_T590567089_H #define COMPONENT_T590567089_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Component struct Component_t590567089 : public Object_t1332387349 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPONENT_T590567089_H #ifndef ANIMATORCONTROLLERPLAYABLE_T3898188599_H #define ANIMATORCONTROLLERPLAYABLE_T3898188599_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Animations.AnimatorControllerPlayable struct AnimatorControllerPlayable_t3898188599 { public: // UnityEngine.Playables.PlayableHandle UnityEngine.Animations.AnimatorControllerPlayable::m_Handle PlayableHandle_t606199888 ___m_Handle_0; public: inline static int32_t get_offset_of_m_Handle_0() { return static_cast(offsetof(AnimatorControllerPlayable_t3898188599, ___m_Handle_0)); } inline PlayableHandle_t606199888 get_m_Handle_0() const { return ___m_Handle_0; } inline PlayableHandle_t606199888 * get_address_of_m_Handle_0() { return &___m_Handle_0; } inline void set_m_Handle_0(PlayableHandle_t606199888 value) { ___m_Handle_0 = value; } }; struct AnimatorControllerPlayable_t3898188599_StaticFields { public: // UnityEngine.Animations.AnimatorControllerPlayable UnityEngine.Animations.AnimatorControllerPlayable::m_NullPlayable AnimatorControllerPlayable_t3898188599 ___m_NullPlayable_1; public: inline static int32_t get_offset_of_m_NullPlayable_1() { return static_cast(offsetof(AnimatorControllerPlayable_t3898188599_StaticFields, ___m_NullPlayable_1)); } inline AnimatorControllerPlayable_t3898188599 get_m_NullPlayable_1() const { return ___m_NullPlayable_1; } inline AnimatorControllerPlayable_t3898188599 * get_address_of_m_NullPlayable_1() { return &___m_NullPlayable_1; } inline void set_m_NullPlayable_1(AnimatorControllerPlayable_t3898188599 value) { ___m_NullPlayable_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ANIMATORCONTROLLERPLAYABLE_T3898188599_H #ifndef RIGIDBODY2D_T860263072_H #define RIGIDBODY2D_T860263072_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rigidbody2D struct Rigidbody2D_t860263072 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RIGIDBODY2D_T860263072_H #ifndef TEXTGENERATOR_T1838611233_H #define TEXTGENERATOR_T1838611233_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextGenerator struct TextGenerator_t1838611233 : public RuntimeObject { public: // System.IntPtr UnityEngine.TextGenerator::m_Ptr IntPtr_t ___m_Ptr_0; // System.String UnityEngine.TextGenerator::m_LastString String_t* ___m_LastString_1; // UnityEngine.TextGenerationSettings UnityEngine.TextGenerator::m_LastSettings TextGenerationSettings_t2955391441 ___m_LastSettings_2; // System.Boolean UnityEngine.TextGenerator::m_HasGenerated bool ___m_HasGenerated_3; // UnityEngine.TextGenerationError UnityEngine.TextGenerator::m_LastValid int32_t ___m_LastValid_4; // System.Collections.Generic.List`1 UnityEngine.TextGenerator::m_Verts List_1_t2359577098 * ___m_Verts_5; // System.Collections.Generic.List`1 UnityEngine.TextGenerator::m_Characters List_1_t369525373 * ___m_Characters_6; // System.Collections.Generic.List`1 UnityEngine.TextGenerator::m_Lines List_1_t1470875743 * ___m_Lines_7; // System.Boolean UnityEngine.TextGenerator::m_CachedVerts bool ___m_CachedVerts_8; // System.Boolean UnityEngine.TextGenerator::m_CachedCharacters bool ___m_CachedCharacters_9; // System.Boolean UnityEngine.TextGenerator::m_CachedLines bool ___m_CachedLines_10; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_Ptr_0)); } inline IntPtr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline IntPtr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(IntPtr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_LastString_1() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_LastString_1)); } inline String_t* get_m_LastString_1() const { return ___m_LastString_1; } inline String_t** get_address_of_m_LastString_1() { return &___m_LastString_1; } inline void set_m_LastString_1(String_t* value) { ___m_LastString_1 = value; Il2CppCodeGenWriteBarrier((&___m_LastString_1), value); } inline static int32_t get_offset_of_m_LastSettings_2() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_LastSettings_2)); } inline TextGenerationSettings_t2955391441 get_m_LastSettings_2() const { return ___m_LastSettings_2; } inline TextGenerationSettings_t2955391441 * get_address_of_m_LastSettings_2() { return &___m_LastSettings_2; } inline void set_m_LastSettings_2(TextGenerationSettings_t2955391441 value) { ___m_LastSettings_2 = value; } inline static int32_t get_offset_of_m_HasGenerated_3() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_HasGenerated_3)); } inline bool get_m_HasGenerated_3() const { return ___m_HasGenerated_3; } inline bool* get_address_of_m_HasGenerated_3() { return &___m_HasGenerated_3; } inline void set_m_HasGenerated_3(bool value) { ___m_HasGenerated_3 = value; } inline static int32_t get_offset_of_m_LastValid_4() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_LastValid_4)); } inline int32_t get_m_LastValid_4() const { return ___m_LastValid_4; } inline int32_t* get_address_of_m_LastValid_4() { return &___m_LastValid_4; } inline void set_m_LastValid_4(int32_t value) { ___m_LastValid_4 = value; } inline static int32_t get_offset_of_m_Verts_5() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_Verts_5)); } inline List_1_t2359577098 * get_m_Verts_5() const { return ___m_Verts_5; } inline List_1_t2359577098 ** get_address_of_m_Verts_5() { return &___m_Verts_5; } inline void set_m_Verts_5(List_1_t2359577098 * value) { ___m_Verts_5 = value; Il2CppCodeGenWriteBarrier((&___m_Verts_5), value); } inline static int32_t get_offset_of_m_Characters_6() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_Characters_6)); } inline List_1_t369525373 * get_m_Characters_6() const { return ___m_Characters_6; } inline List_1_t369525373 ** get_address_of_m_Characters_6() { return &___m_Characters_6; } inline void set_m_Characters_6(List_1_t369525373 * value) { ___m_Characters_6 = value; Il2CppCodeGenWriteBarrier((&___m_Characters_6), value); } inline static int32_t get_offset_of_m_Lines_7() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_Lines_7)); } inline List_1_t1470875743 * get_m_Lines_7() const { return ___m_Lines_7; } inline List_1_t1470875743 ** get_address_of_m_Lines_7() { return &___m_Lines_7; } inline void set_m_Lines_7(List_1_t1470875743 * value) { ___m_Lines_7 = value; Il2CppCodeGenWriteBarrier((&___m_Lines_7), value); } inline static int32_t get_offset_of_m_CachedVerts_8() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_CachedVerts_8)); } inline bool get_m_CachedVerts_8() const { return ___m_CachedVerts_8; } inline bool* get_address_of_m_CachedVerts_8() { return &___m_CachedVerts_8; } inline void set_m_CachedVerts_8(bool value) { ___m_CachedVerts_8 = value; } inline static int32_t get_offset_of_m_CachedCharacters_9() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_CachedCharacters_9)); } inline bool get_m_CachedCharacters_9() const { return ___m_CachedCharacters_9; } inline bool* get_address_of_m_CachedCharacters_9() { return &___m_CachedCharacters_9; } inline void set_m_CachedCharacters_9(bool value) { ___m_CachedCharacters_9 = value; } inline static int32_t get_offset_of_m_CachedLines_10() { return static_cast(offsetof(TextGenerator_t1838611233, ___m_CachedLines_10)); } inline bool get_m_CachedLines_10() const { return ___m_CachedLines_10; } inline bool* get_address_of_m_CachedLines_10() { return &___m_CachedLines_10; } inline void set_m_CachedLines_10(bool value) { ___m_CachedLines_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.TextGenerator struct TextGenerator_t1838611233_marshaled_pinvoke { intptr_t ___m_Ptr_0; char* ___m_LastString_1; TextGenerationSettings_t2955391441_marshaled_pinvoke ___m_LastSettings_2; int32_t ___m_HasGenerated_3; int32_t ___m_LastValid_4; List_1_t2359577098 * ___m_Verts_5; List_1_t369525373 * ___m_Characters_6; List_1_t1470875743 * ___m_Lines_7; int32_t ___m_CachedVerts_8; int32_t ___m_CachedCharacters_9; int32_t ___m_CachedLines_10; }; // Native definition for COM marshalling of UnityEngine.TextGenerator struct TextGenerator_t1838611233_marshaled_com { intptr_t ___m_Ptr_0; Il2CppChar* ___m_LastString_1; TextGenerationSettings_t2955391441_marshaled_com ___m_LastSettings_2; int32_t ___m_HasGenerated_3; int32_t ___m_LastValid_4; List_1_t2359577098 * ___m_Verts_5; List_1_t369525373 * ___m_Characters_6; List_1_t1470875743 * ___m_Lines_7; int32_t ___m_CachedVerts_8; int32_t ___m_CachedCharacters_9; int32_t ___m_CachedLines_10; }; #endif // TEXTGENERATOR_T1838611233_H #ifndef UNITYACTION_2_T1173199225_H #define UNITYACTION_2_T1173199225_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Events.UnityAction`2 struct UnityAction_2_t1173199225 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYACTION_2_T1173199225_H #ifndef TEXTMESH_T2729623642_H #define TEXTMESH_T2729623642_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TextMesh struct TextMesh_t2729623642 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTMESH_T2729623642_H #ifndef UNITYACTION_1_T2300191644_H #define UNITYACTION_1_T2300191644_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Events.UnityAction`1 struct UnityAction_1_t2300191644 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYACTION_1_T2300191644_H #ifndef BEHAVIOUR_T2439740933_H #define BEHAVIOUR_T2439740933_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Behaviour struct Behaviour_t2439740933 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BEHAVIOUR_T2439740933_H #ifndef UNITYACTION_2_T1303706228_H #define UNITYACTION_2_T1303706228_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Events.UnityAction`2 struct UnityAction_2_t1303706228 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYACTION_2_T1303706228_H #ifndef RENDERTEXTURE_T3726137678_H #define RENDERTEXTURE_T3726137678_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RenderTexture struct RenderTexture_t3726137678 : public Texture_t2354860603 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RENDERTEXTURE_T3726137678_H #ifndef ACHIEVEMENT_T2468443294_H #define ACHIEVEMENT_T2468443294_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.Achievement struct Achievement_t2468443294 : public RuntimeObject { public: // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::m_Completed bool ___m_Completed_0; // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::m_Hidden bool ___m_Hidden_1; // System.DateTime UnityEngine.SocialPlatforms.Impl.Achievement::m_LastReportedDate DateTime_t1205928702 ___m_LastReportedDate_2; // System.String UnityEngine.SocialPlatforms.Impl.Achievement::k__BackingField String_t* ___U3CidU3Ek__BackingField_3; // System.Double UnityEngine.SocialPlatforms.Impl.Achievement::k__BackingField double ___U3CpercentCompletedU3Ek__BackingField_4; public: inline static int32_t get_offset_of_m_Completed_0() { return static_cast(offsetof(Achievement_t2468443294, ___m_Completed_0)); } inline bool get_m_Completed_0() const { return ___m_Completed_0; } inline bool* get_address_of_m_Completed_0() { return &___m_Completed_0; } inline void set_m_Completed_0(bool value) { ___m_Completed_0 = value; } inline static int32_t get_offset_of_m_Hidden_1() { return static_cast(offsetof(Achievement_t2468443294, ___m_Hidden_1)); } inline bool get_m_Hidden_1() const { return ___m_Hidden_1; } inline bool* get_address_of_m_Hidden_1() { return &___m_Hidden_1; } inline void set_m_Hidden_1(bool value) { ___m_Hidden_1 = value; } inline static int32_t get_offset_of_m_LastReportedDate_2() { return static_cast(offsetof(Achievement_t2468443294, ___m_LastReportedDate_2)); } inline DateTime_t1205928702 get_m_LastReportedDate_2() const { return ___m_LastReportedDate_2; } inline DateTime_t1205928702 * get_address_of_m_LastReportedDate_2() { return &___m_LastReportedDate_2; } inline void set_m_LastReportedDate_2(DateTime_t1205928702 value) { ___m_LastReportedDate_2 = value; } inline static int32_t get_offset_of_U3CidU3Ek__BackingField_3() { return static_cast(offsetof(Achievement_t2468443294, ___U3CidU3Ek__BackingField_3)); } inline String_t* get_U3CidU3Ek__BackingField_3() const { return ___U3CidU3Ek__BackingField_3; } inline String_t** get_address_of_U3CidU3Ek__BackingField_3() { return &___U3CidU3Ek__BackingField_3; } inline void set_U3CidU3Ek__BackingField_3(String_t* value) { ___U3CidU3Ek__BackingField_3 = value; Il2CppCodeGenWriteBarrier((&___U3CidU3Ek__BackingField_3), value); } inline static int32_t get_offset_of_U3CpercentCompletedU3Ek__BackingField_4() { return static_cast(offsetof(Achievement_t2468443294, ___U3CpercentCompletedU3Ek__BackingField_4)); } inline double get_U3CpercentCompletedU3Ek__BackingField_4() const { return ___U3CpercentCompletedU3Ek__BackingField_4; } inline double* get_address_of_U3CpercentCompletedU3Ek__BackingField_4() { return &___U3CpercentCompletedU3Ek__BackingField_4; } inline void set_U3CpercentCompletedU3Ek__BackingField_4(double value) { ___U3CpercentCompletedU3Ek__BackingField_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACHIEVEMENT_T2468443294_H #ifndef ASYNCCALLBACK_T2537533359_H #define ASYNCCALLBACK_T2537533359_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.AsyncCallback struct AsyncCallback_t2537533359 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASYNCCALLBACK_T2537533359_H #ifndef SCORE_T671349143_H #define SCORE_T671349143_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.Score struct Score_t671349143 : public RuntimeObject { public: // System.DateTime UnityEngine.SocialPlatforms.Impl.Score::m_Date DateTime_t1205928702 ___m_Date_0; // System.String UnityEngine.SocialPlatforms.Impl.Score::m_FormattedValue String_t* ___m_FormattedValue_1; // System.String UnityEngine.SocialPlatforms.Impl.Score::m_UserID String_t* ___m_UserID_2; // System.Int32 UnityEngine.SocialPlatforms.Impl.Score::m_Rank int32_t ___m_Rank_3; // System.String UnityEngine.SocialPlatforms.Impl.Score::k__BackingField String_t* ___U3CleaderboardIDU3Ek__BackingField_4; // System.Int64 UnityEngine.SocialPlatforms.Impl.Score::k__BackingField int64_t ___U3CvalueU3Ek__BackingField_5; public: inline static int32_t get_offset_of_m_Date_0() { return static_cast(offsetof(Score_t671349143, ___m_Date_0)); } inline DateTime_t1205928702 get_m_Date_0() const { return ___m_Date_0; } inline DateTime_t1205928702 * get_address_of_m_Date_0() { return &___m_Date_0; } inline void set_m_Date_0(DateTime_t1205928702 value) { ___m_Date_0 = value; } inline static int32_t get_offset_of_m_FormattedValue_1() { return static_cast(offsetof(Score_t671349143, ___m_FormattedValue_1)); } inline String_t* get_m_FormattedValue_1() const { return ___m_FormattedValue_1; } inline String_t** get_address_of_m_FormattedValue_1() { return &___m_FormattedValue_1; } inline void set_m_FormattedValue_1(String_t* value) { ___m_FormattedValue_1 = value; Il2CppCodeGenWriteBarrier((&___m_FormattedValue_1), value); } inline static int32_t get_offset_of_m_UserID_2() { return static_cast(offsetof(Score_t671349143, ___m_UserID_2)); } inline String_t* get_m_UserID_2() const { return ___m_UserID_2; } inline String_t** get_address_of_m_UserID_2() { return &___m_UserID_2; } inline void set_m_UserID_2(String_t* value) { ___m_UserID_2 = value; Il2CppCodeGenWriteBarrier((&___m_UserID_2), value); } inline static int32_t get_offset_of_m_Rank_3() { return static_cast(offsetof(Score_t671349143, ___m_Rank_3)); } inline int32_t get_m_Rank_3() const { return ___m_Rank_3; } inline int32_t* get_address_of_m_Rank_3() { return &___m_Rank_3; } inline void set_m_Rank_3(int32_t value) { ___m_Rank_3 = value; } inline static int32_t get_offset_of_U3CleaderboardIDU3Ek__BackingField_4() { return static_cast(offsetof(Score_t671349143, ___U3CleaderboardIDU3Ek__BackingField_4)); } inline String_t* get_U3CleaderboardIDU3Ek__BackingField_4() const { return ___U3CleaderboardIDU3Ek__BackingField_4; } inline String_t** get_address_of_U3CleaderboardIDU3Ek__BackingField_4() { return &___U3CleaderboardIDU3Ek__BackingField_4; } inline void set_U3CleaderboardIDU3Ek__BackingField_4(String_t* value) { ___U3CleaderboardIDU3Ek__BackingField_4 = value; Il2CppCodeGenWriteBarrier((&___U3CleaderboardIDU3Ek__BackingField_4), value); } inline static int32_t get_offset_of_U3CvalueU3Ek__BackingField_5() { return static_cast(offsetof(Score_t671349143, ___U3CvalueU3Ek__BackingField_5)); } inline int64_t get_U3CvalueU3Ek__BackingField_5() const { return ___U3CvalueU3Ek__BackingField_5; } inline int64_t* get_address_of_U3CvalueU3Ek__BackingField_5() { return &___U3CvalueU3Ek__BackingField_5; } inline void set_U3CvalueU3Ek__BackingField_5(int64_t value) { ___U3CvalueU3Ek__BackingField_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCORE_T671349143_H #ifndef REAPPLYDRIVENPROPERTIES_T2885473943_H #define REAPPLYDRIVENPROPERTIES_T2885473943_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectTransform/ReapplyDrivenProperties struct ReapplyDrivenProperties_t2885473943 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REAPPLYDRIVENPROPERTIES_T2885473943_H #ifndef ACTION_1_T2897662423_H #define ACTION_1_T2897662423_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1 struct Action_1_t2897662423 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T2897662423_H #ifndef LOCALUSER_T2155741069_H #define LOCALUSER_T2155741069_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.Impl.LocalUser struct LocalUser_t2155741069 : public UserProfile_t2942407481 { public: // UnityEngine.SocialPlatforms.IUserProfile[] UnityEngine.SocialPlatforms.Impl.LocalUser::m_Friends IUserProfileU5BU5D_t3867243727* ___m_Friends_5; // System.Boolean UnityEngine.SocialPlatforms.Impl.LocalUser::m_Authenticated bool ___m_Authenticated_6; // System.Boolean UnityEngine.SocialPlatforms.Impl.LocalUser::m_Underage bool ___m_Underage_7; public: inline static int32_t get_offset_of_m_Friends_5() { return static_cast(offsetof(LocalUser_t2155741069, ___m_Friends_5)); } inline IUserProfileU5BU5D_t3867243727* get_m_Friends_5() const { return ___m_Friends_5; } inline IUserProfileU5BU5D_t3867243727** get_address_of_m_Friends_5() { return &___m_Friends_5; } inline void set_m_Friends_5(IUserProfileU5BU5D_t3867243727* value) { ___m_Friends_5 = value; Il2CppCodeGenWriteBarrier((&___m_Friends_5), value); } inline static int32_t get_offset_of_m_Authenticated_6() { return static_cast(offsetof(LocalUser_t2155741069, ___m_Authenticated_6)); } inline bool get_m_Authenticated_6() const { return ___m_Authenticated_6; } inline bool* get_address_of_m_Authenticated_6() { return &___m_Authenticated_6; } inline void set_m_Authenticated_6(bool value) { ___m_Authenticated_6 = value; } inline static int32_t get_offset_of_m_Underage_7() { return static_cast(offsetof(LocalUser_t2155741069, ___m_Underage_7)); } inline bool get_m_Underage_7() const { return ___m_Underage_7; } inline bool* get_address_of_m_Underage_7() { return &___m_Underage_7; } inline void set_m_Underage_7(bool value) { ___m_Underage_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOCALUSER_T2155741069_H #ifndef ACTION_1_T2674754663_H #define ACTION_1_T2674754663_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1 struct Action_1_t2674754663 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T2674754663_H #ifndef ACTION_2_T3787810730_H #define ACTION_2_T3787810730_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`2 struct Action_2_t3787810730 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_2_T3787810730_H #ifndef ACTION_1_T4096934434_H #define ACTION_1_T4096934434_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1 struct Action_1_t4096934434 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T4096934434_H #ifndef TEXTURE2D_T1384570725_H #define TEXTURE2D_T1384570725_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture2D struct Texture2D_t1384570725 : public Texture_t2354860603 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE2D_T1384570725_H #ifndef TRANSFORM_T2468616896_H #define TRANSFORM_T2468616896_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Transform struct Transform_t2468616896 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_T2468616896_H #ifndef ACTION_1_T604800638_H #define ACTION_1_T604800638_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1 struct Action_1_t604800638 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T604800638_H #ifndef RIGIDBODY_T2809865642_H #define RIGIDBODY_T2809865642_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Rigidbody struct Rigidbody_t2809865642 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RIGIDBODY_T2809865642_H #ifndef COLLIDER_T3058509131_H #define COLLIDER_T3058509131_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Collider struct Collider_t3058509131 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLLIDER_T3058509131_H #ifndef UPDATEDEVENTHANDLER_T860849547_H #define UPDATEDEVENTHANDLER_T860849547_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RemoteSettings/UpdatedEventHandler struct UpdatedEventHandler_t860849547 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UPDATEDEVENTHANDLER_T860849547_H #ifndef RENDERER_T3838459598_H #define RENDERER_T3838459598_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Renderer struct Renderer_t3838459598 : public Component_t590567089 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RENDERER_T3838459598_H #ifndef STATEMACHINEBEHAVIOUR_T2091767483_H #define STATEMACHINEBEHAVIOUR_T2091767483_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.StateMachineBehaviour struct StateMachineBehaviour_t2091767483 : public ScriptableObject_t505592390 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STATEMACHINEBEHAVIOUR_T2091767483_H #ifndef ACTION_1_T1552255288_H #define ACTION_1_T1552255288_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Action`1 struct Action_1_t1552255288 : public MulticastDelegate_t929297072 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T1552255288_H #ifndef CAMERA_T110840138_H #define CAMERA_T110840138_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Camera struct Camera_t110840138 : public Behaviour_t2439740933 { public: public: }; struct Camera_t110840138_StaticFields { public: // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreCull CameraCallback_t2976156859 * ___onPreCull_2; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreRender CameraCallback_t2976156859 * ___onPreRender_3; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPostRender CameraCallback_t2976156859 * ___onPostRender_4; public: inline static int32_t get_offset_of_onPreCull_2() { return static_cast(offsetof(Camera_t110840138_StaticFields, ___onPreCull_2)); } inline CameraCallback_t2976156859 * get_onPreCull_2() const { return ___onPreCull_2; } inline CameraCallback_t2976156859 ** get_address_of_onPreCull_2() { return &___onPreCull_2; } inline void set_onPreCull_2(CameraCallback_t2976156859 * value) { ___onPreCull_2 = value; Il2CppCodeGenWriteBarrier((&___onPreCull_2), value); } inline static int32_t get_offset_of_onPreRender_3() { return static_cast(offsetof(Camera_t110840138_StaticFields, ___onPreRender_3)); } inline CameraCallback_t2976156859 * get_onPreRender_3() const { return ___onPreRender_3; } inline CameraCallback_t2976156859 ** get_address_of_onPreRender_3() { return &___onPreRender_3; } inline void set_onPreRender_3(CameraCallback_t2976156859 * value) { ___onPreRender_3 = value; Il2CppCodeGenWriteBarrier((&___onPreRender_3), value); } inline static int32_t get_offset_of_onPostRender_4() { return static_cast(offsetof(Camera_t110840138_StaticFields, ___onPostRender_4)); } inline CameraCallback_t2976156859 * get_onPostRender_4() const { return ___onPostRender_4; } inline CameraCallback_t2976156859 ** get_address_of_onPostRender_4() { return &___onPostRender_4; } inline void set_onPostRender_4(CameraCallback_t2976156859 * value) { ___onPostRender_4 = value; Il2CppCodeGenWriteBarrier((&___onPostRender_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAMERA_T110840138_H #ifndef GUILAYER_T1356563649_H #define GUILAYER_T1356563649_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GUILayer struct GUILayer_t1356563649 : public Behaviour_t2439740933 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GUILAYER_T1356563649_H #ifndef SPRITERENDERER_T1459332486_H #define SPRITERENDERER_T1459332486_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SpriteRenderer struct SpriteRenderer_t1459332486 : public Renderer_t3838459598 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SPRITERENDERER_T1459332486_H #ifndef CANVAS_T2948613984_H #define CANVAS_T2948613984_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Canvas struct Canvas_t2948613984 : public Behaviour_t2439740933 { public: public: }; struct Canvas_t2948613984_StaticFields { public: // UnityEngine.Canvas/WillRenderCanvases UnityEngine.Canvas::willRenderCanvases WillRenderCanvases_t1008191882 * ___willRenderCanvases_2; public: inline static int32_t get_offset_of_willRenderCanvases_2() { return static_cast(offsetof(Canvas_t2948613984_StaticFields, ___willRenderCanvases_2)); } inline WillRenderCanvases_t1008191882 * get_willRenderCanvases_2() const { return ___willRenderCanvases_2; } inline WillRenderCanvases_t1008191882 ** get_address_of_willRenderCanvases_2() { return &___willRenderCanvases_2; } inline void set_willRenderCanvases_2(WillRenderCanvases_t1008191882 * value) { ___willRenderCanvases_2 = value; Il2CppCodeGenWriteBarrier((&___willRenderCanvases_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CANVAS_T2948613984_H #ifndef COLLIDER2D_T2180151806_H #define COLLIDER2D_T2180151806_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Collider2D struct Collider2D_t2180151806 : public Behaviour_t2439740933 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLLIDER2D_T2180151806_H #ifndef RECTTRANSFORM_T3700156813_H #define RECTTRANSFORM_T3700156813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RectTransform struct RectTransform_t3700156813 : public Transform_t2468616896 { public: public: }; struct RectTransform_t3700156813_StaticFields { public: // UnityEngine.RectTransform/ReapplyDrivenProperties UnityEngine.RectTransform::reapplyDrivenProperties ReapplyDrivenProperties_t2885473943 * ___reapplyDrivenProperties_2; public: inline static int32_t get_offset_of_reapplyDrivenProperties_2() { return static_cast(offsetof(RectTransform_t3700156813_StaticFields, ___reapplyDrivenProperties_2)); } inline ReapplyDrivenProperties_t2885473943 * get_reapplyDrivenProperties_2() const { return ___reapplyDrivenProperties_2; } inline ReapplyDrivenProperties_t2885473943 ** get_address_of_reapplyDrivenProperties_2() { return &___reapplyDrivenProperties_2; } inline void set_reapplyDrivenProperties_2(ReapplyDrivenProperties_t2885473943 * value) { ___reapplyDrivenProperties_2 = value; Il2CppCodeGenWriteBarrier((&___reapplyDrivenProperties_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RECTTRANSFORM_T3700156813_H #ifndef ANIMATOR_T3669487027_H #define ANIMATOR_T3669487027_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Animator struct Animator_t3669487027 : public Behaviour_t2439740933 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ANIMATOR_T3669487027_H #ifndef SPHERECOLLIDER_T2896221692_H #define SPHERECOLLIDER_T2896221692_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SphereCollider struct SphereCollider_t2896221692 : public Collider_t3058509131 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SPHERECOLLIDER_T2896221692_H #ifndef GUIELEMENT_T316128140_H #define GUIELEMENT_T316128140_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GUIElement struct GUIElement_t316128140 : public Behaviour_t2439740933 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GUIELEMENT_T316128140_H // System.Object[] struct ObjectU5BU5D_t3885370135 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject * m_Items[1]; public: inline RuntimeObject * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.Vector3[] struct Vector3U5BU5D_t2251457841 : public RuntimeArray { public: ALIGN_FIELD (8) Vector3_t67624592 m_Items[1]; public: inline Vector3_t67624592 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Vector3_t67624592 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Vector3_t67624592 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline Vector3_t67624592 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Vector3_t67624592 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Vector3_t67624592 value) { m_Items[index] = value; } }; // UnityEngine.Object[] struct ObjectU5BU5D_t348161528 : public RuntimeArray { public: ALIGN_FIELD (8) Object_t1332387349 * m_Items[1]; public: inline Object_t1332387349 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Object_t1332387349 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Object_t1332387349 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline Object_t1332387349 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Object_t1332387349 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Object_t1332387349 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.Camera[] struct CameraU5BU5D_t2507966031 : public RuntimeArray { public: ALIGN_FIELD (8) Camera_t110840138 * m_Items[1]; public: inline Camera_t110840138 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Camera_t110840138 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Camera_t110840138 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline Camera_t110840138 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Camera_t110840138 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Camera_t110840138 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SendMouseEvents/HitInfo[] struct HitInfoU5BU5D_t4176695186 : public RuntimeArray { public: ALIGN_FIELD (8) HitInfo_t2268685571 m_Items[1]; public: inline HitInfo_t2268685571 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline HitInfo_t2268685571 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, HitInfo_t2268685571 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline HitInfo_t2268685571 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline HitInfo_t2268685571 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, HitInfo_t2268685571 value) { m_Items[index] = value; } }; // System.Reflection.ParameterModifier[] struct ParameterModifierU5BU5D_t730609508 : public RuntimeArray { public: ALIGN_FIELD (8) ParameterModifier_t2814373913 m_Items[1]; public: inline ParameterModifier_t2814373913 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline ParameterModifier_t2814373913 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, ParameterModifier_t2814373913 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline ParameterModifier_t2814373913 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline ParameterModifier_t2814373913 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, ParameterModifier_t2814373913 value) { m_Items[index] = value; } }; // System.String[] struct StringU5BU5D_t3608572874 : public RuntimeArray { public: ALIGN_FIELD (8) String_t* m_Items[1]; public: inline String_t* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline String_t** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, String_t* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline String_t* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline String_t** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, String_t* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.Impl.AchievementDescription[] struct AchievementDescriptionU5BU5D_t916063548 : public RuntimeArray { public: ALIGN_FIELD (8) AchievementDescription_t991053089 * m_Items[1]; public: inline AchievementDescription_t991053089 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline AchievementDescription_t991053089 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, AchievementDescription_t991053089 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline AchievementDescription_t991053089 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline AchievementDescription_t991053089 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, AchievementDescription_t991053089 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.IAchievementDescription[] struct IAchievementDescriptionU5BU5D_t3064410227 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject* m_Items[1]; public: inline RuntimeObject* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.Impl.UserProfile[] struct UserProfileU5BU5D_t3377267652 : public RuntimeArray { public: ALIGN_FIELD (8) UserProfile_t2942407481 * m_Items[1]; public: inline UserProfile_t2942407481 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline UserProfile_t2942407481 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, UserProfile_t2942407481 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline UserProfile_t2942407481 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline UserProfile_t2942407481 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, UserProfile_t2942407481 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.IUserProfile[] struct IUserProfileU5BU5D_t3867243727 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject* m_Items[1]; public: inline RuntimeObject* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.GameCenter.GcAchievementData[] struct GcAchievementDataU5BU5D_t1247845579 : public RuntimeArray { public: ALIGN_FIELD (8) GcAchievementData_t3004100478 m_Items[1]; public: inline GcAchievementData_t3004100478 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline GcAchievementData_t3004100478 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, GcAchievementData_t3004100478 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline GcAchievementData_t3004100478 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline GcAchievementData_t3004100478 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, GcAchievementData_t3004100478 value) { m_Items[index] = value; } }; // UnityEngine.SocialPlatforms.Impl.Achievement[] struct AchievementU5BU5D_t867614507 : public RuntimeArray { public: ALIGN_FIELD (8) Achievement_t2468443294 * m_Items[1]; public: inline Achievement_t2468443294 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Achievement_t2468443294 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Achievement_t2468443294 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline Achievement_t2468443294 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Achievement_t2468443294 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Achievement_t2468443294 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.IAchievement[] struct IAchievementU5BU5D_t1865138216 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject* m_Items[1]; public: inline RuntimeObject* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.GameCenter.GcScoreData[] struct GcScoreDataU5BU5D_t859946003 : public RuntimeArray { public: ALIGN_FIELD (8) GcScoreData_t1096391638 m_Items[1]; public: inline GcScoreData_t1096391638 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline GcScoreData_t1096391638 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, GcScoreData_t1096391638 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline GcScoreData_t1096391638 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline GcScoreData_t1096391638 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, GcScoreData_t1096391638 value) { m_Items[index] = value; } }; // UnityEngine.SocialPlatforms.Impl.Score[] struct ScoreU5BU5D_t13505070 : public RuntimeArray { public: ALIGN_FIELD (8) Score_t671349143 * m_Items[1]; public: inline Score_t671349143 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Score_t671349143 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Score_t671349143 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline Score_t671349143 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Score_t671349143 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Score_t671349143 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // UnityEngine.SocialPlatforms.IScore[] struct IScoreU5BU5D_t519731081 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject* m_Items[1]; public: inline RuntimeObject* GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject* value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject* GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject* value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // System.Char[] struct CharU5BU5D_t1522321484 : public RuntimeArray { public: ALIGN_FIELD (8) Il2CppChar m_Items[1]; public: inline Il2CppChar GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Il2CppChar* GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Il2CppChar value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline Il2CppChar GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Il2CppChar* GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Il2CppChar value) { m_Items[index] = value; } }; // System.Reflection.ParameterInfo[] struct ParameterInfoU5BU5D_t2585026604 : public RuntimeArray { public: ALIGN_FIELD (8) ParameterInfo_t1917333745 * m_Items[1]; public: inline ParameterInfo_t1917333745 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline ParameterInfo_t1917333745 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, ParameterInfo_t1917333745 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline ParameterInfo_t1917333745 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline ParameterInfo_t1917333745 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, ParameterInfo_t1917333745 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke(const TextGenerationSettings_t2955391441& unmarshaled, TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled); extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke_back(const TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled, TextGenerationSettings_t2955391441& unmarshaled); extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke_cleanup(TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled); extern "C" void TextGenerationSettings_t2955391441_marshal_com(const TextGenerationSettings_t2955391441& unmarshaled, TextGenerationSettings_t2955391441_marshaled_com& marshaled); extern "C" void TextGenerationSettings_t2955391441_marshal_com_back(const TextGenerationSettings_t2955391441_marshaled_com& marshaled, TextGenerationSettings_t2955391441& unmarshaled); extern "C" void TextGenerationSettings_t2955391441_marshal_com_cleanup(TextGenerationSettings_t2955391441_marshaled_com& marshaled); // System.Boolean UnityEngine.Playables.PlayableOutputHandle::IsPlayableOutputOfType() extern "C" bool PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539_gshared (PlayableOutputHandle_t192146840 * __this, const RuntimeMethod* method); // System.Void UnityEngine.Events.UnityAction`2::Invoke(T0,T1) extern "C" void UnityAction_2_Invoke_m142841862_gshared (UnityAction_2_t1303706228 * __this, Scene_t886992912 p0, int32_t p1, const RuntimeMethod* method); // System.Void UnityEngine.Events.UnityAction`1::Invoke(T0) extern "C" void UnityAction_1_Invoke_m3288951857_gshared (UnityAction_1_t2300191644 * __this, Scene_t886992912 p0, const RuntimeMethod* method); // System.Void UnityEngine.Events.UnityAction`2::Invoke(T0,T1) extern "C" void UnityAction_2_Invoke_m1774221970_gshared (UnityAction_2_t1173199225 * __this, Scene_t886992912 p0, Scene_t886992912 p1, const RuntimeMethod* method); // T UnityEngine.Component::GetComponent() extern "C" RuntimeObject * Component_GetComponent_TisRuntimeObject_m759789627_gshared (Component_t590567089 * __this, const RuntimeMethod* method); // System.Void System.Action`1::Invoke(!0) extern "C" void Action_1_Invoke_m3167810884_gshared (Action_1_t3641405393 * __this, RuntimeObject * p0, const RuntimeMethod* method); // System.Void System.Action`2::Invoke(!0,!1) extern "C" void Action_2_Invoke_m2096004357_gshared (Action_2_t2127932065 * __this, bool p0, RuntimeObject * p1, const RuntimeMethod* method); // System.Void System.Action`1::Invoke(!0) extern "C" void Action_1_Invoke_m3062505204_gshared (Action_1_t2674754663 * __this, bool p0, const RuntimeMethod* method); // System.Void System.Action`2::.ctor(System.Object,System.IntPtr) extern "C" void Action_2__ctor_m1834669280_gshared (Action_2_t2127932065 * __this, RuntimeObject * p0, IntPtr_t p1, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::Add(!0) extern "C" void List_1_Add_m2041078292_gshared (List_1_t1831767026 * __this, RuntimeObject * p0, const RuntimeMethod* method); // System.Collections.Generic.List`1/Enumerator System.Collections.Generic.List`1::GetEnumerator() extern "C" Enumerator_t3520049488 List_1_GetEnumerator_m2562807503_gshared (List_1_t1831767026 * __this, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1/Enumerator::get_Current() extern "C" RuntimeObject * Enumerator_get_Current_m1434536216_gshared (Enumerator_t3520049488 * __this, const RuntimeMethod* method); // System.Boolean System.Collections.Generic.List`1/Enumerator::MoveNext() extern "C" bool Enumerator_MoveNext_m4181024596_gshared (Enumerator_t3520049488 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1/Enumerator::Dispose() extern "C" void Enumerator_Dispose_m215493026_gshared (Enumerator_t3520049488 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor() extern "C" void List_1__ctor_m3371656545_gshared (List_1_t1831767026 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) extern "C" void List_1__ctor_m2525236808_gshared (List_1_t2359577098 * __this, int32_t p0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) extern "C" void List_1__ctor_m691252865_gshared (List_1_t369525373 * __this, int32_t p0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) extern "C" void List_1__ctor_m581423473_gshared (List_1_t1470875743 * __this, int32_t p0, const RuntimeMethod* method); // System.Boolean UnityEngine.Playables.PlayableOutputHandle::IsValid() extern "C" bool PlayableOutputHandle_IsValid_m2825682027 (PlayableOutputHandle_t192146840 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Playables.PlayableOutputHandle::IsPlayableOutputOfType() #define PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539(__this, method) (( bool (*) (PlayableOutputHandle_t192146840 *, const RuntimeMethod*))PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539_gshared)(__this, method) // System.Void System.InvalidCastException::.ctor(System.String) extern "C" void InvalidCastException__ctor_m3226723941 (InvalidCastException_t865352475 * __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Playables.ScriptPlayableOutput::.ctor(UnityEngine.Playables.PlayableOutputHandle) extern "C" void ScriptPlayableOutput__ctor_m1887120702 (ScriptPlayableOutput_t3853613875 * __this, PlayableOutputHandle_t192146840 ___handle0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Playables.PlayableGraph::CreateScriptOutputInternal(UnityEngine.Playables.PlayableGraph&,System.String,UnityEngine.Playables.PlayableOutputHandle&) extern "C" bool PlayableGraph_CreateScriptOutputInternal_m2465551668 (RuntimeObject * __this /* static, unused */, PlayableGraph_t3648426783 * ___graph0, String_t* ___name1, PlayableOutputHandle_t192146840 * ___handle2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Playables.ScriptPlayableOutput UnityEngine.Playables.ScriptPlayableOutput::get_Null() extern "C" ScriptPlayableOutput_t3853613875 ScriptPlayableOutput_get_Null_m1162854030 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.PlayableOutputHandle::get_Null() extern "C" PlayableOutputHandle_t192146840 PlayableOutputHandle_get_Null_m1078851567 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.ScriptPlayableOutput::GetHandle() extern "C" PlayableOutputHandle_t192146840 ScriptPlayableOutput_GetHandle_m1901531121 (ScriptPlayableOutput_t3853613875 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Playables.PlayableOutput::.ctor(UnityEngine.Playables.PlayableOutputHandle) extern "C" void PlayableOutput__ctor_m2391480348 (PlayableOutput_t1264890687 * __this, PlayableOutputHandle_t192146840 ___handle0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.PlayableOutput::GetHandle() extern "C" PlayableOutputHandle_t192146840 PlayableOutput_GetHandle_m135471249 (PlayableOutput_t1264890687 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Attribute::.ctor() extern "C" void Attribute__ctor_m574845334 (Attribute_t739646798 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::.ctor(System.Single,System.Single,System.Single,System.Single) extern "C" void Quaternion__ctor_m4162241598 (Quaternion_t4184531171 * __this, float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::get_up() extern "C" Vector3_t67624592 Vector3_get_up_m1147648688 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::INTERNAL_CALL_LookRotation(UnityEngine.Vector3&,UnityEngine.Vector3&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_LookRotation_m928515228 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 * ___forward0, Vector3_t67624592 * ___upwards1, Quaternion_t4184531171 * ___value2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Lerp(UnityEngine.Quaternion&,UnityEngine.Quaternion&,System.Single,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Lerp_m1992590364 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___a0, Quaternion_t4184531171 * ___b1, float ___t2, Quaternion_t4184531171 * ___value3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Inverse(UnityEngine.Quaternion&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Inverse_m1677209099 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___rotation0, Quaternion_t4184531171 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Quaternion::Internal_ToEulerRad(UnityEngine.Quaternion) extern "C" Vector3_t67624592 Quaternion_Internal_ToEulerRad_m298111895 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___rotation0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::op_Multiply(UnityEngine.Vector3,System.Single) extern "C" Vector3_t67624592 Vector3_op_Multiply_m1441463291 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___a0, float ___d1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Quaternion::Internal_MakePositive(UnityEngine.Vector3) extern "C" Vector3_t67624592 Quaternion_Internal_MakePositive_m281077695 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___euler0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Quaternion::get_eulerAngles() extern "C" Vector3_t67624592 Quaternion_get_eulerAngles_m2921540577 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single) extern "C" void Vector3__ctor_m649967503 (Vector3_t67624592 * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Quaternion UnityEngine.Quaternion::Internal_FromEulerRad(UnityEngine.Vector3) extern "C" Quaternion_t4184531171 Quaternion_Internal_FromEulerRad_m2729453363 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___euler0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Internal_ToEulerRad(UnityEngine.Quaternion&,UnityEngine.Vector3&) extern "C" void Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___rotation0, Vector3_t67624592 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Internal_FromEulerRad(UnityEngine.Vector3&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 * ___euler0, Quaternion_t4184531171 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Quaternion::Dot(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" float Quaternion_Dot_m3305700391 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___a0, Quaternion_t4184531171 ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Quaternion::op_Equality(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" bool Quaternion_op_Equality_m3282458924 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___lhs0, Quaternion_t4184531171 ___rhs1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Single::GetHashCode() extern "C" int32_t Single_GetHashCode_m177552305 (float* __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Quaternion::GetHashCode() extern "C" int32_t Quaternion_GetHashCode_m4096992011 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.Single::Equals(System.Single) extern "C" bool Single_Equals_m767089390 (float* __this, float p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Quaternion::Equals(System.Object) extern "C" bool Quaternion_Equals_m3924578426 (Quaternion_t4184531171 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.UnityString::Format(System.String,System.Object[]) extern "C" String_t* UnityString_Format_m1454782387 (RuntimeObject * __this /* static, unused */, String_t* ___fmt0, ObjectU5BU5D_t3885370135* ___args1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.Quaternion::ToString() extern "C" String_t* Quaternion_ToString_m4223730163 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Random::RandomRangeInt(System.Int32,System.Int32) extern "C" int32_t Random_RandomRangeInt_m708986018 (RuntimeObject * __this /* static, unused */, int32_t ___min0, int32_t ___max1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.PropertyAttribute::.ctor() extern "C" void PropertyAttribute__ctor_m1537537891 (PropertyAttribute_t2314996045 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RangeInt::get_end() extern "C" int32_t RangeInt_get_end_m2625147402 (RangeInt_t772515686 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::get_normalized() extern "C" Vector3_t67624592 Vector3_get_normalized_m2262836590 (Vector3_t67624592 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Ray::.ctor(UnityEngine.Vector3,UnityEngine.Vector3) extern "C" void Ray__ctor_m1769593825 (Ray_t3058960190 * __this, Vector3_t67624592 ___origin0, Vector3_t67624592 ___direction1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Ray::get_origin() extern "C" Vector3_t67624592 Ray_get_origin_m3158142785 (Ray_t3058960190 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Ray::get_direction() extern "C" Vector3_t67624592 Ray_get_direction_m2485610855 (Ray_t3058960190 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::op_Addition(UnityEngine.Vector3,UnityEngine.Vector3) extern "C" Vector3_t67624592 Vector3_op_Addition_m3078548397 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___a0, Vector3_t67624592 ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Ray::GetPoint(System.Single) extern "C" Vector3_t67624592 Ray_GetPoint_m1809995955 (Ray_t3058960190 * __this, float ___distance0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.Ray::ToString() extern "C" String_t* Ray_ToString_m4189095882 (Ray_t3058960190 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() extern "C" Vector3_t67624592 RaycastHit_get_point_m1459319107 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() extern "C" Vector3_t67624592 RaycastHit_get_normal_m2782368312 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.RaycastHit::get_distance() extern "C" float RaycastHit_get_distance_m2739708343 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Collider UnityEngine.RaycastHit::get_collider() extern "C" Collider_t3058509131 * RaycastHit_get_collider_m1042127013 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Object::op_Inequality(UnityEngine.Object,UnityEngine.Object) extern "C" bool Object_op_Inequality_m68474028 (RuntimeObject * __this /* static, unused */, Object_t1332387349 * ___x0, Object_t1332387349 * ___y1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rigidbody UnityEngine.Collider::get_attachedRigidbody() extern "C" Rigidbody_t2809865642 * Collider_get_attachedRigidbody_m4234646872 (Collider_t3058509131 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rigidbody UnityEngine.RaycastHit::get_rigidbody() extern "C" Rigidbody_t2809865642 * RaycastHit_get_rigidbody_m507930372 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Transform UnityEngine.Component::get_transform() extern "C" Transform_t2468616896 * Component_get_transform_m987883457 (Component_t590567089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Transform UnityEngine.RaycastHit::get_transform() extern "C" Transform_t2468616896 * RaycastHit_get_transform_m3831275417 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RaycastHit2D::get_point() extern "C" Vector2_t3854014517 RaycastHit2D_get_point_m2657298746 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RaycastHit2D::get_normal() extern "C" Vector2_t3854014517 RaycastHit2D_get_normal_m3413167889 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.RaycastHit2D::get_distance() extern "C" float RaycastHit2D_get_distance_m1140368293 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Collider2D UnityEngine.RaycastHit2D::get_collider() extern "C" Collider2D_t2180151806 * RaycastHit2D_get_collider_m653937822 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::.ctor(System.Single,System.Single,System.Single,System.Single) extern "C" void Rect__ctor_m2220344300 (Rect_t3345319094 * __this, float ___x0, float ___y1, float ___width2, float ___height3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_x() extern "C" float Rect_get_x_m1272655030 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_x(System.Single) extern "C" void Rect_set_x_m3651671365 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_y() extern "C" float Rect_get_y_m2529319960 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_y(System.Single) extern "C" void Rect_set_y_m2142941418 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Vector2::.ctor(System.Single,System.Single) extern "C" void Vector2__ctor_m2886412624 (Vector2_t3854014517 * __this, float ___x0, float ___y1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rect::get_position() extern "C" Vector2_t3854014517 Rect_get_position_m831243348 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rect::get_center() extern "C" Vector2_t3854014517 Rect_get_center_m3493146972 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_xMin() extern "C" float Rect_get_xMin_m244230138 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_yMin() extern "C" float Rect_get_yMin_m3454706255 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rect::get_min() extern "C" Vector2_t3854014517 Rect_get_min_m1865906224 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_xMax() extern "C" float Rect_get_xMax_m4219133595 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_yMax() extern "C" float Rect_get_yMax_m2538035064 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rect::get_max() extern "C" Vector2_t3854014517 Rect_get_max_m533053384 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_width() extern "C" float Rect_get_width_m1618071060 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_width(System.Single) extern "C" void Rect_set_width_m370999829 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Rect::get_height() extern "C" float Rect_get_height_m2713477301 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_height(System.Single) extern "C" void Rect_set_height_m172432063 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Rect::get_size() extern "C" Vector2_t3854014517 Rect_get_size_m3072131835 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_xMin(System.Single) extern "C" void Rect_set_xMin_m2854702664 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_yMin(System.Single) extern "C" void Rect_set_yMin_m4106440077 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_xMax(System.Single) extern "C" void Rect_set_xMax_m4103720006 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Rect::set_yMax(System.Single) extern "C" void Rect_set_yMax_m29778259 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::Contains(UnityEngine.Vector2) extern "C" bool Rect_Contains_m644002242 (Rect_t3345319094 * __this, Vector2_t3854014517 ___point0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::Contains(UnityEngine.Vector3) extern "C" bool Rect_Contains_m3823093228 (Rect_t3345319094 * __this, Vector3_t67624592 ___point0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::Overlaps(UnityEngine.Rect) extern "C" bool Rect_Overlaps_m598195426 (Rect_t3345319094 * __this, Rect_t3345319094 ___other0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rect UnityEngine.Rect::OrderMinMax(UnityEngine.Rect) extern "C" Rect_t3345319094 Rect_OrderMinMax_m858648141 (RuntimeObject * __this /* static, unused */, Rect_t3345319094 ___rect0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::Overlaps(UnityEngine.Rect,System.Boolean) extern "C" bool Rect_Overlaps_m3515144730 (Rect_t3345319094 * __this, Rect_t3345319094 ___other0, bool ___allowInverse1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::op_Equality(UnityEngine.Rect,UnityEngine.Rect) extern "C" bool Rect_op_Equality_m2493013221 (RuntimeObject * __this /* static, unused */, Rect_t3345319094 ___lhs0, Rect_t3345319094 ___rhs1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Rect::GetHashCode() extern "C" int32_t Rect_GetHashCode_m3046645869 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Rect::Equals(System.Object) extern "C" bool Rect_Equals_m2118345215 (Rect_t3345319094 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.Rect::ToString() extern "C" String_t* Rect_ToString_m3090827388 (Rect_t3345319094 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Object::.ctor() extern "C" void Object__ctor_m1196001181 (RuntimeObject * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectOffset::Init() extern "C" void RectOffset_Init_m1864310113 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectOffset::Cleanup() extern "C" void RectOffset_Cleanup_m1072908984 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Object::Finalize() extern "C" void Object_Finalize_m3696538117 (RuntimeObject * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RectOffset::get_left() extern "C" int32_t RectOffset_get_left_m1369329921 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RectOffset::get_right() extern "C" int32_t RectOffset_get_right_m2365972138 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RectOffset::get_top() extern "C" int32_t RectOffset_get_top_m3242062285 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RectOffset::get_bottom() extern "C" int32_t RectOffset_get_bottom_m3922972562 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_rect(UnityEngine.Rect&) extern "C" void RectTransform_INTERNAL_get_rect_m2728143655 (RectTransform_t3700156813 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_anchorMin(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchorMin_m42883384 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_set_anchorMin(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchorMin_m1456566770 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_anchorMax(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchorMax_m3234636927 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_set_anchorMax(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchorMax_m1391116051 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_anchoredPosition(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchoredPosition_m2955393727 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_set_anchoredPosition(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchoredPosition_m3010510872 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_sizeDelta(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_sizeDelta_m1660093871 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_set_sizeDelta(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_sizeDelta_m2649046399 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_get_pivot(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_pivot_m3267718409 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::INTERNAL_set_pivot(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_pivot_m4113449629 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Delegate System.Delegate::Combine(System.Delegate,System.Delegate) extern "C" Delegate_t2669736448 * Delegate_Combine_m322163940 (RuntimeObject * __this /* static, unused */, Delegate_t2669736448 * p0, Delegate_t2669736448 * p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Delegate System.Delegate::Remove(System.Delegate,System.Delegate) extern "C" Delegate_t2669736448 * Delegate_Remove_m537953058 (RuntimeObject * __this /* static, unused */, Delegate_t2669736448 * p0, Delegate_t2669736448 * p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform/ReapplyDrivenProperties::Invoke(UnityEngine.RectTransform) extern "C" void ReapplyDrivenProperties_Invoke_m3653398493 (ReapplyDrivenProperties_t2885473943 * __this, RectTransform_t3700156813 * ___driven0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Debug::LogError(System.Object) extern "C" void Debug_LogError_m3009049438 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___message0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rect UnityEngine.RectTransform::get_rect() extern "C" Rect_t3345319094 RectTransform_get_rect_m2145828853 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::GetLocalCorners(UnityEngine.Vector3[]) extern "C" void RectTransform_GetLocalCorners_m702431553 (RectTransform_t3700156813 * __this, Vector3U5BU5D_t2251457841* ___fourCornersArray0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Transform::TransformPoint(UnityEngine.Vector3) extern "C" Vector3_t67624592 Transform_TransformPoint_m3154744607 (Transform_t2468616896 * __this, Vector3_t67624592 ___position0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchoredPosition() extern "C" Vector2_t3854014517 RectTransform_get_anchoredPosition_m3838889794 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::get_sizeDelta() extern "C" Vector2_t3854014517 RectTransform_get_sizeDelta_m2732713248 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::get_pivot() extern "C" Vector2_t3854014517 RectTransform_get_pivot_m186250636 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::Scale(UnityEngine.Vector2,UnityEngine.Vector2) extern "C" Vector2_t3854014517 Vector2_Scale_m3102216472 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___a0, Vector2_t3854014517 ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::op_Subtraction(UnityEngine.Vector2,UnityEngine.Vector2) extern "C" Vector2_t3854014517 Vector2_op_Subtraction_m2940341944 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___a0, Vector2_t3854014517 ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::set_sizeDelta(UnityEngine.Vector2) extern "C" void RectTransform_set_sizeDelta_m2388347220 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::get_one() extern "C" Vector2_t3854014517 Vector2_get_one_m3462198535 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::op_Addition(UnityEngine.Vector2,UnityEngine.Vector2) extern "C" Vector2_t3854014517 Vector2_op_Addition_m1125554698 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___a0, Vector2_t3854014517 ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::set_anchoredPosition(UnityEngine.Vector2) extern "C" void RectTransform_set_anchoredPosition_m754568721 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchorMin() extern "C" Vector2_t3854014517 RectTransform_get_anchorMin_m3875085598 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Vector2::set_Item(System.Int32,System.Single) extern "C" void Vector2_set_Item_m1415764177 (Vector2_t3854014517 * __this, int32_t ___index0, float ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::set_anchorMin(UnityEngine.Vector2) extern "C" void RectTransform_set_anchorMin_m813062776 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchorMax() extern "C" Vector2_t3854014517 RectTransform_get_anchorMax_m211673889 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::set_anchorMax(UnityEngine.Vector2) extern "C" void RectTransform_set_anchorMax_m1270568626 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Vector2::get_Item(System.Int32) extern "C" float Vector2_get_Item_m380735974 (Vector2_t3854014517 * __this, int32_t ___index0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransform::GetParentSize() extern "C" Vector2_t3854014517 RectTransform_GetParentSize_m101662412 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Transform UnityEngine.Transform::get_parent() extern "C" Transform_t2468616896 * Transform_get_parent_m4197710916 (Transform_t2468616896 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Object::op_Implicit(UnityEngine.Object) extern "C" bool Object_op_Implicit_m3026831640 (RuntimeObject * __this /* static, unused */, Object_t1332387349 * ___exists0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::get_zero() extern "C" Vector2_t3854014517 Vector2_get_zero_m1977254044 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector2::op_Implicit(UnityEngine.Vector2) extern "C" Vector3_t67624592 Vector2_op_Implicit_m1696140672 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___v0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Ray UnityEngine.RectTransformUtility::ScreenPointToRay(UnityEngine.Camera,UnityEngine.Vector2) extern "C" Ray_t3058960190 RectTransformUtility_ScreenPointToRay_m768706565 (RuntimeObject * __this /* static, unused */, Camera_t110840138 * ___cam0, Vector2_t3854014517 ___screenPos1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Quaternion UnityEngine.Transform::get_rotation() extern "C" Quaternion_t4184531171 Transform_get_rotation_m3767592267 (Transform_t2468616896 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::get_back() extern "C" Vector3_t67624592 Vector3_get_back_m1005823721 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Quaternion::op_Multiply(UnityEngine.Quaternion,UnityEngine.Vector3) extern "C" Vector3_t67624592 Quaternion_op_Multiply_m1066223492 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___rotation0, Vector3_t67624592 ___point1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Transform::get_position() extern "C" Vector3_t67624592 Transform_get_position_m3786962343 (Transform_t2468616896 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Plane::.ctor(UnityEngine.Vector3,UnityEngine.Vector3) extern "C" void Plane__ctor_m1656613681 (Plane_t3179518881 * __this, Vector3_t67624592 ___inNormal0, Vector3_t67624592 ___inPoint1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Plane::Raycast(UnityEngine.Ray,System.Single&) extern "C" bool Plane_Raycast_m1563516470 (Plane_t3179518881 * __this, Ray_t3058960190 ___ray0, float* ___enter1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.RectTransformUtility::ScreenPointToWorldPointInRectangle(UnityEngine.RectTransform,UnityEngine.Vector2,UnityEngine.Camera,UnityEngine.Vector3&) extern "C" bool RectTransformUtility_ScreenPointToWorldPointInRectangle_m949791734 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 ___screenPoint1, Camera_t110840138 * ___cam2, Vector3_t67624592 * ___worldPoint3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Transform::InverseTransformPoint(UnityEngine.Vector3) extern "C" Vector3_t67624592 Transform_InverseTransformPoint_m4188161690 (Transform_t2468616896 * __this, Vector3_t67624592 ___position0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.Vector2::op_Implicit(UnityEngine.Vector3) extern "C" Vector2_t3854014517 Vector2_op_Implicit_m2584888397 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___v0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Ray UnityEngine.Camera::ScreenPointToRay(UnityEngine.Vector3) extern "C" Ray_t3058960190 Camera_ScreenPointToRay_m2745386935 (Camera_t110840138 * __this, Vector3_t67624592 ___position0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Vector3::get_forward() extern "C" Vector3_t67624592 Vector3_get_forward_m326191705 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Object::op_Equality(UnityEngine.Object,UnityEngine.Object) extern "C" bool Object_op_Equality_m1674932247 (RuntimeObject * __this /* static, unused */, Object_t1332387349 * ___x0, Object_t1332387349 * ___y1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Transform UnityEngine.Transform::GetChild(System.Int32) extern "C" Transform_t2468616896 * Transform_GetChild_m5845828 (Transform_t2468616896 * __this, int32_t ___index0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransformUtility::FlipLayoutOnAxis(UnityEngine.RectTransform,System.Int32,System.Boolean,System.Boolean) extern "C" void RectTransformUtility_FlipLayoutOnAxis_m932564554 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, int32_t ___axis1, bool ___keepPositioning2, bool ___recursive3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Transform::get_childCount() extern "C" int32_t Transform_get_childCount_m1791344060 (Transform_t2468616896 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransform::set_pivot(UnityEngine.Vector2) extern "C" void RectTransform_set_pivot_m1268266743 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransformUtility::FlipLayoutAxes(UnityEngine.RectTransform,System.Boolean,System.Boolean) extern "C" void RectTransformUtility_FlipLayoutAxes_m4222183317 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, bool ___keepPositioning1, bool ___recursive2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector2 UnityEngine.RectTransformUtility::GetTransposed(UnityEngine.Vector2) extern "C" Vector2_t3854014517 RectTransformUtility_GetTransposed_m3113223627 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___input0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.RectTransformUtility::INTERNAL_CALL_RectangleContainsScreenPoint(UnityEngine.RectTransform,UnityEngine.Vector2&,UnityEngine.Camera) extern "C" bool RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 * ___screenPoint1, Camera_t110840138 * ___cam2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustPoint(UnityEngine.Vector2&,UnityEngine.Transform,UnityEngine.Canvas,UnityEngine.Vector2&) extern "C" void RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 * ___point0, Transform_t2468616896 * ___elementTransform1, Canvas_t2948613984 * ___canvas2, Vector2_t3854014517 * ___value3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustRect(UnityEngine.RectTransform,UnityEngine.Canvas,UnityEngine.Rect&) extern "C" void RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rectTransform0, Canvas_t2948613984 * ___canvas1, Rect_t3345319094 * ___value2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::Invoke() extern "C" void UpdatedEventHandler_Invoke_m3549789676 (UpdatedEventHandler_t860849547 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RenderTexture::Internal_GetWidth(UnityEngine.RenderTexture) extern "C" int32_t RenderTexture_Internal_GetWidth_m1234090841 (RuntimeObject * __this /* static, unused */, RenderTexture_t3726137678 * ___mono0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.RenderTexture::Internal_GetHeight(UnityEngine.RenderTexture) extern "C" int32_t RenderTexture_Internal_GetHeight_m3898225001 (RuntimeObject * __this /* static, unused */, RenderTexture_t3726137678 * ___mono0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.AsyncOperation::.ctor() extern "C" void AsyncOperation__ctor_m754450522 (AsyncOperation_t1152358279 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Object UnityEngine.Resources::Load(System.String,System.Type) extern "C" Object_t1332387349 * Resources_Load_m3998181239 (RuntimeObject * __this /* static, unused */, String_t* ___path0, Type_t * ___systemTypeInstance1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle) extern "C" Type_t * Type_GetTypeFromHandle_m2676592772 (RuntimeObject * __this /* static, unused */, RuntimeTypeHandle_t1644603945 p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.SceneManagement.Scene::get_handle() extern "C" int32_t Scene_get_handle_m1965217093 (Scene_t886992912 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.SceneManagement.Scene::GetHashCode() extern "C" int32_t Scene_GetHashCode_m2802271517 (Scene_t886992912 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SceneManagement.Scene::Equals(System.Object) extern "C" bool Scene_Equals_m2736381267 (Scene_t886992912 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.UnityAction`2::Invoke(T0,T1) #define UnityAction_2_Invoke_m142841862(__this, p0, p1, method) (( void (*) (UnityAction_2_t1303706228 *, Scene_t886992912 , int32_t, const RuntimeMethod*))UnityAction_2_Invoke_m142841862_gshared)(__this, p0, p1, method) // System.Void UnityEngine.Events.UnityAction`1::Invoke(T0) #define UnityAction_1_Invoke_m3288951857(__this, p0, method) (( void (*) (UnityAction_1_t2300191644 *, Scene_t886992912 , const RuntimeMethod*))UnityAction_1_Invoke_m3288951857_gshared)(__this, p0, method) // System.Void UnityEngine.Events.UnityAction`2::Invoke(T0,T1) #define UnityAction_2_Invoke_m1774221970(__this, p0, p1, method) (( void (*) (UnityAction_2_t1173199225 *, Scene_t886992912 , Scene_t886992912 , const RuntimeMethod*))UnityAction_2_Invoke_m1774221970_gshared)(__this, p0, p1, method) // System.Void UnityEngine.Object::.ctor() extern "C" void Object__ctor_m1201776117 (Object_t1332387349 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.ScriptableObject::Internal_CreateScriptableObject(UnityEngine.ScriptableObject) extern "C" void ScriptableObject_Internal_CreateScriptableObject_m1796591053 (RuntimeObject * __this /* static, unused */, ScriptableObject_t505592390 * ___self0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.ScriptableObject UnityEngine.ScriptableObject::CreateInstanceFromType(System.Type) extern "C" ScriptableObject_t505592390 * ScriptableObject_CreateInstanceFromType_m2579013742 (RuntimeObject * __this /* static, unused */, Type_t * ___type0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Scripting.APIUpdating.MovedFromAttribute::set_Namespace(System.String) extern "C" void MovedFromAttribute_set_Namespace_m947531106 (MovedFromAttribute_t4199174457 * __this, String_t* ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Scripting.APIUpdating.MovedFromAttribute::set_IsInDifferentAssembly(System.Boolean) extern "C" void MovedFromAttribute_set_IsInDifferentAssembly_m2839002675 (MovedFromAttribute_t4199174457 * __this, bool ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Vector3 UnityEngine.Input::get_mousePosition() extern "C" Vector3_t67624592 Input_get_mousePosition_m3815269684 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Camera::get_allCamerasCount() extern "C" int32_t Camera_get_allCamerasCount_m682204080 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Camera::GetAllCameras(UnityEngine.Camera[]) extern "C" int32_t Camera_GetAllCameras_m612307359 (RuntimeObject * __this /* static, unused */, CameraU5BU5D_t2507966031* ___cameras0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.RenderTexture UnityEngine.Camera::get_targetTexture() extern "C" RenderTexture_t3726137678 * Camera_get_targetTexture_m3559565008 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rect UnityEngine.Camera::get_pixelRect() extern "C" Rect_t3345319094 Camera_get_pixelRect_m237037586 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // T UnityEngine.Component::GetComponent() #define Component_GetComponent_TisGUILayer_t1356563649_m427859813(__this, method) (( GUILayer_t1356563649 * (*) (Component_t590567089 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m759789627_gshared)(__this, method) // UnityEngine.GUIElement UnityEngine.GUILayer::HitTest(UnityEngine.Vector3) extern "C" GUIElement_t316128140 * GUILayer_HitTest_m37771484 (GUILayer_t1356563649 * __this, Vector3_t67624592 ___screenPosition0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.GameObject UnityEngine.Component::get_gameObject() extern "C" GameObject_t2923855588 * Component_get_gameObject_m3854382865 (Component_t590567089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Camera::get_eventMask() extern "C" int32_t Camera_get_eventMask_m3597146787 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Mathf::Approximately(System.Single,System.Single) extern "C" bool Mathf_Approximately_m2771810637 (RuntimeObject * __this /* static, unused */, float ___a0, float ___b1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Camera::get_farClipPlane() extern "C" float Camera_get_farClipPlane_m334378459 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Single UnityEngine.Camera::get_nearClipPlane() extern "C" float Camera_get_nearClipPlane_m1776629686 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Camera::get_cullingMask() extern "C" int32_t Camera_get_cullingMask_m123840027 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.GameObject UnityEngine.Camera::RaycastTry(UnityEngine.Ray,System.Single,System.Int32) extern "C" GameObject_t2923855588 * Camera_RaycastTry_m2041275581 (Camera_t110840138 * __this, Ray_t3058960190 ___ray0, float ___distance1, int32_t ___layerMask2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.CameraClearFlags UnityEngine.Camera::get_clearFlags() extern "C" int32_t Camera_get_clearFlags_m3668905607 (Camera_t110840138 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.GameObject UnityEngine.Camera::RaycastTry2D(UnityEngine.Ray,System.Single,System.Int32) extern "C" GameObject_t2923855588 * Camera_RaycastTry2D_m1423852821 (Camera_t110840138 * __this, Ray_t3058960190 ___ray0, float ___distance1, int32_t ___layerMask2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SendMouseEvents::SendEvents(System.Int32,UnityEngine.SendMouseEvents/HitInfo) extern "C" void SendMouseEvents_SendEvents_m1146913201 (RuntimeObject * __this /* static, unused */, int32_t ___i0, HitInfo_t2268685571 ___hit1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Input::GetMouseButtonDown(System.Int32) extern "C" bool Input_GetMouseButtonDown_m2775304371 (RuntimeObject * __this /* static, unused */, int32_t ___button0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Input::GetMouseButton(System.Int32) extern "C" bool Input_GetMouseButton_m1664028110 (RuntimeObject * __this /* static, unused */, int32_t ___button0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SendMouseEvents/HitInfo::op_Implicit(UnityEngine.SendMouseEvents/HitInfo) extern "C" bool HitInfo_op_Implicit_m3724497342 (RuntimeObject * __this /* static, unused */, HitInfo_t2268685571 ___exists0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SendMouseEvents/HitInfo::SendMessage(System.String) extern "C" void HitInfo_SendMessage_m3290389411 (HitInfo_t2268685571 * __this, String_t* ___name0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SendMouseEvents/HitInfo::Compare(UnityEngine.SendMouseEvents/HitInfo,UnityEngine.SendMouseEvents/HitInfo) extern "C" bool HitInfo_Compare_m3962420595 (RuntimeObject * __this /* static, unused */, HitInfo_t2268685571 ___lhs0, HitInfo_t2268685571 ___rhs1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.GameObject::SendMessage(System.String,System.Object,UnityEngine.SendMessageOptions) extern "C" void GameObject_SendMessage_m127802373 (GameObject_t2923855588 * __this, String_t* ___methodName0, RuntimeObject * ___value1, int32_t ___options2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.IntPtr::op_Equality(System.IntPtr,System.IntPtr) extern "C" bool IntPtr_op_Equality_m148131807 (RuntimeObject * __this /* static, unused */, IntPtr_t p0, IntPtr_t p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.ArgumentException::.ctor(System.String,System.String) extern "C" void ArgumentException__ctor_m3841295731 (ArgumentException_t270170821 * __this, String_t* p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void* System.IntPtr::op_Explicit(System.IntPtr) extern "C" void* IntPtr_op_Explicit_m624739794 (RuntimeObject * __this /* static, unused */, IntPtr_t p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Type System.Object::GetType() extern "C" Type_t * Object_GetType_m1749792582 (RuntimeObject * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.SkeletonBone::get_transformModified() extern "C" int32_t SkeletonBone_get_transformModified_m3249991282 (SkeletonBone_t3980876343 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SkeletonBone::set_transformModified(System.Int32) extern "C" void SkeletonBone_set_transformModified_m2293113419 (SkeletonBone_t3980876343 * __this, int32_t ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.Impl.AchievementDescription UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::ToAchievementDescription() extern "C" AchievementDescription_t991053089 * GcAchievementDescriptionData_ToAchievementDescription_m3634773672 (GcAchievementDescriptionData_t1960457254 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Debug::Log(System.Object) extern "C" void Debug_Log_m482196963 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___message0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::SetImage(UnityEngine.Texture2D) extern "C" void AchievementDescription_SetImage_m2104624658 (AchievementDescription_t991053089 * __this, Texture2D_t1384570725 * ___image0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`1::Invoke(!0) #define Action_1_Invoke_m534614836(__this, p0, method) (( void (*) (Action_1_t4096934434 *, IAchievementDescriptionU5BU5D_t3064410227*, const RuntimeMethod*))Action_1_Invoke_m3167810884_gshared)(__this, p0, method) // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::PopulateLocalUser() extern "C" void GameCenterPlatform_PopulateLocalUser_m2400765263 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`2::Invoke(!0,!1) #define Action_2_Invoke_m641279976(__this, p0, p1, method) (( void (*) (Action_2_t3787810730 *, bool, String_t*, const RuntimeMethod*))Action_2_Invoke_m2096004357_gshared)(__this, p0, p1, method) // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SafeClearArray(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,System.Int32) extern "C" void GameCenterPlatform_SafeClearArray_m307863322 (RuntimeObject * __this /* static, unused */, UserProfileU5BU5D_t3377267652** ___array0, int32_t ___size1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::AddToArray(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,System.Int32) extern "C" void GcUserProfileData_AddToArray_m2882040847 (GcUserProfileData_t265536658 * __this, UserProfileU5BU5D_t3377267652** ___array0, int32_t ___number1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SafeSetUserImage(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,UnityEngine.Texture2D,System.Int32) extern "C" void GameCenterPlatform_SafeSetUserImage_m1317299489 (RuntimeObject * __this /* static, unused */, UserProfileU5BU5D_t3377267652** ___array0, Texture2D_t1384570725 * ___texture1, int32_t ___number2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetFriends(UnityEngine.SocialPlatforms.IUserProfile[]) extern "C" void LocalUser_SetFriends_m2359410273 (LocalUser_t2155741069 * __this, IUserProfileU5BU5D_t3867243727* ___friends0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`1::Invoke(!0) #define Action_1_Invoke_m3062505204(__this, p0, method) (( void (*) (Action_1_t2674754663 *, bool, const RuntimeMethod*))Action_1_Invoke_m3062505204_gshared)(__this, p0, method) // UnityEngine.SocialPlatforms.Impl.Achievement UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::ToAchievement() extern "C" Achievement_t2468443294 * GcAchievementData_ToAchievement_m3236287768 (GcAchievementData_t3004100478 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`1::Invoke(!0) #define Action_1_Invoke_m4016068893(__this, p0, method) (( void (*) (Action_1_t2897662423 *, IAchievementU5BU5D_t1865138216*, const RuntimeMethod*))Action_1_Invoke_m3167810884_gshared)(__this, p0, method) // UnityEngine.SocialPlatforms.Impl.Score UnityEngine.SocialPlatforms.GameCenter.GcScoreData::ToScore() extern "C" Score_t671349143 * GcScoreData_ToScore_m3944565042 (GcScoreData_t1096391638 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`1::Invoke(!0) #define Action_1_Invoke_m2262809151(__this, p0, method) (( void (*) (Action_1_t1552255288 *, IScoreU5BU5D_t519731081*, const RuntimeMethod*))Action_1_Invoke_m3167810884_gshared)(__this, p0, method) // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::VerifyAuthentication() extern "C" bool GameCenterPlatform_VerifyAuthentication_m2885445492 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadFriends(System.Object) extern "C" void GameCenterPlatform_Internal_LoadFriends_m881374576 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0::.ctor() extern "C" void U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0__ctor_m639058503 (U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`2::.ctor(System.Object,System.IntPtr) #define Action_2__ctor_m3476159000(__this, p0, p1, method) (( void (*) (Action_2_t3787810730 *, RuntimeObject *, IntPtr_t, const RuntimeMethod*))Action_2__ctor_m1834669280_gshared)(__this, p0, p1, method) // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticate() extern "C" void GameCenterPlatform_Internal_Authenticate_m4080317000 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::.ctor() extern "C" void LocalUser__ctor_m928281921 (LocalUser_t2155741069 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticated() extern "C" bool GameCenterPlatform_Internal_Authenticated_m3332319061 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::get_id() extern "C" String_t* UserProfile_get_id_m2069338772 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.String::op_Equality(System.String,System.String) extern "C" bool String_op_Equality_m767991535 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetAuthenticated(System.Boolean) extern "C" void LocalUser_SetAuthenticated_m85368100 (LocalUser_t2155741069 * __this, bool ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserName() extern "C" String_t* GameCenterPlatform_Internal_UserName_m3116282197 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetUserName(System.String) extern "C" void UserProfile_SetUserName_m3129419512 (UserProfile_t2942407481 * __this, String_t* ___name0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserID() extern "C" String_t* GameCenterPlatform_Internal_UserID_m1253806589 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetUserID(System.String) extern "C" void UserProfile_SetUserID_m836273895 (UserProfile_t2942407481 * __this, String_t* ___id0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Underage() extern "C" bool GameCenterPlatform_Internal_Underage_m4288143883 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetUnderage(System.Boolean) extern "C" void LocalUser_SetUnderage_m192521804 (LocalUser_t2155741069 * __this, bool ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Texture2D UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserImage() extern "C" Texture2D_t1384570725 * GameCenterPlatform_Internal_UserImage_m890633310 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetImage(UnityEngine.Texture2D) extern "C" void UserProfile_SetImage_m4145629067 (UserProfile_t2942407481 * __this, Texture2D_t1384570725 * ___image0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievementDescriptions(System.Object) extern "C" void GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportProgress(System.String,System.Double,System.Object) extern "C" void GameCenterPlatform_Internal_ReportProgress_m1475385389 (RuntimeObject * __this /* static, unused */, String_t* ___id0, double ___progress1, RuntimeObject * ___callback2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievements(System.Object) extern "C" void GameCenterPlatform_Internal_LoadAchievements_m861185230 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportScore(System.Int64,System.String,System.Object) extern "C" void GameCenterPlatform_Internal_ReportScore_m1150348926 (RuntimeObject * __this /* static, unused */, int64_t ___score0, String_t* ___category1, RuntimeObject * ___callback2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadScores(System.String,System.Object) extern "C" void GameCenterPlatform_Internal_LoadScores_m13855206 (RuntimeObject * __this /* static, unused */, String_t* ___category0, RuntimeObject * ___callback1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::.ctor(UnityEngine.SocialPlatforms.Impl.Leaderboard) extern "C" void GcLeaderboard__ctor_m3620341123 (GcLeaderboard_t1761920286 * __this, Leaderboard_t3315266811 * ___board0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Collections.Generic.List`1::Add(!0) #define List_1_Add_m4129652933(__this, p0, method) (( void (*) (List_1_t984806126 *, GcLeaderboard_t1761920286 *, const RuntimeMethod*))List_1_Add_m2041078292_gshared)(__this, p0, method) // System.String[] UnityEngine.SocialPlatforms.Impl.Leaderboard::GetUserFilter() extern "C" StringU5BU5D_t3608572874* Leaderboard_GetUserFilter_m3311896502 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Internal_LoadScores(System.String,System.Int32,System.Int32,System.String[],System.Int32,System.Int32,System.Object) extern "C" void GcLeaderboard_Internal_LoadScores_m2378640477 (GcLeaderboard_t1761920286 * __this, String_t* ___category0, int32_t ___from1, int32_t ___count2, StringU5BU5D_t3608572874* ___userIDs3, int32_t ___playerScope4, int32_t ___timeScope5, RuntimeObject * ___callback6, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Collections.Generic.List`1/Enumerator System.Collections.Generic.List`1::GetEnumerator() #define List_1_GetEnumerator_m2419316156(__this, method) (( Enumerator_t2673088588 (*) (List_1_t984806126 *, const RuntimeMethod*))List_1_GetEnumerator_m2562807503_gshared)(__this, method) // !0 System.Collections.Generic.List`1/Enumerator::get_Current() #define Enumerator_get_Current_m1279669161(__this, method) (( GcLeaderboard_t1761920286 * (*) (Enumerator_t2673088588 *, const RuntimeMethod*))Enumerator_get_Current_m1434536216_gshared)(__this, method) // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Contains(UnityEngine.SocialPlatforms.Impl.Leaderboard) extern "C" bool GcLeaderboard_Contains_m2647914426 (GcLeaderboard_t1761920286 * __this, Leaderboard_t3315266811 * ___board0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Loading() extern "C" bool GcLeaderboard_Loading_m1490059570 (GcLeaderboard_t1761920286 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.Collections.Generic.List`1/Enumerator::MoveNext() #define Enumerator_MoveNext_m1938626111(__this, method) (( bool (*) (Enumerator_t2673088588 *, const RuntimeMethod*))Enumerator_MoveNext_m4181024596_gshared)(__this, method) // System.Void System.Collections.Generic.List`1/Enumerator::Dispose() #define Enumerator_Dispose_m3354874370(__this, method) (( void (*) (Enumerator_t2673088588 *, const RuntimeMethod*))Enumerator_Dispose_m215493026_gshared)(__this, method) // UnityEngine.SocialPlatforms.ILocalUser UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::get_localUser() extern "C" RuntimeObject* GameCenterPlatform_get_localUser_m3939861769 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowAchievementsUI() extern "C" void GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowLeaderboardUI() extern "C" void GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Action`1::Invoke(!0) #define Action_1_Invoke_m4080665887(__this, p0, method) (( void (*) (Action_1_t604800638 *, IUserProfileU5BU5D_t3867243727*, const RuntimeMethod*))Action_1_Invoke_m3167810884_gshared)(__this, p0, method) // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadUsers(System.String[],System.Object) extern "C" void GameCenterPlatform_Internal_LoadUsers_m3161987892 (RuntimeObject * __this /* static, unused */, StringU5BU5D_t3608572874* ___userIds0, RuntimeObject * ___callback1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Texture2D::.ctor(System.Int32,System.Int32) extern "C" void Texture2D__ctor_m400428107 (Texture2D_t1384570725 * __this, int32_t ___width0, int32_t ___height1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::.ctor() extern "C" void Leaderboard__ctor_m4039976758 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor() extern "C" void Achievement__ctor_m926077173 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ResetAllAchievements() extern "C" void GameCenterPlatform_Internal_ResetAllAchievements_m4146765097 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowDefaultAchievementBanner(System.Boolean) extern "C" void GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443 (RuntimeObject * __this /* static, unused */, bool ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowSpecificLeaderboardUI(System.String,System.Int32) extern "C" void GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488 (RuntimeObject * __this /* static, unused */, String_t* ___leaderboardID0, int32_t ___timeScope1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Collections.Generic.List`1::.ctor() #define List_1__ctor_m2431882546(__this, method) (( void (*) (List_1_t984806126 *, const RuntimeMethod*))List_1__ctor_m3371656545_gshared)(__this, method) // System.Void System.DateTime::.ctor(System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32) extern "C" void DateTime__ctor_m312241081 (DateTime_t1205928702 * __this, int32_t p0, int32_t p1, int32_t p2, int32_t p3, int32_t p4, int32_t p5, int32_t p6, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.DateTime System.DateTime::AddSeconds(System.Double) extern "C" DateTime_t1205928702 DateTime_AddSeconds_m3463505250 (DateTime_t1205928702 * __this, double p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor(System.String,System.Double,System.Boolean,System.Boolean,System.DateTime) extern "C" void Achievement__ctor_m1255022360 (Achievement_t2468443294 * __this, String_t* ___id0, double ___percentCompleted1, bool ___completed2, bool ___hidden3, DateTime_t1205928702 ___lastReportedDate4, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::.ctor(System.String,System.String,UnityEngine.Texture2D,System.String,System.String,System.Boolean,System.Int32) extern "C" void AchievementDescription__ctor_m1561486989 (AchievementDescription_t991053089 * __this, String_t* ___id0, String_t* ___title1, Texture2D_t1384570725 * ___image2, String_t* ___achievedDescription3, String_t* ___unachievedDescription4, bool ___hidden5, int32_t ___points6, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Dispose() extern "C" void GcLeaderboard_Dispose_m1078488854 (GcLeaderboard_t1761920286 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetScores(UnityEngine.SocialPlatforms.IScore[]) extern "C" void Leaderboard_SetScores_m1863945428 (Leaderboard_t3315266811 * __this, IScoreU5BU5D_t519731081* ___scores0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetLocalUserScore(UnityEngine.SocialPlatforms.IScore) extern "C" void Leaderboard_SetLocalUserScore_m2947022105 (Leaderboard_t3315266811 * __this, RuntimeObject* ___score0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetMaxRange(System.UInt32) extern "C" void Leaderboard_SetMaxRange_m1441382126 (Leaderboard_t3315266811 * __this, uint32_t ___maxRange0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetTitle(System.String) extern "C" void Leaderboard_SetTitle_m4254570531 (Leaderboard_t3315266811 * __this, String_t* ___title0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Score::.ctor(System.String,System.Int64,System.String,System.DateTime,System.String,System.Int32) extern "C" void Score__ctor_m1424242054 (Score_t671349143 * __this, String_t* ___leaderboardID0, int64_t ___value1, String_t* ___userID2, DateTime_t1205928702 ___date3, String_t* ___formattedValue4, int32_t ___rank5, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::.ctor(System.String,System.String,System.Boolean,UnityEngine.SocialPlatforms.UserState,UnityEngine.Texture2D) extern "C" void UserProfile__ctor_m3004638010 (UserProfile_t2942407481 * __this, String_t* ___name0, String_t* ___id1, bool ___friend2, int32_t ___state3, Texture2D_t1384570725 * ___image4, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.Impl.UserProfile UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::ToUserProfile() extern "C" UserProfile_t2942407481 * GcUserProfileData_ToUserProfile_m1615912729 (GcUserProfileData_t265536658 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::set_id(System.String) extern "C" void Achievement_set_id_m1587115024 (Achievement_t2468443294 * __this, String_t* ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::set_percentCompleted(System.Double) extern "C" void Achievement_set_percentCompleted_m2528710724 (Achievement_t2468443294 * __this, double ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor(System.String,System.Double) extern "C" void Achievement__ctor_m2199514267 (Achievement_t2468443294 * __this, String_t* ___id0, double ___percent1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.Achievement::get_id() extern "C" String_t* Achievement_get_id_m4009128591 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Double UnityEngine.SocialPlatforms.Impl.Achievement::get_percentCompleted() extern "C" double Achievement_get_percentCompleted_m1210462574 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::get_completed() extern "C" bool Achievement_get_completed_m1034346610 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::get_hidden() extern "C" bool Achievement_get_hidden_m1511076689 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.DateTime UnityEngine.SocialPlatforms.Impl.Achievement::get_lastReportedDate() extern "C" DateTime_t1205928702 Achievement_get_lastReportedDate_m2623896959 (Achievement_t2468443294 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Concat(System.Object[]) extern "C" String_t* String_Concat_m2150944860 (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t3885370135* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::set_id(System.String) extern "C" void AchievementDescription_set_id_m1561483604 (AchievementDescription_t991053089 * __this, String_t* ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_id() extern "C" String_t* AchievementDescription_get_id_m2652925627 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_title() extern "C" String_t* AchievementDescription_get_title_m972096089 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_achievedDescription() extern "C" String_t* AchievementDescription_get_achievedDescription_m3194544807 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_unachievedDescription() extern "C" String_t* AchievementDescription_get_unachievedDescription_m613743906 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_points() extern "C" int32_t AchievementDescription_get_points_m2233273081 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_hidden() extern "C" bool AchievementDescription_get_hidden_m2953151423 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_id(System.String) extern "C" void Leaderboard_set_id_m819788632 (Leaderboard_t3315266811 * __this, String_t* ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Range::.ctor(System.Int32,System.Int32) extern "C" void Range__ctor_m3029477343 (Range_t2283206190 * __this, int32_t ___fromValue0, int32_t ___valueCount1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_range(UnityEngine.SocialPlatforms.Range) extern "C" void Leaderboard_set_range_m4172403679 (Leaderboard_t3315266811 * __this, Range_t2283206190 ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_userScope(UnityEngine.SocialPlatforms.UserScope) extern "C" void Leaderboard_set_userScope_m1110642206 (Leaderboard_t3315266811 * __this, int32_t ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_timeScope(UnityEngine.SocialPlatforms.TimeScope) extern "C" void Leaderboard_set_timeScope_m1140780687 (Leaderboard_t3315266811 * __this, int32_t ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Score::.ctor(System.String,System.Int64) extern "C" void Score__ctor_m1838853748 (Score_t671349143 * __this, String_t* ___leaderboardID0, int64_t ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.Leaderboard::get_id() extern "C" String_t* Leaderboard_get_id_m2059568589 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.Range UnityEngine.SocialPlatforms.Impl.Leaderboard::get_range() extern "C" Range_t2283206190 Leaderboard_get_range_m224007063 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.UserScope UnityEngine.SocialPlatforms.Impl.Leaderboard::get_userScope() extern "C" int32_t Leaderboard_get_userScope_m3174579800 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.TimeScope UnityEngine.SocialPlatforms.Impl.Leaderboard::get_timeScope() extern "C" int32_t Leaderboard_get_timeScope_m2393285066 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::.ctor() extern "C" void UserProfile__ctor_m2050922054 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.DateTime System.DateTime::get_Now() extern "C" DateTime_t1205928702 DateTime_get_Now_m2497775987 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Score::set_leaderboardID(System.String) extern "C" void Score_set_leaderboardID_m2411520823 (Score_t671349143 * __this, String_t* ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SocialPlatforms.Impl.Score::set_value(System.Int64) extern "C" void Score_set_value_m2819979283 (Score_t671349143 * __this, int64_t ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int64 UnityEngine.SocialPlatforms.Impl.Score::get_value() extern "C" int64_t Score_get_value_m1477333616 (Score_t671349143 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.Score::get_leaderboardID() extern "C" String_t* Score_get_leaderboardID_m4172359465 (Score_t671349143 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::get_userName() extern "C" String_t* UserProfile_get_userName_m3008791783 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.SocialPlatforms.Impl.UserProfile::get_isFriend() extern "C" bool UserProfile_get_isFriend_m1328512851 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.SocialPlatforms.UserState UnityEngine.SocialPlatforms.Impl.UserProfile::get_state() extern "C" int32_t UserProfile_get_state_m735841295 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Collider::.ctor() extern "C" void Collider__ctor_m3904369873 (Collider_t3058509131 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SphereCollider::INTERNAL_get_center(UnityEngine.Vector3&) extern "C" void SphereCollider_INTERNAL_get_center_m1829176733 (SphereCollider_t2896221692 * __this, Vector3_t67624592 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SphereCollider::INTERNAL_set_center(UnityEngine.Vector3&) extern "C" void SphereCollider_INTERNAL_set_center_m338109470 (SphereCollider_t2896221692 * __this, Vector3_t67624592 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprite::INTERNAL_get_rect(UnityEngine.Rect&) extern "C" void Sprite_INTERNAL_get_rect_m3872599290 (Sprite_t3419621700 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprite::INTERNAL_get_textureRect(UnityEngine.Rect&) extern "C" void Sprite_INTERNAL_get_textureRect_m2787057290 (Sprite_t3419621700 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprite::INTERNAL_get_border(UnityEngine.Vector4&) extern "C" void Sprite_INTERNAL_get_border_m499630133 (Sprite_t3419621700 * __this, Vector4_t4108915337 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.SpriteRenderer::SetSprite_INTERNAL(UnityEngine.Sprite) extern "C" void SpriteRenderer_SetSprite_INTERNAL_m1476729322 (SpriteRenderer_t1459332486 * __this, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetInnerUV(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetOuterUV(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetOuterUV_m230980969 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetPadding(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetPadding_m440627081 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Sprites.DataUtility::Internal_GetMinSize(UnityEngine.Sprite,UnityEngine.Vector2&) extern "C" void DataUtility_Internal_GetMinSize_m928418521 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector2_t3854014517 * ___output1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Replace(System.String,System.String) extern "C" String_t* String_Replace_m212902530 (String_t* __this, String_t* p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Diagnostics.StackTrace::.ctor(System.Int32,System.Boolean) extern "C" void StackTrace__ctor_m3377607597 (StackTrace_t798888381 * __this, int32_t p0, bool p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.StackTraceUtility::ExtractFormattedStackTrace(System.Diagnostics.StackTrace) extern "C" String_t* StackTraceUtility_ExtractFormattedStackTrace_m2265662347 (RuntimeObject * __this /* static, unused */, StackTrace_t798888381 * ___stackTrace0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.String::StartsWith(System.String) extern "C" bool String_StartsWith_m2227418833 (String_t* __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.ArgumentException::.ctor(System.String) extern "C" void ArgumentException__ctor_m3557549525 (ArgumentException_t270170821 * __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 System.String::get_Length() extern "C" int32_t String_get_Length_m38839245 (String_t* __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Text.StringBuilder::.ctor(System.Int32) extern "C" void StringBuilder__ctor_m3754152305 (StringBuilder_t313129557 * __this, int32_t p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Concat(System.String,System.String,System.String) extern "C" String_t* String_Concat_m4226800250 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, String_t* p2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Type System.Exception::GetType() extern "C" Type_t * Exception_GetType_m4106188822 (Exception_t3285241636 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Trim() extern "C" String_t* String_Trim_m2409528586 (String_t* __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Concat(System.String,System.String) extern "C" String_t* String_Concat_m3797386145 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Exception System.Exception::get_InnerException() extern "C" Exception_t3285241636 * Exception_get_InnerException_m3140938854 (Exception_t3285241636 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Concat(System.String,System.String,System.String,System.String) extern "C" String_t* String_Concat_m3900126850 (RuntimeObject * __this /* static, unused */, String_t* p0, String_t* p1, String_t* p2, String_t* p3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Text.StringBuilder System.Text.StringBuilder::Append(System.String) extern "C" StringBuilder_t313129557 * StringBuilder_Append_m1092472320 (StringBuilder_t313129557 * __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String[] System.String::Split(System.Char[]) extern "C" StringU5BU5D_t3608572874* String_Split_m3520467407 (String_t* __this, CharU5BU5D_t1522321484* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Char System.String::get_Chars(System.Int32) extern "C" Il2CppChar String_get_Chars_m1295159314 (String_t* __this, int32_t p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.StackTraceUtility::IsSystemStacktraceType(System.Object) extern "C" bool StackTraceUtility_IsSystemStacktraceType_m70277135 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___name0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 System.String::IndexOf(System.String) extern "C" int32_t String_IndexOf_m1185123121 (String_t* __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Substring(System.Int32,System.Int32) extern "C" String_t* String_Substring_m659618115 (String_t* __this, int32_t p0, int32_t p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.String::EndsWith(System.String) extern "C" bool String_EndsWith_m2914504526 (String_t* __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Remove(System.Int32,System.Int32) extern "C" String_t* String_Remove_m2484650411 (String_t* __this, int32_t p0, int32_t p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 System.String::IndexOf(System.String,System.Int32) extern "C" int32_t String_IndexOf_m3631343126 (String_t* __this, String_t* p0, int32_t p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Replace(System.Char,System.Char) extern "C" String_t* String_Replace_m4026310352 (String_t* __this, Il2CppChar p0, Il2CppChar p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 System.String::LastIndexOf(System.String) extern "C" int32_t String_LastIndexOf_m2697281871 (String_t* __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.String::Insert(System.Int32,System.String) extern "C" String_t* String_Insert_m1241113509 (String_t* __this, int32_t p0, String_t* p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.Int32::ToString() extern "C" String_t* Int32_ToString_m1159740622 (int32_t* __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.ScriptableObject::.ctor() extern "C" void ScriptableObject__ctor_m3935827375 (ScriptableObject_t505592390 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.TextAsset::get_text() extern "C" String_t* TextAsset_get_text_m3742127726 (TextAsset_t2643108631 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.GUIStyle UnityEngine.GUIStyle::get_none() extern "C" GUIStyle_t4033995491 * GUIStyle_get_none_m4014421518 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.GUIContent::.ctor() extern "C" void GUIContent__ctor_m3699292156 (GUIContent_t3165057865 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerationSettings::CompareColors(UnityEngine.Color,UnityEngine.Color) extern "C" bool TextGenerationSettings_CompareColors_m4161672168 (TextGenerationSettings_t2955391441 * __this, Color_t267620335 ___left0, Color_t267620335 ___right1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerationSettings::CompareVector2(UnityEngine.Vector2,UnityEngine.Vector2) extern "C" bool TextGenerationSettings_CompareVector2_m2697891872 (TextGenerationSettings_t2955391441 * __this, Vector2_t3854014517 ___left0, Vector2_t3854014517 ___right1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerationSettings::Equals(UnityEngine.TextGenerationSettings) extern "C" bool TextGenerationSettings_Equals_m872373524 (TextGenerationSettings_t2955391441 * __this, TextGenerationSettings_t2955391441 ___other0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::.ctor(System.Int32) extern "C" void TextGenerator__ctor_m3315225751 (TextGenerator_t1838611233 * __this, int32_t ___initialCapacity0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) #define List_1__ctor_m2525236808(__this, p0, method) (( void (*) (List_1_t2359577098 *, int32_t, const RuntimeMethod*))List_1__ctor_m2525236808_gshared)(__this, p0, method) // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) #define List_1__ctor_m691252865(__this, p0, method) (( void (*) (List_1_t369525373 *, int32_t, const RuntimeMethod*))List_1__ctor_m691252865_gshared)(__this, p0, method) // System.Void System.Collections.Generic.List`1::.ctor(System.Int32) #define List_1__ctor_m581423473(__this, p0, method) (( void (*) (List_1_t1470875743 *, int32_t, const RuntimeMethod*))List_1__ctor_m581423473_gshared)(__this, p0, method) // System.Void UnityEngine.TextGenerator::Init() extern "C" void TextGenerator_Init_m2835255125 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::Dispose_cpp() extern "C" void TextGenerator_Dispose_cpp_m3624568491 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.Font::get_dynamic() extern "C" bool Font_get_dynamic_m1368413874 (Font_t1580130639 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String UnityEngine.Object::get_name() extern "C" String_t* Object_get_name_m1438513735 (Object_t1332387349 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Debug::LogWarningFormat(UnityEngine.Object,System.String,System.Object[]) extern "C" void Debug_LogWarningFormat_m4125348817 (RuntimeObject * __this /* static, unused */, Object_t1332387349 * ___context0, String_t* ___format1, ObjectU5BU5D_t3885370135* ___args2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetCharactersInternal(System.Object) extern "C" void TextGenerator_GetCharactersInternal_m2640027672 (TextGenerator_t1838611233 * __this, RuntimeObject * ___characters0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetLinesInternal(System.Object) extern "C" void TextGenerator_GetLinesInternal_m4053054016 (TextGenerator_t1838611233 * __this, RuntimeObject * ___lines0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetVerticesInternal(System.Object) extern "C" void TextGenerator_GetVerticesInternal_m937574849 (TextGenerator_t1838611233 * __this, RuntimeObject * ___vertices0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerator::Populate(System.String,UnityEngine.TextGenerationSettings) extern "C" bool TextGenerator_Populate_m614341003 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.Rect UnityEngine.TextGenerator::get_rectExtents() extern "C" Rect_t3345319094 TextGenerator_get_rectExtents_m128057140 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.TextGenerationError UnityEngine.TextGenerator::PopulateWithError(System.String,UnityEngine.TextGenerationSettings) extern "C" int32_t TextGenerator_PopulateWithError_m1090609619 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Debug::LogErrorFormat(UnityEngine.Object,System.String,System.Object[]) extern "C" void Debug_LogErrorFormat_m242749776 (RuntimeObject * __this /* static, unused */, Object_t1332387349 * ___context0, String_t* ___format1, ObjectU5BU5D_t3885370135* ___args2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.TextGenerationError UnityEngine.TextGenerator::PopulateAlways(System.String,UnityEngine.TextGenerationSettings) extern "C" int32_t TextGenerator_PopulateAlways_m980987704 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // UnityEngine.TextGenerationSettings UnityEngine.TextGenerator::ValidatedSettings(UnityEngine.TextGenerationSettings) extern "C" TextGenerationSettings_t2955391441 TextGenerator_ValidatedSettings_m3744012953 (TextGenerator_t1838611233 * __this, TextGenerationSettings_t2955391441 ___settings0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerator::Populate_Internal(System.String,UnityEngine.Font,UnityEngine.Color,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,UnityEngine.VerticalWrapMode,UnityEngine.HorizontalWrapMode,System.Boolean,UnityEngine.TextAnchor,UnityEngine.Vector2,UnityEngine.Vector2,System.Boolean,System.Boolean,UnityEngine.TextGenerationError&) extern "C" bool TextGenerator_Populate_Internal_m93079026 (TextGenerator_t1838611233 * __this, String_t* ___str0, Font_t1580130639 * ___font1, Color_t267620335 ___color2, int32_t ___fontSize3, float ___scaleFactor4, float ___lineSpacing5, int32_t ___style6, bool ___richText7, bool ___resizeTextForBestFit8, int32_t ___resizeTextMinSize9, int32_t ___resizeTextMaxSize10, int32_t ___verticalOverFlow11, int32_t ___horizontalOverflow12, bool ___updateBounds13, int32_t ___anchor14, Vector2_t3854014517 ___extents15, Vector2_t3854014517 ___pivot16, bool ___generateOutOfBounds17, bool ___alignByGeometry18, int32_t* ___error19, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetVertices(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetVertices_m2648380066 (TextGenerator_t1838611233 * __this, List_1_t2359577098 * ___vertices0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetCharacters(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetCharacters_m3070669632 (TextGenerator_t1838611233 * __this, List_1_t369525373 * ___characters0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::GetLines(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetLines_m4086371989 (TextGenerator_t1838611233 * __this, List_1_t1470875743 * ___lines0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerator::Populate_Internal_cpp(System.String,UnityEngine.Font,UnityEngine.Color,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.Boolean,UnityEngine.TextAnchor,System.Single,System.Single,System.Single,System.Single,System.Boolean,System.Boolean,System.UInt32&) extern "C" bool TextGenerator_Populate_Internal_cpp_m2278858808 (TextGenerator_t1838611233 * __this, String_t* ___str0, Font_t1580130639 * ___font1, Color_t267620335 ___color2, int32_t ___fontSize3, float ___scaleFactor4, float ___lineSpacing5, int32_t ___style6, bool ___richText7, bool ___resizeTextForBestFit8, int32_t ___resizeTextMinSize9, int32_t ___resizeTextMaxSize10, int32_t ___verticalOverFlow11, int32_t ___horizontalOverflow12, bool ___updateBounds13, int32_t ___anchor14, float ___extentsX15, float ___extentsY16, float ___pivotX17, float ___pivotY18, bool ___generateOutOfBounds19, bool ___alignByGeometry20, uint32_t* ___error21, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean UnityEngine.TextGenerator::INTERNAL_CALL_Populate_Internal_cpp(UnityEngine.TextGenerator,System.String,UnityEngine.Font,UnityEngine.Color&,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.Boolean,UnityEngine.TextAnchor,System.Single,System.Single,System.Single,System.Single,System.Boolean,System.Boolean,System.UInt32&) extern "C" bool TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204 (RuntimeObject * __this /* static, unused */, TextGenerator_t1838611233 * ___self0, String_t* ___str1, Font_t1580130639 * ___font2, Color_t267620335 * ___color3, int32_t ___fontSize4, float ___scaleFactor5, float ___lineSpacing6, int32_t ___style7, bool ___richText8, bool ___resizeTextForBestFit9, int32_t ___resizeTextMinSize10, int32_t ___resizeTextMaxSize11, int32_t ___verticalOverFlow12, int32_t ___horizontalOverflow13, bool ___updateBounds14, int32_t ___anchor15, float ___extentsX16, float ___extentsY17, float ___pivotX18, float ___pivotY19, bool ___generateOutOfBounds20, bool ___alignByGeometry21, uint32_t* ___error22, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextGenerator::INTERNAL_get_rectExtents(UnityEngine.Rect&) extern "C" void TextGenerator_INTERNAL_get_rectExtents_m4191808009 (TextGenerator_t1838611233 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.TextGenerator::get_characterCount() extern "C" int32_t TextGenerator_get_characterCount_m3131948647 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextMesh::INTERNAL_get_color(UnityEngine.Color&) extern "C" void TextMesh_INTERNAL_get_color_m2101696051 (TextMesh_t2729623642 * __this, Color_t267620335 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.TextMesh::INTERNAL_set_color(UnityEngine.Color&) extern "C" void TextMesh_INTERNAL_set_color_m3627446082 (TextMesh_t2729623642 * __this, Color_t267620335 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Texture::Internal_GetWidth(UnityEngine.Texture) extern "C" int32_t Texture_Internal_GetWidth_m1728621115 (RuntimeObject * __this /* static, unused */, Texture_t2354860603 * ___t0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Int32 UnityEngine.Texture::Internal_GetHeight(UnityEngine.Texture) extern "C" int32_t Texture_Internal_GetHeight_m2677419952 (RuntimeObject * __this /* static, unused */, Texture_t2354860603 * ___t0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Texture::INTERNAL_get_texelSize(UnityEngine.Vector2&) extern "C" void Texture_INTERNAL_get_texelSize_m1640036898 (Texture_t2354860603 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Texture::.ctor() extern "C" void Texture__ctor_m3948473377 (Texture_t2354860603 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Texture2D::Internal_Create(UnityEngine.Texture2D,System.Int32,System.Int32,UnityEngine.TextureFormat,System.Boolean,System.Boolean,System.IntPtr) extern "C" void Texture2D_Internal_Create_m2456905009 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___mono0, int32_t ___width1, int32_t ___height2, int32_t ___format3, bool ___mipmap4, bool ___linear5, IntPtr_t ___nativeTex6, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Texture2D::INTERNAL_CALL_GetPixelBilinear(UnityEngine.Texture2D,System.Single,System.Single,UnityEngine.Color&) extern "C" void Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___self0, float ___u1, float ___v2, Color_t267620335 * ___value3, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.Playables.ScriptPlayableOutput::.ctor(UnityEngine.Playables.PlayableOutputHandle) extern "C" void ScriptPlayableOutput__ctor_m1887120702 (ScriptPlayableOutput_t3853613875 * __this, PlayableOutputHandle_t192146840 ___handle0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ScriptPlayableOutput__ctor_m1887120702_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = PlayableOutputHandle_IsValid_m2825682027((&___handle0), /*hidden argument*/NULL); if (!L_0) { goto IL_0026; } } { bool L_1 = PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539((&___handle0), /*hidden argument*/PlayableOutputHandle_IsPlayableOutputOfType_TisScriptPlayableOutput_t3853613875_m880372539_RuntimeMethod_var); if (L_1) { goto IL_0025; } } { InvalidCastException_t865352475 * L_2 = (InvalidCastException_t865352475 *)il2cpp_codegen_object_new(InvalidCastException_t865352475_il2cpp_TypeInfo_var); InvalidCastException__ctor_m3226723941(L_2, _stringLiteral3498337307, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2); } IL_0025: { } IL_0026: { PlayableOutputHandle_t192146840 L_3 = ___handle0; __this->set_m_Handle_0(L_3); return; } } extern "C" void ScriptPlayableOutput__ctor_m1887120702_AdjustorThunk (RuntimeObject * __this, PlayableOutputHandle_t192146840 ___handle0, const RuntimeMethod* method) { ScriptPlayableOutput_t3853613875 * _thisAdjusted = reinterpret_cast(__this + 1); ScriptPlayableOutput__ctor_m1887120702(_thisAdjusted, ___handle0, method); } // UnityEngine.Playables.ScriptPlayableOutput UnityEngine.Playables.ScriptPlayableOutput::Create(UnityEngine.Playables.PlayableGraph,System.String) extern "C" ScriptPlayableOutput_t3853613875 ScriptPlayableOutput_Create_m2062535908 (RuntimeObject * __this /* static, unused */, PlayableGraph_t3648426783 ___graph0, String_t* ___name1, const RuntimeMethod* method) { PlayableOutputHandle_t192146840 V_0; memset(&V_0, 0, sizeof(V_0)); ScriptPlayableOutput_t3853613875 V_1; memset(&V_1, 0, sizeof(V_1)); { String_t* L_0 = ___name1; bool L_1 = PlayableGraph_CreateScriptOutputInternal_m2465551668(NULL /*static, unused*/, (&___graph0), L_0, (&V_0), /*hidden argument*/NULL); if (L_1) { goto IL_001b; } } { ScriptPlayableOutput_t3853613875 L_2 = ScriptPlayableOutput_get_Null_m1162854030(NULL /*static, unused*/, /*hidden argument*/NULL); V_1 = L_2; goto IL_0027; } IL_001b: { PlayableOutputHandle_t192146840 L_3 = V_0; ScriptPlayableOutput_t3853613875 L_4; memset(&L_4, 0, sizeof(L_4)); ScriptPlayableOutput__ctor_m1887120702((&L_4), L_3, /*hidden argument*/NULL); V_1 = L_4; goto IL_0027; } IL_0027: { ScriptPlayableOutput_t3853613875 L_5 = V_1; return L_5; } } // UnityEngine.Playables.ScriptPlayableOutput UnityEngine.Playables.ScriptPlayableOutput::get_Null() extern "C" ScriptPlayableOutput_t3853613875 ScriptPlayableOutput_get_Null_m1162854030 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { ScriptPlayableOutput_t3853613875 V_0; memset(&V_0, 0, sizeof(V_0)); { PlayableOutputHandle_t192146840 L_0 = PlayableOutputHandle_get_Null_m1078851567(NULL /*static, unused*/, /*hidden argument*/NULL); ScriptPlayableOutput_t3853613875 L_1; memset(&L_1, 0, sizeof(L_1)); ScriptPlayableOutput__ctor_m1887120702((&L_1), L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_0011; } IL_0011: { ScriptPlayableOutput_t3853613875 L_2 = V_0; return L_2; } } // UnityEngine.Playables.PlayableOutputHandle UnityEngine.Playables.ScriptPlayableOutput::GetHandle() extern "C" PlayableOutputHandle_t192146840 ScriptPlayableOutput_GetHandle_m1901531121 (ScriptPlayableOutput_t3853613875 * __this, const RuntimeMethod* method) { PlayableOutputHandle_t192146840 V_0; memset(&V_0, 0, sizeof(V_0)); { PlayableOutputHandle_t192146840 L_0 = __this->get_m_Handle_0(); V_0 = L_0; goto IL_000d; } IL_000d: { PlayableOutputHandle_t192146840 L_1 = V_0; return L_1; } } extern "C" PlayableOutputHandle_t192146840 ScriptPlayableOutput_GetHandle_m1901531121_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { ScriptPlayableOutput_t3853613875 * _thisAdjusted = reinterpret_cast(__this + 1); return ScriptPlayableOutput_GetHandle_m1901531121(_thisAdjusted, method); } // UnityEngine.Playables.PlayableOutput UnityEngine.Playables.ScriptPlayableOutput::op_Implicit(UnityEngine.Playables.ScriptPlayableOutput) extern "C" PlayableOutput_t1264890687 ScriptPlayableOutput_op_Implicit_m3792269928 (RuntimeObject * __this /* static, unused */, ScriptPlayableOutput_t3853613875 ___output0, const RuntimeMethod* method) { PlayableOutput_t1264890687 V_0; memset(&V_0, 0, sizeof(V_0)); { PlayableOutputHandle_t192146840 L_0 = ScriptPlayableOutput_GetHandle_m1901531121((&___output0), /*hidden argument*/NULL); PlayableOutput_t1264890687 L_1; memset(&L_1, 0, sizeof(L_1)); PlayableOutput__ctor_m2391480348((&L_1), L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_0013; } IL_0013: { PlayableOutput_t1264890687 L_2 = V_0; return L_2; } } // UnityEngine.Playables.ScriptPlayableOutput UnityEngine.Playables.ScriptPlayableOutput::op_Explicit(UnityEngine.Playables.PlayableOutput) extern "C" ScriptPlayableOutput_t3853613875 ScriptPlayableOutput_op_Explicit_m3590001457 (RuntimeObject * __this /* static, unused */, PlayableOutput_t1264890687 ___output0, const RuntimeMethod* method) { ScriptPlayableOutput_t3853613875 V_0; memset(&V_0, 0, sizeof(V_0)); { PlayableOutputHandle_t192146840 L_0 = PlayableOutput_GetHandle_m135471249((&___output0), /*hidden argument*/NULL); ScriptPlayableOutput_t3853613875 L_1; memset(&L_1, 0, sizeof(L_1)); ScriptPlayableOutput__ctor_m1887120702((&L_1), L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_0013; } IL_0013: { ScriptPlayableOutput_t3853613875 L_2 = V_0; return L_2; } } // System.Void UnityEngine.PreferBinarySerialization::.ctor() extern "C" void PreferBinarySerialization__ctor_m3138052396 (PreferBinarySerialization_t1584085608 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.PropertyAttribute::.ctor() extern "C" void PropertyAttribute__ctor_m1537537891 (PropertyAttribute_t2314996045 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Int32 UnityEngine.QualitySettings::get_vSyncCount() extern "C" int32_t QualitySettings_get_vSyncCount_m514049999 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef int32_t (*QualitySettings_get_vSyncCount_m514049999_ftn) (); static QualitySettings_get_vSyncCount_m514049999_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (QualitySettings_get_vSyncCount_m514049999_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.QualitySettings::get_vSyncCount()"); int32_t retVal = _il2cpp_icall_func(); return retVal; } // System.Void UnityEngine.Quaternion::.ctor(System.Single,System.Single,System.Single,System.Single) extern "C" void Quaternion__ctor_m4162241598 (Quaternion_t4184531171 * __this, float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) { { float L_0 = ___x0; __this->set_x_0(L_0); float L_1 = ___y1; __this->set_y_1(L_1); float L_2 = ___z2; __this->set_z_2(L_2); float L_3 = ___w3; __this->set_w_3(L_3); return; } } extern "C" void Quaternion__ctor_m4162241598_AdjustorThunk (RuntimeObject * __this, float ___x0, float ___y1, float ___z2, float ___w3, const RuntimeMethod* method) { Quaternion_t4184531171 * _thisAdjusted = reinterpret_cast(__this + 1); Quaternion__ctor_m4162241598(_thisAdjusted, ___x0, ___y1, ___z2, ___w3, method); } // UnityEngine.Quaternion UnityEngine.Quaternion::LookRotation(UnityEngine.Vector3) extern "C" Quaternion_t4184531171 Quaternion_LookRotation_m474565940 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___forward0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_LookRotation_m474565940_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); Quaternion_t4184531171 V_1; memset(&V_1, 0, sizeof(V_1)); Quaternion_t4184531171 V_2; memset(&V_2, 0, sizeof(V_2)); { IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_0 = Vector3_get_up_m1147648688(NULL /*static, unused*/, /*hidden argument*/NULL); V_0 = L_0; IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_INTERNAL_CALL_LookRotation_m928515228(NULL /*static, unused*/, (&___forward0), (&V_0), (&V_1), /*hidden argument*/NULL); Quaternion_t4184531171 L_1 = V_1; V_2 = L_1; goto IL_0019; } IL_0019: { Quaternion_t4184531171 L_2 = V_2; return L_2; } } // System.Void UnityEngine.Quaternion::INTERNAL_CALL_LookRotation(UnityEngine.Vector3&,UnityEngine.Vector3&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_LookRotation_m928515228 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 * ___forward0, Vector3_t67624592 * ___upwards1, Quaternion_t4184531171 * ___value2, const RuntimeMethod* method) { typedef void (*Quaternion_INTERNAL_CALL_LookRotation_m928515228_ftn) (Vector3_t67624592 *, Vector3_t67624592 *, Quaternion_t4184531171 *); static Quaternion_INTERNAL_CALL_LookRotation_m928515228_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Quaternion_INTERNAL_CALL_LookRotation_m928515228_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Quaternion::INTERNAL_CALL_LookRotation(UnityEngine.Vector3&,UnityEngine.Vector3&,UnityEngine.Quaternion&)"); _il2cpp_icall_func(___forward0, ___upwards1, ___value2); } // UnityEngine.Quaternion UnityEngine.Quaternion::Lerp(UnityEngine.Quaternion,UnityEngine.Quaternion,System.Single) extern "C" Quaternion_t4184531171 Quaternion_Lerp_m2375651230 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___a0, Quaternion_t4184531171 ___b1, float ___t2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Lerp_m2375651230_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); Quaternion_t4184531171 V_1; memset(&V_1, 0, sizeof(V_1)); { float L_0 = ___t2; IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_INTERNAL_CALL_Lerp_m1992590364(NULL /*static, unused*/, (&___a0), (&___b1), L_0, (&V_0), /*hidden argument*/NULL); Quaternion_t4184531171 L_1 = V_0; V_1 = L_1; goto IL_0014; } IL_0014: { Quaternion_t4184531171 L_2 = V_1; return L_2; } } // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Lerp(UnityEngine.Quaternion&,UnityEngine.Quaternion&,System.Single,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Lerp_m1992590364 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___a0, Quaternion_t4184531171 * ___b1, float ___t2, Quaternion_t4184531171 * ___value3, const RuntimeMethod* method) { typedef void (*Quaternion_INTERNAL_CALL_Lerp_m1992590364_ftn) (Quaternion_t4184531171 *, Quaternion_t4184531171 *, float, Quaternion_t4184531171 *); static Quaternion_INTERNAL_CALL_Lerp_m1992590364_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Quaternion_INTERNAL_CALL_Lerp_m1992590364_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Quaternion::INTERNAL_CALL_Lerp(UnityEngine.Quaternion&,UnityEngine.Quaternion&,System.Single,UnityEngine.Quaternion&)"); _il2cpp_icall_func(___a0, ___b1, ___t2, ___value3); } // UnityEngine.Quaternion UnityEngine.Quaternion::Inverse(UnityEngine.Quaternion) extern "C" Quaternion_t4184531171 Quaternion_Inverse_m390778767 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___rotation0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Inverse_m390778767_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); Quaternion_t4184531171 V_1; memset(&V_1, 0, sizeof(V_1)); { IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_INTERNAL_CALL_Inverse_m1677209099(NULL /*static, unused*/, (&___rotation0), (&V_0), /*hidden argument*/NULL); Quaternion_t4184531171 L_0 = V_0; V_1 = L_0; goto IL_0011; } IL_0011: { Quaternion_t4184531171 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Inverse(UnityEngine.Quaternion&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Inverse_m1677209099 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___rotation0, Quaternion_t4184531171 * ___value1, const RuntimeMethod* method) { typedef void (*Quaternion_INTERNAL_CALL_Inverse_m1677209099_ftn) (Quaternion_t4184531171 *, Quaternion_t4184531171 *); static Quaternion_INTERNAL_CALL_Inverse_m1677209099_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Quaternion_INTERNAL_CALL_Inverse_m1677209099_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Quaternion::INTERNAL_CALL_Inverse(UnityEngine.Quaternion&,UnityEngine.Quaternion&)"); _il2cpp_icall_func(___rotation0, ___value1); } // UnityEngine.Vector3 UnityEngine.Quaternion::get_eulerAngles() extern "C" Vector3_t67624592 Quaternion_get_eulerAngles_m2921540577 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_get_eulerAngles_m2921540577_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Vector3_t67624592 L_0 = Quaternion_Internal_ToEulerRad_m298111895(NULL /*static, unused*/, (*(Quaternion_t4184531171 *)__this), /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_1 = Vector3_op_Multiply_m1441463291(NULL /*static, unused*/, L_0, (57.29578f), /*hidden argument*/NULL); Vector3_t67624592 L_2 = Quaternion_Internal_MakePositive_m281077695(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0021; } IL_0021: { Vector3_t67624592 L_3 = V_0; return L_3; } } extern "C" Vector3_t67624592 Quaternion_get_eulerAngles_m2921540577_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Quaternion_t4184531171 * _thisAdjusted = reinterpret_cast(__this + 1); return Quaternion_get_eulerAngles_m2921540577(_thisAdjusted, method); } // UnityEngine.Quaternion UnityEngine.Quaternion::Euler(System.Single,System.Single,System.Single) extern "C" Quaternion_t4184531171 Quaternion_Euler_m2408383635 (RuntimeObject * __this /* static, unused */, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Euler_m2408383635_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = ___x0; float L_1 = ___y1; float L_2 = ___z2; Vector3_t67624592 L_3; memset(&L_3, 0, sizeof(L_3)); Vector3__ctor_m649967503((&L_3), L_0, L_1, L_2, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_4 = Vector3_op_Multiply_m1441463291(NULL /*static, unused*/, L_3, (0.0174532924f), /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_t4184531171 L_5 = Quaternion_Internal_FromEulerRad_m2729453363(NULL /*static, unused*/, L_4, /*hidden argument*/NULL); V_0 = L_5; goto IL_001e; } IL_001e: { Quaternion_t4184531171 L_6 = V_0; return L_6; } } // UnityEngine.Quaternion UnityEngine.Quaternion::Euler(UnityEngine.Vector3) extern "C" Quaternion_t4184531171 Quaternion_Euler_m725079561 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___euler0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Euler_m725079561_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = ___euler0; IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_1 = Vector3_op_Multiply_m1441463291(NULL /*static, unused*/, L_0, (0.0174532924f), /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_t4184531171 L_2 = Quaternion_Internal_FromEulerRad_m2729453363(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0017; } IL_0017: { Quaternion_t4184531171 L_3 = V_0; return L_3; } } // UnityEngine.Vector3 UnityEngine.Quaternion::Internal_ToEulerRad(UnityEngine.Quaternion) extern "C" Vector3_t67624592 Quaternion_Internal_ToEulerRad_m298111895 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___rotation0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Internal_ToEulerRad_m298111895_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); Vector3_t67624592 V_1; memset(&V_1, 0, sizeof(V_1)); { IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484(NULL /*static, unused*/, (&___rotation0), (&V_0), /*hidden argument*/NULL); Vector3_t67624592 L_0 = V_0; V_1 = L_0; goto IL_0011; } IL_0011: { Vector3_t67624592 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Internal_ToEulerRad(UnityEngine.Quaternion&,UnityEngine.Vector3&) extern "C" void Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 * ___rotation0, Vector3_t67624592 * ___value1, const RuntimeMethod* method) { typedef void (*Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484_ftn) (Quaternion_t4184531171 *, Vector3_t67624592 *); static Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Quaternion_INTERNAL_CALL_Internal_ToEulerRad_m2990705484_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Quaternion::INTERNAL_CALL_Internal_ToEulerRad(UnityEngine.Quaternion&,UnityEngine.Vector3&)"); _il2cpp_icall_func(___rotation0, ___value1); } // UnityEngine.Quaternion UnityEngine.Quaternion::Internal_FromEulerRad(UnityEngine.Vector3) extern "C" Quaternion_t4184531171 Quaternion_Internal_FromEulerRad_m2729453363 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___euler0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Internal_FromEulerRad_m2729453363_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); Quaternion_t4184531171 V_1; memset(&V_1, 0, sizeof(V_1)); { IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937(NULL /*static, unused*/, (&___euler0), (&V_0), /*hidden argument*/NULL); Quaternion_t4184531171 L_0 = V_0; V_1 = L_0; goto IL_0011; } IL_0011: { Quaternion_t4184531171 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Quaternion::INTERNAL_CALL_Internal_FromEulerRad(UnityEngine.Vector3&,UnityEngine.Quaternion&) extern "C" void Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 * ___euler0, Quaternion_t4184531171 * ___value1, const RuntimeMethod* method) { typedef void (*Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937_ftn) (Vector3_t67624592 *, Quaternion_t4184531171 *); static Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Quaternion_INTERNAL_CALL_Internal_FromEulerRad_m3927886937_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Quaternion::INTERNAL_CALL_Internal_FromEulerRad(UnityEngine.Vector3&,UnityEngine.Quaternion&)"); _il2cpp_icall_func(___euler0, ___value1); } // UnityEngine.Quaternion UnityEngine.Quaternion::get_identity() extern "C" Quaternion_t4184531171 Quaternion_get_identity_m647656586 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_get_identity_m647656586_MetadataUsageId); s_Il2CppMethodInitialized = true; } Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); { IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Quaternion_t4184531171 L_0 = ((Quaternion_t4184531171_StaticFields*)il2cpp_codegen_static_fields_for(Quaternion_t4184531171_il2cpp_TypeInfo_var))->get_identityQuaternion_4(); V_0 = L_0; goto IL_000c; } IL_000c: { Quaternion_t4184531171 L_1 = V_0; return L_1; } } // UnityEngine.Quaternion UnityEngine.Quaternion::op_Multiply(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" Quaternion_t4184531171 Quaternion_op_Multiply_m2890986375 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___lhs0, Quaternion_t4184531171 ___rhs1, const RuntimeMethod* method) { Quaternion_t4184531171 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = (&___lhs0)->get_w_3(); float L_1 = (&___rhs1)->get_x_0(); float L_2 = (&___lhs0)->get_x_0(); float L_3 = (&___rhs1)->get_w_3(); float L_4 = (&___lhs0)->get_y_1(); float L_5 = (&___rhs1)->get_z_2(); float L_6 = (&___lhs0)->get_z_2(); float L_7 = (&___rhs1)->get_y_1(); float L_8 = (&___lhs0)->get_w_3(); float L_9 = (&___rhs1)->get_y_1(); float L_10 = (&___lhs0)->get_y_1(); float L_11 = (&___rhs1)->get_w_3(); float L_12 = (&___lhs0)->get_z_2(); float L_13 = (&___rhs1)->get_x_0(); float L_14 = (&___lhs0)->get_x_0(); float L_15 = (&___rhs1)->get_z_2(); float L_16 = (&___lhs0)->get_w_3(); float L_17 = (&___rhs1)->get_z_2(); float L_18 = (&___lhs0)->get_z_2(); float L_19 = (&___rhs1)->get_w_3(); float L_20 = (&___lhs0)->get_x_0(); float L_21 = (&___rhs1)->get_y_1(); float L_22 = (&___lhs0)->get_y_1(); float L_23 = (&___rhs1)->get_x_0(); float L_24 = (&___lhs0)->get_w_3(); float L_25 = (&___rhs1)->get_w_3(); float L_26 = (&___lhs0)->get_x_0(); float L_27 = (&___rhs1)->get_x_0(); float L_28 = (&___lhs0)->get_y_1(); float L_29 = (&___rhs1)->get_y_1(); float L_30 = (&___lhs0)->get_z_2(); float L_31 = (&___rhs1)->get_z_2(); Quaternion_t4184531171 L_32; memset(&L_32, 0, sizeof(L_32)); Quaternion__ctor_m4162241598((&L_32), ((float)((float)((float)((float)((float)((float)((float)((float)L_0*(float)L_1))+(float)((float)((float)L_2*(float)L_3))))+(float)((float)((float)L_4*(float)L_5))))-(float)((float)((float)L_6*(float)L_7)))), ((float)((float)((float)((float)((float)((float)((float)((float)L_8*(float)L_9))+(float)((float)((float)L_10*(float)L_11))))+(float)((float)((float)L_12*(float)L_13))))-(float)((float)((float)L_14*(float)L_15)))), ((float)((float)((float)((float)((float)((float)((float)((float)L_16*(float)L_17))+(float)((float)((float)L_18*(float)L_19))))+(float)((float)((float)L_20*(float)L_21))))-(float)((float)((float)L_22*(float)L_23)))), ((float)((float)((float)((float)((float)((float)((float)((float)L_24*(float)L_25))-(float)((float)((float)L_26*(float)L_27))))-(float)((float)((float)L_28*(float)L_29))))-(float)((float)((float)L_30*(float)L_31)))), /*hidden argument*/NULL); V_0 = L_32; goto IL_0108; } IL_0108: { Quaternion_t4184531171 L_33 = V_0; return L_33; } } // UnityEngine.Vector3 UnityEngine.Quaternion::op_Multiply(UnityEngine.Quaternion,UnityEngine.Vector3) extern "C" Vector3_t67624592 Quaternion_op_Multiply_m1066223492 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___rotation0, Vector3_t67624592 ___point1, const RuntimeMethod* method) { float V_0 = 0.0f; float V_1 = 0.0f; float V_2 = 0.0f; float V_3 = 0.0f; float V_4 = 0.0f; float V_5 = 0.0f; float V_6 = 0.0f; float V_7 = 0.0f; float V_8 = 0.0f; float V_9 = 0.0f; float V_10 = 0.0f; float V_11 = 0.0f; Vector3_t67624592 V_12; memset(&V_12, 0, sizeof(V_12)); Vector3_t67624592 V_13; memset(&V_13, 0, sizeof(V_13)); { float L_0 = (&___rotation0)->get_x_0(); V_0 = ((float)((float)L_0*(float)(2.0f))); float L_1 = (&___rotation0)->get_y_1(); V_1 = ((float)((float)L_1*(float)(2.0f))); float L_2 = (&___rotation0)->get_z_2(); V_2 = ((float)((float)L_2*(float)(2.0f))); float L_3 = (&___rotation0)->get_x_0(); float L_4 = V_0; V_3 = ((float)((float)L_3*(float)L_4)); float L_5 = (&___rotation0)->get_y_1(); float L_6 = V_1; V_4 = ((float)((float)L_5*(float)L_6)); float L_7 = (&___rotation0)->get_z_2(); float L_8 = V_2; V_5 = ((float)((float)L_7*(float)L_8)); float L_9 = (&___rotation0)->get_x_0(); float L_10 = V_1; V_6 = ((float)((float)L_9*(float)L_10)); float L_11 = (&___rotation0)->get_x_0(); float L_12 = V_2; V_7 = ((float)((float)L_11*(float)L_12)); float L_13 = (&___rotation0)->get_y_1(); float L_14 = V_2; V_8 = ((float)((float)L_13*(float)L_14)); float L_15 = (&___rotation0)->get_w_3(); float L_16 = V_0; V_9 = ((float)((float)L_15*(float)L_16)); float L_17 = (&___rotation0)->get_w_3(); float L_18 = V_1; V_10 = ((float)((float)L_17*(float)L_18)); float L_19 = (&___rotation0)->get_w_3(); float L_20 = V_2; V_11 = ((float)((float)L_19*(float)L_20)); float L_21 = V_4; float L_22 = V_5; float L_23 = (&___point1)->get_x_1(); float L_24 = V_6; float L_25 = V_11; float L_26 = (&___point1)->get_y_2(); float L_27 = V_7; float L_28 = V_10; float L_29 = (&___point1)->get_z_3(); (&V_12)->set_x_1(((float)((float)((float)((float)((float)((float)((float)((float)(1.0f)-(float)((float)((float)L_21+(float)L_22))))*(float)L_23))+(float)((float)((float)((float)((float)L_24-(float)L_25))*(float)L_26))))+(float)((float)((float)((float)((float)L_27+(float)L_28))*(float)L_29))))); float L_30 = V_6; float L_31 = V_11; float L_32 = (&___point1)->get_x_1(); float L_33 = V_3; float L_34 = V_5; float L_35 = (&___point1)->get_y_2(); float L_36 = V_8; float L_37 = V_9; float L_38 = (&___point1)->get_z_3(); (&V_12)->set_y_2(((float)((float)((float)((float)((float)((float)((float)((float)L_30+(float)L_31))*(float)L_32))+(float)((float)((float)((float)((float)(1.0f)-(float)((float)((float)L_33+(float)L_34))))*(float)L_35))))+(float)((float)((float)((float)((float)L_36-(float)L_37))*(float)L_38))))); float L_39 = V_7; float L_40 = V_10; float L_41 = (&___point1)->get_x_1(); float L_42 = V_8; float L_43 = V_9; float L_44 = (&___point1)->get_y_2(); float L_45 = V_3; float L_46 = V_4; float L_47 = (&___point1)->get_z_3(); (&V_12)->set_z_3(((float)((float)((float)((float)((float)((float)((float)((float)L_39-(float)L_40))*(float)L_41))+(float)((float)((float)((float)((float)L_42+(float)L_43))*(float)L_44))))+(float)((float)((float)((float)((float)(1.0f)-(float)((float)((float)L_45+(float)L_46))))*(float)L_47))))); Vector3_t67624592 L_48 = V_12; V_13 = L_48; goto IL_0136; } IL_0136: { Vector3_t67624592 L_49 = V_13; return L_49; } } // System.Boolean UnityEngine.Quaternion::op_Equality(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" bool Quaternion_op_Equality_m3282458924 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___lhs0, Quaternion_t4184531171 ___rhs1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_op_Equality_m3282458924_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { Quaternion_t4184531171 L_0 = ___lhs0; Quaternion_t4184531171 L_1 = ___rhs1; IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); float L_2 = Quaternion_Dot_m3305700391(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = (bool)((((float)L_2) > ((float)(0.999999f)))? 1 : 0); goto IL_0015; } IL_0015: { bool L_3 = V_0; return L_3; } } // System.Boolean UnityEngine.Quaternion::op_Inequality(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" bool Quaternion_op_Inequality_m1705400273 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___lhs0, Quaternion_t4184531171 ___rhs1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_op_Inequality_m1705400273_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { Quaternion_t4184531171 L_0 = ___lhs0; Quaternion_t4184531171 L_1 = ___rhs1; IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); bool L_2 = Quaternion_op_Equality_m3282458924(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = (bool)((((int32_t)L_2) == ((int32_t)0))? 1 : 0); goto IL_0011; } IL_0011: { bool L_3 = V_0; return L_3; } } // System.Single UnityEngine.Quaternion::Dot(UnityEngine.Quaternion,UnityEngine.Quaternion) extern "C" float Quaternion_Dot_m3305700391 (RuntimeObject * __this /* static, unused */, Quaternion_t4184531171 ___a0, Quaternion_t4184531171 ___b1, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = (&___a0)->get_x_0(); float L_1 = (&___b1)->get_x_0(); float L_2 = (&___a0)->get_y_1(); float L_3 = (&___b1)->get_y_1(); float L_4 = (&___a0)->get_z_2(); float L_5 = (&___b1)->get_z_2(); float L_6 = (&___a0)->get_w_3(); float L_7 = (&___b1)->get_w_3(); V_0 = ((float)((float)((float)((float)((float)((float)((float)((float)L_0*(float)L_1))+(float)((float)((float)L_2*(float)L_3))))+(float)((float)((float)L_4*(float)L_5))))+(float)((float)((float)L_6*(float)L_7)))); goto IL_0046; } IL_0046: { float L_8 = V_0; return L_8; } } // UnityEngine.Vector3 UnityEngine.Quaternion::Internal_MakePositive(UnityEngine.Vector3) extern "C" Vector3_t67624592 Quaternion_Internal_MakePositive_m281077695 (RuntimeObject * __this /* static, unused */, Vector3_t67624592 ___euler0, const RuntimeMethod* method) { float V_0 = 0.0f; float V_1 = 0.0f; Vector3_t67624592 V_2; memset(&V_2, 0, sizeof(V_2)); { V_0 = (-0.005729578f); float L_0 = V_0; V_1 = ((float)((float)(360.0f)+(float)L_0)); float L_1 = (&___euler0)->get_x_1(); float L_2 = V_0; if ((!(((float)L_1) < ((float)L_2)))) { goto IL_0034; } } { Vector3_t67624592 * L_3 = (&___euler0); float L_4 = L_3->get_x_1(); L_3->set_x_1(((float)((float)L_4+(float)(360.0f)))); goto IL_0054; } IL_0034: { float L_5 = (&___euler0)->get_x_1(); float L_6 = V_1; if ((!(((float)L_5) > ((float)L_6)))) { goto IL_0054; } } { Vector3_t67624592 * L_7 = (&___euler0); float L_8 = L_7->get_x_1(); L_7->set_x_1(((float)((float)L_8-(float)(360.0f)))); } IL_0054: { float L_9 = (&___euler0)->get_y_2(); float L_10 = V_0; if ((!(((float)L_9) < ((float)L_10)))) { goto IL_0079; } } { Vector3_t67624592 * L_11 = (&___euler0); float L_12 = L_11->get_y_2(); L_11->set_y_2(((float)((float)L_12+(float)(360.0f)))); goto IL_0099; } IL_0079: { float L_13 = (&___euler0)->get_y_2(); float L_14 = V_1; if ((!(((float)L_13) > ((float)L_14)))) { goto IL_0099; } } { Vector3_t67624592 * L_15 = (&___euler0); float L_16 = L_15->get_y_2(); L_15->set_y_2(((float)((float)L_16-(float)(360.0f)))); } IL_0099: { float L_17 = (&___euler0)->get_z_3(); float L_18 = V_0; if ((!(((float)L_17) < ((float)L_18)))) { goto IL_00be; } } { Vector3_t67624592 * L_19 = (&___euler0); float L_20 = L_19->get_z_3(); L_19->set_z_3(((float)((float)L_20+(float)(360.0f)))); goto IL_00de; } IL_00be: { float L_21 = (&___euler0)->get_z_3(); float L_22 = V_1; if ((!(((float)L_21) > ((float)L_22)))) { goto IL_00de; } } { Vector3_t67624592 * L_23 = (&___euler0); float L_24 = L_23->get_z_3(); L_23->set_z_3(((float)((float)L_24-(float)(360.0f)))); } IL_00de: { Vector3_t67624592 L_25 = ___euler0; V_2 = L_25; goto IL_00e5; } IL_00e5: { Vector3_t67624592 L_26 = V_2; return L_26; } } // System.Int32 UnityEngine.Quaternion::GetHashCode() extern "C" int32_t Quaternion_GetHashCode_m4096992011 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { float* L_0 = __this->get_address_of_x_0(); int32_t L_1 = Single_GetHashCode_m177552305(L_0, /*hidden argument*/NULL); float* L_2 = __this->get_address_of_y_1(); int32_t L_3 = Single_GetHashCode_m177552305(L_2, /*hidden argument*/NULL); float* L_4 = __this->get_address_of_z_2(); int32_t L_5 = Single_GetHashCode_m177552305(L_4, /*hidden argument*/NULL); float* L_6 = __this->get_address_of_w_3(); int32_t L_7 = Single_GetHashCode_m177552305(L_6, /*hidden argument*/NULL); V_0 = ((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_1^(int32_t)((int32_t)((int32_t)L_3<<(int32_t)2))))^(int32_t)((int32_t)((int32_t)L_5>>(int32_t)2))))^(int32_t)((int32_t)((int32_t)L_7>>(int32_t)1)))); goto IL_0054; } IL_0054: { int32_t L_8 = V_0; return L_8; } } extern "C" int32_t Quaternion_GetHashCode_m4096992011_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Quaternion_t4184531171 * _thisAdjusted = reinterpret_cast(__this + 1); return Quaternion_GetHashCode_m4096992011(_thisAdjusted, method); } // System.Boolean UnityEngine.Quaternion::Equals(System.Object) extern "C" bool Quaternion_Equals_m3924578426 (Quaternion_t4184531171 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_Equals_m3924578426_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; Quaternion_t4184531171 V_1; memset(&V_1, 0, sizeof(V_1)); int32_t G_B7_0 = 0; { RuntimeObject * L_0 = ___other0; if (((RuntimeObject *)IsInstSealed((RuntimeObject*)L_0, Quaternion_t4184531171_il2cpp_TypeInfo_var))) { goto IL_0013; } } { V_0 = (bool)0; goto IL_007a; } IL_0013: { RuntimeObject * L_1 = ___other0; V_1 = ((*(Quaternion_t4184531171 *)((Quaternion_t4184531171 *)UnBox(L_1, Quaternion_t4184531171_il2cpp_TypeInfo_var)))); float* L_2 = __this->get_address_of_x_0(); float L_3 = (&V_1)->get_x_0(); bool L_4 = Single_Equals_m767089390(L_2, L_3, /*hidden argument*/NULL); if (!L_4) { goto IL_0073; } } { float* L_5 = __this->get_address_of_y_1(); float L_6 = (&V_1)->get_y_1(); bool L_7 = Single_Equals_m767089390(L_5, L_6, /*hidden argument*/NULL); if (!L_7) { goto IL_0073; } } { float* L_8 = __this->get_address_of_z_2(); float L_9 = (&V_1)->get_z_2(); bool L_10 = Single_Equals_m767089390(L_8, L_9, /*hidden argument*/NULL); if (!L_10) { goto IL_0073; } } { float* L_11 = __this->get_address_of_w_3(); float L_12 = (&V_1)->get_w_3(); bool L_13 = Single_Equals_m767089390(L_11, L_12, /*hidden argument*/NULL); G_B7_0 = ((int32_t)(L_13)); goto IL_0074; } IL_0073: { G_B7_0 = 0; } IL_0074: { V_0 = (bool)G_B7_0; goto IL_007a; } IL_007a: { bool L_14 = V_0; return L_14; } } extern "C" bool Quaternion_Equals_m3924578426_AdjustorThunk (RuntimeObject * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { Quaternion_t4184531171 * _thisAdjusted = reinterpret_cast(__this + 1); return Quaternion_Equals_m3924578426(_thisAdjusted, ___other0, method); } // System.String UnityEngine.Quaternion::ToString() extern "C" String_t* Quaternion_ToString_m4223730163 (Quaternion_t4184531171 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion_ToString_m4223730163_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)4)); float L_1 = __this->get_x_0(); float L_2 = L_1; RuntimeObject * L_3 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_2); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_3); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_3); ObjectU5BU5D_t3885370135* L_4 = L_0; float L_5 = __this->get_y_1(); float L_6 = L_5; RuntimeObject * L_7 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_6); NullCheck(L_4); ArrayElementTypeCheck (L_4, L_7); (L_4)->SetAt(static_cast(1), (RuntimeObject *)L_7); ObjectU5BU5D_t3885370135* L_8 = L_4; float L_9 = __this->get_z_2(); float L_10 = L_9; RuntimeObject * L_11 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_10); NullCheck(L_8); ArrayElementTypeCheck (L_8, L_11); (L_8)->SetAt(static_cast(2), (RuntimeObject *)L_11); ObjectU5BU5D_t3885370135* L_12 = L_8; float L_13 = __this->get_w_3(); float L_14 = L_13; RuntimeObject * L_15 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_14); NullCheck(L_12); ArrayElementTypeCheck (L_12, L_15); (L_12)->SetAt(static_cast(3), (RuntimeObject *)L_15); String_t* L_16 = UnityString_Format_m1454782387(NULL /*static, unused*/, _stringLiteral1867442433, L_12, /*hidden argument*/NULL); V_0 = L_16; goto IL_004f; } IL_004f: { String_t* L_17 = V_0; return L_17; } } extern "C" String_t* Quaternion_ToString_m4223730163_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Quaternion_t4184531171 * _thisAdjusted = reinterpret_cast(__this + 1); return Quaternion_ToString_m4223730163(_thisAdjusted, method); } // System.Void UnityEngine.Quaternion::.cctor() extern "C" void Quaternion__cctor_m1783079664 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Quaternion__cctor_m1783079664_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Quaternion_t4184531171 L_0; memset(&L_0, 0, sizeof(L_0)); Quaternion__ctor_m4162241598((&L_0), (0.0f), (0.0f), (0.0f), (1.0f), /*hidden argument*/NULL); ((Quaternion_t4184531171_StaticFields*)il2cpp_codegen_static_fields_for(Quaternion_t4184531171_il2cpp_TypeInfo_var))->set_identityQuaternion_4(L_0); return; } } // System.Single UnityEngine.Random::Range(System.Single,System.Single) extern "C" float Random_Range_m3325497068 (RuntimeObject * __this /* static, unused */, float ___min0, float ___max1, const RuntimeMethod* method) { typedef float (*Random_Range_m3325497068_ftn) (float, float); static Random_Range_m3325497068_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Random_Range_m3325497068_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Random::Range(System.Single,System.Single)"); float retVal = _il2cpp_icall_func(___min0, ___max1); return retVal; } // System.Int32 UnityEngine.Random::Range(System.Int32,System.Int32) extern "C" int32_t Random_Range_m721497971 (RuntimeObject * __this /* static, unused */, int32_t ___min0, int32_t ___max1, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = ___min0; int32_t L_1 = ___max1; int32_t L_2 = Random_RandomRangeInt_m708986018(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_000e; } IL_000e: { int32_t L_3 = V_0; return L_3; } } // System.Int32 UnityEngine.Random::RandomRangeInt(System.Int32,System.Int32) extern "C" int32_t Random_RandomRangeInt_m708986018 (RuntimeObject * __this /* static, unused */, int32_t ___min0, int32_t ___max1, const RuntimeMethod* method) { typedef int32_t (*Random_RandomRangeInt_m708986018_ftn) (int32_t, int32_t); static Random_RandomRangeInt_m708986018_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Random_RandomRangeInt_m708986018_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Random::RandomRangeInt(System.Int32,System.Int32)"); int32_t retVal = _il2cpp_icall_func(___min0, ___max1); return retVal; } // System.Void UnityEngine.RangeAttribute::.ctor(System.Single,System.Single) extern "C" void RangeAttribute__ctor_m795913462 (RangeAttribute_t90224693 * __this, float ___min0, float ___max1, const RuntimeMethod* method) { { PropertyAttribute__ctor_m1537537891(__this, /*hidden argument*/NULL); float L_0 = ___min0; __this->set_min_0(L_0); float L_1 = ___max1; __this->set_max_1(L_1); return; } } // System.Int32 UnityEngine.RangeInt::get_end() extern "C" int32_t RangeInt_get_end_m2625147402 (RangeInt_t772515686 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_start_0(); int32_t L_1 = __this->get_length_1(); V_0 = ((int32_t)((int32_t)L_0+(int32_t)L_1)); goto IL_0014; } IL_0014: { int32_t L_2 = V_0; return L_2; } } extern "C" int32_t RangeInt_get_end_m2625147402_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RangeInt_t772515686 * _thisAdjusted = reinterpret_cast(__this + 1); return RangeInt_get_end_m2625147402(_thisAdjusted, method); } // System.Void UnityEngine.Ray::.ctor(UnityEngine.Vector3,UnityEngine.Vector3) extern "C" void Ray__ctor_m1769593825 (Ray_t3058960190 * __this, Vector3_t67624592 ___origin0, Vector3_t67624592 ___direction1, const RuntimeMethod* method) { { Vector3_t67624592 L_0 = ___origin0; __this->set_m_Origin_0(L_0); Vector3_t67624592 L_1 = Vector3_get_normalized_m2262836590((&___direction1), /*hidden argument*/NULL); __this->set_m_Direction_1(L_1); return; } } extern "C" void Ray__ctor_m1769593825_AdjustorThunk (RuntimeObject * __this, Vector3_t67624592 ___origin0, Vector3_t67624592 ___direction1, const RuntimeMethod* method) { Ray_t3058960190 * _thisAdjusted = reinterpret_cast(__this + 1); Ray__ctor_m1769593825(_thisAdjusted, ___origin0, ___direction1, method); } // UnityEngine.Vector3 UnityEngine.Ray::get_origin() extern "C" Vector3_t67624592 Ray_get_origin_m3158142785 (Ray_t3058960190 * __this, const RuntimeMethod* method) { Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = __this->get_m_Origin_0(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector3_t67624592 L_1 = V_0; return L_1; } } extern "C" Vector3_t67624592 Ray_get_origin_m3158142785_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Ray_t3058960190 * _thisAdjusted = reinterpret_cast(__this + 1); return Ray_get_origin_m3158142785(_thisAdjusted, method); } // UnityEngine.Vector3 UnityEngine.Ray::get_direction() extern "C" Vector3_t67624592 Ray_get_direction_m2485610855 (Ray_t3058960190 * __this, const RuntimeMethod* method) { Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = __this->get_m_Direction_1(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector3_t67624592 L_1 = V_0; return L_1; } } extern "C" Vector3_t67624592 Ray_get_direction_m2485610855_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Ray_t3058960190 * _thisAdjusted = reinterpret_cast(__this + 1); return Ray_get_direction_m2485610855(_thisAdjusted, method); } // UnityEngine.Vector3 UnityEngine.Ray::GetPoint(System.Single) extern "C" Vector3_t67624592 Ray_GetPoint_m1809995955 (Ray_t3058960190 * __this, float ___distance0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Ray_GetPoint_m1809995955_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = __this->get_m_Origin_0(); Vector3_t67624592 L_1 = __this->get_m_Direction_1(); float L_2 = ___distance0; IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_3 = Vector3_op_Multiply_m1441463291(NULL /*static, unused*/, L_1, L_2, /*hidden argument*/NULL); Vector3_t67624592 L_4 = Vector3_op_Addition_m3078548397(NULL /*static, unused*/, L_0, L_3, /*hidden argument*/NULL); V_0 = L_4; goto IL_001e; } IL_001e: { Vector3_t67624592 L_5 = V_0; return L_5; } } extern "C" Vector3_t67624592 Ray_GetPoint_m1809995955_AdjustorThunk (RuntimeObject * __this, float ___distance0, const RuntimeMethod* method) { Ray_t3058960190 * _thisAdjusted = reinterpret_cast(__this + 1); return Ray_GetPoint_m1809995955(_thisAdjusted, ___distance0, method); } // System.String UnityEngine.Ray::ToString() extern "C" String_t* Ray_ToString_m4189095882 (Ray_t3058960190 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Ray_ToString_m4189095882_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)2)); Vector3_t67624592 L_1 = __this->get_m_Origin_0(); Vector3_t67624592 L_2 = L_1; RuntimeObject * L_3 = Box(Vector3_t67624592_il2cpp_TypeInfo_var, &L_2); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_3); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_3); ObjectU5BU5D_t3885370135* L_4 = L_0; Vector3_t67624592 L_5 = __this->get_m_Direction_1(); Vector3_t67624592 L_6 = L_5; RuntimeObject * L_7 = Box(Vector3_t67624592_il2cpp_TypeInfo_var, &L_6); NullCheck(L_4); ArrayElementTypeCheck (L_4, L_7); (L_4)->SetAt(static_cast(1), (RuntimeObject *)L_7); String_t* L_8 = UnityString_Format_m1454782387(NULL /*static, unused*/, _stringLiteral2014213472, L_4, /*hidden argument*/NULL); V_0 = L_8; goto IL_0033; } IL_0033: { String_t* L_9 = V_0; return L_9; } } extern "C" String_t* Ray_ToString_m4189095882_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Ray_t3058960190 * _thisAdjusted = reinterpret_cast(__this + 1); return Ray_ToString_m4189095882(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.RaycastHit extern "C" void RaycastHit_t254327561_marshal_pinvoke(const RaycastHit_t254327561& unmarshaled, RaycastHit_t254327561_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } extern "C" void RaycastHit_t254327561_marshal_pinvoke_back(const RaycastHit_t254327561_marshaled_pinvoke& marshaled, RaycastHit_t254327561& unmarshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } // Conversion method for clean up from marshalling of: UnityEngine.RaycastHit extern "C" void RaycastHit_t254327561_marshal_pinvoke_cleanup(RaycastHit_t254327561_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.RaycastHit extern "C" void RaycastHit_t254327561_marshal_com(const RaycastHit_t254327561& unmarshaled, RaycastHit_t254327561_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } extern "C" void RaycastHit_t254327561_marshal_com_back(const RaycastHit_t254327561_marshaled_com& marshaled, RaycastHit_t254327561& unmarshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } // Conversion method for clean up from marshalling of: UnityEngine.RaycastHit extern "C" void RaycastHit_t254327561_marshal_com_cleanup(RaycastHit_t254327561_marshaled_com& marshaled) { } // UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() extern "C" Vector3_t67624592 RaycastHit_get_point_m1459319107 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = __this->get_m_Point_0(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector3_t67624592 L_1 = V_0; return L_1; } } extern "C" Vector3_t67624592 RaycastHit_get_point_m1459319107_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_point_m1459319107(_thisAdjusted, method); } // UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() extern "C" Vector3_t67624592 RaycastHit_get_normal_m2782368312 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector3_t67624592 L_0 = __this->get_m_Normal_1(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector3_t67624592 L_1 = V_0; return L_1; } } extern "C" Vector3_t67624592 RaycastHit_get_normal_m2782368312_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_normal_m2782368312(_thisAdjusted, method); } // System.Single UnityEngine.RaycastHit::get_distance() extern "C" float RaycastHit_get_distance_m2739708343 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Distance_3(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float RaycastHit_get_distance_m2739708343_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_distance_m2739708343(_thisAdjusted, method); } // UnityEngine.Collider UnityEngine.RaycastHit::get_collider() extern "C" Collider_t3058509131 * RaycastHit_get_collider_m1042127013 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { Collider_t3058509131 * V_0 = NULL; { Collider_t3058509131 * L_0 = __this->get_m_Collider_5(); V_0 = L_0; goto IL_000d; } IL_000d: { Collider_t3058509131 * L_1 = V_0; return L_1; } } extern "C" Collider_t3058509131 * RaycastHit_get_collider_m1042127013_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_collider_m1042127013(_thisAdjusted, method); } // UnityEngine.Rigidbody UnityEngine.RaycastHit::get_rigidbody() extern "C" Rigidbody_t2809865642 * RaycastHit_get_rigidbody_m507930372 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RaycastHit_get_rigidbody_m507930372_MetadataUsageId); s_Il2CppMethodInitialized = true; } Rigidbody_t2809865642 * V_0 = NULL; Rigidbody_t2809865642 * G_B3_0 = NULL; { Collider_t3058509131 * L_0 = RaycastHit_get_collider_m1042127013(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0022; } } { Collider_t3058509131 * L_2 = RaycastHit_get_collider_m1042127013(__this, /*hidden argument*/NULL); NullCheck(L_2); Rigidbody_t2809865642 * L_3 = Collider_get_attachedRigidbody_m4234646872(L_2, /*hidden argument*/NULL); G_B3_0 = L_3; goto IL_0023; } IL_0022: { G_B3_0 = ((Rigidbody_t2809865642 *)(NULL)); } IL_0023: { V_0 = G_B3_0; goto IL_0029; } IL_0029: { Rigidbody_t2809865642 * L_4 = V_0; return L_4; } } extern "C" Rigidbody_t2809865642 * RaycastHit_get_rigidbody_m507930372_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_rigidbody_m507930372(_thisAdjusted, method); } // UnityEngine.Transform UnityEngine.RaycastHit::get_transform() extern "C" Transform_t2468616896 * RaycastHit_get_transform_m3831275417 (RaycastHit_t254327561 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RaycastHit_get_transform_m3831275417_MetadataUsageId); s_Il2CppMethodInitialized = true; } Rigidbody_t2809865642 * V_0 = NULL; Transform_t2468616896 * V_1 = NULL; { Rigidbody_t2809865642 * L_0 = RaycastHit_get_rigidbody_m507930372(__this, /*hidden argument*/NULL); V_0 = L_0; Rigidbody_t2809865642 * L_1 = V_0; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_2 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_1, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_2) { goto IL_0020; } } { Rigidbody_t2809865642 * L_3 = V_0; NullCheck(L_3); Transform_t2468616896 * L_4 = Component_get_transform_m987883457(L_3, /*hidden argument*/NULL); V_1 = L_4; goto IL_0049; } IL_0020: { Collider_t3058509131 * L_5 = RaycastHit_get_collider_m1042127013(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_6 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_5, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_6) { goto IL_0042; } } { Collider_t3058509131 * L_7 = RaycastHit_get_collider_m1042127013(__this, /*hidden argument*/NULL); NullCheck(L_7); Transform_t2468616896 * L_8 = Component_get_transform_m987883457(L_7, /*hidden argument*/NULL); V_1 = L_8; goto IL_0049; } IL_0042: { V_1 = (Transform_t2468616896 *)NULL; goto IL_0049; } IL_0049: { Transform_t2468616896 * L_9 = V_1; return L_9; } } extern "C" Transform_t2468616896 * RaycastHit_get_transform_m3831275417_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit_t254327561 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit_get_transform_m3831275417(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.RaycastHit2D extern "C" void RaycastHit2D_t3236695499_marshal_pinvoke(const RaycastHit2D_t3236695499& unmarshaled, RaycastHit2D_t3236695499_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit2D': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } extern "C" void RaycastHit2D_t3236695499_marshal_pinvoke_back(const RaycastHit2D_t3236695499_marshaled_pinvoke& marshaled, RaycastHit2D_t3236695499& unmarshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit2D': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } // Conversion method for clean up from marshalling of: UnityEngine.RaycastHit2D extern "C" void RaycastHit2D_t3236695499_marshal_pinvoke_cleanup(RaycastHit2D_t3236695499_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.RaycastHit2D extern "C" void RaycastHit2D_t3236695499_marshal_com(const RaycastHit2D_t3236695499& unmarshaled, RaycastHit2D_t3236695499_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit2D': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } extern "C" void RaycastHit2D_t3236695499_marshal_com_back(const RaycastHit2D_t3236695499_marshaled_com& marshaled, RaycastHit2D_t3236695499& unmarshaled) { Il2CppCodeGenException* ___m_Collider_5Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Collider' of type 'RaycastHit2D': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Collider_5Exception); } // Conversion method for clean up from marshalling of: UnityEngine.RaycastHit2D extern "C" void RaycastHit2D_t3236695499_marshal_com_cleanup(RaycastHit2D_t3236695499_marshaled_com& marshaled) { } // UnityEngine.Vector2 UnityEngine.RaycastHit2D::get_point() extern "C" Vector2_t3854014517 RaycastHit2D_get_point_m2657298746 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector2_t3854014517 L_0 = __this->get_m_Point_1(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector2_t3854014517 L_1 = V_0; return L_1; } } extern "C" Vector2_t3854014517 RaycastHit2D_get_point_m2657298746_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit2D_t3236695499 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit2D_get_point_m2657298746(_thisAdjusted, method); } // UnityEngine.Vector2 UnityEngine.RaycastHit2D::get_normal() extern "C" Vector2_t3854014517 RaycastHit2D_get_normal_m3413167889 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector2_t3854014517 L_0 = __this->get_m_Normal_2(); V_0 = L_0; goto IL_000d; } IL_000d: { Vector2_t3854014517 L_1 = V_0; return L_1; } } extern "C" Vector2_t3854014517 RaycastHit2D_get_normal_m3413167889_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit2D_t3236695499 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit2D_get_normal_m3413167889(_thisAdjusted, method); } // System.Single UnityEngine.RaycastHit2D::get_distance() extern "C" float RaycastHit2D_get_distance_m1140368293 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Distance_3(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float RaycastHit2D_get_distance_m1140368293_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit2D_t3236695499 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit2D_get_distance_m1140368293(_thisAdjusted, method); } // UnityEngine.Collider2D UnityEngine.RaycastHit2D::get_collider() extern "C" Collider2D_t2180151806 * RaycastHit2D_get_collider_m653937822 (RaycastHit2D_t3236695499 * __this, const RuntimeMethod* method) { Collider2D_t2180151806 * V_0 = NULL; { Collider2D_t2180151806 * L_0 = __this->get_m_Collider_5(); V_0 = L_0; goto IL_000d; } IL_000d: { Collider2D_t2180151806 * L_1 = V_0; return L_1; } } extern "C" Collider2D_t2180151806 * RaycastHit2D_get_collider_m653937822_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { RaycastHit2D_t3236695499 * _thisAdjusted = reinterpret_cast(__this + 1); return RaycastHit2D_get_collider_m653937822(_thisAdjusted, method); } // System.Void UnityEngine.Rect::.ctor(System.Single,System.Single,System.Single,System.Single) extern "C" void Rect__ctor_m2220344300 (Rect_t3345319094 * __this, float ___x0, float ___y1, float ___width2, float ___height3, const RuntimeMethod* method) { { float L_0 = ___x0; __this->set_m_XMin_0(L_0); float L_1 = ___y1; __this->set_m_YMin_1(L_1); float L_2 = ___width2; __this->set_m_Width_2(L_2); float L_3 = ___height3; __this->set_m_Height_3(L_3); return; } } extern "C" void Rect__ctor_m2220344300_AdjustorThunk (RuntimeObject * __this, float ___x0, float ___y1, float ___width2, float ___height3, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect__ctor_m2220344300(_thisAdjusted, ___x0, ___y1, ___width2, ___height3, method); } // System.Single UnityEngine.Rect::get_x() extern "C" float Rect_get_x_m1272655030 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_XMin_0(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_x_m1272655030_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_x_m1272655030(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_x(System.Single) extern "C" void Rect_set_x_m3651671365 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_XMin_0(L_0); return; } } extern "C" void Rect_set_x_m3651671365_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_x_m3651671365(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.Rect::get_y() extern "C" float Rect_get_y_m2529319960 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_YMin_1(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_y_m2529319960_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_y_m2529319960(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_y(System.Single) extern "C" void Rect_set_y_m2142941418 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_YMin_1(L_0); return; } } extern "C" void Rect_set_y_m2142941418_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_y_m2142941418(_thisAdjusted, ___value0, method); } // UnityEngine.Vector2 UnityEngine.Rect::get_position() extern "C" Vector2_t3854014517 Rect_get_position_m831243348 (Rect_t3345319094 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = __this->get_m_XMin_0(); float L_1 = __this->get_m_YMin_1(); Vector2_t3854014517 L_2; memset(&L_2, 0, sizeof(L_2)); Vector2__ctor_m2886412624((&L_2), L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0018; } IL_0018: { Vector2_t3854014517 L_3 = V_0; return L_3; } } extern "C" Vector2_t3854014517 Rect_get_position_m831243348_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_position_m831243348(_thisAdjusted, method); } // UnityEngine.Vector2 UnityEngine.Rect::get_center() extern "C" Vector2_t3854014517 Rect_get_center_m3493146972 (Rect_t3345319094 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = Rect_get_x_m1272655030(__this, /*hidden argument*/NULL); float L_1 = __this->get_m_Width_2(); float L_2 = Rect_get_y_m2529319960(__this, /*hidden argument*/NULL); float L_3 = __this->get_m_Height_3(); Vector2_t3854014517 L_4; memset(&L_4, 0, sizeof(L_4)); Vector2__ctor_m2886412624((&L_4), ((float)((float)L_0+(float)((float)((float)L_1/(float)(2.0f))))), ((float)((float)L_2+(float)((float)((float)L_3/(float)(2.0f))))), /*hidden argument*/NULL); V_0 = L_4; goto IL_0032; } IL_0032: { Vector2_t3854014517 L_5 = V_0; return L_5; } } extern "C" Vector2_t3854014517 Rect_get_center_m3493146972_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_center_m3493146972(_thisAdjusted, method); } // UnityEngine.Vector2 UnityEngine.Rect::get_min() extern "C" Vector2_t3854014517 Rect_get_min_m1865906224 (Rect_t3345319094 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = Rect_get_xMin_m244230138(__this, /*hidden argument*/NULL); float L_1 = Rect_get_yMin_m3454706255(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_2; memset(&L_2, 0, sizeof(L_2)); Vector2__ctor_m2886412624((&L_2), L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0018; } IL_0018: { Vector2_t3854014517 L_3 = V_0; return L_3; } } extern "C" Vector2_t3854014517 Rect_get_min_m1865906224_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_min_m1865906224(_thisAdjusted, method); } // UnityEngine.Vector2 UnityEngine.Rect::get_max() extern "C" Vector2_t3854014517 Rect_get_max_m533053384 (Rect_t3345319094 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = Rect_get_xMax_m4219133595(__this, /*hidden argument*/NULL); float L_1 = Rect_get_yMax_m2538035064(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_2; memset(&L_2, 0, sizeof(L_2)); Vector2__ctor_m2886412624((&L_2), L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0018; } IL_0018: { Vector2_t3854014517 L_3 = V_0; return L_3; } } extern "C" Vector2_t3854014517 Rect_get_max_m533053384_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_max_m533053384(_thisAdjusted, method); } // System.Single UnityEngine.Rect::get_width() extern "C" float Rect_get_width_m1618071060 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Width_2(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_width_m1618071060_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_width_m1618071060(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_width(System.Single) extern "C" void Rect_set_width_m370999829 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_Width_2(L_0); return; } } extern "C" void Rect_set_width_m370999829_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_width_m370999829(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.Rect::get_height() extern "C" float Rect_get_height_m2713477301 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Height_3(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_height_m2713477301_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_height_m2713477301(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_height(System.Single) extern "C" void Rect_set_height_m172432063 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_Height_3(L_0); return; } } extern "C" void Rect_set_height_m172432063_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_height_m172432063(_thisAdjusted, ___value0, method); } // UnityEngine.Vector2 UnityEngine.Rect::get_size() extern "C" Vector2_t3854014517 Rect_get_size_m3072131835 (Rect_t3345319094 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = __this->get_m_Width_2(); float L_1 = __this->get_m_Height_3(); Vector2_t3854014517 L_2; memset(&L_2, 0, sizeof(L_2)); Vector2__ctor_m2886412624((&L_2), L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0018; } IL_0018: { Vector2_t3854014517 L_3 = V_0; return L_3; } } extern "C" Vector2_t3854014517 Rect_get_size_m3072131835_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_size_m3072131835(_thisAdjusted, method); } // System.Single UnityEngine.Rect::get_xMin() extern "C" float Rect_get_xMin_m244230138 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_XMin_0(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_xMin_m244230138_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_xMin_m244230138(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_xMin(System.Single) extern "C" void Rect_set_xMin_m2854702664 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = Rect_get_xMax_m4219133595(__this, /*hidden argument*/NULL); V_0 = L_0; float L_1 = ___value0; __this->set_m_XMin_0(L_1); float L_2 = V_0; float L_3 = __this->get_m_XMin_0(); __this->set_m_Width_2(((float)((float)L_2-(float)L_3))); return; } } extern "C" void Rect_set_xMin_m2854702664_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_xMin_m2854702664(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.Rect::get_yMin() extern "C" float Rect_get_yMin_m3454706255 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_YMin_1(); V_0 = L_0; goto IL_000d; } IL_000d: { float L_1 = V_0; return L_1; } } extern "C" float Rect_get_yMin_m3454706255_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_yMin_m3454706255(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_yMin(System.Single) extern "C" void Rect_set_yMin_m4106440077 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = Rect_get_yMax_m2538035064(__this, /*hidden argument*/NULL); V_0 = L_0; float L_1 = ___value0; __this->set_m_YMin_1(L_1); float L_2 = V_0; float L_3 = __this->get_m_YMin_1(); __this->set_m_Height_3(((float)((float)L_2-(float)L_3))); return; } } extern "C" void Rect_set_yMin_m4106440077_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_yMin_m4106440077(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.Rect::get_xMax() extern "C" float Rect_get_xMax_m4219133595 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Width_2(); float L_1 = __this->get_m_XMin_0(); V_0 = ((float)((float)L_0+(float)L_1)); goto IL_0014; } IL_0014: { float L_2 = V_0; return L_2; } } extern "C" float Rect_get_xMax_m4219133595_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_xMax_m4219133595(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_xMax(System.Single) extern "C" void Rect_set_xMax_m4103720006 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; float L_1 = __this->get_m_XMin_0(); __this->set_m_Width_2(((float)((float)L_0-(float)L_1))); return; } } extern "C" void Rect_set_xMax_m4103720006_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_xMax_m4103720006(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.Rect::get_yMax() extern "C" float Rect_get_yMax_m2538035064 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; { float L_0 = __this->get_m_Height_3(); float L_1 = __this->get_m_YMin_1(); V_0 = ((float)((float)L_0+(float)L_1)); goto IL_0014; } IL_0014: { float L_2 = V_0; return L_2; } } extern "C" float Rect_get_yMax_m2538035064_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_get_yMax_m2538035064(_thisAdjusted, method); } // System.Void UnityEngine.Rect::set_yMax(System.Single) extern "C" void Rect_set_yMax_m29778259 (Rect_t3345319094 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; float L_1 = __this->get_m_YMin_1(); __this->set_m_Height_3(((float)((float)L_0-(float)L_1))); return; } } extern "C" void Rect_set_yMax_m29778259_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); Rect_set_yMax_m29778259(_thisAdjusted, ___value0, method); } // System.Boolean UnityEngine.Rect::Contains(UnityEngine.Vector2) extern "C" bool Rect_Contains_m644002242 (Rect_t3345319094 * __this, Vector2_t3854014517 ___point0, const RuntimeMethod* method) { bool V_0 = false; int32_t G_B5_0 = 0; { float L_0 = (&___point0)->get_x_0(); float L_1 = Rect_get_xMin_m244230138(__this, /*hidden argument*/NULL); if ((!(((float)L_0) >= ((float)L_1)))) { goto IL_0048; } } { float L_2 = (&___point0)->get_x_0(); float L_3 = Rect_get_xMax_m4219133595(__this, /*hidden argument*/NULL); if ((!(((float)L_2) < ((float)L_3)))) { goto IL_0048; } } { float L_4 = (&___point0)->get_y_1(); float L_5 = Rect_get_yMin_m3454706255(__this, /*hidden argument*/NULL); if ((!(((float)L_4) >= ((float)L_5)))) { goto IL_0048; } } { float L_6 = (&___point0)->get_y_1(); float L_7 = Rect_get_yMax_m2538035064(__this, /*hidden argument*/NULL); G_B5_0 = ((((float)L_6) < ((float)L_7))? 1 : 0); goto IL_0049; } IL_0048: { G_B5_0 = 0; } IL_0049: { V_0 = (bool)G_B5_0; goto IL_004f; } IL_004f: { bool L_8 = V_0; return L_8; } } extern "C" bool Rect_Contains_m644002242_AdjustorThunk (RuntimeObject * __this, Vector2_t3854014517 ___point0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_Contains_m644002242(_thisAdjusted, ___point0, method); } // System.Boolean UnityEngine.Rect::Contains(UnityEngine.Vector3) extern "C" bool Rect_Contains_m3823093228 (Rect_t3345319094 * __this, Vector3_t67624592 ___point0, const RuntimeMethod* method) { bool V_0 = false; int32_t G_B5_0 = 0; { float L_0 = (&___point0)->get_x_1(); float L_1 = Rect_get_xMin_m244230138(__this, /*hidden argument*/NULL); if ((!(((float)L_0) >= ((float)L_1)))) { goto IL_0048; } } { float L_2 = (&___point0)->get_x_1(); float L_3 = Rect_get_xMax_m4219133595(__this, /*hidden argument*/NULL); if ((!(((float)L_2) < ((float)L_3)))) { goto IL_0048; } } { float L_4 = (&___point0)->get_y_2(); float L_5 = Rect_get_yMin_m3454706255(__this, /*hidden argument*/NULL); if ((!(((float)L_4) >= ((float)L_5)))) { goto IL_0048; } } { float L_6 = (&___point0)->get_y_2(); float L_7 = Rect_get_yMax_m2538035064(__this, /*hidden argument*/NULL); G_B5_0 = ((((float)L_6) < ((float)L_7))? 1 : 0); goto IL_0049; } IL_0048: { G_B5_0 = 0; } IL_0049: { V_0 = (bool)G_B5_0; goto IL_004f; } IL_004f: { bool L_8 = V_0; return L_8; } } extern "C" bool Rect_Contains_m3823093228_AdjustorThunk (RuntimeObject * __this, Vector3_t67624592 ___point0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_Contains_m3823093228(_thisAdjusted, ___point0, method); } // UnityEngine.Rect UnityEngine.Rect::OrderMinMax(UnityEngine.Rect) extern "C" Rect_t3345319094 Rect_OrderMinMax_m858648141 (RuntimeObject * __this /* static, unused */, Rect_t3345319094 ___rect0, const RuntimeMethod* method) { float V_0 = 0.0f; float V_1 = 0.0f; Rect_t3345319094 V_2; memset(&V_2, 0, sizeof(V_2)); { float L_0 = Rect_get_xMin_m244230138((&___rect0), /*hidden argument*/NULL); float L_1 = Rect_get_xMax_m4219133595((&___rect0), /*hidden argument*/NULL); if ((!(((float)L_0) > ((float)L_1)))) { goto IL_0034; } } { float L_2 = Rect_get_xMin_m244230138((&___rect0), /*hidden argument*/NULL); V_0 = L_2; float L_3 = Rect_get_xMax_m4219133595((&___rect0), /*hidden argument*/NULL); Rect_set_xMin_m2854702664((&___rect0), L_3, /*hidden argument*/NULL); float L_4 = V_0; Rect_set_xMax_m4103720006((&___rect0), L_4, /*hidden argument*/NULL); } IL_0034: { float L_5 = Rect_get_yMin_m3454706255((&___rect0), /*hidden argument*/NULL); float L_6 = Rect_get_yMax_m2538035064((&___rect0), /*hidden argument*/NULL); if ((!(((float)L_5) > ((float)L_6)))) { goto IL_0067; } } { float L_7 = Rect_get_yMin_m3454706255((&___rect0), /*hidden argument*/NULL); V_1 = L_7; float L_8 = Rect_get_yMax_m2538035064((&___rect0), /*hidden argument*/NULL); Rect_set_yMin_m4106440077((&___rect0), L_8, /*hidden argument*/NULL); float L_9 = V_1; Rect_set_yMax_m29778259((&___rect0), L_9, /*hidden argument*/NULL); } IL_0067: { Rect_t3345319094 L_10 = ___rect0; V_2 = L_10; goto IL_006e; } IL_006e: { Rect_t3345319094 L_11 = V_2; return L_11; } } // System.Boolean UnityEngine.Rect::Overlaps(UnityEngine.Rect) extern "C" bool Rect_Overlaps_m598195426 (Rect_t3345319094 * __this, Rect_t3345319094 ___other0, const RuntimeMethod* method) { bool V_0 = false; int32_t G_B5_0 = 0; { float L_0 = Rect_get_xMax_m4219133595((&___other0), /*hidden argument*/NULL); float L_1 = Rect_get_xMin_m244230138(__this, /*hidden argument*/NULL); if ((!(((float)L_0) > ((float)L_1)))) { goto IL_0048; } } { float L_2 = Rect_get_xMin_m244230138((&___other0), /*hidden argument*/NULL); float L_3 = Rect_get_xMax_m4219133595(__this, /*hidden argument*/NULL); if ((!(((float)L_2) < ((float)L_3)))) { goto IL_0048; } } { float L_4 = Rect_get_yMax_m2538035064((&___other0), /*hidden argument*/NULL); float L_5 = Rect_get_yMin_m3454706255(__this, /*hidden argument*/NULL); if ((!(((float)L_4) > ((float)L_5)))) { goto IL_0048; } } { float L_6 = Rect_get_yMin_m3454706255((&___other0), /*hidden argument*/NULL); float L_7 = Rect_get_yMax_m2538035064(__this, /*hidden argument*/NULL); G_B5_0 = ((((float)L_6) < ((float)L_7))? 1 : 0); goto IL_0049; } IL_0048: { G_B5_0 = 0; } IL_0049: { V_0 = (bool)G_B5_0; goto IL_004f; } IL_004f: { bool L_8 = V_0; return L_8; } } extern "C" bool Rect_Overlaps_m598195426_AdjustorThunk (RuntimeObject * __this, Rect_t3345319094 ___other0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_Overlaps_m598195426(_thisAdjusted, ___other0, method); } // System.Boolean UnityEngine.Rect::Overlaps(UnityEngine.Rect,System.Boolean) extern "C" bool Rect_Overlaps_m3515144730 (Rect_t3345319094 * __this, Rect_t3345319094 ___other0, bool ___allowInverse1, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); bool V_1 = false; { V_0 = (*(Rect_t3345319094 *)__this); bool L_0 = ___allowInverse1; if (!L_0) { goto IL_001f; } } { Rect_t3345319094 L_1 = V_0; Rect_t3345319094 L_2 = Rect_OrderMinMax_m858648141(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); V_0 = L_2; Rect_t3345319094 L_3 = ___other0; Rect_t3345319094 L_4 = Rect_OrderMinMax_m858648141(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); ___other0 = L_4; } IL_001f: { Rect_t3345319094 L_5 = ___other0; bool L_6 = Rect_Overlaps_m598195426((&V_0), L_5, /*hidden argument*/NULL); V_1 = L_6; goto IL_002d; } IL_002d: { bool L_7 = V_1; return L_7; } } extern "C" bool Rect_Overlaps_m3515144730_AdjustorThunk (RuntimeObject * __this, Rect_t3345319094 ___other0, bool ___allowInverse1, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_Overlaps_m3515144730(_thisAdjusted, ___other0, ___allowInverse1, method); } // System.Boolean UnityEngine.Rect::op_Inequality(UnityEngine.Rect,UnityEngine.Rect) extern "C" bool Rect_op_Inequality_m2636656371 (RuntimeObject * __this /* static, unused */, Rect_t3345319094 ___lhs0, Rect_t3345319094 ___rhs1, const RuntimeMethod* method) { bool V_0 = false; { Rect_t3345319094 L_0 = ___lhs0; Rect_t3345319094 L_1 = ___rhs1; bool L_2 = Rect_op_Equality_m2493013221(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = (bool)((((int32_t)L_2) == ((int32_t)0))? 1 : 0); goto IL_0011; } IL_0011: { bool L_3 = V_0; return L_3; } } // System.Boolean UnityEngine.Rect::op_Equality(UnityEngine.Rect,UnityEngine.Rect) extern "C" bool Rect_op_Equality_m2493013221 (RuntimeObject * __this /* static, unused */, Rect_t3345319094 ___lhs0, Rect_t3345319094 ___rhs1, const RuntimeMethod* method) { bool V_0 = false; int32_t G_B5_0 = 0; { float L_0 = Rect_get_x_m1272655030((&___lhs0), /*hidden argument*/NULL); float L_1 = Rect_get_x_m1272655030((&___rhs1), /*hidden argument*/NULL); if ((!(((float)L_0) == ((float)L_1)))) { goto IL_004c; } } { float L_2 = Rect_get_y_m2529319960((&___lhs0), /*hidden argument*/NULL); float L_3 = Rect_get_y_m2529319960((&___rhs1), /*hidden argument*/NULL); if ((!(((float)L_2) == ((float)L_3)))) { goto IL_004c; } } { float L_4 = Rect_get_width_m1618071060((&___lhs0), /*hidden argument*/NULL); float L_5 = Rect_get_width_m1618071060((&___rhs1), /*hidden argument*/NULL); if ((!(((float)L_4) == ((float)L_5)))) { goto IL_004c; } } { float L_6 = Rect_get_height_m2713477301((&___lhs0), /*hidden argument*/NULL); float L_7 = Rect_get_height_m2713477301((&___rhs1), /*hidden argument*/NULL); G_B5_0 = ((((float)L_6) == ((float)L_7))? 1 : 0); goto IL_004d; } IL_004c: { G_B5_0 = 0; } IL_004d: { V_0 = (bool)G_B5_0; goto IL_0053; } IL_0053: { bool L_8 = V_0; return L_8; } } // System.Int32 UnityEngine.Rect::GetHashCode() extern "C" int32_t Rect_GetHashCode_m3046645869 (Rect_t3345319094 * __this, const RuntimeMethod* method) { float V_0 = 0.0f; float V_1 = 0.0f; float V_2 = 0.0f; float V_3 = 0.0f; int32_t V_4 = 0; { float L_0 = Rect_get_x_m1272655030(__this, /*hidden argument*/NULL); V_0 = L_0; int32_t L_1 = Single_GetHashCode_m177552305((&V_0), /*hidden argument*/NULL); float L_2 = Rect_get_width_m1618071060(__this, /*hidden argument*/NULL); V_1 = L_2; int32_t L_3 = Single_GetHashCode_m177552305((&V_1), /*hidden argument*/NULL); float L_4 = Rect_get_y_m2529319960(__this, /*hidden argument*/NULL); V_2 = L_4; int32_t L_5 = Single_GetHashCode_m177552305((&V_2), /*hidden argument*/NULL); float L_6 = Rect_get_height_m2713477301(__this, /*hidden argument*/NULL); V_3 = L_6; int32_t L_7 = Single_GetHashCode_m177552305((&V_3), /*hidden argument*/NULL); V_4 = ((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_1^(int32_t)((int32_t)((int32_t)L_3<<(int32_t)2))))^(int32_t)((int32_t)((int32_t)L_5>>(int32_t)2))))^(int32_t)((int32_t)((int32_t)L_7>>(int32_t)1)))); goto IL_0061; } IL_0061: { int32_t L_8 = V_4; return L_8; } } extern "C" int32_t Rect_GetHashCode_m3046645869_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_GetHashCode_m3046645869(_thisAdjusted, method); } // System.Boolean UnityEngine.Rect::Equals(System.Object) extern "C" bool Rect_Equals_m2118345215 (Rect_t3345319094 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Rect_Equals_m2118345215_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); float V_2 = 0.0f; float V_3 = 0.0f; float V_4 = 0.0f; float V_5 = 0.0f; int32_t G_B7_0 = 0; { RuntimeObject * L_0 = ___other0; if (((RuntimeObject *)IsInstSealed((RuntimeObject*)L_0, Rect_t3345319094_il2cpp_TypeInfo_var))) { goto IL_0013; } } { V_0 = (bool)0; goto IL_0088; } IL_0013: { RuntimeObject * L_1 = ___other0; V_1 = ((*(Rect_t3345319094 *)((Rect_t3345319094 *)UnBox(L_1, Rect_t3345319094_il2cpp_TypeInfo_var)))); float L_2 = Rect_get_x_m1272655030(__this, /*hidden argument*/NULL); V_2 = L_2; float L_3 = Rect_get_x_m1272655030((&V_1), /*hidden argument*/NULL); bool L_4 = Single_Equals_m767089390((&V_2), L_3, /*hidden argument*/NULL); if (!L_4) { goto IL_0081; } } { float L_5 = Rect_get_y_m2529319960(__this, /*hidden argument*/NULL); V_3 = L_5; float L_6 = Rect_get_y_m2529319960((&V_1), /*hidden argument*/NULL); bool L_7 = Single_Equals_m767089390((&V_3), L_6, /*hidden argument*/NULL); if (!L_7) { goto IL_0081; } } { float L_8 = Rect_get_width_m1618071060(__this, /*hidden argument*/NULL); V_4 = L_8; float L_9 = Rect_get_width_m1618071060((&V_1), /*hidden argument*/NULL); bool L_10 = Single_Equals_m767089390((&V_4), L_9, /*hidden argument*/NULL); if (!L_10) { goto IL_0081; } } { float L_11 = Rect_get_height_m2713477301(__this, /*hidden argument*/NULL); V_5 = L_11; float L_12 = Rect_get_height_m2713477301((&V_1), /*hidden argument*/NULL); bool L_13 = Single_Equals_m767089390((&V_5), L_12, /*hidden argument*/NULL); G_B7_0 = ((int32_t)(L_13)); goto IL_0082; } IL_0081: { G_B7_0 = 0; } IL_0082: { V_0 = (bool)G_B7_0; goto IL_0088; } IL_0088: { bool L_14 = V_0; return L_14; } } extern "C" bool Rect_Equals_m2118345215_AdjustorThunk (RuntimeObject * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_Equals_m2118345215(_thisAdjusted, ___other0, method); } // System.String UnityEngine.Rect::ToString() extern "C" String_t* Rect_ToString_m3090827388 (Rect_t3345319094 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Rect_ToString_m3090827388_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)4)); float L_1 = Rect_get_x_m1272655030(__this, /*hidden argument*/NULL); float L_2 = L_1; RuntimeObject * L_3 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_2); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_3); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_3); ObjectU5BU5D_t3885370135* L_4 = L_0; float L_5 = Rect_get_y_m2529319960(__this, /*hidden argument*/NULL); float L_6 = L_5; RuntimeObject * L_7 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_6); NullCheck(L_4); ArrayElementTypeCheck (L_4, L_7); (L_4)->SetAt(static_cast(1), (RuntimeObject *)L_7); ObjectU5BU5D_t3885370135* L_8 = L_4; float L_9 = Rect_get_width_m1618071060(__this, /*hidden argument*/NULL); float L_10 = L_9; RuntimeObject * L_11 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_10); NullCheck(L_8); ArrayElementTypeCheck (L_8, L_11); (L_8)->SetAt(static_cast(2), (RuntimeObject *)L_11); ObjectU5BU5D_t3885370135* L_12 = L_8; float L_13 = Rect_get_height_m2713477301(__this, /*hidden argument*/NULL); float L_14 = L_13; RuntimeObject * L_15 = Box(Single_t3320337292_il2cpp_TypeInfo_var, &L_14); NullCheck(L_12); ArrayElementTypeCheck (L_12, L_15); (L_12)->SetAt(static_cast(3), (RuntimeObject *)L_15); String_t* L_16 = UnityString_Format_m1454782387(NULL /*static, unused*/, _stringLiteral2888673510, L_12, /*hidden argument*/NULL); V_0 = L_16; goto IL_004f; } IL_004f: { String_t* L_17 = V_0; return L_17; } } extern "C" String_t* Rect_ToString_m3090827388_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Rect_t3345319094 * _thisAdjusted = reinterpret_cast(__this + 1); return Rect_ToString_m3090827388(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.RectOffset extern "C" void RectOffset_t3582970358_marshal_pinvoke(const RectOffset_t3582970358& unmarshaled, RectOffset_t3582970358_marshaled_pinvoke& marshaled) { marshaled.___m_Ptr_0 = reinterpret_cast((unmarshaled.get_m_Ptr_0()).get_m_value_0()); if (unmarshaled.get_m_SourceStyle_1() != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(unmarshaled.get_m_SourceStyle_1())) { il2cpp_hresult_t hr = ((Il2CppComObject *)unmarshaled.get_m_SourceStyle_1())->identity->QueryInterface(Il2CppIUnknown::IID, reinterpret_cast(&marshaled.___m_SourceStyle_1)); il2cpp_codegen_com_raise_exception_if_failed(hr, false); } else { marshaled.___m_SourceStyle_1 = il2cpp_codegen_com_get_or_create_ccw(unmarshaled.get_m_SourceStyle_1()); } } else { marshaled.___m_SourceStyle_1 = NULL; } } extern "C" void RectOffset_t3582970358_marshal_pinvoke_back(const RectOffset_t3582970358_marshaled_pinvoke& marshaled, RectOffset_t3582970358& unmarshaled) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectOffset_t3582970358_pinvoke_FromNativeMethodDefinition_MetadataUsageId); s_Il2CppMethodInitialized = true; } IntPtr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); IntPtr_t unmarshaled_m_Ptr_temp_0_temp; unmarshaled_m_Ptr_temp_0_temp.set_m_value_0(reinterpret_cast((intptr_t)(marshaled.___m_Ptr_0))); unmarshaled_m_Ptr_temp_0 = unmarshaled_m_Ptr_temp_0_temp; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); if (marshaled.___m_SourceStyle_1 != NULL) { unmarshaled.set_m_SourceStyle_1(il2cpp_codegen_com_get_or_create_rcw_from_iunknown(marshaled.___m_SourceStyle_1, Il2CppComObject_il2cpp_TypeInfo_var)); } else { unmarshaled.set_m_SourceStyle_1(NULL); } } // Conversion method for clean up from marshalling of: UnityEngine.RectOffset extern "C" void RectOffset_t3582970358_marshal_pinvoke_cleanup(RectOffset_t3582970358_marshaled_pinvoke& marshaled) { if (marshaled.___m_SourceStyle_1 != NULL) { (marshaled.___m_SourceStyle_1)->Release(); marshaled.___m_SourceStyle_1 = NULL; } } // Conversion methods for marshalling of: UnityEngine.RectOffset extern "C" void RectOffset_t3582970358_marshal_com(const RectOffset_t3582970358& unmarshaled, RectOffset_t3582970358_marshaled_com& marshaled) { marshaled.___m_Ptr_0 = reinterpret_cast((unmarshaled.get_m_Ptr_0()).get_m_value_0()); if (unmarshaled.get_m_SourceStyle_1() != NULL) { if (il2cpp_codegen_is_import_or_windows_runtime(unmarshaled.get_m_SourceStyle_1())) { il2cpp_hresult_t hr = ((Il2CppComObject *)unmarshaled.get_m_SourceStyle_1())->identity->QueryInterface(Il2CppIUnknown::IID, reinterpret_cast(&marshaled.___m_SourceStyle_1)); il2cpp_codegen_com_raise_exception_if_failed(hr, true); } else { marshaled.___m_SourceStyle_1 = il2cpp_codegen_com_get_or_create_ccw(unmarshaled.get_m_SourceStyle_1()); } } else { marshaled.___m_SourceStyle_1 = NULL; } } extern "C" void RectOffset_t3582970358_marshal_com_back(const RectOffset_t3582970358_marshaled_com& marshaled, RectOffset_t3582970358& unmarshaled) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectOffset_t3582970358_com_FromNativeMethodDefinition_MetadataUsageId); s_Il2CppMethodInitialized = true; } IntPtr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); IntPtr_t unmarshaled_m_Ptr_temp_0_temp; unmarshaled_m_Ptr_temp_0_temp.set_m_value_0(reinterpret_cast((intptr_t)(marshaled.___m_Ptr_0))); unmarshaled_m_Ptr_temp_0 = unmarshaled_m_Ptr_temp_0_temp; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); if (marshaled.___m_SourceStyle_1 != NULL) { unmarshaled.set_m_SourceStyle_1(il2cpp_codegen_com_get_or_create_rcw_from_iunknown(marshaled.___m_SourceStyle_1, Il2CppComObject_il2cpp_TypeInfo_var)); } else { unmarshaled.set_m_SourceStyle_1(NULL); } } // Conversion method for clean up from marshalling of: UnityEngine.RectOffset extern "C" void RectOffset_t3582970358_marshal_com_cleanup(RectOffset_t3582970358_marshaled_com& marshaled) { if (marshaled.___m_SourceStyle_1 != NULL) { (marshaled.___m_SourceStyle_1)->Release(); marshaled.___m_SourceStyle_1 = NULL; } } // System.Void UnityEngine.RectOffset::.ctor() extern "C" void RectOffset__ctor_m2739168565 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); RectOffset_Init_m1864310113(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectOffset::.ctor(System.Object,System.IntPtr) extern "C" void RectOffset__ctor_m2003134233 (RectOffset_t3582970358 * __this, RuntimeObject * ___sourceStyle0, IntPtr_t ___source1, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); RuntimeObject * L_0 = ___sourceStyle0; __this->set_m_SourceStyle_1(L_0); IntPtr_t L_1 = ___source1; __this->set_m_Ptr_0(L_1); return; } } // System.Void UnityEngine.RectOffset::Init() extern "C" void RectOffset_Init_m1864310113 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef void (*RectOffset_Init_m1864310113_ftn) (RectOffset_t3582970358 *); static RectOffset_Init_m1864310113_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_Init_m1864310113_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::Init()"); _il2cpp_icall_func(__this); } // System.Void UnityEngine.RectOffset::Cleanup() extern "C" void RectOffset_Cleanup_m1072908984 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef void (*RectOffset_Cleanup_m1072908984_ftn) (RectOffset_t3582970358 *); static RectOffset_Cleanup_m1072908984_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_Cleanup_m1072908984_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::Cleanup()"); _il2cpp_icall_func(__this); } // System.Int32 UnityEngine.RectOffset::get_left() extern "C" int32_t RectOffset_get_left_m1369329921 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_left_m1369329921_ftn) (RectOffset_t3582970358 *); static RectOffset_get_left_m1369329921_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_left_m1369329921_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_left()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.RectOffset::set_left(System.Int32) extern "C" void RectOffset_set_left_m3512058938 (RectOffset_t3582970358 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*RectOffset_set_left_m3512058938_ftn) (RectOffset_t3582970358 *, int32_t); static RectOffset_set_left_m3512058938_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_set_left_m3512058938_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::set_left(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.RectOffset::get_right() extern "C" int32_t RectOffset_get_right_m2365972138 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_right_m2365972138_ftn) (RectOffset_t3582970358 *); static RectOffset_get_right_m2365972138_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_right_m2365972138_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_right()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.RectOffset::set_right(System.Int32) extern "C" void RectOffset_set_right_m3642623872 (RectOffset_t3582970358 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*RectOffset_set_right_m3642623872_ftn) (RectOffset_t3582970358 *, int32_t); static RectOffset_set_right_m3642623872_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_set_right_m3642623872_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::set_right(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.RectOffset::get_top() extern "C" int32_t RectOffset_get_top_m3242062285 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_top_m3242062285_ftn) (RectOffset_t3582970358 *); static RectOffset_get_top_m3242062285_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_top_m3242062285_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_top()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.RectOffset::set_top(System.Int32) extern "C" void RectOffset_set_top_m1888076224 (RectOffset_t3582970358 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*RectOffset_set_top_m1888076224_ftn) (RectOffset_t3582970358 *, int32_t); static RectOffset_set_top_m1888076224_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_set_top_m1888076224_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::set_top(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.RectOffset::get_bottom() extern "C" int32_t RectOffset_get_bottom_m3922972562 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_bottom_m3922972562_ftn) (RectOffset_t3582970358 *); static RectOffset_get_bottom_m3922972562_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_bottom_m3922972562_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_bottom()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.RectOffset::set_bottom(System.Int32) extern "C" void RectOffset_set_bottom_m2795127723 (RectOffset_t3582970358 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*RectOffset_set_bottom_m2795127723_ftn) (RectOffset_t3582970358 *, int32_t); static RectOffset_set_bottom_m2795127723_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_set_bottom_m2795127723_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::set_bottom(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.RectOffset::get_horizontal() extern "C" int32_t RectOffset_get_horizontal_m2966247018 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_horizontal_m2966247018_ftn) (RectOffset_t3582970358 *); static RectOffset_get_horizontal_m2966247018_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_horizontal_m2966247018_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_horizontal()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Int32 UnityEngine.RectOffset::get_vertical() extern "C" int32_t RectOffset_get_vertical_m2563864720 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { typedef int32_t (*RectOffset_get_vertical_m2563864720_ftn) (RectOffset_t3582970358 *); static RectOffset_get_vertical_m2563864720_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectOffset_get_vertical_m2563864720_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectOffset::get_vertical()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.RectOffset::Finalize() extern "C" void RectOffset_Finalize_m751896286 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { Exception_t3285241636 * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t3285241636 * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = 0; NO_UNUSED_WARNING (__leave_target); { } IL_0001: try { // begin try (depth: 1) { RuntimeObject * L_0 = __this->get_m_SourceStyle_1(); if (L_0) { goto IL_0012; } } IL_000c: { RectOffset_Cleanup_m1072908984(__this, /*hidden argument*/NULL); } IL_0012: { IL2CPP_LEAVE(0x1E, FINALLY_0017); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t3285241636 *)e.ex; goto FINALLY_0017; } FINALLY_0017: { // begin finally (depth: 1) Object_Finalize_m3696538117(__this, /*hidden argument*/NULL); IL2CPP_END_FINALLY(23) } // end finally (depth: 1) IL2CPP_CLEANUP(23) { IL2CPP_JUMP_TBL(0x1E, IL_001e) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t3285241636 *) } IL_001e: { return; } } // System.String UnityEngine.RectOffset::ToString() extern "C" String_t* RectOffset_ToString_m1410907684 (RectOffset_t3582970358 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectOffset_ToString_m1410907684_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)4)); int32_t L_1 = RectOffset_get_left_m1369329921(__this, /*hidden argument*/NULL); int32_t L_2 = L_1; RuntimeObject * L_3 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_2); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_3); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_3); ObjectU5BU5D_t3885370135* L_4 = L_0; int32_t L_5 = RectOffset_get_right_m2365972138(__this, /*hidden argument*/NULL); int32_t L_6 = L_5; RuntimeObject * L_7 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_6); NullCheck(L_4); ArrayElementTypeCheck (L_4, L_7); (L_4)->SetAt(static_cast(1), (RuntimeObject *)L_7); ObjectU5BU5D_t3885370135* L_8 = L_4; int32_t L_9 = RectOffset_get_top_m3242062285(__this, /*hidden argument*/NULL); int32_t L_10 = L_9; RuntimeObject * L_11 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_10); NullCheck(L_8); ArrayElementTypeCheck (L_8, L_11); (L_8)->SetAt(static_cast(2), (RuntimeObject *)L_11); ObjectU5BU5D_t3885370135* L_12 = L_8; int32_t L_13 = RectOffset_get_bottom_m3922972562(__this, /*hidden argument*/NULL); int32_t L_14 = L_13; RuntimeObject * L_15 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_14); NullCheck(L_12); ArrayElementTypeCheck (L_12, L_15); (L_12)->SetAt(static_cast(3), (RuntimeObject *)L_15); String_t* L_16 = UnityString_Format_m1454782387(NULL /*static, unused*/, _stringLiteral389894490, L_12, /*hidden argument*/NULL); V_0 = L_16; goto IL_004f; } IL_004f: { String_t* L_17 = V_0; return L_17; } } // UnityEngine.Rect UnityEngine.RectTransform::get_rect() extern "C" Rect_t3345319094 RectTransform_get_rect_m2145828853 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_rect_m2728143655(__this, (&V_0), /*hidden argument*/NULL); Rect_t3345319094 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Rect_t3345319094 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_rect(UnityEngine.Rect&) extern "C" void RectTransform_INTERNAL_get_rect_m2728143655 (RectTransform_t3700156813 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_rect_m2728143655_ftn) (RectTransform_t3700156813 *, Rect_t3345319094 *); static RectTransform_INTERNAL_get_rect_m2728143655_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_rect_m2728143655_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_rect(UnityEngine.Rect&)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchorMin() extern "C" Vector2_t3854014517 RectTransform_get_anchorMin_m3875085598 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_anchorMin_m42883384(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::set_anchorMin(UnityEngine.Vector2) extern "C" void RectTransform_set_anchorMin_m813062776 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { { RectTransform_INTERNAL_set_anchorMin_m1456566770(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_anchorMin(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchorMin_m42883384 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_anchorMin_m42883384_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_get_anchorMin_m42883384_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_anchorMin_m42883384_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_anchorMin(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::INTERNAL_set_anchorMin(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchorMin_m1456566770 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_set_anchorMin_m1456566770_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_set_anchorMin_m1456566770_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_set_anchorMin_m1456566770_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_set_anchorMin(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchorMax() extern "C" Vector2_t3854014517 RectTransform_get_anchorMax_m211673889 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_anchorMax_m3234636927(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::set_anchorMax(UnityEngine.Vector2) extern "C" void RectTransform_set_anchorMax_m1270568626 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { { RectTransform_INTERNAL_set_anchorMax_m1391116051(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_anchorMax(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchorMax_m3234636927 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_anchorMax_m3234636927_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_get_anchorMax_m3234636927_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_anchorMax_m3234636927_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_anchorMax(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::INTERNAL_set_anchorMax(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchorMax_m1391116051 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_set_anchorMax_m1391116051_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_set_anchorMax_m1391116051_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_set_anchorMax_m1391116051_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_set_anchorMax(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Vector2 UnityEngine.RectTransform::get_anchoredPosition() extern "C" Vector2_t3854014517 RectTransform_get_anchoredPosition_m3838889794 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_anchoredPosition_m2955393727(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::set_anchoredPosition(UnityEngine.Vector2) extern "C" void RectTransform_set_anchoredPosition_m754568721 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { { RectTransform_INTERNAL_set_anchoredPosition_m3010510872(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_anchoredPosition(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_anchoredPosition_m2955393727 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_anchoredPosition_m2955393727_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_get_anchoredPosition_m2955393727_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_anchoredPosition_m2955393727_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_anchoredPosition(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::INTERNAL_set_anchoredPosition(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_anchoredPosition_m3010510872 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_set_anchoredPosition_m3010510872_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_set_anchoredPosition_m3010510872_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_set_anchoredPosition_m3010510872_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_set_anchoredPosition(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Vector2 UnityEngine.RectTransform::get_sizeDelta() extern "C" Vector2_t3854014517 RectTransform_get_sizeDelta_m2732713248 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_sizeDelta_m1660093871(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::set_sizeDelta(UnityEngine.Vector2) extern "C" void RectTransform_set_sizeDelta_m2388347220 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { { RectTransform_INTERNAL_set_sizeDelta_m2649046399(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_sizeDelta(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_sizeDelta_m1660093871 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_sizeDelta_m1660093871_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_get_sizeDelta_m1660093871_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_sizeDelta_m1660093871_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_sizeDelta(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::INTERNAL_set_sizeDelta(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_sizeDelta_m2649046399 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_set_sizeDelta_m2649046399_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_set_sizeDelta_m2649046399_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_set_sizeDelta_m2649046399_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_set_sizeDelta(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Vector2 UnityEngine.RectTransform::get_pivot() extern "C" Vector2_t3854014517 RectTransform_get_pivot_m186250636 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_INTERNAL_get_pivot_m3267718409(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.RectTransform::set_pivot(UnityEngine.Vector2) extern "C" void RectTransform_set_pivot_m1268266743 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { { RectTransform_INTERNAL_set_pivot_m4113449629(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::INTERNAL_get_pivot(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_get_pivot_m3267718409 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_get_pivot_m3267718409_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_get_pivot_m3267718409_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_get_pivot_m3267718409_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_get_pivot(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::INTERNAL_set_pivot(UnityEngine.Vector2&) extern "C" void RectTransform_INTERNAL_set_pivot_m4113449629 (RectTransform_t3700156813 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*RectTransform_INTERNAL_set_pivot_m4113449629_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *); static RectTransform_INTERNAL_set_pivot_m4113449629_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransform_INTERNAL_set_pivot_m4113449629_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransform::INTERNAL_set_pivot(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.RectTransform::add_reapplyDrivenProperties(UnityEngine.RectTransform/ReapplyDrivenProperties) extern "C" void RectTransform_add_reapplyDrivenProperties_m1640178877 (RuntimeObject * __this /* static, unused */, ReapplyDrivenProperties_t2885473943 * ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_add_reapplyDrivenProperties_m1640178877_MetadataUsageId); s_Il2CppMethodInitialized = true; } ReapplyDrivenProperties_t2885473943 * V_0 = NULL; ReapplyDrivenProperties_t2885473943 * V_1 = NULL; { ReapplyDrivenProperties_t2885473943 * L_0 = ((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_reapplyDrivenProperties_2(); V_0 = L_0; } IL_0006: { ReapplyDrivenProperties_t2885473943 * L_1 = V_0; V_1 = L_1; ReapplyDrivenProperties_t2885473943 * L_2 = V_1; ReapplyDrivenProperties_t2885473943 * L_3 = ___value0; Delegate_t2669736448 * L_4 = Delegate_Combine_m322163940(NULL /*static, unused*/, L_2, L_3, /*hidden argument*/NULL); ReapplyDrivenProperties_t2885473943 * L_5 = V_0; ReapplyDrivenProperties_t2885473943 * L_6 = InterlockedCompareExchangeImpl((((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_address_of_reapplyDrivenProperties_2()), ((ReapplyDrivenProperties_t2885473943 *)CastclassSealed((RuntimeObject*)L_4, ReapplyDrivenProperties_t2885473943_il2cpp_TypeInfo_var)), L_5); V_0 = L_6; ReapplyDrivenProperties_t2885473943 * L_7 = V_0; ReapplyDrivenProperties_t2885473943 * L_8 = V_1; if ((!(((RuntimeObject*)(ReapplyDrivenProperties_t2885473943 *)L_7) == ((RuntimeObject*)(ReapplyDrivenProperties_t2885473943 *)L_8)))) { goto IL_0006; } } { return; } } // System.Void UnityEngine.RectTransform::remove_reapplyDrivenProperties(UnityEngine.RectTransform/ReapplyDrivenProperties) extern "C" void RectTransform_remove_reapplyDrivenProperties_m2994591780 (RuntimeObject * __this /* static, unused */, ReapplyDrivenProperties_t2885473943 * ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_remove_reapplyDrivenProperties_m2994591780_MetadataUsageId); s_Il2CppMethodInitialized = true; } ReapplyDrivenProperties_t2885473943 * V_0 = NULL; ReapplyDrivenProperties_t2885473943 * V_1 = NULL; { ReapplyDrivenProperties_t2885473943 * L_0 = ((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_reapplyDrivenProperties_2(); V_0 = L_0; } IL_0006: { ReapplyDrivenProperties_t2885473943 * L_1 = V_0; V_1 = L_1; ReapplyDrivenProperties_t2885473943 * L_2 = V_1; ReapplyDrivenProperties_t2885473943 * L_3 = ___value0; Delegate_t2669736448 * L_4 = Delegate_Remove_m537953058(NULL /*static, unused*/, L_2, L_3, /*hidden argument*/NULL); ReapplyDrivenProperties_t2885473943 * L_5 = V_0; ReapplyDrivenProperties_t2885473943 * L_6 = InterlockedCompareExchangeImpl((((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_address_of_reapplyDrivenProperties_2()), ((ReapplyDrivenProperties_t2885473943 *)CastclassSealed((RuntimeObject*)L_4, ReapplyDrivenProperties_t2885473943_il2cpp_TypeInfo_var)), L_5); V_0 = L_6; ReapplyDrivenProperties_t2885473943 * L_7 = V_0; ReapplyDrivenProperties_t2885473943 * L_8 = V_1; if ((!(((RuntimeObject*)(ReapplyDrivenProperties_t2885473943 *)L_7) == ((RuntimeObject*)(ReapplyDrivenProperties_t2885473943 *)L_8)))) { goto IL_0006; } } { return; } } // System.Void UnityEngine.RectTransform::SendReapplyDrivenProperties(UnityEngine.RectTransform) extern "C" void RectTransform_SendReapplyDrivenProperties_m815986292 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___driven0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_SendReapplyDrivenProperties_m815986292_MetadataUsageId); s_Il2CppMethodInitialized = true; } { ReapplyDrivenProperties_t2885473943 * L_0 = ((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_reapplyDrivenProperties_2(); if (!L_0) { goto IL_0016; } } { ReapplyDrivenProperties_t2885473943 * L_1 = ((RectTransform_t3700156813_StaticFields*)il2cpp_codegen_static_fields_for(RectTransform_t3700156813_il2cpp_TypeInfo_var))->get_reapplyDrivenProperties_2(); RectTransform_t3700156813 * L_2 = ___driven0; NullCheck(L_1); ReapplyDrivenProperties_Invoke_m3653398493(L_1, L_2, /*hidden argument*/NULL); } IL_0016: { return; } } // System.Void UnityEngine.RectTransform::GetLocalCorners(UnityEngine.Vector3[]) extern "C" void RectTransform_GetLocalCorners_m702431553 (RectTransform_t3700156813 * __this, Vector3U5BU5D_t2251457841* ___fourCornersArray0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_GetLocalCorners_m702431553_MetadataUsageId); s_Il2CppMethodInitialized = true; } Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); float V_1 = 0.0f; float V_2 = 0.0f; float V_3 = 0.0f; float V_4 = 0.0f; { Vector3U5BU5D_t2251457841* L_0 = ___fourCornersArray0; if (!L_0) { goto IL_0010; } } { Vector3U5BU5D_t2251457841* L_1 = ___fourCornersArray0; NullCheck(L_1); if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length))))) >= ((int32_t)4))) { goto IL_0020; } } IL_0010: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogError_m3009049438(NULL /*static, unused*/, _stringLiteral1042552891, /*hidden argument*/NULL); goto IL_00aa; } IL_0020: { Rect_t3345319094 L_2 = RectTransform_get_rect_m2145828853(__this, /*hidden argument*/NULL); V_0 = L_2; float L_3 = Rect_get_x_m1272655030((&V_0), /*hidden argument*/NULL); V_1 = L_3; float L_4 = Rect_get_y_m2529319960((&V_0), /*hidden argument*/NULL); V_2 = L_4; float L_5 = Rect_get_xMax_m4219133595((&V_0), /*hidden argument*/NULL); V_3 = L_5; float L_6 = Rect_get_yMax_m2538035064((&V_0), /*hidden argument*/NULL); V_4 = L_6; Vector3U5BU5D_t2251457841* L_7 = ___fourCornersArray0; NullCheck(L_7); float L_8 = V_1; float L_9 = V_2; Vector3_t67624592 L_10; memset(&L_10, 0, sizeof(L_10)); Vector3__ctor_m649967503((&L_10), L_8, L_9, (0.0f), /*hidden argument*/NULL); *(Vector3_t67624592 *)((L_7)->GetAddressAt(static_cast(0))) = L_10; Vector3U5BU5D_t2251457841* L_11 = ___fourCornersArray0; NullCheck(L_11); float L_12 = V_1; float L_13 = V_4; Vector3_t67624592 L_14; memset(&L_14, 0, sizeof(L_14)); Vector3__ctor_m649967503((&L_14), L_12, L_13, (0.0f), /*hidden argument*/NULL); *(Vector3_t67624592 *)((L_11)->GetAddressAt(static_cast(1))) = L_14; Vector3U5BU5D_t2251457841* L_15 = ___fourCornersArray0; NullCheck(L_15); float L_16 = V_3; float L_17 = V_4; Vector3_t67624592 L_18; memset(&L_18, 0, sizeof(L_18)); Vector3__ctor_m649967503((&L_18), L_16, L_17, (0.0f), /*hidden argument*/NULL); *(Vector3_t67624592 *)((L_15)->GetAddressAt(static_cast(2))) = L_18; Vector3U5BU5D_t2251457841* L_19 = ___fourCornersArray0; NullCheck(L_19); float L_20 = V_3; float L_21 = V_2; Vector3_t67624592 L_22; memset(&L_22, 0, sizeof(L_22)); Vector3__ctor_m649967503((&L_22), L_20, L_21, (0.0f), /*hidden argument*/NULL); *(Vector3_t67624592 *)((L_19)->GetAddressAt(static_cast(3))) = L_22; } IL_00aa: { return; } } // System.Void UnityEngine.RectTransform::GetWorldCorners(UnityEngine.Vector3[]) extern "C" void RectTransform_GetWorldCorners_m1981831296 (RectTransform_t3700156813 * __this, Vector3U5BU5D_t2251457841* ___fourCornersArray0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_GetWorldCorners_m1981831296_MetadataUsageId); s_Il2CppMethodInitialized = true; } Transform_t2468616896 * V_0 = NULL; int32_t V_1 = 0; { Vector3U5BU5D_t2251457841* L_0 = ___fourCornersArray0; if (!L_0) { goto IL_0010; } } { Vector3U5BU5D_t2251457841* L_1 = ___fourCornersArray0; NullCheck(L_1); if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length))))) >= ((int32_t)4))) { goto IL_0020; } } IL_0010: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogError_m3009049438(NULL /*static, unused*/, _stringLiteral2700877699, /*hidden argument*/NULL); goto IL_005e; } IL_0020: { Vector3U5BU5D_t2251457841* L_2 = ___fourCornersArray0; RectTransform_GetLocalCorners_m702431553(__this, L_2, /*hidden argument*/NULL); Transform_t2468616896 * L_3 = Component_get_transform_m987883457(__this, /*hidden argument*/NULL); V_0 = L_3; V_1 = 0; goto IL_0057; } IL_0035: { Vector3U5BU5D_t2251457841* L_4 = ___fourCornersArray0; int32_t L_5 = V_1; NullCheck(L_4); Transform_t2468616896 * L_6 = V_0; Vector3U5BU5D_t2251457841* L_7 = ___fourCornersArray0; int32_t L_8 = V_1; NullCheck(L_7); NullCheck(L_6); Vector3_t67624592 L_9 = Transform_TransformPoint_m3154744607(L_6, (*(Vector3_t67624592 *)((L_7)->GetAddressAt(static_cast(L_8)))), /*hidden argument*/NULL); *(Vector3_t67624592 *)((L_4)->GetAddressAt(static_cast(L_5))) = L_9; int32_t L_10 = V_1; V_1 = ((int32_t)((int32_t)L_10+(int32_t)1)); } IL_0057: { int32_t L_11 = V_1; if ((((int32_t)L_11) < ((int32_t)4))) { goto IL_0035; } } IL_005e: { return; } } // System.Void UnityEngine.RectTransform::set_offsetMin(UnityEngine.Vector2) extern "C" void RectTransform_set_offsetMin_m1964412094 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_set_offsetMin_m1964412094_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector2_t3854014517 L_0 = ___value0; Vector2_t3854014517 L_1 = RectTransform_get_anchoredPosition_m3838889794(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_2 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_3 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_4 = Vector2_Scale_m3102216472(NULL /*static, unused*/, L_2, L_3, /*hidden argument*/NULL); Vector2_t3854014517 L_5 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_1, L_4, /*hidden argument*/NULL); Vector2_t3854014517 L_6 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_0, L_5, /*hidden argument*/NULL); V_0 = L_6; Vector2_t3854014517 L_7 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_8 = V_0; Vector2_t3854014517 L_9 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_7, L_8, /*hidden argument*/NULL); RectTransform_set_sizeDelta_m2388347220(__this, L_9, /*hidden argument*/NULL); Vector2_t3854014517 L_10 = RectTransform_get_anchoredPosition_m3838889794(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_11 = V_0; Vector2_t3854014517 L_12 = Vector2_get_one_m3462198535(NULL /*static, unused*/, /*hidden argument*/NULL); Vector2_t3854014517 L_13 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_14 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_12, L_13, /*hidden argument*/NULL); Vector2_t3854014517 L_15 = Vector2_Scale_m3102216472(NULL /*static, unused*/, L_11, L_14, /*hidden argument*/NULL); Vector2_t3854014517 L_16 = Vector2_op_Addition_m1125554698(NULL /*static, unused*/, L_10, L_15, /*hidden argument*/NULL); RectTransform_set_anchoredPosition_m754568721(__this, L_16, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::set_offsetMax(UnityEngine.Vector2) extern "C" void RectTransform_set_offsetMax_m3548632212 (RectTransform_t3700156813 * __this, Vector2_t3854014517 ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_set_offsetMax_m3548632212_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { Vector2_t3854014517 L_0 = ___value0; Vector2_t3854014517 L_1 = RectTransform_get_anchoredPosition_m3838889794(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_2 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_3 = Vector2_get_one_m3462198535(NULL /*static, unused*/, /*hidden argument*/NULL); Vector2_t3854014517 L_4 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_5 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); Vector2_t3854014517 L_6 = Vector2_Scale_m3102216472(NULL /*static, unused*/, L_2, L_5, /*hidden argument*/NULL); Vector2_t3854014517 L_7 = Vector2_op_Addition_m1125554698(NULL /*static, unused*/, L_1, L_6, /*hidden argument*/NULL); Vector2_t3854014517 L_8 = Vector2_op_Subtraction_m2940341944(NULL /*static, unused*/, L_0, L_7, /*hidden argument*/NULL); V_0 = L_8; Vector2_t3854014517 L_9 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_10 = V_0; Vector2_t3854014517 L_11 = Vector2_op_Addition_m1125554698(NULL /*static, unused*/, L_9, L_10, /*hidden argument*/NULL); RectTransform_set_sizeDelta_m2388347220(__this, L_11, /*hidden argument*/NULL); Vector2_t3854014517 L_12 = RectTransform_get_anchoredPosition_m3838889794(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_13 = V_0; Vector2_t3854014517 L_14 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); Vector2_t3854014517 L_15 = Vector2_Scale_m3102216472(NULL /*static, unused*/, L_13, L_14, /*hidden argument*/NULL); Vector2_t3854014517 L_16 = Vector2_op_Addition_m1125554698(NULL /*static, unused*/, L_12, L_15, /*hidden argument*/NULL); RectTransform_set_anchoredPosition_m754568721(__this, L_16, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::SetInsetAndSizeFromParentEdge(UnityEngine.RectTransform/Edge,System.Single,System.Single) extern "C" void RectTransform_SetInsetAndSizeFromParentEdge_m2723032112 (RectTransform_t3700156813 * __this, int32_t ___edge0, float ___inset1, float ___size2, const RuntimeMethod* method) { int32_t V_0 = 0; bool V_1 = false; float V_2 = 0.0f; Vector2_t3854014517 V_3; memset(&V_3, 0, sizeof(V_3)); Vector2_t3854014517 V_4; memset(&V_4, 0, sizeof(V_4)); Vector2_t3854014517 V_5; memset(&V_5, 0, sizeof(V_5)); Vector2_t3854014517 V_6; memset(&V_6, 0, sizeof(V_6)); Vector2_t3854014517 V_7; memset(&V_7, 0, sizeof(V_7)); int32_t G_B4_0 = 0; int32_t G_B7_0 = 0; int32_t G_B10_0 = 0; int32_t G_B12_0 = 0; Vector2_t3854014517 * G_B12_1 = NULL; int32_t G_B11_0 = 0; Vector2_t3854014517 * G_B11_1 = NULL; float G_B13_0 = 0.0f; int32_t G_B13_1 = 0; Vector2_t3854014517 * G_B13_2 = NULL; { int32_t L_0 = ___edge0; if ((((int32_t)L_0) == ((int32_t)2))) { goto IL_000f; } } { int32_t L_1 = ___edge0; if ((!(((uint32_t)L_1) == ((uint32_t)3)))) { goto IL_0015; } } IL_000f: { G_B4_0 = 1; goto IL_0016; } IL_0015: { G_B4_0 = 0; } IL_0016: { V_0 = G_B4_0; int32_t L_2 = ___edge0; if ((((int32_t)L_2) == ((int32_t)2))) { goto IL_0024; } } { int32_t L_3 = ___edge0; G_B7_0 = ((((int32_t)L_3) == ((int32_t)1))? 1 : 0); goto IL_0025; } IL_0024: { G_B7_0 = 1; } IL_0025: { V_1 = (bool)G_B7_0; bool L_4 = V_1; if (!L_4) { goto IL_0032; } } { G_B10_0 = 1; goto IL_0033; } IL_0032: { G_B10_0 = 0; } IL_0033: { V_2 = (((float)((float)G_B10_0))); Vector2_t3854014517 L_5 = RectTransform_get_anchorMin_m3875085598(__this, /*hidden argument*/NULL); V_3 = L_5; int32_t L_6 = V_0; float L_7 = V_2; Vector2_set_Item_m1415764177((&V_3), L_6, L_7, /*hidden argument*/NULL); Vector2_t3854014517 L_8 = V_3; RectTransform_set_anchorMin_m813062776(__this, L_8, /*hidden argument*/NULL); Vector2_t3854014517 L_9 = RectTransform_get_anchorMax_m211673889(__this, /*hidden argument*/NULL); V_3 = L_9; int32_t L_10 = V_0; float L_11 = V_2; Vector2_set_Item_m1415764177((&V_3), L_10, L_11, /*hidden argument*/NULL); Vector2_t3854014517 L_12 = V_3; RectTransform_set_anchorMax_m1270568626(__this, L_12, /*hidden argument*/NULL); Vector2_t3854014517 L_13 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); V_4 = L_13; int32_t L_14 = V_0; float L_15 = ___size2; Vector2_set_Item_m1415764177((&V_4), L_14, L_15, /*hidden argument*/NULL); Vector2_t3854014517 L_16 = V_4; RectTransform_set_sizeDelta_m2388347220(__this, L_16, /*hidden argument*/NULL); Vector2_t3854014517 L_17 = RectTransform_get_anchoredPosition_m3838889794(__this, /*hidden argument*/NULL); V_5 = L_17; int32_t L_18 = V_0; bool L_19 = V_1; G_B11_0 = L_18; G_B11_1 = (&V_5); if (!L_19) { G_B12_0 = L_18; G_B12_1 = (&V_5); goto IL_00ad; } } { float L_20 = ___inset1; float L_21 = ___size2; Vector2_t3854014517 L_22 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); V_6 = L_22; int32_t L_23 = V_0; float L_24 = Vector2_get_Item_m380735974((&V_6), L_23, /*hidden argument*/NULL); G_B13_0 = ((float)((float)((-L_20))-(float)((float)((float)L_21*(float)((float)((float)(1.0f)-(float)L_24)))))); G_B13_1 = G_B11_0; G_B13_2 = G_B11_1; goto IL_00c1; } IL_00ad: { float L_25 = ___inset1; float L_26 = ___size2; Vector2_t3854014517 L_27 = RectTransform_get_pivot_m186250636(__this, /*hidden argument*/NULL); V_7 = L_27; int32_t L_28 = V_0; float L_29 = Vector2_get_Item_m380735974((&V_7), L_28, /*hidden argument*/NULL); G_B13_0 = ((float)((float)L_25+(float)((float)((float)L_26*(float)L_29)))); G_B13_1 = G_B12_0; G_B13_2 = G_B12_1; } IL_00c1: { Vector2_set_Item_m1415764177(G_B13_2, G_B13_1, G_B13_0, /*hidden argument*/NULL); Vector2_t3854014517 L_30 = V_5; RectTransform_set_anchoredPosition_m754568721(__this, L_30, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RectTransform::SetSizeWithCurrentAnchors(UnityEngine.RectTransform/Axis,System.Single) extern "C" void RectTransform_SetSizeWithCurrentAnchors_m4081032634 (RectTransform_t3700156813 * __this, int32_t ___axis0, float ___size1, const RuntimeMethod* method) { int32_t V_0 = 0; Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); Vector2_t3854014517 V_2; memset(&V_2, 0, sizeof(V_2)); Vector2_t3854014517 V_3; memset(&V_3, 0, sizeof(V_3)); Vector2_t3854014517 V_4; memset(&V_4, 0, sizeof(V_4)); { int32_t L_0 = ___axis0; V_0 = L_0; Vector2_t3854014517 L_1 = RectTransform_get_sizeDelta_m2732713248(__this, /*hidden argument*/NULL); V_1 = L_1; int32_t L_2 = V_0; float L_3 = ___size1; Vector2_t3854014517 L_4 = RectTransform_GetParentSize_m101662412(__this, /*hidden argument*/NULL); V_2 = L_4; int32_t L_5 = V_0; float L_6 = Vector2_get_Item_m380735974((&V_2), L_5, /*hidden argument*/NULL); Vector2_t3854014517 L_7 = RectTransform_get_anchorMax_m211673889(__this, /*hidden argument*/NULL); V_3 = L_7; int32_t L_8 = V_0; float L_9 = Vector2_get_Item_m380735974((&V_3), L_8, /*hidden argument*/NULL); Vector2_t3854014517 L_10 = RectTransform_get_anchorMin_m3875085598(__this, /*hidden argument*/NULL); V_4 = L_10; int32_t L_11 = V_0; float L_12 = Vector2_get_Item_m380735974((&V_4), L_11, /*hidden argument*/NULL); Vector2_set_Item_m1415764177((&V_1), L_2, ((float)((float)L_3-(float)((float)((float)L_6*(float)((float)((float)L_9-(float)L_12)))))), /*hidden argument*/NULL); Vector2_t3854014517 L_13 = V_1; RectTransform_set_sizeDelta_m2388347220(__this, L_13, /*hidden argument*/NULL); return; } } // UnityEngine.Vector2 UnityEngine.RectTransform::GetParentSize() extern "C" Vector2_t3854014517 RectTransform_GetParentSize_m101662412 (RectTransform_t3700156813 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransform_GetParentSize_m101662412_MetadataUsageId); s_Il2CppMethodInitialized = true; } RectTransform_t3700156813 * V_0 = NULL; Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); Rect_t3345319094 V_2; memset(&V_2, 0, sizeof(V_2)); { Transform_t2468616896 * L_0 = Transform_get_parent_m4197710916(__this, /*hidden argument*/NULL); V_0 = ((RectTransform_t3700156813 *)IsInstSealed((RuntimeObject*)L_0, RectTransform_t3700156813_il2cpp_TypeInfo_var)); RectTransform_t3700156813 * L_1 = V_0; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_2 = Object_op_Implicit_m3026831640(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); if (L_2) { goto IL_0023; } } { IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_3 = Vector2_get_zero_m1977254044(NULL /*static, unused*/, /*hidden argument*/NULL); V_1 = L_3; goto IL_0037; } IL_0023: { RectTransform_t3700156813 * L_4 = V_0; NullCheck(L_4); Rect_t3345319094 L_5 = RectTransform_get_rect_m2145828853(L_4, /*hidden argument*/NULL); V_2 = L_5; Vector2_t3854014517 L_6 = Rect_get_size_m3072131835((&V_2), /*hidden argument*/NULL); V_1 = L_6; goto IL_0037; } IL_0037: { Vector2_t3854014517 L_7 = V_1; return L_7; } } // System.Void UnityEngine.RectTransform/ReapplyDrivenProperties::.ctor(System.Object,System.IntPtr) extern "C" void ReapplyDrivenProperties__ctor_m2878196105 (ReapplyDrivenProperties_t2885473943 * __this, RuntimeObject * ___object0, IntPtr_t ___method1, const RuntimeMethod* method) { __this->set_method_ptr_0(il2cpp_codegen_get_method_pointer((RuntimeMethod*)___method1.get_m_value_0())); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void UnityEngine.RectTransform/ReapplyDrivenProperties::Invoke(UnityEngine.RectTransform) extern "C" void ReapplyDrivenProperties_Invoke_m3653398493 (ReapplyDrivenProperties_t2885473943 * __this, RectTransform_t3700156813 * ___driven0, const RuntimeMethod* method) { if(__this->get_prev_9() != NULL) { ReapplyDrivenProperties_Invoke_m3653398493((ReapplyDrivenProperties_t2885473943 *)__this->get_prev_9(),___driven0, method); } il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found((RuntimeMethod*)(__this->get_method_3().get_m_value_0())); bool ___methodIsStatic = MethodIsStatic((RuntimeMethod*)(__this->get_method_3().get_m_value_0())); if (__this->get_m_target_2() != NULL && ___methodIsStatic) { typedef void (*FunctionPointerType) (RuntimeObject *, void* __this, RectTransform_t3700156813 * ___driven0, const RuntimeMethod* method); ((FunctionPointerType)__this->get_method_ptr_0())(NULL,__this->get_m_target_2(),___driven0,(RuntimeMethod*)(__this->get_method_3().get_m_value_0())); } else if (__this->get_m_target_2() != NULL || ___methodIsStatic) { typedef void (*FunctionPointerType) (void* __this, RectTransform_t3700156813 * ___driven0, const RuntimeMethod* method); ((FunctionPointerType)__this->get_method_ptr_0())(__this->get_m_target_2(),___driven0,(RuntimeMethod*)(__this->get_method_3().get_m_value_0())); } else { typedef void (*FunctionPointerType) (void* __this, const RuntimeMethod* method); ((FunctionPointerType)__this->get_method_ptr_0())(___driven0,(RuntimeMethod*)(__this->get_method_3().get_m_value_0())); } } // System.IAsyncResult UnityEngine.RectTransform/ReapplyDrivenProperties::BeginInvoke(UnityEngine.RectTransform,System.AsyncCallback,System.Object) extern "C" RuntimeObject* ReapplyDrivenProperties_BeginInvoke_m3255828871 (ReapplyDrivenProperties_t2885473943 * __this, RectTransform_t3700156813 * ___driven0, AsyncCallback_t2537533359 * ___callback1, RuntimeObject * ___object2, const RuntimeMethod* method) { void *__d_args[2] = {0}; __d_args[0] = ___driven0; return (RuntimeObject*)il2cpp_codegen_delegate_begin_invoke((Il2CppDelegate*)__this, __d_args, (Il2CppDelegate*)___callback1, (RuntimeObject*)___object2); } // System.Void UnityEngine.RectTransform/ReapplyDrivenProperties::EndInvoke(System.IAsyncResult) extern "C" void ReapplyDrivenProperties_EndInvoke_m242296835 (ReapplyDrivenProperties_t2885473943 * __this, RuntimeObject* ___result0, const RuntimeMethod* method) { il2cpp_codegen_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } // System.Boolean UnityEngine.RectTransformUtility::ScreenPointToWorldPointInRectangle(UnityEngine.RectTransform,UnityEngine.Vector2,UnityEngine.Camera,UnityEngine.Vector3&) extern "C" bool RectTransformUtility_ScreenPointToWorldPointInRectangle_m949791734 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 ___screenPoint1, Camera_t110840138 * ___cam2, Vector3_t67624592 * ___worldPoint3, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_ScreenPointToWorldPointInRectangle_m949791734_MetadataUsageId); s_Il2CppMethodInitialized = true; } Ray_t3058960190 V_0; memset(&V_0, 0, sizeof(V_0)); Plane_t3179518881 V_1; memset(&V_1, 0, sizeof(V_1)); float V_2 = 0.0f; bool V_3 = false; { Vector3_t67624592 * L_0 = ___worldPoint3; IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_1 = Vector2_get_zero_m1977254044(NULL /*static, unused*/, /*hidden argument*/NULL); Vector3_t67624592 L_2 = Vector2_op_Implicit_m1696140672(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); *(Vector3_t67624592 *)L_0 = L_2; Camera_t110840138 * L_3 = ___cam2; Vector2_t3854014517 L_4 = ___screenPoint1; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); Ray_t3058960190 L_5 = RectTransformUtility_ScreenPointToRay_m768706565(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); V_0 = L_5; RectTransform_t3700156813 * L_6 = ___rect0; NullCheck(L_6); Quaternion_t4184531171 L_7 = Transform_get_rotation_m3767592267(L_6, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_8 = Vector3_get_back_m1005823721(NULL /*static, unused*/, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t4184531171_il2cpp_TypeInfo_var); Vector3_t67624592 L_9 = Quaternion_op_Multiply_m1066223492(NULL /*static, unused*/, L_7, L_8, /*hidden argument*/NULL); RectTransform_t3700156813 * L_10 = ___rect0; NullCheck(L_10); Vector3_t67624592 L_11 = Transform_get_position_m3786962343(L_10, /*hidden argument*/NULL); Plane__ctor_m1656613681((&V_1), L_9, L_11, /*hidden argument*/NULL); Ray_t3058960190 L_12 = V_0; bool L_13 = Plane_Raycast_m1563516470((&V_1), L_12, (&V_2), /*hidden argument*/NULL); if (L_13) { goto IL_004c; } } { V_3 = (bool)0; goto IL_0061; } IL_004c: { Vector3_t67624592 * L_14 = ___worldPoint3; float L_15 = V_2; Vector3_t67624592 L_16 = Ray_GetPoint_m1809995955((&V_0), L_15, /*hidden argument*/NULL); *(Vector3_t67624592 *)L_14 = L_16; V_3 = (bool)1; goto IL_0061; } IL_0061: { bool L_17 = V_3; return L_17; } } // System.Boolean UnityEngine.RectTransformUtility::ScreenPointToLocalPointInRectangle(UnityEngine.RectTransform,UnityEngine.Vector2,UnityEngine.Camera,UnityEngine.Vector2&) extern "C" bool RectTransformUtility_ScreenPointToLocalPointInRectangle_m2140708364 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 ___screenPoint1, Camera_t110840138 * ___cam2, Vector2_t3854014517 * ___localPoint3, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_ScreenPointToLocalPointInRectangle_m2140708364_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); bool V_1 = false; { Vector2_t3854014517 * L_0 = ___localPoint3; IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_1 = Vector2_get_zero_m1977254044(NULL /*static, unused*/, /*hidden argument*/NULL); *(Vector2_t3854014517 *)L_0 = L_1; RectTransform_t3700156813 * L_2 = ___rect0; Vector2_t3854014517 L_3 = ___screenPoint1; Camera_t110840138 * L_4 = ___cam2; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); bool L_5 = RectTransformUtility_ScreenPointToWorldPointInRectangle_m949791734(NULL /*static, unused*/, L_2, L_3, L_4, (&V_0), /*hidden argument*/NULL); if (!L_5) { goto IL_0035; } } { Vector2_t3854014517 * L_6 = ___localPoint3; RectTransform_t3700156813 * L_7 = ___rect0; Vector3_t67624592 L_8 = V_0; NullCheck(L_7); Vector3_t67624592 L_9 = Transform_InverseTransformPoint_m4188161690(L_7, L_8, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_10 = Vector2_op_Implicit_m2584888397(NULL /*static, unused*/, L_9, /*hidden argument*/NULL); *(Vector2_t3854014517 *)L_6 = L_10; V_1 = (bool)1; goto IL_003c; } IL_0035: { V_1 = (bool)0; goto IL_003c; } IL_003c: { bool L_11 = V_1; return L_11; } } // UnityEngine.Ray UnityEngine.RectTransformUtility::ScreenPointToRay(UnityEngine.Camera,UnityEngine.Vector2) extern "C" Ray_t3058960190 RectTransformUtility_ScreenPointToRay_m768706565 (RuntimeObject * __this /* static, unused */, Camera_t110840138 * ___cam0, Vector2_t3854014517 ___screenPos1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_ScreenPointToRay_m768706565_MetadataUsageId); s_Il2CppMethodInitialized = true; } Ray_t3058960190 V_0; memset(&V_0, 0, sizeof(V_0)); Vector3_t67624592 V_1; memset(&V_1, 0, sizeof(V_1)); { Camera_t110840138 * L_0 = ___cam0; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_001f; } } { Camera_t110840138 * L_2 = ___cam0; Vector2_t3854014517 L_3 = ___screenPos1; IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector3_t67624592 L_4 = Vector2_op_Implicit_m1696140672(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); NullCheck(L_2); Ray_t3058960190 L_5 = Camera_ScreenPointToRay_m2745386935(L_2, L_4, /*hidden argument*/NULL); V_0 = L_5; goto IL_004a; } IL_001f: { Vector2_t3854014517 L_6 = ___screenPos1; IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector3_t67624592 L_7 = Vector2_op_Implicit_m1696140672(NULL /*static, unused*/, L_6, /*hidden argument*/NULL); V_1 = L_7; Vector3_t67624592 * L_8 = (&V_1); float L_9 = L_8->get_z_3(); L_8->set_z_3(((float)((float)L_9-(float)(100.0f)))); Vector3_t67624592 L_10 = V_1; IL2CPP_RUNTIME_CLASS_INIT(Vector3_t67624592_il2cpp_TypeInfo_var); Vector3_t67624592 L_11 = Vector3_get_forward_m326191705(NULL /*static, unused*/, /*hidden argument*/NULL); Ray_t3058960190 L_12; memset(&L_12, 0, sizeof(L_12)); Ray__ctor_m1769593825((&L_12), L_10, L_11, /*hidden argument*/NULL); V_0 = L_12; goto IL_004a; } IL_004a: { Ray_t3058960190 L_13 = V_0; return L_13; } } // System.Void UnityEngine.RectTransformUtility::FlipLayoutOnAxis(UnityEngine.RectTransform,System.Int32,System.Boolean,System.Boolean) extern "C" void RectTransformUtility_FlipLayoutOnAxis_m932564554 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, int32_t ___axis1, bool ___keepPositioning2, bool ___recursive3, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_FlipLayoutOnAxis_m932564554_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; RectTransform_t3700156813 * V_1 = NULL; Vector2_t3854014517 V_2; memset(&V_2, 0, sizeof(V_2)); Vector2_t3854014517 V_3; memset(&V_3, 0, sizeof(V_3)); Vector2_t3854014517 V_4; memset(&V_4, 0, sizeof(V_4)); Vector2_t3854014517 V_5; memset(&V_5, 0, sizeof(V_5)); float V_6 = 0.0f; { RectTransform_t3700156813 * L_0 = ___rect0; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0012; } } { goto IL_00f3; } IL_0012: { bool L_2 = ___recursive3; if (!L_2) { goto IL_0055; } } { V_0 = 0; goto IL_0048; } IL_0020: { RectTransform_t3700156813 * L_3 = ___rect0; int32_t L_4 = V_0; NullCheck(L_3); Transform_t2468616896 * L_5 = Transform_GetChild_m5845828(L_3, L_4, /*hidden argument*/NULL); V_1 = ((RectTransform_t3700156813 *)IsInstSealed((RuntimeObject*)L_5, RectTransform_t3700156813_il2cpp_TypeInfo_var)); RectTransform_t3700156813 * L_6 = V_1; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_7 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_6, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_7) { goto IL_0043; } } { RectTransform_t3700156813 * L_8 = V_1; int32_t L_9 = ___axis1; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); RectTransformUtility_FlipLayoutOnAxis_m932564554(NULL /*static, unused*/, L_8, L_9, (bool)0, (bool)1, /*hidden argument*/NULL); } IL_0043: { int32_t L_10 = V_0; V_0 = ((int32_t)((int32_t)L_10+(int32_t)1)); } IL_0048: { int32_t L_11 = V_0; RectTransform_t3700156813 * L_12 = ___rect0; NullCheck(L_12); int32_t L_13 = Transform_get_childCount_m1791344060(L_12, /*hidden argument*/NULL); if ((((int32_t)L_11) < ((int32_t)L_13))) { goto IL_0020; } } { } IL_0055: { RectTransform_t3700156813 * L_14 = ___rect0; NullCheck(L_14); Vector2_t3854014517 L_15 = RectTransform_get_pivot_m186250636(L_14, /*hidden argument*/NULL); V_2 = L_15; int32_t L_16 = ___axis1; int32_t L_17 = ___axis1; float L_18 = Vector2_get_Item_m380735974((&V_2), L_17, /*hidden argument*/NULL); Vector2_set_Item_m1415764177((&V_2), L_16, ((float)((float)(1.0f)-(float)L_18)), /*hidden argument*/NULL); RectTransform_t3700156813 * L_19 = ___rect0; Vector2_t3854014517 L_20 = V_2; NullCheck(L_19); RectTransform_set_pivot_m1268266743(L_19, L_20, /*hidden argument*/NULL); bool L_21 = ___keepPositioning2; if (!L_21) { goto IL_0084; } } { goto IL_00f3; } IL_0084: { RectTransform_t3700156813 * L_22 = ___rect0; NullCheck(L_22); Vector2_t3854014517 L_23 = RectTransform_get_anchoredPosition_m3838889794(L_22, /*hidden argument*/NULL); V_3 = L_23; int32_t L_24 = ___axis1; int32_t L_25 = ___axis1; float L_26 = Vector2_get_Item_m380735974((&V_3), L_25, /*hidden argument*/NULL); Vector2_set_Item_m1415764177((&V_3), L_24, ((-L_26)), /*hidden argument*/NULL); RectTransform_t3700156813 * L_27 = ___rect0; Vector2_t3854014517 L_28 = V_3; NullCheck(L_27); RectTransform_set_anchoredPosition_m754568721(L_27, L_28, /*hidden argument*/NULL); RectTransform_t3700156813 * L_29 = ___rect0; NullCheck(L_29); Vector2_t3854014517 L_30 = RectTransform_get_anchorMin_m3875085598(L_29, /*hidden argument*/NULL); V_4 = L_30; RectTransform_t3700156813 * L_31 = ___rect0; NullCheck(L_31); Vector2_t3854014517 L_32 = RectTransform_get_anchorMax_m211673889(L_31, /*hidden argument*/NULL); V_5 = L_32; int32_t L_33 = ___axis1; float L_34 = Vector2_get_Item_m380735974((&V_4), L_33, /*hidden argument*/NULL); V_6 = L_34; int32_t L_35 = ___axis1; int32_t L_36 = ___axis1; float L_37 = Vector2_get_Item_m380735974((&V_5), L_36, /*hidden argument*/NULL); Vector2_set_Item_m1415764177((&V_4), L_35, ((float)((float)(1.0f)-(float)L_37)), /*hidden argument*/NULL); int32_t L_38 = ___axis1; float L_39 = V_6; Vector2_set_Item_m1415764177((&V_5), L_38, ((float)((float)(1.0f)-(float)L_39)), /*hidden argument*/NULL); RectTransform_t3700156813 * L_40 = ___rect0; Vector2_t3854014517 L_41 = V_4; NullCheck(L_40); RectTransform_set_anchorMin_m813062776(L_40, L_41, /*hidden argument*/NULL); RectTransform_t3700156813 * L_42 = ___rect0; Vector2_t3854014517 L_43 = V_5; NullCheck(L_42); RectTransform_set_anchorMax_m1270568626(L_42, L_43, /*hidden argument*/NULL); } IL_00f3: { return; } } // System.Void UnityEngine.RectTransformUtility::FlipLayoutAxes(UnityEngine.RectTransform,System.Boolean,System.Boolean) extern "C" void RectTransformUtility_FlipLayoutAxes_m4222183317 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, bool ___keepPositioning1, bool ___recursive2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_FlipLayoutAxes_m4222183317_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; RectTransform_t3700156813 * V_1 = NULL; { RectTransform_t3700156813 * L_0 = ___rect0; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0012; } } { goto IL_00b4; } IL_0012: { bool L_2 = ___recursive2; if (!L_2) { goto IL_0054; } } { V_0 = 0; goto IL_0047; } IL_0020: { RectTransform_t3700156813 * L_3 = ___rect0; int32_t L_4 = V_0; NullCheck(L_3); Transform_t2468616896 * L_5 = Transform_GetChild_m5845828(L_3, L_4, /*hidden argument*/NULL); V_1 = ((RectTransform_t3700156813 *)IsInstSealed((RuntimeObject*)L_5, RectTransform_t3700156813_il2cpp_TypeInfo_var)); RectTransform_t3700156813 * L_6 = V_1; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_7 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_6, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_7) { goto IL_0042; } } { RectTransform_t3700156813 * L_8 = V_1; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); RectTransformUtility_FlipLayoutAxes_m4222183317(NULL /*static, unused*/, L_8, (bool)0, (bool)1, /*hidden argument*/NULL); } IL_0042: { int32_t L_9 = V_0; V_0 = ((int32_t)((int32_t)L_9+(int32_t)1)); } IL_0047: { int32_t L_10 = V_0; RectTransform_t3700156813 * L_11 = ___rect0; NullCheck(L_11); int32_t L_12 = Transform_get_childCount_m1791344060(L_11, /*hidden argument*/NULL); if ((((int32_t)L_10) < ((int32_t)L_12))) { goto IL_0020; } } { } IL_0054: { RectTransform_t3700156813 * L_13 = ___rect0; RectTransform_t3700156813 * L_14 = ___rect0; NullCheck(L_14); Vector2_t3854014517 L_15 = RectTransform_get_pivot_m186250636(L_14, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); Vector2_t3854014517 L_16 = RectTransformUtility_GetTransposed_m3113223627(NULL /*static, unused*/, L_15, /*hidden argument*/NULL); NullCheck(L_13); RectTransform_set_pivot_m1268266743(L_13, L_16, /*hidden argument*/NULL); RectTransform_t3700156813 * L_17 = ___rect0; RectTransform_t3700156813 * L_18 = ___rect0; NullCheck(L_18); Vector2_t3854014517 L_19 = RectTransform_get_sizeDelta_m2732713248(L_18, /*hidden argument*/NULL); Vector2_t3854014517 L_20 = RectTransformUtility_GetTransposed_m3113223627(NULL /*static, unused*/, L_19, /*hidden argument*/NULL); NullCheck(L_17); RectTransform_set_sizeDelta_m2388347220(L_17, L_20, /*hidden argument*/NULL); bool L_21 = ___keepPositioning1; if (!L_21) { goto IL_0081; } } { goto IL_00b4; } IL_0081: { RectTransform_t3700156813 * L_22 = ___rect0; RectTransform_t3700156813 * L_23 = ___rect0; NullCheck(L_23); Vector2_t3854014517 L_24 = RectTransform_get_anchoredPosition_m3838889794(L_23, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); Vector2_t3854014517 L_25 = RectTransformUtility_GetTransposed_m3113223627(NULL /*static, unused*/, L_24, /*hidden argument*/NULL); NullCheck(L_22); RectTransform_set_anchoredPosition_m754568721(L_22, L_25, /*hidden argument*/NULL); RectTransform_t3700156813 * L_26 = ___rect0; RectTransform_t3700156813 * L_27 = ___rect0; NullCheck(L_27); Vector2_t3854014517 L_28 = RectTransform_get_anchorMin_m3875085598(L_27, /*hidden argument*/NULL); Vector2_t3854014517 L_29 = RectTransformUtility_GetTransposed_m3113223627(NULL /*static, unused*/, L_28, /*hidden argument*/NULL); NullCheck(L_26); RectTransform_set_anchorMin_m813062776(L_26, L_29, /*hidden argument*/NULL); RectTransform_t3700156813 * L_30 = ___rect0; RectTransform_t3700156813 * L_31 = ___rect0; NullCheck(L_31); Vector2_t3854014517 L_32 = RectTransform_get_anchorMax_m211673889(L_31, /*hidden argument*/NULL); Vector2_t3854014517 L_33 = RectTransformUtility_GetTransposed_m3113223627(NULL /*static, unused*/, L_32, /*hidden argument*/NULL); NullCheck(L_30); RectTransform_set_anchorMax_m1270568626(L_30, L_33, /*hidden argument*/NULL); } IL_00b4: { return; } } // UnityEngine.Vector2 UnityEngine.RectTransformUtility::GetTransposed(UnityEngine.Vector2) extern "C" Vector2_t3854014517 RectTransformUtility_GetTransposed_m3113223627 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___input0, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); { float L_0 = (&___input0)->get_y_1(); float L_1 = (&___input0)->get_x_0(); Vector2_t3854014517 L_2; memset(&L_2, 0, sizeof(L_2)); Vector2__ctor_m2886412624((&L_2), L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_001a; } IL_001a: { Vector2_t3854014517 L_3 = V_0; return L_3; } } // System.Boolean UnityEngine.RectTransformUtility::RectangleContainsScreenPoint(UnityEngine.RectTransform,UnityEngine.Vector2,UnityEngine.Camera) extern "C" bool RectTransformUtility_RectangleContainsScreenPoint_m3537473567 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 ___screenPoint1, Camera_t110840138 * ___cam2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_RectangleContainsScreenPoint_m3537473567_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { RectTransform_t3700156813 * L_0 = ___rect0; Camera_t110840138 * L_1 = ___cam2; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); bool L_2 = RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628(NULL /*static, unused*/, L_0, (&___screenPoint1), L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0010; } IL_0010: { bool L_3 = V_0; return L_3; } } // System.Boolean UnityEngine.RectTransformUtility::INTERNAL_CALL_RectangleContainsScreenPoint(UnityEngine.RectTransform,UnityEngine.Vector2&,UnityEngine.Camera) extern "C" bool RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rect0, Vector2_t3854014517 * ___screenPoint1, Camera_t110840138 * ___cam2, const RuntimeMethod* method) { typedef bool (*RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628_ftn) (RectTransform_t3700156813 *, Vector2_t3854014517 *, Camera_t110840138 *); static RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransformUtility_INTERNAL_CALL_RectangleContainsScreenPoint_m1133491628_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransformUtility::INTERNAL_CALL_RectangleContainsScreenPoint(UnityEngine.RectTransform,UnityEngine.Vector2&,UnityEngine.Camera)"); bool retVal = _il2cpp_icall_func(___rect0, ___screenPoint1, ___cam2); return retVal; } // UnityEngine.Vector2 UnityEngine.RectTransformUtility::PixelAdjustPoint(UnityEngine.Vector2,UnityEngine.Transform,UnityEngine.Canvas) extern "C" Vector2_t3854014517 RectTransformUtility_PixelAdjustPoint_m216690555 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 ___point0, Transform_t2468616896 * ___elementTransform1, Canvas_t2948613984 * ___canvas2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_PixelAdjustPoint_m216690555_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { Transform_t2468616896 * L_0 = ___elementTransform1; Canvas_t2948613984 * L_1 = ___canvas2; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083(NULL /*static, unused*/, (&___point0), L_0, L_1, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_2 = V_0; V_1 = L_2; goto IL_0013; } IL_0013: { Vector2_t3854014517 L_3 = V_1; return L_3; } } // System.Void UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustPoint(UnityEngine.Vector2&,UnityEngine.Transform,UnityEngine.Canvas,UnityEngine.Vector2&) extern "C" void RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083 (RuntimeObject * __this /* static, unused */, Vector2_t3854014517 * ___point0, Transform_t2468616896 * ___elementTransform1, Canvas_t2948613984 * ___canvas2, Vector2_t3854014517 * ___value3, const RuntimeMethod* method) { typedef void (*RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083_ftn) (Vector2_t3854014517 *, Transform_t2468616896 *, Canvas_t2948613984 *, Vector2_t3854014517 *); static RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransformUtility_INTERNAL_CALL_PixelAdjustPoint_m1157207083_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustPoint(UnityEngine.Vector2&,UnityEngine.Transform,UnityEngine.Canvas,UnityEngine.Vector2&)"); _il2cpp_icall_func(___point0, ___elementTransform1, ___canvas2, ___value3); } // UnityEngine.Rect UnityEngine.RectTransformUtility::PixelAdjustRect(UnityEngine.RectTransform,UnityEngine.Canvas) extern "C" Rect_t3345319094 RectTransformUtility_PixelAdjustRect_m3656622349 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rectTransform0, Canvas_t2948613984 * ___canvas1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility_PixelAdjustRect_m3656622349_MetadataUsageId); s_Il2CppMethodInitialized = true; } Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); { RectTransform_t3700156813 * L_0 = ___rectTransform0; Canvas_t2948613984 * L_1 = ___canvas1; IL2CPP_RUNTIME_CLASS_INIT(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var); RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901(NULL /*static, unused*/, L_0, L_1, (&V_0), /*hidden argument*/NULL); Rect_t3345319094 L_2 = V_0; V_1 = L_2; goto IL_0011; } IL_0011: { Rect_t3345319094 L_3 = V_1; return L_3; } } // System.Void UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustRect(UnityEngine.RectTransform,UnityEngine.Canvas,UnityEngine.Rect&) extern "C" void RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901 (RuntimeObject * __this /* static, unused */, RectTransform_t3700156813 * ___rectTransform0, Canvas_t2948613984 * ___canvas1, Rect_t3345319094 * ___value2, const RuntimeMethod* method) { typedef void (*RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901_ftn) (RectTransform_t3700156813 *, Canvas_t2948613984 *, Rect_t3345319094 *); static RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RectTransformUtility_INTERNAL_CALL_PixelAdjustRect_m3899764901_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RectTransformUtility::INTERNAL_CALL_PixelAdjustRect(UnityEngine.RectTransform,UnityEngine.Canvas,UnityEngine.Rect&)"); _il2cpp_icall_func(___rectTransform0, ___canvas1, ___value2); } // System.Void UnityEngine.RectTransformUtility::.cctor() extern "C" void RectTransformUtility__cctor_m698144985 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RectTransformUtility__cctor_m698144985_MetadataUsageId); s_Il2CppMethodInitialized = true; } { ((RectTransformUtility_t1869061041_StaticFields*)il2cpp_codegen_static_fields_for(RectTransformUtility_t1869061041_il2cpp_TypeInfo_var))->set_s_Corners_0(((Vector3U5BU5D_t2251457841*)SZArrayNew(Vector3U5BU5D_t2251457841_il2cpp_TypeInfo_var, (uint32_t)4))); return; } } // System.Void UnityEngine.RemoteSettings::CallOnUpdate() extern "C" void RemoteSettings_CallOnUpdate_m1065707692 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteSettings_CallOnUpdate_m1065707692_MetadataUsageId); s_Il2CppMethodInitialized = true; } UpdatedEventHandler_t860849547 * V_0 = NULL; { UpdatedEventHandler_t860849547 * L_0 = ((RemoteSettings_t1084722070_StaticFields*)il2cpp_codegen_static_fields_for(RemoteSettings_t1084722070_il2cpp_TypeInfo_var))->get_Updated_0(); V_0 = L_0; UpdatedEventHandler_t860849547 * L_1 = V_0; if (!L_1) { goto IL_0013; } } { UpdatedEventHandler_t860849547 * L_2 = V_0; NullCheck(L_2); UpdatedEventHandler_Invoke_m3549789676(L_2, /*hidden argument*/NULL); } IL_0013: { return; } } extern "C" void DelegatePInvokeWrapper_UpdatedEventHandler_t860849547 (UpdatedEventHandler_t860849547 * __this, const RuntimeMethod* method) { typedef void (STDCALL *PInvokeFunc)(); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast(il2cpp_codegen_get_method_pointer(((Il2CppDelegate*)__this)->method)); // Native function invocation il2cppPInvokeFunc(); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::.ctor(System.Object,System.IntPtr) extern "C" void UpdatedEventHandler__ctor_m924619110 (UpdatedEventHandler_t860849547 * __this, RuntimeObject * ___object0, IntPtr_t ___method1, const RuntimeMethod* method) { __this->set_method_ptr_0(il2cpp_codegen_get_method_pointer((RuntimeMethod*)___method1.get_m_value_0())); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::Invoke() extern "C" void UpdatedEventHandler_Invoke_m3549789676 (UpdatedEventHandler_t860849547 * __this, const RuntimeMethod* method) { if(__this->get_prev_9() != NULL) { UpdatedEventHandler_Invoke_m3549789676((UpdatedEventHandler_t860849547 *)__this->get_prev_9(), method); } il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found((RuntimeMethod*)(__this->get_method_3().get_m_value_0())); bool ___methodIsStatic = MethodIsStatic((RuntimeMethod*)(__this->get_method_3().get_m_value_0())); if ((__this->get_m_target_2() != NULL || MethodHasParameters((RuntimeMethod*)(__this->get_method_3().get_m_value_0()))) && ___methodIsStatic) { typedef void (*FunctionPointerType) (RuntimeObject *, void* __this, const RuntimeMethod* method); ((FunctionPointerType)__this->get_method_ptr_0())(NULL,__this->get_m_target_2(),(RuntimeMethod*)(__this->get_method_3().get_m_value_0())); } else { typedef void (*FunctionPointerType) (void* __this, const RuntimeMethod* method); ((FunctionPointerType)__this->get_method_ptr_0())(__this->get_m_target_2(),(RuntimeMethod*)(__this->get_method_3().get_m_value_0())); } } // System.IAsyncResult UnityEngine.RemoteSettings/UpdatedEventHandler::BeginInvoke(System.AsyncCallback,System.Object) extern "C" RuntimeObject* UpdatedEventHandler_BeginInvoke_m470701130 (UpdatedEventHandler_t860849547 * __this, AsyncCallback_t2537533359 * ___callback0, RuntimeObject * ___object1, const RuntimeMethod* method) { void *__d_args[1] = {0}; return (RuntimeObject*)il2cpp_codegen_delegate_begin_invoke((Il2CppDelegate*)__this, __d_args, (Il2CppDelegate*)___callback0, (RuntimeObject*)___object1); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::EndInvoke(System.IAsyncResult) extern "C" void UpdatedEventHandler_EndInvoke_m3446798910 (UpdatedEventHandler_t860849547 * __this, RuntimeObject* ___result0, const RuntimeMethod* method) { il2cpp_codegen_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } // System.Void UnityEngine.Renderer::set_enabled(System.Boolean) extern "C" void Renderer_set_enabled_m2252647185 (Renderer_t3838459598 * __this, bool ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_enabled_m2252647185_ftn) (Renderer_t3838459598 *, bool); static Renderer_set_enabled_m2252647185_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_enabled_m2252647185_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_enabled(System.Boolean)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.Renderer::set_shadowCastingMode(UnityEngine.Rendering.ShadowCastingMode) extern "C" void Renderer_set_shadowCastingMode_m2716814938 (Renderer_t3838459598 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_shadowCastingMode_m2716814938_ftn) (Renderer_t3838459598 *, int32_t); static Renderer_set_shadowCastingMode_m2716814938_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_shadowCastingMode_m2716814938_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_shadowCastingMode(UnityEngine.Rendering.ShadowCastingMode)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.Renderer::set_receiveShadows(System.Boolean) extern "C" void Renderer_set_receiveShadows_m1624688890 (Renderer_t3838459598 * __this, bool ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_receiveShadows_m1624688890_ftn) (Renderer_t3838459598 *, bool); static Renderer_set_receiveShadows_m1624688890_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_receiveShadows_m1624688890_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_receiveShadows(System.Boolean)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Material UnityEngine.Renderer::get_material() extern "C" Material_t3939796247 * Renderer_get_material_m1577873558 (Renderer_t3838459598 * __this, const RuntimeMethod* method) { typedef Material_t3939796247 * (*Renderer_get_material_m1577873558_ftn) (Renderer_t3838459598 *); static Renderer_get_material_m1577873558_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_get_material_m1577873558_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::get_material()"); Material_t3939796247 * retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Material UnityEngine.Renderer::get_sharedMaterial() extern "C" Material_t3939796247 * Renderer_get_sharedMaterial_m2526350125 (Renderer_t3838459598 * __this, const RuntimeMethod* method) { typedef Material_t3939796247 * (*Renderer_get_sharedMaterial_m2526350125_ftn) (Renderer_t3838459598 *); static Renderer_get_sharedMaterial_m2526350125_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_get_sharedMaterial_m2526350125_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::get_sharedMaterial()"); Material_t3939796247 * retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.Renderer::set_sharedMaterial(UnityEngine.Material) extern "C" void Renderer_set_sharedMaterial_m16809607 (Renderer_t3838459598 * __this, Material_t3939796247 * ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_sharedMaterial_m16809607_ftn) (Renderer_t3838459598 *, Material_t3939796247 *); static Renderer_set_sharedMaterial_m16809607_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_sharedMaterial_m16809607_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_sharedMaterial(UnityEngine.Material)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.Renderer::get_sortingLayerID() extern "C" int32_t Renderer_get_sortingLayerID_m847110273 (Renderer_t3838459598 * __this, const RuntimeMethod* method) { typedef int32_t (*Renderer_get_sortingLayerID_m847110273_ftn) (Renderer_t3838459598 *); static Renderer_get_sortingLayerID_m847110273_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_get_sortingLayerID_m847110273_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::get_sortingLayerID()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.Renderer::set_sortingLayerID(System.Int32) extern "C" void Renderer_set_sortingLayerID_m4237311790 (Renderer_t3838459598 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_sortingLayerID_m4237311790_ftn) (Renderer_t3838459598 *, int32_t); static Renderer_set_sortingLayerID_m4237311790_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_sortingLayerID_m4237311790_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_sortingLayerID(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.Renderer::get_sortingOrder() extern "C" int32_t Renderer_get_sortingOrder_m4086282400 (Renderer_t3838459598 * __this, const RuntimeMethod* method) { typedef int32_t (*Renderer_get_sortingOrder_m4086282400_ftn) (Renderer_t3838459598 *); static Renderer_get_sortingOrder_m4086282400_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_get_sortingOrder_m4086282400_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::get_sortingOrder()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.Renderer::set_sortingOrder(System.Int32) extern "C" void Renderer_set_sortingOrder_m3273664689 (Renderer_t3838459598 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*Renderer_set_sortingOrder_m3273664689_ftn) (Renderer_t3838459598 *, int32_t); static Renderer_set_sortingOrder_m3273664689_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Renderer_set_sortingOrder_m3273664689_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Renderer::set_sortingOrder(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Int32 UnityEngine.RenderTexture::Internal_GetWidth(UnityEngine.RenderTexture) extern "C" int32_t RenderTexture_Internal_GetWidth_m1234090841 (RuntimeObject * __this /* static, unused */, RenderTexture_t3726137678 * ___mono0, const RuntimeMethod* method) { typedef int32_t (*RenderTexture_Internal_GetWidth_m1234090841_ftn) (RenderTexture_t3726137678 *); static RenderTexture_Internal_GetWidth_m1234090841_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RenderTexture_Internal_GetWidth_m1234090841_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RenderTexture::Internal_GetWidth(UnityEngine.RenderTexture)"); int32_t retVal = _il2cpp_icall_func(___mono0); return retVal; } // System.Int32 UnityEngine.RenderTexture::Internal_GetHeight(UnityEngine.RenderTexture) extern "C" int32_t RenderTexture_Internal_GetHeight_m3898225001 (RuntimeObject * __this /* static, unused */, RenderTexture_t3726137678 * ___mono0, const RuntimeMethod* method) { typedef int32_t (*RenderTexture_Internal_GetHeight_m3898225001_ftn) (RenderTexture_t3726137678 *); static RenderTexture_Internal_GetHeight_m3898225001_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RenderTexture_Internal_GetHeight_m3898225001_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.RenderTexture::Internal_GetHeight(UnityEngine.RenderTexture)"); int32_t retVal = _il2cpp_icall_func(___mono0); return retVal; } // System.Int32 UnityEngine.RenderTexture::get_width() extern "C" int32_t RenderTexture_get_width_m2767638148 (RenderTexture_t3726137678 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = RenderTexture_Internal_GetWidth_m1234090841(NULL /*static, unused*/, __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // System.Int32 UnityEngine.RenderTexture::get_height() extern "C" int32_t RenderTexture_get_height_m1758949530 (RenderTexture_t3726137678 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = RenderTexture_Internal_GetHeight_m3898225001(NULL /*static, unused*/, __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.RequireComponent::.ctor(System.Type) extern "C" void RequireComponent__ctor_m2613472252 (RequireComponent_t2926973319 * __this, Type_t * ___requiredComponent0, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); Type_t * L_0 = ___requiredComponent0; __this->set_m_Type0_0(L_0); return; } } // System.Void UnityEngine.RequireComponent::.ctor(System.Type,System.Type) extern "C" void RequireComponent__ctor_m4080690983 (RequireComponent_t2926973319 * __this, Type_t * ___requiredComponent0, Type_t * ___requiredComponent21, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); Type_t * L_0 = ___requiredComponent0; __this->set_m_Type0_0(L_0); Type_t * L_1 = ___requiredComponent21; __this->set_m_Type1_1(L_1); return; } } // Conversion methods for marshalling of: UnityEngine.ResourceRequest extern "C" void ResourceRequest_t718765924_marshal_pinvoke(const ResourceRequest_t718765924& unmarshaled, ResourceRequest_t718765924_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_Type_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Type' of type 'ResourceRequest': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Type_2Exception); } extern "C" void ResourceRequest_t718765924_marshal_pinvoke_back(const ResourceRequest_t718765924_marshaled_pinvoke& marshaled, ResourceRequest_t718765924& unmarshaled) { Il2CppCodeGenException* ___m_Type_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Type' of type 'ResourceRequest': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Type_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.ResourceRequest extern "C" void ResourceRequest_t718765924_marshal_pinvoke_cleanup(ResourceRequest_t718765924_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.ResourceRequest extern "C" void ResourceRequest_t718765924_marshal_com(const ResourceRequest_t718765924& unmarshaled, ResourceRequest_t718765924_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_Type_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Type' of type 'ResourceRequest': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Type_2Exception); } extern "C" void ResourceRequest_t718765924_marshal_com_back(const ResourceRequest_t718765924_marshaled_com& marshaled, ResourceRequest_t718765924& unmarshaled) { Il2CppCodeGenException* ___m_Type_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Type' of type 'ResourceRequest': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Type_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.ResourceRequest extern "C" void ResourceRequest_t718765924_marshal_com_cleanup(ResourceRequest_t718765924_marshaled_com& marshaled) { } // System.Void UnityEngine.ResourceRequest::.ctor() extern "C" void ResourceRequest__ctor_m1332315309 (ResourceRequest_t718765924 * __this, const RuntimeMethod* method) { { AsyncOperation__ctor_m754450522(__this, /*hidden argument*/NULL); return; } } // UnityEngine.Object UnityEngine.ResourceRequest::get_asset() extern "C" Object_t1332387349 * ResourceRequest_get_asset_m2219825282 (ResourceRequest_t718765924 * __this, const RuntimeMethod* method) { Object_t1332387349 * V_0 = NULL; { String_t* L_0 = __this->get_m_Path_1(); Type_t * L_1 = __this->get_m_Type_2(); Object_t1332387349 * L_2 = Resources_Load_m3998181239(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0018; } IL_0018: { Object_t1332387349 * L_3 = V_0; return L_3; } } // UnityEngine.Object UnityEngine.Resources::Load(System.String) extern "C" Object_t1332387349 * Resources_Load_m1443494906 (RuntimeObject * __this /* static, unused */, String_t* ___path0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Resources_Load_m1443494906_MetadataUsageId); s_Il2CppMethodInitialized = true; } Object_t1332387349 * V_0 = NULL; { String_t* L_0 = ___path0; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m2676592772(NULL /*static, unused*/, LoadTypeToken(Object_t1332387349_0_0_0_var), /*hidden argument*/NULL); Object_t1332387349 * L_2 = Resources_Load_m3998181239(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; goto IL_0017; } IL_0017: { Object_t1332387349 * L_3 = V_0; return L_3; } } // UnityEngine.Object UnityEngine.Resources::Load(System.String,System.Type) extern "C" Object_t1332387349 * Resources_Load_m3998181239 (RuntimeObject * __this /* static, unused */, String_t* ___path0, Type_t * ___systemTypeInstance1, const RuntimeMethod* method) { typedef Object_t1332387349 * (*Resources_Load_m3998181239_ftn) (String_t*, Type_t *); static Resources_Load_m3998181239_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Resources_Load_m3998181239_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Resources::Load(System.String,System.Type)"); Object_t1332387349 * retVal = _il2cpp_icall_func(___path0, ___systemTypeInstance1); return retVal; } // UnityEngine.Object[] UnityEngine.Resources::LoadAll(System.String,System.Type) extern "C" ObjectU5BU5D_t348161528* Resources_LoadAll_m2844136750 (RuntimeObject * __this /* static, unused */, String_t* ___path0, Type_t * ___systemTypeInstance1, const RuntimeMethod* method) { typedef ObjectU5BU5D_t348161528* (*Resources_LoadAll_m2844136750_ftn) (String_t*, Type_t *); static Resources_LoadAll_m2844136750_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Resources_LoadAll_m2844136750_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Resources::LoadAll(System.String,System.Type)"); ObjectU5BU5D_t348161528* retVal = _il2cpp_icall_func(___path0, ___systemTypeInstance1); return retVal; } // UnityEngine.Object UnityEngine.Resources::GetBuiltinResource(System.Type,System.String) extern "C" Object_t1332387349 * Resources_GetBuiltinResource_m2182068646 (RuntimeObject * __this /* static, unused */, Type_t * ___type0, String_t* ___path1, const RuntimeMethod* method) { typedef Object_t1332387349 * (*Resources_GetBuiltinResource_m2182068646_ftn) (Type_t *, String_t*); static Resources_GetBuiltinResource_m2182068646_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Resources_GetBuiltinResource_m2182068646_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Resources::GetBuiltinResource(System.Type,System.String)"); Object_t1332387349 * retVal = _il2cpp_icall_func(___type0, ___path1); return retVal; } // System.Void UnityEngine.RPC::.ctor() extern "C" void RPC__ctor_m140908878 (RPC_t80633788 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Int32 UnityEngine.SceneManagement.Scene::get_handle() extern "C" int32_t Scene_get_handle_m1965217093 (Scene_t886992912 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_m_Handle_0(); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } extern "C" int32_t Scene_get_handle_m1965217093_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Scene_t886992912 * _thisAdjusted = reinterpret_cast(__this + 1); return Scene_get_handle_m1965217093(_thisAdjusted, method); } // System.Int32 UnityEngine.SceneManagement.Scene::GetHashCode() extern "C" int32_t Scene_GetHashCode_m2802271517 (Scene_t886992912 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_m_Handle_0(); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } extern "C" int32_t Scene_GetHashCode_m2802271517_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { Scene_t886992912 * _thisAdjusted = reinterpret_cast(__this + 1); return Scene_GetHashCode_m2802271517(_thisAdjusted, method); } // System.Boolean UnityEngine.SceneManagement.Scene::Equals(System.Object) extern "C" bool Scene_Equals_m2736381267 (Scene_t886992912 * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Scene_Equals_m2736381267_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; Scene_t886992912 V_1; memset(&V_1, 0, sizeof(V_1)); { RuntimeObject * L_0 = ___other0; if (((RuntimeObject *)IsInstSealed((RuntimeObject*)L_0, Scene_t886992912_il2cpp_TypeInfo_var))) { goto IL_0013; } } { V_0 = (bool)0; goto IL_002f; } IL_0013: { RuntimeObject * L_1 = ___other0; V_1 = ((*(Scene_t886992912 *)((Scene_t886992912 *)UnBox(L_1, Scene_t886992912_il2cpp_TypeInfo_var)))); int32_t L_2 = Scene_get_handle_m1965217093(__this, /*hidden argument*/NULL); int32_t L_3 = Scene_get_handle_m1965217093((&V_1), /*hidden argument*/NULL); V_0 = (bool)((((int32_t)L_2) == ((int32_t)L_3))? 1 : 0); goto IL_002f; } IL_002f: { bool L_4 = V_0; return L_4; } } extern "C" bool Scene_Equals_m2736381267_AdjustorThunk (RuntimeObject * __this, RuntimeObject * ___other0, const RuntimeMethod* method) { Scene_t886992912 * _thisAdjusted = reinterpret_cast(__this + 1); return Scene_Equals_m2736381267(_thisAdjusted, ___other0, method); } // System.Void UnityEngine.SceneManagement.SceneManager::Internal_SceneLoaded(UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.LoadSceneMode) extern "C" void SceneManager_Internal_SceneLoaded_m3767349395 (RuntimeObject * __this /* static, unused */, Scene_t886992912 ___scene0, int32_t ___mode1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SceneManager_Internal_SceneLoaded_m3767349395_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UnityAction_2_t1303706228 * L_0 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_sceneLoaded_0(); if (!L_0) { goto IL_0019; } } { UnityAction_2_t1303706228 * L_1 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_sceneLoaded_0(); Scene_t886992912 L_2 = ___scene0; int32_t L_3 = ___mode1; NullCheck(L_1); UnityAction_2_Invoke_m142841862(L_1, L_2, L_3, /*hidden argument*/UnityAction_2_Invoke_m142841862_RuntimeMethod_var); } IL_0019: { return; } } // System.Void UnityEngine.SceneManagement.SceneManager::Internal_SceneUnloaded(UnityEngine.SceneManagement.Scene) extern "C" void SceneManager_Internal_SceneUnloaded_m3153820635 (RuntimeObject * __this /* static, unused */, Scene_t886992912 ___scene0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SceneManager_Internal_SceneUnloaded_m3153820635_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UnityAction_1_t2300191644 * L_0 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_sceneUnloaded_1(); if (!L_0) { goto IL_0018; } } { UnityAction_1_t2300191644 * L_1 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_sceneUnloaded_1(); Scene_t886992912 L_2 = ___scene0; NullCheck(L_1); UnityAction_1_Invoke_m3288951857(L_1, L_2, /*hidden argument*/UnityAction_1_Invoke_m3288951857_RuntimeMethod_var); } IL_0018: { return; } } // System.Void UnityEngine.SceneManagement.SceneManager::Internal_ActiveSceneChanged(UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.Scene) extern "C" void SceneManager_Internal_ActiveSceneChanged_m1881093419 (RuntimeObject * __this /* static, unused */, Scene_t886992912 ___previousActiveScene0, Scene_t886992912 ___newActiveScene1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SceneManager_Internal_ActiveSceneChanged_m1881093419_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UnityAction_2_t1173199225 * L_0 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_activeSceneChanged_2(); if (!L_0) { goto IL_0019; } } { UnityAction_2_t1173199225 * L_1 = ((SceneManager_t2619984172_StaticFields*)il2cpp_codegen_static_fields_for(SceneManager_t2619984172_il2cpp_TypeInfo_var))->get_activeSceneChanged_2(); Scene_t886992912 L_2 = ___previousActiveScene0; Scene_t886992912 L_3 = ___newActiveScene1; NullCheck(L_1); UnityAction_2_Invoke_m1774221970(L_1, L_2, L_3, /*hidden argument*/UnityAction_2_Invoke_m1774221970_RuntimeMethod_var); } IL_0019: { return; } } // System.Int32 UnityEngine.Screen::get_width() extern "C" int32_t Screen_get_width_m4045119376 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef int32_t (*Screen_get_width_m4045119376_ftn) (); static Screen_get_width_m4045119376_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Screen_get_width_m4045119376_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Screen::get_width()"); int32_t retVal = _il2cpp_icall_func(); return retVal; } // System.Int32 UnityEngine.Screen::get_height() extern "C" int32_t Screen_get_height_m1431771146 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef int32_t (*Screen_get_height_m1431771146_ftn) (); static Screen_get_height_m1431771146_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Screen_get_height_m1431771146_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Screen::get_height()"); int32_t retVal = _il2cpp_icall_func(); return retVal; } // System.Single UnityEngine.Screen::get_dpi() extern "C" float Screen_get_dpi_m713551052 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef float (*Screen_get_dpi_m713551052_ftn) (); static Screen_get_dpi_m713551052_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Screen_get_dpi_m713551052_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Screen::get_dpi()"); float retVal = _il2cpp_icall_func(); return retVal; } // Conversion methods for marshalling of: UnityEngine.ScriptableObject extern "C" void ScriptableObject_t505592390_marshal_pinvoke(const ScriptableObject_t505592390& unmarshaled, ScriptableObject_t505592390_marshaled_pinvoke& marshaled) { marshaled.___m_CachedPtr_0 = reinterpret_cast((unmarshaled.get_m_CachedPtr_0()).get_m_value_0()); } extern "C" void ScriptableObject_t505592390_marshal_pinvoke_back(const ScriptableObject_t505592390_marshaled_pinvoke& marshaled, ScriptableObject_t505592390& unmarshaled) { IntPtr_t unmarshaled_m_CachedPtr_temp_0; memset(&unmarshaled_m_CachedPtr_temp_0, 0, sizeof(unmarshaled_m_CachedPtr_temp_0)); IntPtr_t unmarshaled_m_CachedPtr_temp_0_temp; unmarshaled_m_CachedPtr_temp_0_temp.set_m_value_0(reinterpret_cast((intptr_t)(marshaled.___m_CachedPtr_0))); unmarshaled_m_CachedPtr_temp_0 = unmarshaled_m_CachedPtr_temp_0_temp; unmarshaled.set_m_CachedPtr_0(unmarshaled_m_CachedPtr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.ScriptableObject extern "C" void ScriptableObject_t505592390_marshal_pinvoke_cleanup(ScriptableObject_t505592390_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.ScriptableObject extern "C" void ScriptableObject_t505592390_marshal_com(const ScriptableObject_t505592390& unmarshaled, ScriptableObject_t505592390_marshaled_com& marshaled) { marshaled.___m_CachedPtr_0 = reinterpret_cast((unmarshaled.get_m_CachedPtr_0()).get_m_value_0()); } extern "C" void ScriptableObject_t505592390_marshal_com_back(const ScriptableObject_t505592390_marshaled_com& marshaled, ScriptableObject_t505592390& unmarshaled) { IntPtr_t unmarshaled_m_CachedPtr_temp_0; memset(&unmarshaled_m_CachedPtr_temp_0, 0, sizeof(unmarshaled_m_CachedPtr_temp_0)); IntPtr_t unmarshaled_m_CachedPtr_temp_0_temp; unmarshaled_m_CachedPtr_temp_0_temp.set_m_value_0(reinterpret_cast((intptr_t)(marshaled.___m_CachedPtr_0))); unmarshaled_m_CachedPtr_temp_0 = unmarshaled_m_CachedPtr_temp_0_temp; unmarshaled.set_m_CachedPtr_0(unmarshaled_m_CachedPtr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.ScriptableObject extern "C" void ScriptableObject_t505592390_marshal_com_cleanup(ScriptableObject_t505592390_marshaled_com& marshaled) { } // System.Void UnityEngine.ScriptableObject::.ctor() extern "C" void ScriptableObject__ctor_m3935827375 (ScriptableObject_t505592390 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ScriptableObject__ctor_m3935827375_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); Object__ctor_m1201776117(__this, /*hidden argument*/NULL); ScriptableObject_Internal_CreateScriptableObject_m1796591053(NULL /*static, unused*/, __this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ScriptableObject::Internal_CreateScriptableObject(UnityEngine.ScriptableObject) extern "C" void ScriptableObject_Internal_CreateScriptableObject_m1796591053 (RuntimeObject * __this /* static, unused */, ScriptableObject_t505592390 * ___self0, const RuntimeMethod* method) { typedef void (*ScriptableObject_Internal_CreateScriptableObject_m1796591053_ftn) (ScriptableObject_t505592390 *); static ScriptableObject_Internal_CreateScriptableObject_m1796591053_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ScriptableObject_Internal_CreateScriptableObject_m1796591053_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ScriptableObject::Internal_CreateScriptableObject(UnityEngine.ScriptableObject)"); _il2cpp_icall_func(___self0); } // UnityEngine.ScriptableObject UnityEngine.ScriptableObject::CreateInstance(System.String) extern "C" ScriptableObject_t505592390 * ScriptableObject_CreateInstance_m3257090339 (RuntimeObject * __this /* static, unused */, String_t* ___className0, const RuntimeMethod* method) { typedef ScriptableObject_t505592390 * (*ScriptableObject_CreateInstance_m3257090339_ftn) (String_t*); static ScriptableObject_CreateInstance_m3257090339_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ScriptableObject_CreateInstance_m3257090339_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ScriptableObject::CreateInstance(System.String)"); ScriptableObject_t505592390 * retVal = _il2cpp_icall_func(___className0); return retVal; } // UnityEngine.ScriptableObject UnityEngine.ScriptableObject::CreateInstance(System.Type) extern "C" ScriptableObject_t505592390 * ScriptableObject_CreateInstance_m3574610820 (RuntimeObject * __this /* static, unused */, Type_t * ___type0, const RuntimeMethod* method) { ScriptableObject_t505592390 * V_0 = NULL; { Type_t * L_0 = ___type0; ScriptableObject_t505592390 * L_1 = ScriptableObject_CreateInstanceFromType_m2579013742(NULL /*static, unused*/, L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_000d; } IL_000d: { ScriptableObject_t505592390 * L_2 = V_0; return L_2; } } // UnityEngine.ScriptableObject UnityEngine.ScriptableObject::CreateInstanceFromType(System.Type) extern "C" ScriptableObject_t505592390 * ScriptableObject_CreateInstanceFromType_m2579013742 (RuntimeObject * __this /* static, unused */, Type_t * ___type0, const RuntimeMethod* method) { typedef ScriptableObject_t505592390 * (*ScriptableObject_CreateInstanceFromType_m2579013742_ftn) (Type_t *); static ScriptableObject_CreateInstanceFromType_m2579013742_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ScriptableObject_CreateInstanceFromType_m2579013742_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ScriptableObject::CreateInstanceFromType(System.Type)"); ScriptableObject_t505592390 * retVal = _il2cpp_icall_func(___type0); return retVal; } // System.Void UnityEngine.Scripting.APIUpdating.MovedFromAttribute::.ctor(System.String,System.Boolean) extern "C" void MovedFromAttribute__ctor_m2008018292 (MovedFromAttribute_t4199174457 * __this, String_t* ___sourceNamespace0, bool ___isInDifferentAssembly1, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); String_t* L_0 = ___sourceNamespace0; MovedFromAttribute_set_Namespace_m947531106(__this, L_0, /*hidden argument*/NULL); bool L_1 = ___isInDifferentAssembly1; MovedFromAttribute_set_IsInDifferentAssembly_m2839002675(__this, L_1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.Scripting.APIUpdating.MovedFromAttribute::set_Namespace(System.String) extern "C" void MovedFromAttribute_set_Namespace_m947531106 (MovedFromAttribute_t4199174457 * __this, String_t* ___value0, const RuntimeMethod* method) { { String_t* L_0 = ___value0; __this->set_U3CNamespaceU3Ek__BackingField_0(L_0); return; } } // System.Void UnityEngine.Scripting.APIUpdating.MovedFromAttribute::set_IsInDifferentAssembly(System.Boolean) extern "C" void MovedFromAttribute_set_IsInDifferentAssembly_m2839002675 (MovedFromAttribute_t4199174457 * __this, bool ___value0, const RuntimeMethod* method) { { bool L_0 = ___value0; __this->set_U3CIsInDifferentAssemblyU3Ek__BackingField_1(L_0); return; } } // System.Void UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute::.ctor() extern "C" void GeneratedByOldBindingsGeneratorAttribute__ctor_m1094570928 (GeneratedByOldBindingsGeneratorAttribute_t1965560690 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.Scripting.RequiredByNativeCodeAttribute::.ctor() extern "C" void RequiredByNativeCodeAttribute__ctor_m4150753923 (RequiredByNativeCodeAttribute_t2549902335 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.Scripting.UsedByNativeCodeAttribute::.ctor() extern "C" void UsedByNativeCodeAttribute__ctor_m115988778 (UsedByNativeCodeAttribute_t542057536 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ScrollViewState::.ctor() extern "C" void ScrollViewState__ctor_m423496794 (ScrollViewState_t3481701544 * __this, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SelectionBaseAttribute::.ctor() extern "C" void SelectionBaseAttribute__ctor_m1148743818 (SelectionBaseAttribute_t3732655813 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SendMouseEvents::SetMouseMoved() extern "C" void SendMouseEvents_SetMouseMoved_m2459912751 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SendMouseEvents_SetMouseMoved_m2459912751_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_s_MouseUsed_0((bool)1); return; } } // System.Void UnityEngine.SendMouseEvents::DoSendMouseEvents(System.Int32) extern "C" void SendMouseEvents_DoSendMouseEvents_m384073153 (RuntimeObject * __this /* static, unused */, int32_t ___skipRTCameras0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SendMouseEvents_DoSendMouseEvents_m384073153_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); int32_t V_1 = 0; int32_t V_2 = 0; HitInfo_t2268685571 V_3; memset(&V_3, 0, sizeof(V_3)); Camera_t110840138 * V_4 = NULL; CameraU5BU5D_t2507966031* V_5 = NULL; int32_t V_6 = 0; Rect_t3345319094 V_7; memset(&V_7, 0, sizeof(V_7)); GUILayer_t1356563649 * V_8 = NULL; GUIElement_t316128140 * V_9 = NULL; Ray_t3058960190 V_10; memset(&V_10, 0, sizeof(V_10)); float V_11 = 0.0f; Vector3_t67624592 V_12; memset(&V_12, 0, sizeof(V_12)); float V_13 = 0.0f; GameObject_t2923855588 * V_14 = NULL; GameObject_t2923855588 * V_15 = NULL; int32_t V_16 = 0; float G_B24_0 = 0.0f; { IL2CPP_RUNTIME_CLASS_INIT(Input_t560450644_il2cpp_TypeInfo_var); Vector3_t67624592 L_0 = Input_get_mousePosition_m3815269684(NULL /*static, unused*/, /*hidden argument*/NULL); V_0 = L_0; int32_t L_1 = Camera_get_allCamerasCount_m682204080(NULL /*static, unused*/, /*hidden argument*/NULL); V_1 = L_1; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); CameraU5BU5D_t2507966031* L_2 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_Cameras_4(); if (!L_2) { goto IL_0024; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); CameraU5BU5D_t2507966031* L_3 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_Cameras_4(); NullCheck(L_3); int32_t L_4 = V_1; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_3)->max_length))))) == ((int32_t)L_4))) { goto IL_002f; } } IL_0024: { int32_t L_5 = V_1; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_m_Cameras_4(((CameraU5BU5D_t2507966031*)SZArrayNew(CameraU5BU5D_t2507966031_il2cpp_TypeInfo_var, (uint32_t)L_5))); } IL_002f: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); CameraU5BU5D_t2507966031* L_6 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_Cameras_4(); Camera_GetAllCameras_m612307359(NULL /*static, unused*/, L_6, /*hidden argument*/NULL); V_2 = 0; goto IL_005e; } IL_0041: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_7 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); int32_t L_8 = V_2; NullCheck(L_7); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_3)); HitInfo_t2268685571 L_9 = V_3; *(HitInfo_t2268685571 *)((L_7)->GetAddressAt(static_cast(L_8))) = L_9; int32_t L_10 = V_2; V_2 = ((int32_t)((int32_t)L_10+(int32_t)1)); } IL_005e: { int32_t L_11 = V_2; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_12 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_12); if ((((int32_t)L_11) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_12)->max_length))))))) { goto IL_0041; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); bool L_13 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_s_MouseUsed_0(); if (L_13) { goto IL_02ec; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); CameraU5BU5D_t2507966031* L_14 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_Cameras_4(); V_5 = L_14; V_6 = 0; goto IL_02e0; } IL_0086: { CameraU5BU5D_t2507966031* L_15 = V_5; int32_t L_16 = V_6; NullCheck(L_15); int32_t L_17 = L_16; Camera_t110840138 * L_18 = (L_15)->GetAt(static_cast(L_17)); V_4 = L_18; Camera_t110840138 * L_19 = V_4; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_20 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_19, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (L_20) { goto IL_00b3; } } { int32_t L_21 = ___skipRTCameras0; if (!L_21) { goto IL_00b8; } } { Camera_t110840138 * L_22 = V_4; NullCheck(L_22); RenderTexture_t3726137678 * L_23 = Camera_get_targetTexture_m3559565008(L_22, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_24 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_23, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_24) { goto IL_00b8; } } IL_00b3: { goto IL_02da; } IL_00b8: { Camera_t110840138 * L_25 = V_4; NullCheck(L_25); Rect_t3345319094 L_26 = Camera_get_pixelRect_m237037586(L_25, /*hidden argument*/NULL); V_7 = L_26; Vector3_t67624592 L_27 = V_0; bool L_28 = Rect_Contains_m3823093228((&V_7), L_27, /*hidden argument*/NULL); if (L_28) { goto IL_00d3; } } { goto IL_02da; } IL_00d3: { Camera_t110840138 * L_29 = V_4; NullCheck(L_29); GUILayer_t1356563649 * L_30 = Component_GetComponent_TisGUILayer_t1356563649_m427859813(L_29, /*hidden argument*/Component_GetComponent_TisGUILayer_t1356563649_m427859813_RuntimeMethod_var); V_8 = L_30; GUILayer_t1356563649 * L_31 = V_8; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_32 = Object_op_Implicit_m3026831640(NULL /*static, unused*/, L_31, /*hidden argument*/NULL); if (!L_32) { goto IL_0154; } } { GUILayer_t1356563649 * L_33 = V_8; Vector3_t67624592 L_34 = V_0; NullCheck(L_33); GUIElement_t316128140 * L_35 = GUILayer_HitTest_m37771484(L_33, L_34, /*hidden argument*/NULL); V_9 = L_35; GUIElement_t316128140 * L_36 = V_9; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_37 = Object_op_Implicit_m3026831640(NULL /*static, unused*/, L_36, /*hidden argument*/NULL); if (!L_37) { goto IL_012f; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_38 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_38); GUIElement_t316128140 * L_39 = V_9; NullCheck(L_39); GameObject_t2923855588 * L_40 = Component_get_gameObject_m3854382865(L_39, /*hidden argument*/NULL); ((L_38)->GetAddressAt(static_cast(0)))->set_target_0(L_40); HitInfoU5BU5D_t4176695186* L_41 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_41); Camera_t110840138 * L_42 = V_4; ((L_41)->GetAddressAt(static_cast(0)))->set_camera_1(L_42); goto IL_0153; } IL_012f: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_43 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_43); ((L_43)->GetAddressAt(static_cast(0)))->set_target_0((GameObject_t2923855588 *)NULL); HitInfoU5BU5D_t4176695186* L_44 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_44); ((L_44)->GetAddressAt(static_cast(0)))->set_camera_1((Camera_t110840138 *)NULL); } IL_0153: { } IL_0154: { Camera_t110840138 * L_45 = V_4; NullCheck(L_45); int32_t L_46 = Camera_get_eventMask_m3597146787(L_45, /*hidden argument*/NULL); if (L_46) { goto IL_0165; } } { goto IL_02da; } IL_0165: { Camera_t110840138 * L_47 = V_4; Vector3_t67624592 L_48 = V_0; NullCheck(L_47); Ray_t3058960190 L_49 = Camera_ScreenPointToRay_m2745386935(L_47, L_48, /*hidden argument*/NULL); V_10 = L_49; Vector3_t67624592 L_50 = Ray_get_direction_m2485610855((&V_10), /*hidden argument*/NULL); V_12 = L_50; float L_51 = (&V_12)->get_z_3(); V_11 = L_51; float L_52 = V_11; IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_53 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, (0.0f), L_52, /*hidden argument*/NULL); if (!L_53) { goto IL_019c; } } { G_B24_0 = (std::numeric_limits::infinity()); goto IL_01b3; } IL_019c: { Camera_t110840138 * L_54 = V_4; NullCheck(L_54); float L_55 = Camera_get_farClipPlane_m334378459(L_54, /*hidden argument*/NULL); Camera_t110840138 * L_56 = V_4; NullCheck(L_56); float L_57 = Camera_get_nearClipPlane_m1776629686(L_56, /*hidden argument*/NULL); float L_58 = V_11; IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); float L_59 = fabsf(((float)((float)((float)((float)L_55-(float)L_57))/(float)L_58))); G_B24_0 = L_59; } IL_01b3: { V_13 = G_B24_0; Camera_t110840138 * L_60 = V_4; Ray_t3058960190 L_61 = V_10; float L_62 = V_13; Camera_t110840138 * L_63 = V_4; NullCheck(L_63); int32_t L_64 = Camera_get_cullingMask_m123840027(L_63, /*hidden argument*/NULL); Camera_t110840138 * L_65 = V_4; NullCheck(L_65); int32_t L_66 = Camera_get_eventMask_m3597146787(L_65, /*hidden argument*/NULL); NullCheck(L_60); GameObject_t2923855588 * L_67 = Camera_RaycastTry_m2041275581(L_60, L_61, L_62, ((int32_t)((int32_t)L_64&(int32_t)L_66)), /*hidden argument*/NULL); V_14 = L_67; GameObject_t2923855588 * L_68 = V_14; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_69 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_68, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_69) { goto IL_0209; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_70 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_70); GameObject_t2923855588 * L_71 = V_14; ((L_70)->GetAddressAt(static_cast(1)))->set_target_0(L_71); HitInfoU5BU5D_t4176695186* L_72 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_72); Camera_t110840138 * L_73 = V_4; ((L_72)->GetAddressAt(static_cast(1)))->set_camera_1(L_73); goto IL_0247; } IL_0209: { Camera_t110840138 * L_74 = V_4; NullCheck(L_74); int32_t L_75 = Camera_get_clearFlags_m3668905607(L_74, /*hidden argument*/NULL); if ((((int32_t)L_75) == ((int32_t)1))) { goto IL_0223; } } { Camera_t110840138 * L_76 = V_4; NullCheck(L_76); int32_t L_77 = Camera_get_clearFlags_m3668905607(L_76, /*hidden argument*/NULL); if ((!(((uint32_t)L_77) == ((uint32_t)2)))) { goto IL_0247; } } IL_0223: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_78 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_78); ((L_78)->GetAddressAt(static_cast(1)))->set_target_0((GameObject_t2923855588 *)NULL); HitInfoU5BU5D_t4176695186* L_79 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_79); ((L_79)->GetAddressAt(static_cast(1)))->set_camera_1((Camera_t110840138 *)NULL); } IL_0247: { Camera_t110840138 * L_80 = V_4; Ray_t3058960190 L_81 = V_10; float L_82 = V_13; Camera_t110840138 * L_83 = V_4; NullCheck(L_83); int32_t L_84 = Camera_get_cullingMask_m123840027(L_83, /*hidden argument*/NULL); Camera_t110840138 * L_85 = V_4; NullCheck(L_85); int32_t L_86 = Camera_get_eventMask_m3597146787(L_85, /*hidden argument*/NULL); NullCheck(L_80); GameObject_t2923855588 * L_87 = Camera_RaycastTry2D_m1423852821(L_80, L_81, L_82, ((int32_t)((int32_t)L_84&(int32_t)L_86)), /*hidden argument*/NULL); V_15 = L_87; GameObject_t2923855588 * L_88 = V_15; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_89 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_88, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_89) { goto IL_029b; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_90 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_90); GameObject_t2923855588 * L_91 = V_15; ((L_90)->GetAddressAt(static_cast(2)))->set_target_0(L_91); HitInfoU5BU5D_t4176695186* L_92 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_92); Camera_t110840138 * L_93 = V_4; ((L_92)->GetAddressAt(static_cast(2)))->set_camera_1(L_93); goto IL_02d9; } IL_029b: { Camera_t110840138 * L_94 = V_4; NullCheck(L_94); int32_t L_95 = Camera_get_clearFlags_m3668905607(L_94, /*hidden argument*/NULL); if ((((int32_t)L_95) == ((int32_t)1))) { goto IL_02b5; } } { Camera_t110840138 * L_96 = V_4; NullCheck(L_96); int32_t L_97 = Camera_get_clearFlags_m3668905607(L_96, /*hidden argument*/NULL); if ((!(((uint32_t)L_97) == ((uint32_t)2)))) { goto IL_02d9; } } IL_02b5: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_98 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_98); ((L_98)->GetAddressAt(static_cast(2)))->set_target_0((GameObject_t2923855588 *)NULL); HitInfoU5BU5D_t4176695186* L_99 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_99); ((L_99)->GetAddressAt(static_cast(2)))->set_camera_1((Camera_t110840138 *)NULL); } IL_02d9: { } IL_02da: { int32_t L_100 = V_6; V_6 = ((int32_t)((int32_t)L_100+(int32_t)1)); } IL_02e0: { int32_t L_101 = V_6; CameraU5BU5D_t2507966031* L_102 = V_5; NullCheck(L_102); if ((((int32_t)L_101) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_102)->max_length))))))) { goto IL_0086; } } { } IL_02ec: { V_16 = 0; goto IL_0312; } IL_02f4: { int32_t L_103 = V_16; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_104 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); int32_t L_105 = V_16; NullCheck(L_104); SendMouseEvents_SendEvents_m1146913201(NULL /*static, unused*/, L_103, (*(HitInfo_t2268685571 *)((L_104)->GetAddressAt(static_cast(L_105)))), /*hidden argument*/NULL); int32_t L_106 = V_16; V_16 = ((int32_t)((int32_t)L_106+(int32_t)1)); } IL_0312: { int32_t L_107 = V_16; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_108 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_CurrentHit_3(); NullCheck(L_108); if ((((int32_t)L_107) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_108)->max_length))))))) { goto IL_02f4; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_s_MouseUsed_0((bool)0); return; } } // System.Void UnityEngine.SendMouseEvents::SendEvents(System.Int32,UnityEngine.SendMouseEvents/HitInfo) extern "C" void SendMouseEvents_SendEvents_m1146913201 (RuntimeObject * __this /* static, unused */, int32_t ___i0, HitInfo_t2268685571 ___hit1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SendMouseEvents_SendEvents_m1146913201_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; bool V_1 = false; HitInfo_t2268685571 V_2; memset(&V_2, 0, sizeof(V_2)); { IL2CPP_RUNTIME_CLASS_INIT(Input_t560450644_il2cpp_TypeInfo_var); bool L_0 = Input_GetMouseButtonDown_m2775304371(NULL /*static, unused*/, 0, /*hidden argument*/NULL); V_0 = L_0; bool L_1 = Input_GetMouseButton_m1664028110(NULL /*static, unused*/, 0, /*hidden argument*/NULL); V_1 = L_1; bool L_2 = V_0; if (!L_2) { goto IL_004f; } } { HitInfo_t2268685571 L_3 = ___hit1; bool L_4 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); if (!L_4) { goto IL_0049; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_5 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_6 = ___i0; NullCheck(L_5); HitInfo_t2268685571 L_7 = ___hit1; *(HitInfo_t2268685571 *)((L_5)->GetAddressAt(static_cast(L_6))) = L_7; HitInfoU5BU5D_t4176695186* L_8 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_9 = ___i0; NullCheck(L_8); HitInfo_SendMessage_m3290389411(((L_8)->GetAddressAt(static_cast(L_9))), _stringLiteral2558053113, /*hidden argument*/NULL); } IL_0049: { goto IL_0107; } IL_004f: { bool L_10 = V_1; if (L_10) { goto IL_00d6; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_11 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_12 = ___i0; NullCheck(L_11); bool L_13 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, (*(HitInfo_t2268685571 *)((L_11)->GetAddressAt(static_cast(L_12)))), /*hidden argument*/NULL); if (!L_13) { goto IL_00d0; } } { HitInfo_t2268685571 L_14 = ___hit1; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_15 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_16 = ___i0; NullCheck(L_15); bool L_17 = HitInfo_Compare_m3962420595(NULL /*static, unused*/, L_14, (*(HitInfo_t2268685571 *)((L_15)->GetAddressAt(static_cast(L_16)))), /*hidden argument*/NULL); if (!L_17) { goto IL_00a1; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_18 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_19 = ___i0; NullCheck(L_18); HitInfo_SendMessage_m3290389411(((L_18)->GetAddressAt(static_cast(L_19))), _stringLiteral2906149351, /*hidden argument*/NULL); } IL_00a1: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_20 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_21 = ___i0; NullCheck(L_20); HitInfo_SendMessage_m3290389411(((L_20)->GetAddressAt(static_cast(L_21))), _stringLiteral3147111904, /*hidden argument*/NULL); HitInfoU5BU5D_t4176695186* L_22 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_23 = ___i0; NullCheck(L_22); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_2)); HitInfo_t2268685571 L_24 = V_2; *(HitInfo_t2268685571 *)((L_22)->GetAddressAt(static_cast(L_23))) = L_24; } IL_00d0: { goto IL_0107; } IL_00d6: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_25 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_26 = ___i0; NullCheck(L_25); bool L_27 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, (*(HitInfo_t2268685571 *)((L_25)->GetAddressAt(static_cast(L_26)))), /*hidden argument*/NULL); if (!L_27) { goto IL_0107; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_28 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_MouseDownHit_2(); int32_t L_29 = ___i0; NullCheck(L_28); HitInfo_SendMessage_m3290389411(((L_28)->GetAddressAt(static_cast(L_29))), _stringLiteral417825151, /*hidden argument*/NULL); } IL_0107: { HitInfo_t2268685571 L_30 = ___hit1; IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_31 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_LastHit_1(); int32_t L_32 = ___i0; NullCheck(L_31); bool L_33 = HitInfo_Compare_m3962420595(NULL /*static, unused*/, L_30, (*(HitInfo_t2268685571 *)((L_31)->GetAddressAt(static_cast(L_32)))), /*hidden argument*/NULL); if (!L_33) { goto IL_0140; } } { HitInfo_t2268685571 L_34 = ___hit1; bool L_35 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, L_34, /*hidden argument*/NULL); if (!L_35) { goto IL_013a; } } { HitInfo_SendMessage_m3290389411((&___hit1), _stringLiteral3932688994, /*hidden argument*/NULL); } IL_013a: { goto IL_0198; } IL_0140: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_36 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_LastHit_1(); int32_t L_37 = ___i0; NullCheck(L_36); bool L_38 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, (*(HitInfo_t2268685571 *)((L_36)->GetAddressAt(static_cast(L_37)))), /*hidden argument*/NULL); if (!L_38) { goto IL_0172; } } { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_39 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_LastHit_1(); int32_t L_40 = ___i0; NullCheck(L_39); HitInfo_SendMessage_m3290389411(((L_39)->GetAddressAt(static_cast(L_40))), _stringLiteral3422424824, /*hidden argument*/NULL); } IL_0172: { HitInfo_t2268685571 L_41 = ___hit1; bool L_42 = HitInfo_op_Implicit_m3724497342(NULL /*static, unused*/, L_41, /*hidden argument*/NULL); if (!L_42) { goto IL_0197; } } { HitInfo_SendMessage_m3290389411((&___hit1), _stringLiteral3662012992, /*hidden argument*/NULL); HitInfo_SendMessage_m3290389411((&___hit1), _stringLiteral3932688994, /*hidden argument*/NULL); } IL_0197: { } IL_0198: { IL2CPP_RUNTIME_CLASS_INIT(SendMouseEvents_t955851818_il2cpp_TypeInfo_var); HitInfoU5BU5D_t4176695186* L_43 = ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->get_m_LastHit_1(); int32_t L_44 = ___i0; NullCheck(L_43); HitInfo_t2268685571 L_45 = ___hit1; *(HitInfo_t2268685571 *)((L_43)->GetAddressAt(static_cast(L_44))) = L_45; return; } } // System.Void UnityEngine.SendMouseEvents::.cctor() extern "C" void SendMouseEvents__cctor_m4110553720 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SendMouseEvents__cctor_m4110553720_MetadataUsageId); s_Il2CppMethodInitialized = true; } HitInfo_t2268685571 V_0; memset(&V_0, 0, sizeof(V_0)); HitInfo_t2268685571 V_1; memset(&V_1, 0, sizeof(V_1)); HitInfo_t2268685571 V_2; memset(&V_2, 0, sizeof(V_2)); HitInfo_t2268685571 V_3; memset(&V_3, 0, sizeof(V_3)); HitInfo_t2268685571 V_4; memset(&V_4, 0, sizeof(V_4)); HitInfo_t2268685571 V_5; memset(&V_5, 0, sizeof(V_5)); HitInfo_t2268685571 V_6; memset(&V_6, 0, sizeof(V_6)); HitInfo_t2268685571 V_7; memset(&V_7, 0, sizeof(V_7)); HitInfo_t2268685571 V_8; memset(&V_8, 0, sizeof(V_8)); { ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_s_MouseUsed_0((bool)0); HitInfoU5BU5D_t4176695186* L_0 = ((HitInfoU5BU5D_t4176695186*)SZArrayNew(HitInfoU5BU5D_t4176695186_il2cpp_TypeInfo_var, (uint32_t)3)); NullCheck(L_0); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_0)); HitInfo_t2268685571 L_1 = V_0; *(HitInfo_t2268685571 *)((L_0)->GetAddressAt(static_cast(0))) = L_1; HitInfoU5BU5D_t4176695186* L_2 = L_0; NullCheck(L_2); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_1)); HitInfo_t2268685571 L_3 = V_1; *(HitInfo_t2268685571 *)((L_2)->GetAddressAt(static_cast(1))) = L_3; HitInfoU5BU5D_t4176695186* L_4 = L_2; NullCheck(L_4); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_2)); HitInfo_t2268685571 L_5 = V_2; *(HitInfo_t2268685571 *)((L_4)->GetAddressAt(static_cast(2))) = L_5; ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_m_LastHit_1(L_4); HitInfoU5BU5D_t4176695186* L_6 = ((HitInfoU5BU5D_t4176695186*)SZArrayNew(HitInfoU5BU5D_t4176695186_il2cpp_TypeInfo_var, (uint32_t)3)); NullCheck(L_6); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_3)); HitInfo_t2268685571 L_7 = V_3; *(HitInfo_t2268685571 *)((L_6)->GetAddressAt(static_cast(0))) = L_7; HitInfoU5BU5D_t4176695186* L_8 = L_6; NullCheck(L_8); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_4)); HitInfo_t2268685571 L_9 = V_4; *(HitInfo_t2268685571 *)((L_8)->GetAddressAt(static_cast(1))) = L_9; HitInfoU5BU5D_t4176695186* L_10 = L_8; NullCheck(L_10); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_5)); HitInfo_t2268685571 L_11 = V_5; *(HitInfo_t2268685571 *)((L_10)->GetAddressAt(static_cast(2))) = L_11; ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_m_MouseDownHit_2(L_10); HitInfoU5BU5D_t4176695186* L_12 = ((HitInfoU5BU5D_t4176695186*)SZArrayNew(HitInfoU5BU5D_t4176695186_il2cpp_TypeInfo_var, (uint32_t)3)); NullCheck(L_12); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_6)); HitInfo_t2268685571 L_13 = V_6; *(HitInfo_t2268685571 *)((L_12)->GetAddressAt(static_cast(0))) = L_13; HitInfoU5BU5D_t4176695186* L_14 = L_12; NullCheck(L_14); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_7)); HitInfo_t2268685571 L_15 = V_7; *(HitInfo_t2268685571 *)((L_14)->GetAddressAt(static_cast(1))) = L_15; HitInfoU5BU5D_t4176695186* L_16 = L_14; NullCheck(L_16); Initobj (HitInfo_t2268685571_il2cpp_TypeInfo_var, (&V_8)); HitInfo_t2268685571 L_17 = V_8; *(HitInfo_t2268685571 *)((L_16)->GetAddressAt(static_cast(2))) = L_17; ((SendMouseEvents_t955851818_StaticFields*)il2cpp_codegen_static_fields_for(SendMouseEvents_t955851818_il2cpp_TypeInfo_var))->set_m_CurrentHit_3(L_16); return; } } // Conversion methods for marshalling of: UnityEngine.SendMouseEvents/HitInfo extern "C" void HitInfo_t2268685571_marshal_pinvoke(const HitInfo_t2268685571& unmarshaled, HitInfo_t2268685571_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___target_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'target' of type 'HitInfo': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___target_0Exception); } extern "C" void HitInfo_t2268685571_marshal_pinvoke_back(const HitInfo_t2268685571_marshaled_pinvoke& marshaled, HitInfo_t2268685571& unmarshaled) { Il2CppCodeGenException* ___target_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'target' of type 'HitInfo': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___target_0Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SendMouseEvents/HitInfo extern "C" void HitInfo_t2268685571_marshal_pinvoke_cleanup(HitInfo_t2268685571_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.SendMouseEvents/HitInfo extern "C" void HitInfo_t2268685571_marshal_com(const HitInfo_t2268685571& unmarshaled, HitInfo_t2268685571_marshaled_com& marshaled) { Il2CppCodeGenException* ___target_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'target' of type 'HitInfo': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___target_0Exception); } extern "C" void HitInfo_t2268685571_marshal_com_back(const HitInfo_t2268685571_marshaled_com& marshaled, HitInfo_t2268685571& unmarshaled) { Il2CppCodeGenException* ___target_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'target' of type 'HitInfo': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___target_0Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SendMouseEvents/HitInfo extern "C" void HitInfo_t2268685571_marshal_com_cleanup(HitInfo_t2268685571_marshaled_com& marshaled) { } // System.Void UnityEngine.SendMouseEvents/HitInfo::SendMessage(System.String) extern "C" void HitInfo_SendMessage_m3290389411 (HitInfo_t2268685571 * __this, String_t* ___name0, const RuntimeMethod* method) { { GameObject_t2923855588 * L_0 = __this->get_target_0(); String_t* L_1 = ___name0; NullCheck(L_0); GameObject_SendMessage_m127802373(L_0, L_1, NULL, 1, /*hidden argument*/NULL); return; } } extern "C" void HitInfo_SendMessage_m3290389411_AdjustorThunk (RuntimeObject * __this, String_t* ___name0, const RuntimeMethod* method) { HitInfo_t2268685571 * _thisAdjusted = reinterpret_cast(__this + 1); HitInfo_SendMessage_m3290389411(_thisAdjusted, ___name0, method); } // System.Boolean UnityEngine.SendMouseEvents/HitInfo::op_Implicit(UnityEngine.SendMouseEvents/HitInfo) extern "C" bool HitInfo_op_Implicit_m3724497342 (RuntimeObject * __this /* static, unused */, HitInfo_t2268685571 ___exists0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (HitInfo_op_Implicit_m3724497342_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; int32_t G_B3_0 = 0; { GameObject_t2923855588 * L_0 = (&___exists0)->get_target_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0022; } } { Camera_t110840138 * L_2 = (&___exists0)->get_camera_1(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_3 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_2, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); G_B3_0 = ((int32_t)(L_3)); goto IL_0023; } IL_0022: { G_B3_0 = 0; } IL_0023: { V_0 = (bool)G_B3_0; goto IL_0029; } IL_0029: { bool L_4 = V_0; return L_4; } } // System.Boolean UnityEngine.SendMouseEvents/HitInfo::Compare(UnityEngine.SendMouseEvents/HitInfo,UnityEngine.SendMouseEvents/HitInfo) extern "C" bool HitInfo_Compare_m3962420595 (RuntimeObject * __this /* static, unused */, HitInfo_t2268685571 ___lhs0, HitInfo_t2268685571 ___rhs1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (HitInfo_Compare_m3962420595_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; int32_t G_B3_0 = 0; { GameObject_t2923855588 * L_0 = (&___lhs0)->get_target_0(); GameObject_t2923855588 * L_1 = (&___rhs1)->get_target_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_2 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_002e; } } { Camera_t110840138 * L_3 = (&___lhs0)->get_camera_1(); Camera_t110840138 * L_4 = (&___rhs1)->get_camera_1(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_5 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); G_B3_0 = ((int32_t)(L_5)); goto IL_002f; } IL_002e: { G_B3_0 = 0; } IL_002f: { V_0 = (bool)G_B3_0; goto IL_0035; } IL_0035: { bool L_6 = V_0; return L_6; } } // System.Void UnityEngine.Serialization.FormerlySerializedAsAttribute::.ctor(System.String) extern "C" void FormerlySerializedAsAttribute__ctor_m1193260366 (FormerlySerializedAsAttribute_t2004262931 * __this, String_t* ___oldName0, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); String_t* L_0 = ___oldName0; __this->set_m_oldName_0(L_0); return; } } // System.String UnityEngine.Serialization.FormerlySerializedAsAttribute::get_oldName() extern "C" String_t* FormerlySerializedAsAttribute_get_oldName_m1909070604 (FormerlySerializedAsAttribute_t2004262931 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_oldName_0(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.SerializeField::.ctor() extern "C" void SerializeField__ctor_m3116255803 (SerializeField_t2526071389 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SerializePrivateVariables::.ctor() extern "C" void SerializePrivateVariables__ctor_m1924752413 (SerializePrivateVariables_t3415835997 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SetupCoroutine::InvokeMoveNext(System.Collections.IEnumerator,System.IntPtr) extern "C" void SetupCoroutine_InvokeMoveNext_m3883473951 (RuntimeObject * __this /* static, unused */, RuntimeObject* ___enumerator0, IntPtr_t ___returnValueAddress1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SetupCoroutine_InvokeMoveNext_m3883473951_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IntPtr_t L_0 = ___returnValueAddress1; IntPtr_t L_1 = ((IntPtr_t_StaticFields*)il2cpp_codegen_static_fields_for(IntPtr_t_il2cpp_TypeInfo_var))->get_Zero_1(); bool L_2 = IntPtr_op_Equality_m148131807(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_0021; } } { ArgumentException_t270170821 * L_3 = (ArgumentException_t270170821 *)il2cpp_codegen_object_new(ArgumentException_t270170821_il2cpp_TypeInfo_var); ArgumentException__ctor_m3841295731(L_3, _stringLiteral866912693, _stringLiteral1457260809, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_3); } IL_0021: { IntPtr_t L_4 = ___returnValueAddress1; void* L_5 = IntPtr_op_Explicit_m624739794(NULL /*static, unused*/, L_4, /*hidden argument*/NULL); RuntimeObject* L_6 = ___enumerator0; NullCheck(L_6); bool L_7 = InterfaceFuncInvoker0< bool >::Invoke(1 /* System.Boolean System.Collections.IEnumerator::MoveNext() */, IEnumerator_t2002634998_il2cpp_TypeInfo_var, L_6); *((int8_t*)(L_5)) = (int8_t)L_7; return; } } // System.Object UnityEngine.SetupCoroutine::InvokeMember(System.Object,System.String,System.Object) extern "C" RuntimeObject * SetupCoroutine_InvokeMember_m817333955 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___behaviour0, String_t* ___name1, RuntimeObject * ___variable2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SetupCoroutine_InvokeMember_m817333955_MetadataUsageId); s_Il2CppMethodInitialized = true; } ObjectU5BU5D_t3885370135* V_0 = NULL; RuntimeObject * V_1 = NULL; { V_0 = (ObjectU5BU5D_t3885370135*)NULL; RuntimeObject * L_0 = ___variable2; if (!L_0) { goto IL_0016; } } { V_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)1)); ObjectU5BU5D_t3885370135* L_1 = V_0; RuntimeObject * L_2 = ___variable2; NullCheck(L_1); ArrayElementTypeCheck (L_1, L_2); (L_1)->SetAt(static_cast(0), (RuntimeObject *)L_2); } IL_0016: { RuntimeObject * L_3 = ___behaviour0; NullCheck(L_3); Type_t * L_4 = Object_GetType_m1749792582(L_3, /*hidden argument*/NULL); String_t* L_5 = ___name1; RuntimeObject * L_6 = ___behaviour0; ObjectU5BU5D_t3885370135* L_7 = V_0; NullCheck(L_4); RuntimeObject * L_8 = VirtFuncInvoker8< RuntimeObject *, String_t*, int32_t, Binder_t530160220 *, RuntimeObject *, ObjectU5BU5D_t3885370135*, ParameterModifierU5BU5D_t730609508*, CultureInfo_t703400772 *, StringU5BU5D_t3608572874* >::Invoke(75 /* System.Object System.Type::InvokeMember(System.String,System.Reflection.BindingFlags,System.Reflection.Binder,System.Object,System.Object[],System.Reflection.ParameterModifier[],System.Globalization.CultureInfo,System.String[]) */, L_4, L_5, ((int32_t)308), (Binder_t530160220 *)NULL, L_6, L_7, (ParameterModifierU5BU5D_t730609508*)(ParameterModifierU5BU5D_t730609508*)NULL, (CultureInfo_t703400772 *)NULL, (StringU5BU5D_t3608572874*)(StringU5BU5D_t3608572874*)NULL); V_1 = L_8; goto IL_0033; } IL_0033: { RuntimeObject * L_9 = V_1; return L_9; } } // UnityEngine.Shader UnityEngine.Shader::Find(System.String) extern "C" Shader_t610183752 * Shader_Find_m751989341 (RuntimeObject * __this /* static, unused */, String_t* ___name0, const RuntimeMethod* method) { typedef Shader_t610183752 * (*Shader_Find_m751989341_ftn) (String_t*); static Shader_Find_m751989341_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Shader_Find_m751989341_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Shader::Find(System.String)"); Shader_t610183752 * retVal = _il2cpp_icall_func(___name0); return retVal; } // System.Int32 UnityEngine.Shader::PropertyToID(System.String) extern "C" int32_t Shader_PropertyToID_m427373576 (RuntimeObject * __this /* static, unused */, String_t* ___name0, const RuntimeMethod* method) { typedef int32_t (*Shader_PropertyToID_m427373576_ftn) (String_t*); static Shader_PropertyToID_m427373576_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Shader_PropertyToID_m427373576_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Shader::PropertyToID(System.String)"); int32_t retVal = _il2cpp_icall_func(___name0); return retVal; } // System.Void UnityEngine.SharedBetweenAnimatorsAttribute::.ctor() extern "C" void SharedBetweenAnimatorsAttribute__ctor_m210544062 (SharedBetweenAnimatorsAttribute_t1365952581 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } // Conversion methods for marshalling of: UnityEngine.SkeletonBone extern "C" void SkeletonBone_t3980876343_marshal_pinvoke(const SkeletonBone_t3980876343& unmarshaled, SkeletonBone_t3980876343_marshaled_pinvoke& marshaled) { marshaled.___name_0 = il2cpp_codegen_marshal_string(unmarshaled.get_name_0()); marshaled.___parentName_1 = il2cpp_codegen_marshal_string(unmarshaled.get_parentName_1()); marshaled.___position_2 = unmarshaled.get_position_2(); marshaled.___rotation_3 = unmarshaled.get_rotation_3(); marshaled.___scale_4 = unmarshaled.get_scale_4(); } extern "C" void SkeletonBone_t3980876343_marshal_pinvoke_back(const SkeletonBone_t3980876343_marshaled_pinvoke& marshaled, SkeletonBone_t3980876343& unmarshaled) { unmarshaled.set_name_0(il2cpp_codegen_marshal_string_result(marshaled.___name_0)); unmarshaled.set_parentName_1(il2cpp_codegen_marshal_string_result(marshaled.___parentName_1)); Vector3_t67624592 unmarshaled_position_temp_2; memset(&unmarshaled_position_temp_2, 0, sizeof(unmarshaled_position_temp_2)); unmarshaled_position_temp_2 = marshaled.___position_2; unmarshaled.set_position_2(unmarshaled_position_temp_2); Quaternion_t4184531171 unmarshaled_rotation_temp_3; memset(&unmarshaled_rotation_temp_3, 0, sizeof(unmarshaled_rotation_temp_3)); unmarshaled_rotation_temp_3 = marshaled.___rotation_3; unmarshaled.set_rotation_3(unmarshaled_rotation_temp_3); Vector3_t67624592 unmarshaled_scale_temp_4; memset(&unmarshaled_scale_temp_4, 0, sizeof(unmarshaled_scale_temp_4)); unmarshaled_scale_temp_4 = marshaled.___scale_4; unmarshaled.set_scale_4(unmarshaled_scale_temp_4); } // Conversion method for clean up from marshalling of: UnityEngine.SkeletonBone extern "C" void SkeletonBone_t3980876343_marshal_pinvoke_cleanup(SkeletonBone_t3980876343_marshaled_pinvoke& marshaled) { il2cpp_codegen_marshal_free(marshaled.___name_0); marshaled.___name_0 = NULL; il2cpp_codegen_marshal_free(marshaled.___parentName_1); marshaled.___parentName_1 = NULL; } // Conversion methods for marshalling of: UnityEngine.SkeletonBone extern "C" void SkeletonBone_t3980876343_marshal_com(const SkeletonBone_t3980876343& unmarshaled, SkeletonBone_t3980876343_marshaled_com& marshaled) { marshaled.___name_0 = il2cpp_codegen_marshal_bstring(unmarshaled.get_name_0()); marshaled.___parentName_1 = il2cpp_codegen_marshal_bstring(unmarshaled.get_parentName_1()); marshaled.___position_2 = unmarshaled.get_position_2(); marshaled.___rotation_3 = unmarshaled.get_rotation_3(); marshaled.___scale_4 = unmarshaled.get_scale_4(); } extern "C" void SkeletonBone_t3980876343_marshal_com_back(const SkeletonBone_t3980876343_marshaled_com& marshaled, SkeletonBone_t3980876343& unmarshaled) { unmarshaled.set_name_0(il2cpp_codegen_marshal_bstring_result(marshaled.___name_0)); unmarshaled.set_parentName_1(il2cpp_codegen_marshal_bstring_result(marshaled.___parentName_1)); Vector3_t67624592 unmarshaled_position_temp_2; memset(&unmarshaled_position_temp_2, 0, sizeof(unmarshaled_position_temp_2)); unmarshaled_position_temp_2 = marshaled.___position_2; unmarshaled.set_position_2(unmarshaled_position_temp_2); Quaternion_t4184531171 unmarshaled_rotation_temp_3; memset(&unmarshaled_rotation_temp_3, 0, sizeof(unmarshaled_rotation_temp_3)); unmarshaled_rotation_temp_3 = marshaled.___rotation_3; unmarshaled.set_rotation_3(unmarshaled_rotation_temp_3); Vector3_t67624592 unmarshaled_scale_temp_4; memset(&unmarshaled_scale_temp_4, 0, sizeof(unmarshaled_scale_temp_4)); unmarshaled_scale_temp_4 = marshaled.___scale_4; unmarshaled.set_scale_4(unmarshaled_scale_temp_4); } // Conversion method for clean up from marshalling of: UnityEngine.SkeletonBone extern "C" void SkeletonBone_t3980876343_marshal_com_cleanup(SkeletonBone_t3980876343_marshaled_com& marshaled) { il2cpp_codegen_marshal_free_bstring(marshaled.___name_0); marshaled.___name_0 = NULL; il2cpp_codegen_marshal_free_bstring(marshaled.___parentName_1); marshaled.___parentName_1 = NULL; } // System.Int32 UnityEngine.SkeletonBone::get_transformModified() extern "C" int32_t SkeletonBone_get_transformModified_m3249991282 (SkeletonBone_t3980876343 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = 0; goto IL_0008; } IL_0008: { int32_t L_0 = V_0; return L_0; } } extern "C" int32_t SkeletonBone_get_transformModified_m3249991282_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { SkeletonBone_t3980876343 * _thisAdjusted = reinterpret_cast(__this + 1); return SkeletonBone_get_transformModified_m3249991282(_thisAdjusted, method); } // System.Void UnityEngine.SkeletonBone::set_transformModified(System.Int32) extern "C" void SkeletonBone_set_transformModified_m2293113419 (SkeletonBone_t3980876343 * __this, int32_t ___value0, const RuntimeMethod* method) { { return; } } extern "C" void SkeletonBone_set_transformModified_m2293113419_AdjustorThunk (RuntimeObject * __this, int32_t ___value0, const RuntimeMethod* method) { SkeletonBone_t3980876343 * _thisAdjusted = reinterpret_cast(__this + 1); SkeletonBone_set_transformModified_m2293113419(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.SliderState::.ctor() extern "C" void SliderState__ctor_m3304661917 (SliderState_t1582857496 * __this, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::.ctor() extern "C" void GameCenterPlatform__ctor_m1098683453 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ClearAchievementDescriptions(System.Int32) extern "C" void GameCenterPlatform_ClearAchievementDescriptions_m3061750857 (RuntimeObject * __this /* static, unused */, int32_t ___size0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ClearAchievementDescriptions_m3061750857_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); if (!L_0) { goto IL_0018; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); NullCheck(L_1); int32_t L_2 = ___size0; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length))))) == ((int32_t)L_2))) { goto IL_0023; } } IL_0018: { int32_t L_3 = ___size0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_adCache_1(((AchievementDescriptionU5BU5D_t916063548*)SZArrayNew(AchievementDescriptionU5BU5D_t916063548_il2cpp_TypeInfo_var, (uint32_t)L_3))); } IL_0023: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetAchievementDescription(UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData,System.Int32) extern "C" void GameCenterPlatform_SetAchievementDescription_m1606698321 (RuntimeObject * __this /* static, unused */, GcAchievementDescriptionData_t1960457254 ___data0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetAchievementDescription_m1606698321_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); int32_t L_1 = ___number1; AchievementDescription_t991053089 * L_2 = GcAchievementDescriptionData_ToAchievementDescription_m3634773672((&___data0), /*hidden argument*/NULL); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_2); (L_0)->SetAt(static_cast(L_1), (AchievementDescription_t991053089 *)L_2); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetAchievementDescriptionImage(UnityEngine.Texture2D,System.Int32) extern "C" void GameCenterPlatform_SetAchievementDescriptionImage_m1171918828 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___texture0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetAchievementDescriptionImage_m1171918828_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); NullCheck(L_0); int32_t L_1 = ___number1; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_0)->max_length))))) <= ((int32_t)L_1))) { goto IL_0015; } } { int32_t L_2 = ___number1; if ((((int32_t)L_2) >= ((int32_t)0))) { goto IL_0025; } } IL_0015: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral800264308, /*hidden argument*/NULL); goto IL_0032; } IL_0025: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_3 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); int32_t L_4 = ___number1; NullCheck(L_3); int32_t L_5 = L_4; AchievementDescription_t991053089 * L_6 = (L_3)->GetAt(static_cast(L_5)); Texture2D_t1384570725 * L_7 = ___texture0; NullCheck(L_6); AchievementDescription_SetImage_m2104624658(L_6, L_7, /*hidden argument*/NULL); } IL_0032: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::TriggerAchievementDescriptionCallback(System.Action`1) extern "C" void GameCenterPlatform_TriggerAchievementDescriptionCallback_m512691905 (RuntimeObject * __this /* static, unused */, Action_1_t4096934434 * ___callback0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_TriggerAchievementDescriptionCallback_m512691905_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t4096934434 * L_0 = ___callback0; if (!L_0) { goto IL_0034; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); if (!L_1) { goto IL_0034; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_2 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); NullCheck(L_2); if ((((int32_t)((int32_t)(((RuntimeArray *)L_2)->max_length))))) { goto IL_0028; } } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral1515164757, /*hidden argument*/NULL); } IL_0028: { Action_1_t4096934434 * L_3 = ___callback0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); AchievementDescriptionU5BU5D_t916063548* L_4 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_adCache_1(); NullCheck(L_3); Action_1_Invoke_m534614836(L_3, (IAchievementDescriptionU5BU5D_t3064410227*)(IAchievementDescriptionU5BU5D_t3064410227*)L_4, /*hidden argument*/Action_1_Invoke_m534614836_RuntimeMethod_var); } IL_0034: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::AuthenticateCallbackWrapper(System.Int32,System.String) extern "C" void GameCenterPlatform_AuthenticateCallbackWrapper_m2263980947 (RuntimeObject * __this /* static, unused */, int32_t ___result0, String_t* ___error1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_AuthenticateCallbackWrapper_m2263980947_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_2_t3787810730 * G_B3_0 = NULL; Action_2_t3787810730 * G_B2_0 = NULL; int32_t G_B4_0 = 0; Action_2_t3787810730 * G_B4_1 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_PopulateLocalUser_m2400765263(NULL /*static, unused*/, /*hidden argument*/NULL); Action_2_t3787810730 * L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_AuthenticateCallback_0(); if (!L_0) { goto IL_0031; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); Action_2_t3787810730 * L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_AuthenticateCallback_0(); int32_t L_2 = ___result0; G_B2_0 = L_1; if ((!(((uint32_t)L_2) == ((uint32_t)1)))) { G_B3_0 = L_1; goto IL_0023; } } { G_B4_0 = 1; G_B4_1 = G_B2_0; goto IL_0024; } IL_0023: { G_B4_0 = 0; G_B4_1 = G_B3_0; } IL_0024: { String_t* L_3 = ___error1; NullCheck(G_B4_1); Action_2_Invoke_m641279976(G_B4_1, (bool)G_B4_0, L_3, /*hidden argument*/Action_2_Invoke_m641279976_RuntimeMethod_var); IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_AuthenticateCallback_0((Action_2_t3787810730 *)NULL); } IL_0031: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ClearFriends(System.Int32) extern "C" void GameCenterPlatform_ClearFriends_m613985707 (RuntimeObject * __this /* static, unused */, int32_t ___size0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ClearFriends_m613985707_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); int32_t L_0 = ___size0; GameCenterPlatform_SafeClearArray_m307863322(NULL /*static, unused*/, (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_friends_2()), L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetFriends(UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData,System.Int32) extern "C" void GameCenterPlatform_SetFriends_m133258073 (RuntimeObject * __this /* static, unused */, GcUserProfileData_t265536658 ___data0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetFriends_m133258073_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); int32_t L_0 = ___number1; GcUserProfileData_AddToArray_m2882040847((&___data0), (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_friends_2()), L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetFriendImage(UnityEngine.Texture2D,System.Int32) extern "C" void GameCenterPlatform_SetFriendImage_m3088999821 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___texture0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetFriendImage_m3088999821_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); Texture2D_t1384570725 * L_0 = ___texture0; int32_t L_1 = ___number1; GameCenterPlatform_SafeSetUserImage_m1317299489(NULL /*static, unused*/, (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_friends_2()), L_0, L_1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::TriggerFriendsCallbackWrapper(System.Action`1,System.Int32) extern "C" void GameCenterPlatform_TriggerFriendsCallbackWrapper_m3241103450 (RuntimeObject * __this /* static, unused */, Action_1_t2674754663 * ___callback0, int32_t ___result1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_TriggerFriendsCallbackWrapper_m3241103450_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_1_t2674754663 * G_B5_0 = NULL; Action_1_t2674754663 * G_B4_0 = NULL; int32_t G_B6_0 = 0; Action_1_t2674754663 * G_B6_1 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); UserProfileU5BU5D_t3377267652* L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_friends_2(); if (!L_0) { goto IL_001a; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); LocalUser_t2155741069 * L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); UserProfileU5BU5D_t3377267652* L_2 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_friends_2(); NullCheck(L_1); LocalUser_SetFriends_m2359410273(L_1, (IUserProfileU5BU5D_t3867243727*)(IUserProfileU5BU5D_t3867243727*)L_2, /*hidden argument*/NULL); } IL_001a: { Action_1_t2674754663 * L_3 = ___callback0; if (!L_3) { goto IL_0034; } } { Action_1_t2674754663 * L_4 = ___callback0; int32_t L_5 = ___result1; G_B4_0 = L_4; if ((!(((uint32_t)L_5) == ((uint32_t)1)))) { G_B5_0 = L_4; goto IL_002e; } } { G_B6_0 = 1; G_B6_1 = G_B4_0; goto IL_002f; } IL_002e: { G_B6_0 = 0; G_B6_1 = G_B5_0; } IL_002f: { NullCheck(G_B6_1); Action_1_Invoke_m3062505204(G_B6_1, (bool)G_B6_0, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_0034: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::AchievementCallbackWrapper(System.Action`1,UnityEngine.SocialPlatforms.GameCenter.GcAchievementData[]) extern "C" void GameCenterPlatform_AchievementCallbackWrapper_m3148814100 (RuntimeObject * __this /* static, unused */, Action_1_t2897662423 * ___callback0, GcAchievementDataU5BU5D_t1247845579* ___result1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_AchievementCallbackWrapper_m3148814100_MetadataUsageId); s_Il2CppMethodInitialized = true; } AchievementU5BU5D_t867614507* V_0 = NULL; int32_t V_1 = 0; { Action_1_t2897662423 * L_0 = ___callback0; if (!L_0) { goto IL_004e; } } { GcAchievementDataU5BU5D_t1247845579* L_1 = ___result1; NullCheck(L_1); if ((((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length))))) { goto IL_001a; } } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral1000174466, /*hidden argument*/NULL); } IL_001a: { GcAchievementDataU5BU5D_t1247845579* L_2 = ___result1; NullCheck(L_2); V_0 = ((AchievementU5BU5D_t867614507*)SZArrayNew(AchievementU5BU5D_t867614507_il2cpp_TypeInfo_var, (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_2)->max_length)))))); V_1 = 0; goto IL_003d; } IL_002a: { AchievementU5BU5D_t867614507* L_3 = V_0; int32_t L_4 = V_1; GcAchievementDataU5BU5D_t1247845579* L_5 = ___result1; int32_t L_6 = V_1; NullCheck(L_5); Achievement_t2468443294 * L_7 = GcAchievementData_ToAchievement_m3236287768(((L_5)->GetAddressAt(static_cast(L_6))), /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_7); (L_3)->SetAt(static_cast(L_4), (Achievement_t2468443294 *)L_7); int32_t L_8 = V_1; V_1 = ((int32_t)((int32_t)L_8+(int32_t)1)); } IL_003d: { int32_t L_9 = V_1; GcAchievementDataU5BU5D_t1247845579* L_10 = ___result1; NullCheck(L_10); if ((((int32_t)L_9) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_10)->max_length))))))) { goto IL_002a; } } { Action_1_t2897662423 * L_11 = ___callback0; AchievementU5BU5D_t867614507* L_12 = V_0; NullCheck(L_11); Action_1_Invoke_m4016068893(L_11, (IAchievementU5BU5D_t1865138216*)(IAchievementU5BU5D_t1865138216*)L_12, /*hidden argument*/Action_1_Invoke_m4016068893_RuntimeMethod_var); } IL_004e: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ProgressCallbackWrapper(System.Action`1,System.Boolean) extern "C" void GameCenterPlatform_ProgressCallbackWrapper_m1646544226 (RuntimeObject * __this /* static, unused */, Action_1_t2674754663 * ___callback0, bool ___success1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ProgressCallbackWrapper_m1646544226_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t2674754663 * L_0 = ___callback0; if (!L_0) { goto IL_000e; } } { Action_1_t2674754663 * L_1 = ___callback0; bool L_2 = ___success1; NullCheck(L_1); Action_1_Invoke_m3062505204(L_1, L_2, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_000e: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ScoreCallbackWrapper(System.Action`1,System.Boolean) extern "C" void GameCenterPlatform_ScoreCallbackWrapper_m2822221228 (RuntimeObject * __this /* static, unused */, Action_1_t2674754663 * ___callback0, bool ___success1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ScoreCallbackWrapper_m2822221228_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t2674754663 * L_0 = ___callback0; if (!L_0) { goto IL_000e; } } { Action_1_t2674754663 * L_1 = ___callback0; bool L_2 = ___success1; NullCheck(L_1); Action_1_Invoke_m3062505204(L_1, L_2, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_000e: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ScoreLoaderCallbackWrapper(System.Action`1,UnityEngine.SocialPlatforms.GameCenter.GcScoreData[]) extern "C" void GameCenterPlatform_ScoreLoaderCallbackWrapper_m2682991831 (RuntimeObject * __this /* static, unused */, Action_1_t1552255288 * ___callback0, GcScoreDataU5BU5D_t859946003* ___result1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ScoreLoaderCallbackWrapper_m2682991831_MetadataUsageId); s_Il2CppMethodInitialized = true; } ScoreU5BU5D_t13505070* V_0 = NULL; int32_t V_1 = 0; { Action_1_t1552255288 * L_0 = ___callback0; if (!L_0) { goto IL_003c; } } { GcScoreDataU5BU5D_t859946003* L_1 = ___result1; NullCheck(L_1); V_0 = ((ScoreU5BU5D_t13505070*)SZArrayNew(ScoreU5BU5D_t13505070_il2cpp_TypeInfo_var, (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length)))))); V_1 = 0; goto IL_002b; } IL_0018: { ScoreU5BU5D_t13505070* L_2 = V_0; int32_t L_3 = V_1; GcScoreDataU5BU5D_t859946003* L_4 = ___result1; int32_t L_5 = V_1; NullCheck(L_4); Score_t671349143 * L_6 = GcScoreData_ToScore_m3944565042(((L_4)->GetAddressAt(static_cast(L_5))), /*hidden argument*/NULL); NullCheck(L_2); ArrayElementTypeCheck (L_2, L_6); (L_2)->SetAt(static_cast(L_3), (Score_t671349143 *)L_6); int32_t L_7 = V_1; V_1 = ((int32_t)((int32_t)L_7+(int32_t)1)); } IL_002b: { int32_t L_8 = V_1; GcScoreDataU5BU5D_t859946003* L_9 = ___result1; NullCheck(L_9); if ((((int32_t)L_8) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_9)->max_length))))))) { goto IL_0018; } } { Action_1_t1552255288 * L_10 = ___callback0; ScoreU5BU5D_t13505070* L_11 = V_0; NullCheck(L_10); Action_1_Invoke_m2262809151(L_10, (IScoreU5BU5D_t519731081*)(IScoreU5BU5D_t519731081*)L_11, /*hidden argument*/Action_1_Invoke_m2262809151_RuntimeMethod_var); } IL_003c: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::UnityEngine.SocialPlatforms.ISocialPlatform.LoadFriends(UnityEngine.SocialPlatforms.ILocalUser,System.Action`1) extern "C" void GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_LoadFriends_m328693879 (GameCenterPlatform_t1308980868 * __this, RuntimeObject* ___user0, Action_1_t2674754663 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_LoadFriends_m328693879_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_001f; } } { Action_1_t2674754663 * L_1 = ___callback1; if (!L_1) { goto IL_001a; } } { Action_1_t2674754663 * L_2 = ___callback1; NullCheck(L_2); Action_1_Invoke_m3062505204(L_2, (bool)0, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_001a: { goto IL_0025; } IL_001f: { Action_1_t2674754663 * L_3 = ___callback1; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_LoadFriends_m881374576(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); } IL_0025: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::UnityEngine.SocialPlatforms.ISocialPlatform.Authenticate(UnityEngine.SocialPlatforms.ILocalUser,System.Action`1) extern "C" void GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1866259755 (GameCenterPlatform_t1308980868 * __this, RuntimeObject* ___user0, Action_1_t2674754663 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1866259755_MetadataUsageId); s_Il2CppMethodInitialized = true; } U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * V_0 = NULL; { U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * L_0 = (U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 *)il2cpp_codegen_object_new(U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699_il2cpp_TypeInfo_var); U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0__ctor_m639058503(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * L_1 = V_0; Action_1_t2674754663 * L_2 = ___callback1; NullCheck(L_1); L_1->set_callback_0(L_2); RuntimeObject* L_3 = ___user0; U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * L_4 = V_0; IntPtr_t L_5; L_5.set_m_value_0((void*)(void*)U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_U3CU3Em__0_m2206341105_RuntimeMethod_var); Action_2_t3787810730 * L_6 = (Action_2_t3787810730 *)il2cpp_codegen_object_new(Action_2_t3787810730_il2cpp_TypeInfo_var); Action_2__ctor_m3476159000(L_6, L_4, L_5, /*hidden argument*/Action_2__ctor_m3476159000_RuntimeMethod_var); InterfaceActionInvoker2< RuntimeObject*, Action_2_t3787810730 * >::Invoke(1 /* System.Void UnityEngine.SocialPlatforms.ISocialPlatform::Authenticate(UnityEngine.SocialPlatforms.ILocalUser,System.Action`2) */, ISocialPlatform_t2229370286_il2cpp_TypeInfo_var, __this, L_3, L_6); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::UnityEngine.SocialPlatforms.ISocialPlatform.Authenticate(UnityEngine.SocialPlatforms.ILocalUser,System.Action`2) extern "C" void GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1627378436 (GameCenterPlatform_t1308980868 * __this, RuntimeObject* ___user0, Action_2_t3787810730 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_UnityEngine_SocialPlatforms_ISocialPlatform_Authenticate_m1627378436_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_2_t3787810730 * L_0 = ___callback1; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_AuthenticateCallback_0(L_0); GameCenterPlatform_Internal_Authenticate_m4080317000(NULL /*static, unused*/, /*hidden argument*/NULL); return; } } // UnityEngine.SocialPlatforms.ILocalUser UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::get_localUser() extern "C" RuntimeObject* GameCenterPlatform_get_localUser_m3939861769 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_get_localUser_m3939861769_MetadataUsageId); s_Il2CppMethodInitialized = true; } RuntimeObject* V_0 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); LocalUser_t2155741069 * L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); if (L_0) { goto IL_0015; } } { LocalUser_t2155741069 * L_1 = (LocalUser_t2155741069 *)il2cpp_codegen_object_new(LocalUser_t2155741069_il2cpp_TypeInfo_var); LocalUser__ctor_m928281921(L_1, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_m_LocalUser_5(L_1); } IL_0015: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); bool L_2 = GameCenterPlatform_Internal_Authenticated_m3332319061(NULL /*static, unused*/, /*hidden argument*/NULL); if (!L_2) { goto IL_003d; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); LocalUser_t2155741069 * L_3 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); NullCheck(L_3); String_t* L_4 = UserProfile_get_id_m2069338772(L_3, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_5 = String_op_Equality_m767991535(NULL /*static, unused*/, L_4, _stringLiteral1666647875, /*hidden argument*/NULL); if (!L_5) { goto IL_003d; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_PopulateLocalUser_m2400765263(NULL /*static, unused*/, /*hidden argument*/NULL); } IL_003d: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); LocalUser_t2155741069 * L_6 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); V_0 = L_6; goto IL_0048; } IL_0048: { RuntimeObject* L_7 = V_0; return L_7; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::PopulateLocalUser() extern "C" void GameCenterPlatform_PopulateLocalUser_m2400765263 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_PopulateLocalUser_m2400765263_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); LocalUser_t2155741069 * L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); bool L_1 = GameCenterPlatform_Internal_Authenticated_m3332319061(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_0); LocalUser_SetAuthenticated_m85368100(L_0, L_1, /*hidden argument*/NULL); LocalUser_t2155741069 * L_2 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); String_t* L_3 = GameCenterPlatform_Internal_UserName_m3116282197(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_2); UserProfile_SetUserName_m3129419512(L_2, L_3, /*hidden argument*/NULL); LocalUser_t2155741069 * L_4 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); String_t* L_5 = GameCenterPlatform_Internal_UserID_m1253806589(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_4); UserProfile_SetUserID_m836273895(L_4, L_5, /*hidden argument*/NULL); LocalUser_t2155741069 * L_6 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); bool L_7 = GameCenterPlatform_Internal_Underage_m4288143883(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_6); LocalUser_SetUnderage_m192521804(L_6, L_7, /*hidden argument*/NULL); LocalUser_t2155741069 * L_8 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_LocalUser_5(); Texture2D_t1384570725 * L_9 = GameCenterPlatform_Internal_UserImage_m890633310(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_8); UserProfile_SetImage_m4145629067(L_8, L_9, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LoadAchievementDescriptions(System.Action`1) extern "C" void GameCenterPlatform_LoadAchievementDescriptions_m69720184 (GameCenterPlatform_t1308980868 * __this, Action_1_t4096934434 * ___callback0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LoadAchievementDescriptions_m69720184_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0024; } } { Action_1_t4096934434 * L_1 = ___callback0; if (!L_1) { goto IL_001f; } } { Action_1_t4096934434 * L_2 = ___callback0; NullCheck(L_2); Action_1_Invoke_m534614836(L_2, (IAchievementDescriptionU5BU5D_t3064410227*)(IAchievementDescriptionU5BU5D_t3064410227*)((AchievementDescriptionU5BU5D_t916063548*)SZArrayNew(AchievementDescriptionU5BU5D_t916063548_il2cpp_TypeInfo_var, (uint32_t)0)), /*hidden argument*/Action_1_Invoke_m534614836_RuntimeMethod_var); } IL_001f: { goto IL_002a; } IL_0024: { Action_1_t4096934434 * L_3 = ___callback0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); } IL_002a: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ReportProgress(System.String,System.Double,System.Action`1) extern "C" void GameCenterPlatform_ReportProgress_m3320181035 (GameCenterPlatform_t1308980868 * __this, String_t* ___id0, double ___progress1, Action_1_t2674754663 * ___callback2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ReportProgress_m3320181035_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_001f; } } { Action_1_t2674754663 * L_1 = ___callback2; if (!L_1) { goto IL_001a; } } { Action_1_t2674754663 * L_2 = ___callback2; NullCheck(L_2); Action_1_Invoke_m3062505204(L_2, (bool)0, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_001a: { goto IL_0027; } IL_001f: { String_t* L_3 = ___id0; double L_4 = ___progress1; Action_1_t2674754663 * L_5 = ___callback2; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ReportProgress_m1475385389(NULL /*static, unused*/, L_3, L_4, L_5, /*hidden argument*/NULL); } IL_0027: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LoadAchievements(System.Action`1) extern "C" void GameCenterPlatform_LoadAchievements_m3779334338 (GameCenterPlatform_t1308980868 * __this, Action_1_t2897662423 * ___callback0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LoadAchievements_m3779334338_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0024; } } { Action_1_t2897662423 * L_1 = ___callback0; if (!L_1) { goto IL_001f; } } { Action_1_t2897662423 * L_2 = ___callback0; NullCheck(L_2); Action_1_Invoke_m4016068893(L_2, (IAchievementU5BU5D_t1865138216*)(IAchievementU5BU5D_t1865138216*)((AchievementU5BU5D_t867614507*)SZArrayNew(AchievementU5BU5D_t867614507_il2cpp_TypeInfo_var, (uint32_t)0)), /*hidden argument*/Action_1_Invoke_m4016068893_RuntimeMethod_var); } IL_001f: { goto IL_002a; } IL_0024: { Action_1_t2897662423 * L_3 = ___callback0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_LoadAchievements_m861185230(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); } IL_002a: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ReportScore(System.Int64,System.String,System.Action`1) extern "C" void GameCenterPlatform_ReportScore_m2179106046 (GameCenterPlatform_t1308980868 * __this, int64_t ___score0, String_t* ___board1, Action_1_t2674754663 * ___callback2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ReportScore_m2179106046_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_001f; } } { Action_1_t2674754663 * L_1 = ___callback2; if (!L_1) { goto IL_001a; } } { Action_1_t2674754663 * L_2 = ___callback2; NullCheck(L_2); Action_1_Invoke_m3062505204(L_2, (bool)0, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_001a: { goto IL_0027; } IL_001f: { int64_t L_3 = ___score0; String_t* L_4 = ___board1; Action_1_t2674754663 * L_5 = ___callback2; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ReportScore_m1150348926(NULL /*static, unused*/, L_3, L_4, L_5, /*hidden argument*/NULL); } IL_0027: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LoadScores(System.String,System.Action`1) extern "C" void GameCenterPlatform_LoadScores_m1004090045 (GameCenterPlatform_t1308980868 * __this, String_t* ___category0, Action_1_t1552255288 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LoadScores_m1004090045_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0024; } } { Action_1_t1552255288 * L_1 = ___callback1; if (!L_1) { goto IL_001f; } } { Action_1_t1552255288 * L_2 = ___callback1; NullCheck(L_2); Action_1_Invoke_m2262809151(L_2, (IScoreU5BU5D_t519731081*)(IScoreU5BU5D_t519731081*)((ScoreU5BU5D_t13505070*)SZArrayNew(ScoreU5BU5D_t13505070_il2cpp_TypeInfo_var, (uint32_t)0)), /*hidden argument*/Action_1_Invoke_m2262809151_RuntimeMethod_var); } IL_001f: { goto IL_002b; } IL_0024: { String_t* L_3 = ___category0; Action_1_t1552255288 * L_4 = ___callback1; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_LoadScores_m13855206(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LoadScores(UnityEngine.SocialPlatforms.ILeaderboard,System.Action`1) extern "C" void GameCenterPlatform_LoadScores_m3163647240 (GameCenterPlatform_t1308980868 * __this, RuntimeObject* ___board0, Action_1_t2674754663 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LoadScores_m3163647240_MetadataUsageId); s_Il2CppMethodInitialized = true; } Leaderboard_t3315266811 * V_0 = NULL; GcLeaderboard_t1761920286 * V_1 = NULL; StringU5BU5D_t3608572874* V_2 = NULL; Range_t2283206190 V_3; memset(&V_3, 0, sizeof(V_3)); Range_t2283206190 V_4; memset(&V_4, 0, sizeof(V_4)); { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_001f; } } { Action_1_t2674754663 * L_1 = ___callback1; if (!L_1) { goto IL_001a; } } { Action_1_t2674754663 * L_2 = ___callback1; NullCheck(L_2); Action_1_Invoke_m3062505204(L_2, (bool)0, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_001a: { goto IL_0080; } IL_001f: { RuntimeObject* L_3 = ___board0; V_0 = ((Leaderboard_t3315266811 *)CastclassClass((RuntimeObject*)L_3, Leaderboard_t3315266811_il2cpp_TypeInfo_var)); Leaderboard_t3315266811 * L_4 = V_0; GcLeaderboard_t1761920286 * L_5 = (GcLeaderboard_t1761920286 *)il2cpp_codegen_object_new(GcLeaderboard_t1761920286_il2cpp_TypeInfo_var); GcLeaderboard__ctor_m3620341123(L_5, L_4, /*hidden argument*/NULL); V_1 = L_5; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); List_1_t984806126 * L_6 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_GcBoards_6(); GcLeaderboard_t1761920286 * L_7 = V_1; NullCheck(L_6); List_1_Add_m4129652933(L_6, L_7, /*hidden argument*/List_1_Add_m4129652933_RuntimeMethod_var); Leaderboard_t3315266811 * L_8 = V_0; NullCheck(L_8); StringU5BU5D_t3608572874* L_9 = Leaderboard_GetUserFilter_m3311896502(L_8, /*hidden argument*/NULL); V_2 = L_9; StringU5BU5D_t3608572874* L_10 = V_2; NullCheck(L_10); if ((((int32_t)((int32_t)(((RuntimeArray *)L_10)->max_length))))) { goto IL_0049; } } { V_2 = (StringU5BU5D_t3608572874*)NULL; } IL_0049: { GcLeaderboard_t1761920286 * L_11 = V_1; RuntimeObject* L_12 = ___board0; NullCheck(L_12); String_t* L_13 = InterfaceFuncInvoker0< String_t* >::Invoke(0 /* System.String UnityEngine.SocialPlatforms.ILeaderboard::get_id() */, ILeaderboard_t2637439402_il2cpp_TypeInfo_var, L_12); RuntimeObject* L_14 = ___board0; NullCheck(L_14); Range_t2283206190 L_15 = InterfaceFuncInvoker0< Range_t2283206190 >::Invoke(2 /* UnityEngine.SocialPlatforms.Range UnityEngine.SocialPlatforms.ILeaderboard::get_range() */, ILeaderboard_t2637439402_il2cpp_TypeInfo_var, L_14); V_3 = L_15; int32_t L_16 = (&V_3)->get_from_0(); RuntimeObject* L_17 = ___board0; NullCheck(L_17); Range_t2283206190 L_18 = InterfaceFuncInvoker0< Range_t2283206190 >::Invoke(2 /* UnityEngine.SocialPlatforms.Range UnityEngine.SocialPlatforms.ILeaderboard::get_range() */, ILeaderboard_t2637439402_il2cpp_TypeInfo_var, L_17); V_4 = L_18; int32_t L_19 = (&V_4)->get_count_1(); StringU5BU5D_t3608572874* L_20 = V_2; RuntimeObject* L_21 = ___board0; NullCheck(L_21); int32_t L_22 = InterfaceFuncInvoker0< int32_t >::Invoke(1 /* UnityEngine.SocialPlatforms.UserScope UnityEngine.SocialPlatforms.ILeaderboard::get_userScope() */, ILeaderboard_t2637439402_il2cpp_TypeInfo_var, L_21); RuntimeObject* L_23 = ___board0; NullCheck(L_23); int32_t L_24 = InterfaceFuncInvoker0< int32_t >::Invoke(3 /* UnityEngine.SocialPlatforms.TimeScope UnityEngine.SocialPlatforms.ILeaderboard::get_timeScope() */, ILeaderboard_t2637439402_il2cpp_TypeInfo_var, L_23); Action_1_t2674754663 * L_25 = ___callback1; NullCheck(L_11); GcLeaderboard_Internal_LoadScores_m2378640477(L_11, L_13, L_16, L_19, L_20, L_22, L_24, L_25, /*hidden argument*/NULL); } IL_0080: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LeaderboardCallbackWrapper(System.Action`1,System.Boolean) extern "C" void GameCenterPlatform_LeaderboardCallbackWrapper_m2805116717 (RuntimeObject * __this /* static, unused */, Action_1_t2674754663 * ___callback0, bool ___success1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LeaderboardCallbackWrapper_m2805116717_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t2674754663 * L_0 = ___callback0; if (!L_0) { goto IL_000e; } } { Action_1_t2674754663 * L_1 = ___callback0; bool L_2 = ___success1; NullCheck(L_1); Action_1_Invoke_m3062505204(L_1, L_2, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_000e: { return; } } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::GetLoading(UnityEngine.SocialPlatforms.ILeaderboard) extern "C" bool GameCenterPlatform_GetLoading_m2822327733 (GameCenterPlatform_t1308980868 * __this, RuntimeObject* ___board0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_GetLoading_m2822327733_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; GcLeaderboard_t1761920286 * V_1 = NULL; Enumerator_t2673088588 V_2; memset(&V_2, 0, sizeof(V_2)); Exception_t3285241636 * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t3285241636 * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = 0; NO_UNUSED_WARNING (__leave_target); { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0013; } } { V_0 = (bool)0; goto IL_0071; } IL_0013: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); List_1_t984806126 * L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_m_GcBoards_6(); NullCheck(L_1); Enumerator_t2673088588 L_2 = List_1_GetEnumerator_m2419316156(L_1, /*hidden argument*/List_1_GetEnumerator_m2419316156_RuntimeMethod_var); V_2 = L_2; } IL_001f: try { // begin try (depth: 1) { goto IL_004b; } IL_0024: { GcLeaderboard_t1761920286 * L_3 = Enumerator_get_Current_m1279669161((&V_2), /*hidden argument*/Enumerator_get_Current_m1279669161_RuntimeMethod_var); V_1 = L_3; GcLeaderboard_t1761920286 * L_4 = V_1; RuntimeObject* L_5 = ___board0; NullCheck(L_4); bool L_6 = GcLeaderboard_Contains_m2647914426(L_4, ((Leaderboard_t3315266811 *)CastclassClass((RuntimeObject*)L_5, Leaderboard_t3315266811_il2cpp_TypeInfo_var)), /*hidden argument*/NULL); if (!L_6) { goto IL_004a; } } IL_003e: { GcLeaderboard_t1761920286 * L_7 = V_1; NullCheck(L_7); bool L_8 = GcLeaderboard_Loading_m1490059570(L_7, /*hidden argument*/NULL); V_0 = L_8; IL2CPP_LEAVE(0x71, FINALLY_005c); } IL_004a: { } IL_004b: { bool L_9 = Enumerator_MoveNext_m1938626111((&V_2), /*hidden argument*/Enumerator_MoveNext_m1938626111_RuntimeMethod_var); if (L_9) { goto IL_0024; } } IL_0057: { IL2CPP_LEAVE(0x6A, FINALLY_005c); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t3285241636 *)e.ex; goto FINALLY_005c; } FINALLY_005c: { // begin finally (depth: 1) Enumerator_Dispose_m3354874370((&V_2), /*hidden argument*/Enumerator_Dispose_m3354874370_RuntimeMethod_var); IL2CPP_END_FINALLY(92) } // end finally (depth: 1) IL2CPP_CLEANUP(92) { IL2CPP_JUMP_TBL(0x71, IL_0071) IL2CPP_JUMP_TBL(0x6A, IL_006a) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t3285241636 *) } IL_006a: { V_0 = (bool)0; goto IL_0071; } IL_0071: { bool L_10 = V_0; return L_10; } } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::VerifyAuthentication() extern "C" bool GameCenterPlatform_VerifyAuthentication_m2885445492 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_VerifyAuthentication_m2885445492_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { RuntimeObject* L_0 = GameCenterPlatform_get_localUser_m3939861769(__this, /*hidden argument*/NULL); NullCheck(L_0); bool L_1 = InterfaceFuncInvoker0< bool >::Invoke(0 /* System.Boolean UnityEngine.SocialPlatforms.ILocalUser::get_authenticated() */, ILocalUser_t1088443743_il2cpp_TypeInfo_var, L_0); if (L_1) { goto IL_0023; } } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral376256666, /*hidden argument*/NULL); V_0 = (bool)0; goto IL_002a; } IL_0023: { V_0 = (bool)1; goto IL_002a; } IL_002a: { bool L_2 = V_0; return L_2; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ShowAchievementsUI() extern "C" void GameCenterPlatform_ShowAchievementsUI_m4196866121 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ShowAchievementsUI_m4196866121_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0011; } } { goto IL_0016; } IL_0011: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629(NULL /*static, unused*/, /*hidden argument*/NULL); } IL_0016: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ShowLeaderboardUI() extern "C" void GameCenterPlatform_ShowLeaderboardUI_m2825835288 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ShowLeaderboardUI_m2825835288_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0011; } } { goto IL_0016; } IL_0011: { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824(NULL /*static, unused*/, /*hidden argument*/NULL); } IL_0016: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ClearUsers(System.Int32) extern "C" void GameCenterPlatform_ClearUsers_m1938413165 (RuntimeObject * __this /* static, unused */, int32_t ___size0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ClearUsers_m1938413165_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); int32_t L_0 = ___size0; GameCenterPlatform_SafeClearArray_m307863322(NULL /*static, unused*/, (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_users_3()), L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetUser(UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData,System.Int32) extern "C" void GameCenterPlatform_SetUser_m4141801796 (RuntimeObject * __this /* static, unused */, GcUserProfileData_t265536658 ___data0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetUser_m4141801796_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); int32_t L_0 = ___number1; GcUserProfileData_AddToArray_m2882040847((&___data0), (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_users_3()), L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SetUserImage(UnityEngine.Texture2D,System.Int32) extern "C" void GameCenterPlatform_SetUserImage_m603143526 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___texture0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SetUserImage_m603143526_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); Texture2D_t1384570725 * L_0 = ___texture0; int32_t L_1 = ___number1; GameCenterPlatform_SafeSetUserImage_m1317299489(NULL /*static, unused*/, (((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_address_of_s_users_3()), L_0, L_1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::TriggerUsersCallbackWrapper(System.Action`1) extern "C" void GameCenterPlatform_TriggerUsersCallbackWrapper_m3826154348 (RuntimeObject * __this /* static, unused */, Action_1_t604800638 * ___callback0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_TriggerUsersCallbackWrapper_m3826154348_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t604800638 * L_0 = ___callback0; if (!L_0) { goto IL_0012; } } { Action_1_t604800638 * L_1 = ___callback0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); UserProfileU5BU5D_t3377267652* L_2 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_users_3(); NullCheck(L_1); Action_1_Invoke_m4080665887(L_1, (IUserProfileU5BU5D_t3867243727*)(IUserProfileU5BU5D_t3867243727*)L_2, /*hidden argument*/Action_1_Invoke_m4080665887_RuntimeMethod_var); } IL_0012: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::LoadUsers(System.String[],System.Action`1) extern "C" void GameCenterPlatform_LoadUsers_m136435526 (GameCenterPlatform_t1308980868 * __this, StringU5BU5D_t3608572874* ___userIds0, Action_1_t604800638 * ___callback1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_LoadUsers_m136435526_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = GameCenterPlatform_VerifyAuthentication_m2885445492(__this, /*hidden argument*/NULL); if (L_0) { goto IL_0024; } } { Action_1_t604800638 * L_1 = ___callback1; if (!L_1) { goto IL_001f; } } { Action_1_t604800638 * L_2 = ___callback1; NullCheck(L_2); Action_1_Invoke_m4080665887(L_2, (IUserProfileU5BU5D_t3867243727*)(IUserProfileU5BU5D_t3867243727*)((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)0)), /*hidden argument*/Action_1_Invoke_m4080665887_RuntimeMethod_var); } IL_001f: { goto IL_002b; } IL_0024: { StringU5BU5D_t3608572874* L_3 = ___userIds0; Action_1_t604800638 * L_4 = ___callback1; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_LoadUsers_m3161987892(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SafeSetUserImage(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,UnityEngine.Texture2D,System.Int32) extern "C" void GameCenterPlatform_SafeSetUserImage_m1317299489 (RuntimeObject * __this /* static, unused */, UserProfileU5BU5D_t3377267652** ___array0, Texture2D_t1384570725 * ___texture1, int32_t ___number2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SafeSetUserImage_m1317299489_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UserProfileU5BU5D_t3377267652** L_0 = ___array0; NullCheck((*((UserProfileU5BU5D_t3377267652**)L_0))); int32_t L_1 = ___number2; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)(*((UserProfileU5BU5D_t3377267652**)L_0)))->max_length))))) <= ((int32_t)L_1))) { goto IL_0012; } } { int32_t L_2 = ___number2; if ((((int32_t)L_2) >= ((int32_t)0))) { goto IL_0029; } } IL_0012: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral2464944457, /*hidden argument*/NULL); Texture2D_t1384570725 * L_3 = (Texture2D_t1384570725 *)il2cpp_codegen_object_new(Texture2D_t1384570725_il2cpp_TypeInfo_var); Texture2D__ctor_m400428107(L_3, ((int32_t)76), ((int32_t)76), /*hidden argument*/NULL); ___texture1 = L_3; } IL_0029: { UserProfileU5BU5D_t3377267652** L_4 = ___array0; NullCheck((*((UserProfileU5BU5D_t3377267652**)L_4))); int32_t L_5 = ___number2; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)(*((UserProfileU5BU5D_t3377267652**)L_4)))->max_length))))) <= ((int32_t)L_5))) { goto IL_0049; } } { int32_t L_6 = ___number2; if ((((int32_t)L_6) < ((int32_t)0))) { goto IL_0049; } } { UserProfileU5BU5D_t3377267652** L_7 = ___array0; int32_t L_8 = ___number2; NullCheck((*((UserProfileU5BU5D_t3377267652**)L_7))); int32_t L_9 = L_8; UserProfile_t2942407481 * L_10 = ((*((UserProfileU5BU5D_t3377267652**)L_7)))->GetAt(static_cast(L_9)); Texture2D_t1384570725 * L_11 = ___texture1; NullCheck(L_10); UserProfile_SetImage_m4145629067(L_10, L_11, /*hidden argument*/NULL); goto IL_0053; } IL_0049: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral3953696827, /*hidden argument*/NULL); } IL_0053: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::SafeClearArray(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,System.Int32) extern "C" void GameCenterPlatform_SafeClearArray_m307863322 (RuntimeObject * __this /* static, unused */, UserProfileU5BU5D_t3377267652** ___array0, int32_t ___size1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_SafeClearArray_m307863322_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UserProfileU5BU5D_t3377267652** L_0 = ___array0; if (!(*((UserProfileU5BU5D_t3377267652**)L_0))) { goto IL_0012; } } { UserProfileU5BU5D_t3377267652** L_1 = ___array0; NullCheck((*((UserProfileU5BU5D_t3377267652**)L_1))); int32_t L_2 = ___size1; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)(*((UserProfileU5BU5D_t3377267652**)L_1)))->max_length))))) == ((int32_t)L_2))) { goto IL_001a; } } IL_0012: { UserProfileU5BU5D_t3377267652** L_3 = ___array0; int32_t L_4 = ___size1; *((RuntimeObject **)(L_3)) = (RuntimeObject *)((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)L_4)); Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_3), (RuntimeObject *)((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)L_4))); } IL_001a: { return; } } // UnityEngine.SocialPlatforms.ILeaderboard UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::CreateLeaderboard() extern "C" RuntimeObject* GameCenterPlatform_CreateLeaderboard_m2624606266 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_CreateLeaderboard_m2624606266_MetadataUsageId); s_Il2CppMethodInitialized = true; } Leaderboard_t3315266811 * V_0 = NULL; RuntimeObject* V_1 = NULL; { Leaderboard_t3315266811 * L_0 = (Leaderboard_t3315266811 *)il2cpp_codegen_object_new(Leaderboard_t3315266811_il2cpp_TypeInfo_var); Leaderboard__ctor_m4039976758(L_0, /*hidden argument*/NULL); V_0 = L_0; Leaderboard_t3315266811 * L_1 = V_0; V_1 = L_1; goto IL_000e; } IL_000e: { RuntimeObject* L_2 = V_1; return L_2; } } // UnityEngine.SocialPlatforms.IAchievement UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::CreateAchievement() extern "C" RuntimeObject* GameCenterPlatform_CreateAchievement_m2311892317 (GameCenterPlatform_t1308980868 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_CreateAchievement_m2311892317_MetadataUsageId); s_Il2CppMethodInitialized = true; } Achievement_t2468443294 * V_0 = NULL; RuntimeObject* V_1 = NULL; { Achievement_t2468443294 * L_0 = (Achievement_t2468443294 *)il2cpp_codegen_object_new(Achievement_t2468443294_il2cpp_TypeInfo_var); Achievement__ctor_m926077173(L_0, /*hidden argument*/NULL); V_0 = L_0; Achievement_t2468443294 * L_1 = V_0; V_1 = L_1; goto IL_000e; } IL_000e: { RuntimeObject* L_2 = V_1; return L_2; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::TriggerResetAchievementCallback(System.Boolean) extern "C" void GameCenterPlatform_TriggerResetAchievementCallback_m456631406 (RuntimeObject * __this /* static, unused */, bool ___result0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_TriggerResetAchievementCallback_m456631406_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); Action_1_t2674754663 * L_0 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_ResetAchievements_4(); if (!L_0) { goto IL_0016; } } { IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); Action_1_t2674754663 * L_1 = ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->get_s_ResetAchievements_4(); bool L_2 = ___result0; NullCheck(L_1); Action_1_Invoke_m3062505204(L_1, L_2, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); } IL_0016: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticate() extern "C" void GameCenterPlatform_Internal_Authenticate_m4080317000 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_Authenticate_m4080317000_ftn) (); static GameCenterPlatform_Internal_Authenticate_m4080317000_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_Authenticate_m4080317000_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticate()"); _il2cpp_icall_func(); } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticated() extern "C" bool GameCenterPlatform_Internal_Authenticated_m3332319061 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef bool (*GameCenterPlatform_Internal_Authenticated_m3332319061_ftn) (); static GameCenterPlatform_Internal_Authenticated_m3332319061_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_Authenticated_m3332319061_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Authenticated()"); bool retVal = _il2cpp_icall_func(); return retVal; } // System.String UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserName() extern "C" String_t* GameCenterPlatform_Internal_UserName_m3116282197 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef String_t* (*GameCenterPlatform_Internal_UserName_m3116282197_ftn) (); static GameCenterPlatform_Internal_UserName_m3116282197_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_UserName_m3116282197_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserName()"); String_t* retVal = _il2cpp_icall_func(); return retVal; } // System.String UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserID() extern "C" String_t* GameCenterPlatform_Internal_UserID_m1253806589 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef String_t* (*GameCenterPlatform_Internal_UserID_m1253806589_ftn) (); static GameCenterPlatform_Internal_UserID_m1253806589_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_UserID_m1253806589_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserID()"); String_t* retVal = _il2cpp_icall_func(); return retVal; } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Underage() extern "C" bool GameCenterPlatform_Internal_Underage_m4288143883 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef bool (*GameCenterPlatform_Internal_Underage_m4288143883_ftn) (); static GameCenterPlatform_Internal_Underage_m4288143883_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_Underage_m4288143883_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_Underage()"); bool retVal = _il2cpp_icall_func(); return retVal; } // UnityEngine.Texture2D UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserImage() extern "C" Texture2D_t1384570725 * GameCenterPlatform_Internal_UserImage_m890633310 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef Texture2D_t1384570725 * (*GameCenterPlatform_Internal_UserImage_m890633310_ftn) (); static GameCenterPlatform_Internal_UserImage_m890633310_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_UserImage_m890633310_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_UserImage()"); Texture2D_t1384570725 * retVal = _il2cpp_icall_func(); return retVal; } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadFriends(System.Object) extern "C" void GameCenterPlatform_Internal_LoadFriends_m881374576 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_LoadFriends_m881374576_ftn) (RuntimeObject *); static GameCenterPlatform_Internal_LoadFriends_m881374576_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_LoadFriends_m881374576_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadFriends(System.Object)"); _il2cpp_icall_func(___callback0); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievementDescriptions(System.Object) extern "C" void GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504_ftn) (RuntimeObject *); static GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_LoadAchievementDescriptions_m3640245504_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievementDescriptions(System.Object)"); _il2cpp_icall_func(___callback0); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievements(System.Object) extern "C" void GameCenterPlatform_Internal_LoadAchievements_m861185230 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___callback0, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_LoadAchievements_m861185230_ftn) (RuntimeObject *); static GameCenterPlatform_Internal_LoadAchievements_m861185230_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_LoadAchievements_m861185230_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadAchievements(System.Object)"); _il2cpp_icall_func(___callback0); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportProgress(System.String,System.Double,System.Object) extern "C" void GameCenterPlatform_Internal_ReportProgress_m1475385389 (RuntimeObject * __this /* static, unused */, String_t* ___id0, double ___progress1, RuntimeObject * ___callback2, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ReportProgress_m1475385389_ftn) (String_t*, double, RuntimeObject *); static GameCenterPlatform_Internal_ReportProgress_m1475385389_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ReportProgress_m1475385389_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportProgress(System.String,System.Double,System.Object)"); _il2cpp_icall_func(___id0, ___progress1, ___callback2); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportScore(System.Int64,System.String,System.Object) extern "C" void GameCenterPlatform_Internal_ReportScore_m1150348926 (RuntimeObject * __this /* static, unused */, int64_t ___score0, String_t* ___category1, RuntimeObject * ___callback2, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ReportScore_m1150348926_ftn) (int64_t, String_t*, RuntimeObject *); static GameCenterPlatform_Internal_ReportScore_m1150348926_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ReportScore_m1150348926_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ReportScore(System.Int64,System.String,System.Object)"); _il2cpp_icall_func(___score0, ___category1, ___callback2); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadScores(System.String,System.Object) extern "C" void GameCenterPlatform_Internal_LoadScores_m13855206 (RuntimeObject * __this /* static, unused */, String_t* ___category0, RuntimeObject * ___callback1, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_LoadScores_m13855206_ftn) (String_t*, RuntimeObject *); static GameCenterPlatform_Internal_LoadScores_m13855206_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_LoadScores_m13855206_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadScores(System.String,System.Object)"); _il2cpp_icall_func(___category0, ___callback1); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowAchievementsUI() extern "C" void GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629_ftn) (); static GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ShowAchievementsUI_m1219625629_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowAchievementsUI()"); _il2cpp_icall_func(); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowLeaderboardUI() extern "C" void GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824_ftn) (); static GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ShowLeaderboardUI_m2532233824_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowLeaderboardUI()"); _il2cpp_icall_func(); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadUsers(System.String[],System.Object) extern "C" void GameCenterPlatform_Internal_LoadUsers_m3161987892 (RuntimeObject * __this /* static, unused */, StringU5BU5D_t3608572874* ___userIds0, RuntimeObject * ___callback1, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_LoadUsers_m3161987892_ftn) (StringU5BU5D_t3608572874*, RuntimeObject *); static GameCenterPlatform_Internal_LoadUsers_m3161987892_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_LoadUsers_m3161987892_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_LoadUsers(System.String[],System.Object)"); _il2cpp_icall_func(___userIds0, ___callback1); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ResetAllAchievements() extern "C" void GameCenterPlatform_Internal_ResetAllAchievements_m4146765097 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ResetAllAchievements_m4146765097_ftn) (); static GameCenterPlatform_Internal_ResetAllAchievements_m4146765097_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ResetAllAchievements_m4146765097_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ResetAllAchievements()"); _il2cpp_icall_func(); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowDefaultAchievementBanner(System.Boolean) extern "C" void GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443 (RuntimeObject * __this /* static, unused */, bool ___value0, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443_ftn) (bool); static GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowDefaultAchievementBanner(System.Boolean)"); _il2cpp_icall_func(___value0); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ResetAllAchievements(System.Action`1) extern "C" void GameCenterPlatform_ResetAllAchievements_m2467887278 (RuntimeObject * __this /* static, unused */, Action_1_t2674754663 * ___callback0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ResetAllAchievements_m2467887278_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t2674754663 * L_0 = ___callback0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_ResetAchievements_4(L_0); GameCenterPlatform_Internal_ResetAllAchievements_m4146765097(NULL /*static, unused*/, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ShowDefaultAchievementCompletionBanner(System.Boolean) extern "C" void GameCenterPlatform_ShowDefaultAchievementCompletionBanner_m1663095311 (RuntimeObject * __this /* static, unused */, bool ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ShowDefaultAchievementCompletionBanner_m1663095311_MetadataUsageId); s_Il2CppMethodInitialized = true; } { bool L_0 = ___value0; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ShowDefaultAchievementBanner_m2872173443(NULL /*static, unused*/, L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::ShowLeaderboardUI(System.String,UnityEngine.SocialPlatforms.TimeScope) extern "C" void GameCenterPlatform_ShowLeaderboardUI_m194791289 (RuntimeObject * __this /* static, unused */, String_t* ___leaderboardID0, int32_t ___timeScope1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform_ShowLeaderboardUI_m194791289_MetadataUsageId); s_Il2CppMethodInitialized = true; } { String_t* L_0 = ___leaderboardID0; int32_t L_1 = ___timeScope1; IL2CPP_RUNTIME_CLASS_INIT(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var); GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowSpecificLeaderboardUI(System.String,System.Int32) extern "C" void GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488 (RuntimeObject * __this /* static, unused */, String_t* ___leaderboardID0, int32_t ___timeScope1, const RuntimeMethod* method) { typedef void (*GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488_ftn) (String_t*, int32_t); static GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GameCenterPlatform_Internal_ShowSpecificLeaderboardUI_m2188582488_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::Internal_ShowSpecificLeaderboardUI(System.String,System.Int32)"); _il2cpp_icall_func(___leaderboardID0, ___timeScope1); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform::.cctor() extern "C" void GameCenterPlatform__cctor_m2051892260 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GameCenterPlatform__cctor_m2051892260_MetadataUsageId); s_Il2CppMethodInitialized = true; } { ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_adCache_1(((AchievementDescriptionU5BU5D_t916063548*)SZArrayNew(AchievementDescriptionU5BU5D_t916063548_il2cpp_TypeInfo_var, (uint32_t)0))); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_friends_2(((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)0))); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_s_users_3(((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)0))); List_1_t984806126 * L_0 = (List_1_t984806126 *)il2cpp_codegen_object_new(List_1_t984806126_il2cpp_TypeInfo_var); List_1__ctor_m2431882546(L_0, /*hidden argument*/List_1__ctor_m2431882546_RuntimeMethod_var); ((GameCenterPlatform_t1308980868_StaticFields*)il2cpp_codegen_static_fields_for(GameCenterPlatform_t1308980868_il2cpp_TypeInfo_var))->set_m_GcBoards_6(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0::.ctor() extern "C" void U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0__ctor_m639058503 (U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * __this, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GameCenterPlatform/c__AnonStorey0::<>m__0(System.Boolean,System.String) extern "C" void U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_U3CU3Em__0_m2206341105 (U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_t4230897699 * __this, bool ___success0, String_t* ___error1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (U3CUnityEngine_SocialPlatforms_ISocialPlatform_AuthenticateU3Ec__AnonStorey0_U3CU3Em__0_m2206341105_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Action_1_t2674754663 * L_0 = __this->get_callback_0(); bool L_1 = ___success0; NullCheck(L_0); Action_1_Invoke_m3062505204(L_0, L_1, /*hidden argument*/Action_1_Invoke_m3062505204_RuntimeMethod_var); return; } } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementData extern "C" void GcAchievementData_t3004100478_marshal_pinvoke(const GcAchievementData_t3004100478& unmarshaled, GcAchievementData_t3004100478_marshaled_pinvoke& marshaled) { marshaled.___m_Identifier_0 = il2cpp_codegen_marshal_string(unmarshaled.get_m_Identifier_0()); marshaled.___m_PercentCompleted_1 = unmarshaled.get_m_PercentCompleted_1(); marshaled.___m_Completed_2 = unmarshaled.get_m_Completed_2(); marshaled.___m_Hidden_3 = unmarshaled.get_m_Hidden_3(); marshaled.___m_LastReportedDate_4 = unmarshaled.get_m_LastReportedDate_4(); } extern "C" void GcAchievementData_t3004100478_marshal_pinvoke_back(const GcAchievementData_t3004100478_marshaled_pinvoke& marshaled, GcAchievementData_t3004100478& unmarshaled) { unmarshaled.set_m_Identifier_0(il2cpp_codegen_marshal_string_result(marshaled.___m_Identifier_0)); double unmarshaled_m_PercentCompleted_temp_1 = 0.0; unmarshaled_m_PercentCompleted_temp_1 = marshaled.___m_PercentCompleted_1; unmarshaled.set_m_PercentCompleted_1(unmarshaled_m_PercentCompleted_temp_1); int32_t unmarshaled_m_Completed_temp_2 = 0; unmarshaled_m_Completed_temp_2 = marshaled.___m_Completed_2; unmarshaled.set_m_Completed_2(unmarshaled_m_Completed_temp_2); int32_t unmarshaled_m_Hidden_temp_3 = 0; unmarshaled_m_Hidden_temp_3 = marshaled.___m_Hidden_3; unmarshaled.set_m_Hidden_3(unmarshaled_m_Hidden_temp_3); int32_t unmarshaled_m_LastReportedDate_temp_4 = 0; unmarshaled_m_LastReportedDate_temp_4 = marshaled.___m_LastReportedDate_4; unmarshaled.set_m_LastReportedDate_4(unmarshaled_m_LastReportedDate_temp_4); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementData extern "C" void GcAchievementData_t3004100478_marshal_pinvoke_cleanup(GcAchievementData_t3004100478_marshaled_pinvoke& marshaled) { il2cpp_codegen_marshal_free(marshaled.___m_Identifier_0); marshaled.___m_Identifier_0 = NULL; } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementData extern "C" void GcAchievementData_t3004100478_marshal_com(const GcAchievementData_t3004100478& unmarshaled, GcAchievementData_t3004100478_marshaled_com& marshaled) { marshaled.___m_Identifier_0 = il2cpp_codegen_marshal_bstring(unmarshaled.get_m_Identifier_0()); marshaled.___m_PercentCompleted_1 = unmarshaled.get_m_PercentCompleted_1(); marshaled.___m_Completed_2 = unmarshaled.get_m_Completed_2(); marshaled.___m_Hidden_3 = unmarshaled.get_m_Hidden_3(); marshaled.___m_LastReportedDate_4 = unmarshaled.get_m_LastReportedDate_4(); } extern "C" void GcAchievementData_t3004100478_marshal_com_back(const GcAchievementData_t3004100478_marshaled_com& marshaled, GcAchievementData_t3004100478& unmarshaled) { unmarshaled.set_m_Identifier_0(il2cpp_codegen_marshal_bstring_result(marshaled.___m_Identifier_0)); double unmarshaled_m_PercentCompleted_temp_1 = 0.0; unmarshaled_m_PercentCompleted_temp_1 = marshaled.___m_PercentCompleted_1; unmarshaled.set_m_PercentCompleted_1(unmarshaled_m_PercentCompleted_temp_1); int32_t unmarshaled_m_Completed_temp_2 = 0; unmarshaled_m_Completed_temp_2 = marshaled.___m_Completed_2; unmarshaled.set_m_Completed_2(unmarshaled_m_Completed_temp_2); int32_t unmarshaled_m_Hidden_temp_3 = 0; unmarshaled_m_Hidden_temp_3 = marshaled.___m_Hidden_3; unmarshaled.set_m_Hidden_3(unmarshaled_m_Hidden_temp_3); int32_t unmarshaled_m_LastReportedDate_temp_4 = 0; unmarshaled_m_LastReportedDate_temp_4 = marshaled.___m_LastReportedDate_4; unmarshaled.set_m_LastReportedDate_4(unmarshaled_m_LastReportedDate_temp_4); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementData extern "C" void GcAchievementData_t3004100478_marshal_com_cleanup(GcAchievementData_t3004100478_marshaled_com& marshaled) { il2cpp_codegen_marshal_free_bstring(marshaled.___m_Identifier_0); marshaled.___m_Identifier_0 = NULL; } // UnityEngine.SocialPlatforms.Impl.Achievement UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::ToAchievement() extern "C" Achievement_t2468443294 * GcAchievementData_ToAchievement_m3236287768 (GcAchievementData_t3004100478 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcAchievementData_ToAchievement_m3236287768_MetadataUsageId); s_Il2CppMethodInitialized = true; } DateTime_t1205928702 V_0; memset(&V_0, 0, sizeof(V_0)); Achievement_t2468443294 * V_1 = NULL; double G_B2_0 = 0.0; String_t* G_B2_1 = NULL; double G_B1_0 = 0.0; String_t* G_B1_1 = NULL; int32_t G_B3_0 = 0; double G_B3_1 = 0.0; String_t* G_B3_2 = NULL; int32_t G_B5_0 = 0; double G_B5_1 = 0.0; String_t* G_B5_2 = NULL; int32_t G_B4_0 = 0; double G_B4_1 = 0.0; String_t* G_B4_2 = NULL; int32_t G_B6_0 = 0; int32_t G_B6_1 = 0; double G_B6_2 = 0.0; String_t* G_B6_3 = NULL; { String_t* L_0 = __this->get_m_Identifier_0(); double L_1 = __this->get_m_PercentCompleted_1(); int32_t L_2 = __this->get_m_Completed_2(); G_B1_0 = L_1; G_B1_1 = L_0; if (L_2) { G_B2_0 = L_1; G_B2_1 = L_0; goto IL_001e; } } { G_B3_0 = 0; G_B3_1 = G_B1_0; G_B3_2 = G_B1_1; goto IL_001f; } IL_001e: { G_B3_0 = 1; G_B3_1 = G_B2_0; G_B3_2 = G_B2_1; } IL_001f: { int32_t L_3 = __this->get_m_Hidden_3(); G_B4_0 = G_B3_0; G_B4_1 = G_B3_1; G_B4_2 = G_B3_2; if (L_3) { G_B5_0 = G_B3_0; G_B5_1 = G_B3_1; G_B5_2 = G_B3_2; goto IL_0030; } } { G_B6_0 = 0; G_B6_1 = G_B4_0; G_B6_2 = G_B4_1; G_B6_3 = G_B4_2; goto IL_0031; } IL_0030: { G_B6_0 = 1; G_B6_1 = G_B5_0; G_B6_2 = G_B5_1; G_B6_3 = G_B5_2; } IL_0031: { DateTime__ctor_m312241081((&V_0), ((int32_t)1970), 1, 1, 0, 0, 0, 0, /*hidden argument*/NULL); int32_t L_4 = __this->get_m_LastReportedDate_4(); DateTime_t1205928702 L_5 = DateTime_AddSeconds_m3463505250((&V_0), (((double)((double)L_4))), /*hidden argument*/NULL); Achievement_t2468443294 * L_6 = (Achievement_t2468443294 *)il2cpp_codegen_object_new(Achievement_t2468443294_il2cpp_TypeInfo_var); Achievement__ctor_m1255022360(L_6, G_B6_3, G_B6_2, (bool)G_B6_1, (bool)G_B6_0, L_5, /*hidden argument*/NULL); V_1 = L_6; goto IL_005c; } IL_005c: { Achievement_t2468443294 * L_7 = V_1; return L_7; } } extern "C" Achievement_t2468443294 * GcAchievementData_ToAchievement_m3236287768_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { GcAchievementData_t3004100478 * _thisAdjusted = reinterpret_cast(__this + 1); return GcAchievementData_ToAchievement_m3236287768(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData extern "C" void GcAchievementDescriptionData_t1960457254_marshal_pinvoke(const GcAchievementDescriptionData_t1960457254& unmarshaled, GcAchievementDescriptionData_t1960457254_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_Image_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Image' of type 'GcAchievementDescriptionData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Image_2Exception); } extern "C" void GcAchievementDescriptionData_t1960457254_marshal_pinvoke_back(const GcAchievementDescriptionData_t1960457254_marshaled_pinvoke& marshaled, GcAchievementDescriptionData_t1960457254& unmarshaled) { Il2CppCodeGenException* ___m_Image_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Image' of type 'GcAchievementDescriptionData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Image_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData extern "C" void GcAchievementDescriptionData_t1960457254_marshal_pinvoke_cleanup(GcAchievementDescriptionData_t1960457254_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData extern "C" void GcAchievementDescriptionData_t1960457254_marshal_com(const GcAchievementDescriptionData_t1960457254& unmarshaled, GcAchievementDescriptionData_t1960457254_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_Image_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Image' of type 'GcAchievementDescriptionData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Image_2Exception); } extern "C" void GcAchievementDescriptionData_t1960457254_marshal_com_back(const GcAchievementDescriptionData_t1960457254_marshaled_com& marshaled, GcAchievementDescriptionData_t1960457254& unmarshaled) { Il2CppCodeGenException* ___m_Image_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_Image' of type 'GcAchievementDescriptionData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_Image_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData extern "C" void GcAchievementDescriptionData_t1960457254_marshal_com_cleanup(GcAchievementDescriptionData_t1960457254_marshaled_com& marshaled) { } // UnityEngine.SocialPlatforms.Impl.AchievementDescription UnityEngine.SocialPlatforms.GameCenter.GcAchievementDescriptionData::ToAchievementDescription() extern "C" AchievementDescription_t991053089 * GcAchievementDescriptionData_ToAchievementDescription_m3634773672 (GcAchievementDescriptionData_t1960457254 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcAchievementDescriptionData_ToAchievementDescription_m3634773672_MetadataUsageId); s_Il2CppMethodInitialized = true; } AchievementDescription_t991053089 * V_0 = NULL; String_t* G_B2_0 = NULL; String_t* G_B2_1 = NULL; Texture2D_t1384570725 * G_B2_2 = NULL; String_t* G_B2_3 = NULL; String_t* G_B2_4 = NULL; String_t* G_B1_0 = NULL; String_t* G_B1_1 = NULL; Texture2D_t1384570725 * G_B1_2 = NULL; String_t* G_B1_3 = NULL; String_t* G_B1_4 = NULL; int32_t G_B3_0 = 0; String_t* G_B3_1 = NULL; String_t* G_B3_2 = NULL; Texture2D_t1384570725 * G_B3_3 = NULL; String_t* G_B3_4 = NULL; String_t* G_B3_5 = NULL; { String_t* L_0 = __this->get_m_Identifier_0(); String_t* L_1 = __this->get_m_Title_1(); Texture2D_t1384570725 * L_2 = __this->get_m_Image_2(); String_t* L_3 = __this->get_m_AchievedDescription_3(); String_t* L_4 = __this->get_m_UnachievedDescription_4(); int32_t L_5 = __this->get_m_Hidden_5(); G_B1_0 = L_4; G_B1_1 = L_3; G_B1_2 = L_2; G_B1_3 = L_1; G_B1_4 = L_0; if (L_5) { G_B2_0 = L_4; G_B2_1 = L_3; G_B2_2 = L_2; G_B2_3 = L_1; G_B2_4 = L_0; goto IL_0030; } } { G_B3_0 = 0; G_B3_1 = G_B1_0; G_B3_2 = G_B1_1; G_B3_3 = G_B1_2; G_B3_4 = G_B1_3; G_B3_5 = G_B1_4; goto IL_0031; } IL_0030: { G_B3_0 = 1; G_B3_1 = G_B2_0; G_B3_2 = G_B2_1; G_B3_3 = G_B2_2; G_B3_4 = G_B2_3; G_B3_5 = G_B2_4; } IL_0031: { int32_t L_6 = __this->get_m_Points_6(); AchievementDescription_t991053089 * L_7 = (AchievementDescription_t991053089 *)il2cpp_codegen_object_new(AchievementDescription_t991053089_il2cpp_TypeInfo_var); AchievementDescription__ctor_m1561486989(L_7, G_B3_5, G_B3_4, G_B3_3, G_B3_2, G_B3_1, (bool)G_B3_0, L_6, /*hidden argument*/NULL); V_0 = L_7; goto IL_0042; } IL_0042: { AchievementDescription_t991053089 * L_8 = V_0; return L_8; } } extern "C" AchievementDescription_t991053089 * GcAchievementDescriptionData_ToAchievementDescription_m3634773672_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { GcAchievementDescriptionData_t1960457254 * _thisAdjusted = reinterpret_cast(__this + 1); return GcAchievementDescriptionData_ToAchievementDescription_m3634773672(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard extern "C" void GcLeaderboard_t1761920286_marshal_pinvoke(const GcLeaderboard_t1761920286& unmarshaled, GcLeaderboard_t1761920286_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_GenericLeaderboard_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_GenericLeaderboard' of type 'GcLeaderboard': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_GenericLeaderboard_1Exception); } extern "C" void GcLeaderboard_t1761920286_marshal_pinvoke_back(const GcLeaderboard_t1761920286_marshaled_pinvoke& marshaled, GcLeaderboard_t1761920286& unmarshaled) { Il2CppCodeGenException* ___m_GenericLeaderboard_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_GenericLeaderboard' of type 'GcLeaderboard': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_GenericLeaderboard_1Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard extern "C" void GcLeaderboard_t1761920286_marshal_pinvoke_cleanup(GcLeaderboard_t1761920286_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard extern "C" void GcLeaderboard_t1761920286_marshal_com(const GcLeaderboard_t1761920286& unmarshaled, GcLeaderboard_t1761920286_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_GenericLeaderboard_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_GenericLeaderboard' of type 'GcLeaderboard': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_GenericLeaderboard_1Exception); } extern "C" void GcLeaderboard_t1761920286_marshal_com_back(const GcLeaderboard_t1761920286_marshaled_com& marshaled, GcLeaderboard_t1761920286& unmarshaled) { Il2CppCodeGenException* ___m_GenericLeaderboard_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_GenericLeaderboard' of type 'GcLeaderboard': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_GenericLeaderboard_1Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard extern "C" void GcLeaderboard_t1761920286_marshal_com_cleanup(GcLeaderboard_t1761920286_marshaled_com& marshaled) { } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::.ctor(UnityEngine.SocialPlatforms.Impl.Leaderboard) extern "C" void GcLeaderboard__ctor_m3620341123 (GcLeaderboard_t1761920286 * __this, Leaderboard_t3315266811 * ___board0, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); Leaderboard_t3315266811 * L_0 = ___board0; __this->set_m_GenericLeaderboard_1(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Finalize() extern "C" void GcLeaderboard_Finalize_m1224211017 (GcLeaderboard_t1761920286 * __this, const RuntimeMethod* method) { Exception_t3285241636 * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t3285241636 * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = 0; NO_UNUSED_WARNING (__leave_target); { } IL_0001: try { // begin try (depth: 1) GcLeaderboard_Dispose_m1078488854(__this, /*hidden argument*/NULL); IL2CPP_LEAVE(0x13, FINALLY_000c); } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t3285241636 *)e.ex; goto FINALLY_000c; } FINALLY_000c: { // begin finally (depth: 1) Object_Finalize_m3696538117(__this, /*hidden argument*/NULL); IL2CPP_END_FINALLY(12) } // end finally (depth: 1) IL2CPP_CLEANUP(12) { IL2CPP_JUMP_TBL(0x13, IL_0013) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t3285241636 *) } IL_0013: { return; } } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Contains(UnityEngine.SocialPlatforms.Impl.Leaderboard) extern "C" bool GcLeaderboard_Contains_m2647914426 (GcLeaderboard_t1761920286 * __this, Leaderboard_t3315266811 * ___board0, const RuntimeMethod* method) { bool V_0 = false; { Leaderboard_t3315266811 * L_0 = __this->get_m_GenericLeaderboard_1(); Leaderboard_t3315266811 * L_1 = ___board0; V_0 = (bool)((((RuntimeObject*)(Leaderboard_t3315266811 *)L_0) == ((RuntimeObject*)(Leaderboard_t3315266811 *)L_1))? 1 : 0); goto IL_0010; } IL_0010: { bool L_2 = V_0; return L_2; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::SetScores(UnityEngine.SocialPlatforms.GameCenter.GcScoreData[]) extern "C" void GcLeaderboard_SetScores_m865112260 (GcLeaderboard_t1761920286 * __this, GcScoreDataU5BU5D_t859946003* ___scoreDatas0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcLeaderboard_SetScores_m865112260_MetadataUsageId); s_Il2CppMethodInitialized = true; } ScoreU5BU5D_t13505070* V_0 = NULL; int32_t V_1 = 0; { Leaderboard_t3315266811 * L_0 = __this->get_m_GenericLeaderboard_1(); if (!L_0) { goto IL_0046; } } { GcScoreDataU5BU5D_t859946003* L_1 = ___scoreDatas0; NullCheck(L_1); V_0 = ((ScoreU5BU5D_t13505070*)SZArrayNew(ScoreU5BU5D_t13505070_il2cpp_TypeInfo_var, (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_1)->max_length)))))); V_1 = 0; goto IL_0030; } IL_001d: { ScoreU5BU5D_t13505070* L_2 = V_0; int32_t L_3 = V_1; GcScoreDataU5BU5D_t859946003* L_4 = ___scoreDatas0; int32_t L_5 = V_1; NullCheck(L_4); Score_t671349143 * L_6 = GcScoreData_ToScore_m3944565042(((L_4)->GetAddressAt(static_cast(L_5))), /*hidden argument*/NULL); NullCheck(L_2); ArrayElementTypeCheck (L_2, L_6); (L_2)->SetAt(static_cast(L_3), (Score_t671349143 *)L_6); int32_t L_7 = V_1; V_1 = ((int32_t)((int32_t)L_7+(int32_t)1)); } IL_0030: { int32_t L_8 = V_1; GcScoreDataU5BU5D_t859946003* L_9 = ___scoreDatas0; NullCheck(L_9); if ((((int32_t)L_8) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_9)->max_length))))))) { goto IL_001d; } } { Leaderboard_t3315266811 * L_10 = __this->get_m_GenericLeaderboard_1(); ScoreU5BU5D_t13505070* L_11 = V_0; NullCheck(L_10); Leaderboard_SetScores_m1863945428(L_10, (IScoreU5BU5D_t519731081*)(IScoreU5BU5D_t519731081*)L_11, /*hidden argument*/NULL); } IL_0046: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::SetLocalScore(UnityEngine.SocialPlatforms.GameCenter.GcScoreData) extern "C" void GcLeaderboard_SetLocalScore_m3962587913 (GcLeaderboard_t1761920286 * __this, GcScoreData_t1096391638 ___scoreData0, const RuntimeMethod* method) { { Leaderboard_t3315266811 * L_0 = __this->get_m_GenericLeaderboard_1(); if (!L_0) { goto IL_001e; } } { Leaderboard_t3315266811 * L_1 = __this->get_m_GenericLeaderboard_1(); Score_t671349143 * L_2 = GcScoreData_ToScore_m3944565042((&___scoreData0), /*hidden argument*/NULL); NullCheck(L_1); Leaderboard_SetLocalUserScore_m2947022105(L_1, L_2, /*hidden argument*/NULL); } IL_001e: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::SetMaxRange(System.UInt32) extern "C" void GcLeaderboard_SetMaxRange_m489212132 (GcLeaderboard_t1761920286 * __this, uint32_t ___maxRange0, const RuntimeMethod* method) { { Leaderboard_t3315266811 * L_0 = __this->get_m_GenericLeaderboard_1(); if (!L_0) { goto IL_0018; } } { Leaderboard_t3315266811 * L_1 = __this->get_m_GenericLeaderboard_1(); uint32_t L_2 = ___maxRange0; NullCheck(L_1); Leaderboard_SetMaxRange_m1441382126(L_1, L_2, /*hidden argument*/NULL); } IL_0018: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::SetTitle(System.String) extern "C" void GcLeaderboard_SetTitle_m1835362805 (GcLeaderboard_t1761920286 * __this, String_t* ___title0, const RuntimeMethod* method) { { Leaderboard_t3315266811 * L_0 = __this->get_m_GenericLeaderboard_1(); if (!L_0) { goto IL_0018; } } { Leaderboard_t3315266811 * L_1 = __this->get_m_GenericLeaderboard_1(); String_t* L_2 = ___title0; NullCheck(L_1); Leaderboard_SetTitle_m4254570531(L_1, L_2, /*hidden argument*/NULL); } IL_0018: { return; } } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Internal_LoadScores(System.String,System.Int32,System.Int32,System.String[],System.Int32,System.Int32,System.Object) extern "C" void GcLeaderboard_Internal_LoadScores_m2378640477 (GcLeaderboard_t1761920286 * __this, String_t* ___category0, int32_t ___from1, int32_t ___count2, StringU5BU5D_t3608572874* ___userIDs3, int32_t ___playerScope4, int32_t ___timeScope5, RuntimeObject * ___callback6, const RuntimeMethod* method) { typedef void (*GcLeaderboard_Internal_LoadScores_m2378640477_ftn) (GcLeaderboard_t1761920286 *, String_t*, int32_t, int32_t, StringU5BU5D_t3608572874*, int32_t, int32_t, RuntimeObject *); static GcLeaderboard_Internal_LoadScores_m2378640477_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GcLeaderboard_Internal_LoadScores_m2378640477_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Internal_LoadScores(System.String,System.Int32,System.Int32,System.String[],System.Int32,System.Int32,System.Object)"); _il2cpp_icall_func(__this, ___category0, ___from1, ___count2, ___userIDs3, ___playerScope4, ___timeScope5, ___callback6); } // System.Boolean UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Loading() extern "C" bool GcLeaderboard_Loading_m1490059570 (GcLeaderboard_t1761920286 * __this, const RuntimeMethod* method) { typedef bool (*GcLeaderboard_Loading_m1490059570_ftn) (GcLeaderboard_t1761920286 *); static GcLeaderboard_Loading_m1490059570_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GcLeaderboard_Loading_m1490059570_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Loading()"); bool retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Dispose() extern "C" void GcLeaderboard_Dispose_m1078488854 (GcLeaderboard_t1761920286 * __this, const RuntimeMethod* method) { typedef void (*GcLeaderboard_Dispose_m1078488854_ftn) (GcLeaderboard_t1761920286 *); static GcLeaderboard_Dispose_m1078488854_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (GcLeaderboard_Dispose_m1078488854_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SocialPlatforms.GameCenter.GcLeaderboard::Dispose()"); _il2cpp_icall_func(__this); } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcScoreData extern "C" void GcScoreData_t1096391638_marshal_pinvoke(const GcScoreData_t1096391638& unmarshaled, GcScoreData_t1096391638_marshaled_pinvoke& marshaled) { marshaled.___m_Category_0 = il2cpp_codegen_marshal_string(unmarshaled.get_m_Category_0()); marshaled.___m_ValueLow_1 = unmarshaled.get_m_ValueLow_1(); marshaled.___m_ValueHigh_2 = unmarshaled.get_m_ValueHigh_2(); marshaled.___m_Date_3 = unmarshaled.get_m_Date_3(); marshaled.___m_FormattedValue_4 = il2cpp_codegen_marshal_string(unmarshaled.get_m_FormattedValue_4()); marshaled.___m_PlayerID_5 = il2cpp_codegen_marshal_string(unmarshaled.get_m_PlayerID_5()); marshaled.___m_Rank_6 = unmarshaled.get_m_Rank_6(); } extern "C" void GcScoreData_t1096391638_marshal_pinvoke_back(const GcScoreData_t1096391638_marshaled_pinvoke& marshaled, GcScoreData_t1096391638& unmarshaled) { unmarshaled.set_m_Category_0(il2cpp_codegen_marshal_string_result(marshaled.___m_Category_0)); uint32_t unmarshaled_m_ValueLow_temp_1 = 0; unmarshaled_m_ValueLow_temp_1 = marshaled.___m_ValueLow_1; unmarshaled.set_m_ValueLow_1(unmarshaled_m_ValueLow_temp_1); int32_t unmarshaled_m_ValueHigh_temp_2 = 0; unmarshaled_m_ValueHigh_temp_2 = marshaled.___m_ValueHigh_2; unmarshaled.set_m_ValueHigh_2(unmarshaled_m_ValueHigh_temp_2); int32_t unmarshaled_m_Date_temp_3 = 0; unmarshaled_m_Date_temp_3 = marshaled.___m_Date_3; unmarshaled.set_m_Date_3(unmarshaled_m_Date_temp_3); unmarshaled.set_m_FormattedValue_4(il2cpp_codegen_marshal_string_result(marshaled.___m_FormattedValue_4)); unmarshaled.set_m_PlayerID_5(il2cpp_codegen_marshal_string_result(marshaled.___m_PlayerID_5)); int32_t unmarshaled_m_Rank_temp_6 = 0; unmarshaled_m_Rank_temp_6 = marshaled.___m_Rank_6; unmarshaled.set_m_Rank_6(unmarshaled_m_Rank_temp_6); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcScoreData extern "C" void GcScoreData_t1096391638_marshal_pinvoke_cleanup(GcScoreData_t1096391638_marshaled_pinvoke& marshaled) { il2cpp_codegen_marshal_free(marshaled.___m_Category_0); marshaled.___m_Category_0 = NULL; il2cpp_codegen_marshal_free(marshaled.___m_FormattedValue_4); marshaled.___m_FormattedValue_4 = NULL; il2cpp_codegen_marshal_free(marshaled.___m_PlayerID_5); marshaled.___m_PlayerID_5 = NULL; } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcScoreData extern "C" void GcScoreData_t1096391638_marshal_com(const GcScoreData_t1096391638& unmarshaled, GcScoreData_t1096391638_marshaled_com& marshaled) { marshaled.___m_Category_0 = il2cpp_codegen_marshal_bstring(unmarshaled.get_m_Category_0()); marshaled.___m_ValueLow_1 = unmarshaled.get_m_ValueLow_1(); marshaled.___m_ValueHigh_2 = unmarshaled.get_m_ValueHigh_2(); marshaled.___m_Date_3 = unmarshaled.get_m_Date_3(); marshaled.___m_FormattedValue_4 = il2cpp_codegen_marshal_bstring(unmarshaled.get_m_FormattedValue_4()); marshaled.___m_PlayerID_5 = il2cpp_codegen_marshal_bstring(unmarshaled.get_m_PlayerID_5()); marshaled.___m_Rank_6 = unmarshaled.get_m_Rank_6(); } extern "C" void GcScoreData_t1096391638_marshal_com_back(const GcScoreData_t1096391638_marshaled_com& marshaled, GcScoreData_t1096391638& unmarshaled) { unmarshaled.set_m_Category_0(il2cpp_codegen_marshal_bstring_result(marshaled.___m_Category_0)); uint32_t unmarshaled_m_ValueLow_temp_1 = 0; unmarshaled_m_ValueLow_temp_1 = marshaled.___m_ValueLow_1; unmarshaled.set_m_ValueLow_1(unmarshaled_m_ValueLow_temp_1); int32_t unmarshaled_m_ValueHigh_temp_2 = 0; unmarshaled_m_ValueHigh_temp_2 = marshaled.___m_ValueHigh_2; unmarshaled.set_m_ValueHigh_2(unmarshaled_m_ValueHigh_temp_2); int32_t unmarshaled_m_Date_temp_3 = 0; unmarshaled_m_Date_temp_3 = marshaled.___m_Date_3; unmarshaled.set_m_Date_3(unmarshaled_m_Date_temp_3); unmarshaled.set_m_FormattedValue_4(il2cpp_codegen_marshal_bstring_result(marshaled.___m_FormattedValue_4)); unmarshaled.set_m_PlayerID_5(il2cpp_codegen_marshal_bstring_result(marshaled.___m_PlayerID_5)); int32_t unmarshaled_m_Rank_temp_6 = 0; unmarshaled_m_Rank_temp_6 = marshaled.___m_Rank_6; unmarshaled.set_m_Rank_6(unmarshaled_m_Rank_temp_6); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcScoreData extern "C" void GcScoreData_t1096391638_marshal_com_cleanup(GcScoreData_t1096391638_marshaled_com& marshaled) { il2cpp_codegen_marshal_free_bstring(marshaled.___m_Category_0); marshaled.___m_Category_0 = NULL; il2cpp_codegen_marshal_free_bstring(marshaled.___m_FormattedValue_4); marshaled.___m_FormattedValue_4 = NULL; il2cpp_codegen_marshal_free_bstring(marshaled.___m_PlayerID_5); marshaled.___m_PlayerID_5 = NULL; } // UnityEngine.SocialPlatforms.Impl.Score UnityEngine.SocialPlatforms.GameCenter.GcScoreData::ToScore() extern "C" Score_t671349143 * GcScoreData_ToScore_m3944565042 (GcScoreData_t1096391638 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcScoreData_ToScore_m3944565042_MetadataUsageId); s_Il2CppMethodInitialized = true; } DateTime_t1205928702 V_0; memset(&V_0, 0, sizeof(V_0)); Score_t671349143 * V_1 = NULL; { String_t* L_0 = __this->get_m_Category_0(); int32_t L_1 = __this->get_m_ValueHigh_2(); uint32_t L_2 = __this->get_m_ValueLow_1(); String_t* L_3 = __this->get_m_PlayerID_5(); DateTime__ctor_m312241081((&V_0), ((int32_t)1970), 1, 1, 0, 0, 0, 0, /*hidden argument*/NULL); int32_t L_4 = __this->get_m_Date_3(); DateTime_t1205928702 L_5 = DateTime_AddSeconds_m3463505250((&V_0), (((double)((double)L_4))), /*hidden argument*/NULL); String_t* L_6 = __this->get_m_FormattedValue_4(); int32_t L_7 = __this->get_m_Rank_6(); Score_t671349143 * L_8 = (Score_t671349143 *)il2cpp_codegen_object_new(Score_t671349143_il2cpp_TypeInfo_var); Score__ctor_m1424242054(L_8, L_0, ((int64_t)((int64_t)((int64_t)((int64_t)(((int64_t)((int64_t)L_1)))<<(int32_t)((int32_t)32)))+(int64_t)(((int64_t)((uint64_t)L_2))))), L_3, L_5, L_6, L_7, /*hidden argument*/NULL); V_1 = L_8; goto IL_0056; } IL_0056: { Score_t671349143 * L_9 = V_1; return L_9; } } extern "C" Score_t671349143 * GcScoreData_ToScore_m3944565042_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { GcScoreData_t1096391638 * _thisAdjusted = reinterpret_cast(__this + 1); return GcScoreData_ToScore_m3944565042(_thisAdjusted, method); } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData extern "C" void GcUserProfileData_t265536658_marshal_pinvoke(const GcUserProfileData_t265536658& unmarshaled, GcUserProfileData_t265536658_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___image_3Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'image' of type 'GcUserProfileData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___image_3Exception); } extern "C" void GcUserProfileData_t265536658_marshal_pinvoke_back(const GcUserProfileData_t265536658_marshaled_pinvoke& marshaled, GcUserProfileData_t265536658& unmarshaled) { Il2CppCodeGenException* ___image_3Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'image' of type 'GcUserProfileData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___image_3Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData extern "C" void GcUserProfileData_t265536658_marshal_pinvoke_cleanup(GcUserProfileData_t265536658_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData extern "C" void GcUserProfileData_t265536658_marshal_com(const GcUserProfileData_t265536658& unmarshaled, GcUserProfileData_t265536658_marshaled_com& marshaled) { Il2CppCodeGenException* ___image_3Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'image' of type 'GcUserProfileData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___image_3Exception); } extern "C" void GcUserProfileData_t265536658_marshal_com_back(const GcUserProfileData_t265536658_marshaled_com& marshaled, GcUserProfileData_t265536658& unmarshaled) { Il2CppCodeGenException* ___image_3Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'image' of type 'GcUserProfileData': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___image_3Exception); } // Conversion method for clean up from marshalling of: UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData extern "C" void GcUserProfileData_t265536658_marshal_com_cleanup(GcUserProfileData_t265536658_marshaled_com& marshaled) { } // UnityEngine.SocialPlatforms.Impl.UserProfile UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::ToUserProfile() extern "C" UserProfile_t2942407481 * GcUserProfileData_ToUserProfile_m1615912729 (GcUserProfileData_t265536658 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcUserProfileData_ToUserProfile_m1615912729_MetadataUsageId); s_Il2CppMethodInitialized = true; } UserProfile_t2942407481 * V_0 = NULL; String_t* G_B2_0 = NULL; String_t* G_B2_1 = NULL; String_t* G_B1_0 = NULL; String_t* G_B1_1 = NULL; int32_t G_B3_0 = 0; String_t* G_B3_1 = NULL; String_t* G_B3_2 = NULL; { String_t* L_0 = __this->get_userName_0(); String_t* L_1 = __this->get_userID_1(); int32_t L_2 = __this->get_isFriend_2(); G_B1_0 = L_1; G_B1_1 = L_0; if ((!(((uint32_t)L_2) == ((uint32_t)1)))) { G_B2_0 = L_1; G_B2_1 = L_0; goto IL_001f; } } { G_B3_0 = 1; G_B3_1 = G_B1_0; G_B3_2 = G_B1_1; goto IL_0020; } IL_001f: { G_B3_0 = 0; G_B3_1 = G_B2_0; G_B3_2 = G_B2_1; } IL_0020: { Texture2D_t1384570725 * L_3 = __this->get_image_3(); UserProfile_t2942407481 * L_4 = (UserProfile_t2942407481 *)il2cpp_codegen_object_new(UserProfile_t2942407481_il2cpp_TypeInfo_var); UserProfile__ctor_m3004638010(L_4, G_B3_2, G_B3_1, (bool)G_B3_0, 3, L_3, /*hidden argument*/NULL); V_0 = L_4; goto IL_0032; } IL_0032: { UserProfile_t2942407481 * L_5 = V_0; return L_5; } } extern "C" UserProfile_t2942407481 * GcUserProfileData_ToUserProfile_m1615912729_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { GcUserProfileData_t265536658 * _thisAdjusted = reinterpret_cast(__this + 1); return GcUserProfileData_ToUserProfile_m1615912729(_thisAdjusted, method); } // System.Void UnityEngine.SocialPlatforms.GameCenter.GcUserProfileData::AddToArray(UnityEngine.SocialPlatforms.Impl.UserProfile[]&,System.Int32) extern "C" void GcUserProfileData_AddToArray_m2882040847 (GcUserProfileData_t265536658 * __this, UserProfileU5BU5D_t3377267652** ___array0, int32_t ___number1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (GcUserProfileData_AddToArray_m2882040847_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UserProfileU5BU5D_t3377267652** L_0 = ___array0; NullCheck((*((UserProfileU5BU5D_t3377267652**)L_0))); int32_t L_1 = ___number1; if ((((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)(*((UserProfileU5BU5D_t3377267652**)L_0)))->max_length))))) <= ((int32_t)L_1))) { goto IL_0021; } } { int32_t L_2 = ___number1; if ((((int32_t)L_2) < ((int32_t)0))) { goto IL_0021; } } { UserProfileU5BU5D_t3377267652** L_3 = ___array0; int32_t L_4 = ___number1; UserProfile_t2942407481 * L_5 = GcUserProfileData_ToUserProfile_m1615912729(__this, /*hidden argument*/NULL); NullCheck((*((UserProfileU5BU5D_t3377267652**)L_3))); ArrayElementTypeCheck ((*((UserProfileU5BU5D_t3377267652**)L_3)), L_5); ((*((UserProfileU5BU5D_t3377267652**)L_3)))->SetAt(static_cast(L_4), (UserProfile_t2942407481 *)L_5); goto IL_002b; } IL_0021: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_Log_m482196963(NULL /*static, unused*/, _stringLiteral3922184876, /*hidden argument*/NULL); } IL_002b: { return; } } extern "C" void GcUserProfileData_AddToArray_m2882040847_AdjustorThunk (RuntimeObject * __this, UserProfileU5BU5D_t3377267652** ___array0, int32_t ___number1, const RuntimeMethod* method) { GcUserProfileData_t265536658 * _thisAdjusted = reinterpret_cast(__this + 1); GcUserProfileData_AddToArray_m2882040847(_thisAdjusted, ___array0, ___number1, method); } // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor(System.String,System.Double,System.Boolean,System.Boolean,System.DateTime) extern "C" void Achievement__ctor_m1255022360 (Achievement_t2468443294 * __this, String_t* ___id0, double ___percentCompleted1, bool ___completed2, bool ___hidden3, DateTime_t1205928702 ___lastReportedDate4, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); String_t* L_0 = ___id0; Achievement_set_id_m1587115024(__this, L_0, /*hidden argument*/NULL); double L_1 = ___percentCompleted1; Achievement_set_percentCompleted_m2528710724(__this, L_1, /*hidden argument*/NULL); bool L_2 = ___completed2; __this->set_m_Completed_0(L_2); bool L_3 = ___hidden3; __this->set_m_Hidden_1(L_3); DateTime_t1205928702 L_4 = ___lastReportedDate4; __this->set_m_LastReportedDate_2(L_4); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor(System.String,System.Double) extern "C" void Achievement__ctor_m2199514267 (Achievement_t2468443294 * __this, String_t* ___id0, double ___percent1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Achievement__ctor_m2199514267_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); String_t* L_0 = ___id0; Achievement_set_id_m1587115024(__this, L_0, /*hidden argument*/NULL); double L_1 = ___percent1; Achievement_set_percentCompleted_m2528710724(__this, L_1, /*hidden argument*/NULL); __this->set_m_Hidden_1((bool)0); __this->set_m_Completed_0((bool)0); IL2CPP_RUNTIME_CLASS_INIT(DateTime_t1205928702_il2cpp_TypeInfo_var); DateTime_t1205928702 L_2 = ((DateTime_t1205928702_StaticFields*)il2cpp_codegen_static_fields_for(DateTime_t1205928702_il2cpp_TypeInfo_var))->get_MinValue_13(); __this->set_m_LastReportedDate_2(L_2); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::.ctor() extern "C" void Achievement__ctor_m926077173 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Achievement__ctor_m926077173_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Achievement__ctor_m2199514267(__this, _stringLiteral3933156751, (0.0), /*hidden argument*/NULL); return; } } // System.String UnityEngine.SocialPlatforms.Impl.Achievement::ToString() extern "C" String_t* Achievement_ToString_m3086492804 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Achievement_ToString_m3086492804_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)((int32_t)9))); String_t* L_1 = Achievement_get_id_m4009128591(__this, /*hidden argument*/NULL); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_1); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_1); ObjectU5BU5D_t3885370135* L_2 = L_0; NullCheck(L_2); ArrayElementTypeCheck (L_2, _stringLiteral41011391); (L_2)->SetAt(static_cast(1), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_3 = L_2; double L_4 = Achievement_get_percentCompleted_m1210462574(__this, /*hidden argument*/NULL); double L_5 = L_4; RuntimeObject * L_6 = Box(Double_t2492335957_il2cpp_TypeInfo_var, &L_5); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_6); (L_3)->SetAt(static_cast(2), (RuntimeObject *)L_6); ObjectU5BU5D_t3885370135* L_7 = L_3; NullCheck(L_7); ArrayElementTypeCheck (L_7, _stringLiteral41011391); (L_7)->SetAt(static_cast(3), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_8 = L_7; bool L_9 = Achievement_get_completed_m1034346610(__this, /*hidden argument*/NULL); bool L_10 = L_9; RuntimeObject * L_11 = Box(Boolean_t1642230456_il2cpp_TypeInfo_var, &L_10); NullCheck(L_8); ArrayElementTypeCheck (L_8, L_11); (L_8)->SetAt(static_cast(4), (RuntimeObject *)L_11); ObjectU5BU5D_t3885370135* L_12 = L_8; NullCheck(L_12); ArrayElementTypeCheck (L_12, _stringLiteral41011391); (L_12)->SetAt(static_cast(5), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_13 = L_12; bool L_14 = Achievement_get_hidden_m1511076689(__this, /*hidden argument*/NULL); bool L_15 = L_14; RuntimeObject * L_16 = Box(Boolean_t1642230456_il2cpp_TypeInfo_var, &L_15); NullCheck(L_13); ArrayElementTypeCheck (L_13, L_16); (L_13)->SetAt(static_cast(6), (RuntimeObject *)L_16); ObjectU5BU5D_t3885370135* L_17 = L_13; NullCheck(L_17); ArrayElementTypeCheck (L_17, _stringLiteral41011391); (L_17)->SetAt(static_cast(7), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_18 = L_17; DateTime_t1205928702 L_19 = Achievement_get_lastReportedDate_m2623896959(__this, /*hidden argument*/NULL); DateTime_t1205928702 L_20 = L_19; RuntimeObject * L_21 = Box(DateTime_t1205928702_il2cpp_TypeInfo_var, &L_20); NullCheck(L_18); ArrayElementTypeCheck (L_18, L_21); (L_18)->SetAt(static_cast(8), (RuntimeObject *)L_21); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_22 = String_Concat_m2150944860(NULL /*static, unused*/, L_18, /*hidden argument*/NULL); V_0 = L_22; goto IL_0074; } IL_0074: { String_t* L_23 = V_0; return L_23; } } // System.String UnityEngine.SocialPlatforms.Impl.Achievement::get_id() extern "C" String_t* Achievement_get_id_m4009128591 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_U3CidU3Ek__BackingField_3(); V_0 = L_0; goto IL_000c; } IL_000c: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::set_id(System.String) extern "C" void Achievement_set_id_m1587115024 (Achievement_t2468443294 * __this, String_t* ___value0, const RuntimeMethod* method) { { String_t* L_0 = ___value0; __this->set_U3CidU3Ek__BackingField_3(L_0); return; } } // System.Double UnityEngine.SocialPlatforms.Impl.Achievement::get_percentCompleted() extern "C" double Achievement_get_percentCompleted_m1210462574 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { double V_0 = 0.0; { double L_0 = __this->get_U3CpercentCompletedU3Ek__BackingField_4(); V_0 = L_0; goto IL_000c; } IL_000c: { double L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Achievement::set_percentCompleted(System.Double) extern "C" void Achievement_set_percentCompleted_m2528710724 (Achievement_t2468443294 * __this, double ___value0, const RuntimeMethod* method) { { double L_0 = ___value0; __this->set_U3CpercentCompletedU3Ek__BackingField_4(L_0); return; } } // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::get_completed() extern "C" bool Achievement_get_completed_m1034346610 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { bool V_0 = false; { bool L_0 = __this->get_m_Completed_0(); V_0 = L_0; goto IL_000d; } IL_000d: { bool L_1 = V_0; return L_1; } } // System.Boolean UnityEngine.SocialPlatforms.Impl.Achievement::get_hidden() extern "C" bool Achievement_get_hidden_m1511076689 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { bool V_0 = false; { bool L_0 = __this->get_m_Hidden_1(); V_0 = L_0; goto IL_000d; } IL_000d: { bool L_1 = V_0; return L_1; } } // System.DateTime UnityEngine.SocialPlatforms.Impl.Achievement::get_lastReportedDate() extern "C" DateTime_t1205928702 Achievement_get_lastReportedDate_m2623896959 (Achievement_t2468443294 * __this, const RuntimeMethod* method) { DateTime_t1205928702 V_0; memset(&V_0, 0, sizeof(V_0)); { DateTime_t1205928702 L_0 = __this->get_m_LastReportedDate_2(); V_0 = L_0; goto IL_000d; } IL_000d: { DateTime_t1205928702 L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::.ctor(System.String,System.String,UnityEngine.Texture2D,System.String,System.String,System.Boolean,System.Int32) extern "C" void AchievementDescription__ctor_m1561486989 (AchievementDescription_t991053089 * __this, String_t* ___id0, String_t* ___title1, Texture2D_t1384570725 * ___image2, String_t* ___achievedDescription3, String_t* ___unachievedDescription4, bool ___hidden5, int32_t ___points6, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); String_t* L_0 = ___id0; AchievementDescription_set_id_m1561483604(__this, L_0, /*hidden argument*/NULL); String_t* L_1 = ___title1; __this->set_m_Title_0(L_1); Texture2D_t1384570725 * L_2 = ___image2; __this->set_m_Image_1(L_2); String_t* L_3 = ___achievedDescription3; __this->set_m_AchievedDescription_2(L_3); String_t* L_4 = ___unachievedDescription4; __this->set_m_UnachievedDescription_3(L_4); bool L_5 = ___hidden5; __this->set_m_Hidden_4(L_5); int32_t L_6 = ___points6; __this->set_m_Points_5(L_6); return; } } // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::ToString() extern "C" String_t* AchievementDescription_ToString_m1994678446 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AchievementDescription_ToString_m1994678446_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)((int32_t)11))); String_t* L_1 = AchievementDescription_get_id_m2652925627(__this, /*hidden argument*/NULL); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_1); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_1); ObjectU5BU5D_t3885370135* L_2 = L_0; NullCheck(L_2); ArrayElementTypeCheck (L_2, _stringLiteral41011391); (L_2)->SetAt(static_cast(1), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_3 = L_2; String_t* L_4 = AchievementDescription_get_title_m972096089(__this, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_4); (L_3)->SetAt(static_cast(2), (RuntimeObject *)L_4); ObjectU5BU5D_t3885370135* L_5 = L_3; NullCheck(L_5); ArrayElementTypeCheck (L_5, _stringLiteral41011391); (L_5)->SetAt(static_cast(3), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_6 = L_5; String_t* L_7 = AchievementDescription_get_achievedDescription_m3194544807(__this, /*hidden argument*/NULL); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_7); (L_6)->SetAt(static_cast(4), (RuntimeObject *)L_7); ObjectU5BU5D_t3885370135* L_8 = L_6; NullCheck(L_8); ArrayElementTypeCheck (L_8, _stringLiteral41011391); (L_8)->SetAt(static_cast(5), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_9 = L_8; String_t* L_10 = AchievementDescription_get_unachievedDescription_m613743906(__this, /*hidden argument*/NULL); NullCheck(L_9); ArrayElementTypeCheck (L_9, L_10); (L_9)->SetAt(static_cast(6), (RuntimeObject *)L_10); ObjectU5BU5D_t3885370135* L_11 = L_9; NullCheck(L_11); ArrayElementTypeCheck (L_11, _stringLiteral41011391); (L_11)->SetAt(static_cast(7), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_12 = L_11; int32_t L_13 = AchievementDescription_get_points_m2233273081(__this, /*hidden argument*/NULL); int32_t L_14 = L_13; RuntimeObject * L_15 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_14); NullCheck(L_12); ArrayElementTypeCheck (L_12, L_15); (L_12)->SetAt(static_cast(8), (RuntimeObject *)L_15); ObjectU5BU5D_t3885370135* L_16 = L_12; NullCheck(L_16); ArrayElementTypeCheck (L_16, _stringLiteral41011391); (L_16)->SetAt(static_cast(((int32_t)9)), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_17 = L_16; bool L_18 = AchievementDescription_get_hidden_m2953151423(__this, /*hidden argument*/NULL); bool L_19 = L_18; RuntimeObject * L_20 = Box(Boolean_t1642230456_il2cpp_TypeInfo_var, &L_19); NullCheck(L_17); ArrayElementTypeCheck (L_17, L_20); (L_17)->SetAt(static_cast(((int32_t)10)), (RuntimeObject *)L_20); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_21 = String_Concat_m2150944860(NULL /*static, unused*/, L_17, /*hidden argument*/NULL); V_0 = L_21; goto IL_007d; } IL_007d: { String_t* L_22 = V_0; return L_22; } } // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::SetImage(UnityEngine.Texture2D) extern "C" void AchievementDescription_SetImage_m2104624658 (AchievementDescription_t991053089 * __this, Texture2D_t1384570725 * ___image0, const RuntimeMethod* method) { { Texture2D_t1384570725 * L_0 = ___image0; __this->set_m_Image_1(L_0); return; } } // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_id() extern "C" String_t* AchievementDescription_get_id_m2652925627 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_U3CidU3Ek__BackingField_6(); V_0 = L_0; goto IL_000c; } IL_000c: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.AchievementDescription::set_id(System.String) extern "C" void AchievementDescription_set_id_m1561483604 (AchievementDescription_t991053089 * __this, String_t* ___value0, const RuntimeMethod* method) { { String_t* L_0 = ___value0; __this->set_U3CidU3Ek__BackingField_6(L_0); return; } } // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_title() extern "C" String_t* AchievementDescription_get_title_m972096089 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_Title_0(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_achievedDescription() extern "C" String_t* AchievementDescription_get_achievedDescription_m3194544807 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_AchievedDescription_2(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.String UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_unachievedDescription() extern "C" String_t* AchievementDescription_get_unachievedDescription_m613743906 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_UnachievedDescription_3(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.Boolean UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_hidden() extern "C" bool AchievementDescription_get_hidden_m2953151423 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { bool V_0 = false; { bool L_0 = __this->get_m_Hidden_4(); V_0 = L_0; goto IL_000d; } IL_000d: { bool L_1 = V_0; return L_1; } } // System.Int32 UnityEngine.SocialPlatforms.Impl.AchievementDescription::get_points() extern "C" int32_t AchievementDescription_get_points_m2233273081 (AchievementDescription_t991053089 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_m_Points_5(); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::.ctor() extern "C" void Leaderboard__ctor_m4039976758 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Leaderboard__ctor_m4039976758_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); Leaderboard_set_id_m819788632(__this, _stringLiteral1347337112, /*hidden argument*/NULL); Range_t2283206190 L_0; memset(&L_0, 0, sizeof(L_0)); Range__ctor_m3029477343((&L_0), 1, ((int32_t)10), /*hidden argument*/NULL); Leaderboard_set_range_m4172403679(__this, L_0, /*hidden argument*/NULL); Leaderboard_set_userScope_m1110642206(__this, 0, /*hidden argument*/NULL); Leaderboard_set_timeScope_m1140780687(__this, 2, /*hidden argument*/NULL); __this->set_m_Loading_0((bool)0); Score_t671349143 * L_1 = (Score_t671349143 *)il2cpp_codegen_object_new(Score_t671349143_il2cpp_TypeInfo_var); Score__ctor_m1838853748(L_1, _stringLiteral1347337112, (((int64_t)((int64_t)0))), /*hidden argument*/NULL); __this->set_m_LocalUserScore_1(L_1); __this->set_m_MaxRange_2(0); __this->set_m_Scores_3((IScoreU5BU5D_t519731081*)((ScoreU5BU5D_t13505070*)SZArrayNew(ScoreU5BU5D_t13505070_il2cpp_TypeInfo_var, (uint32_t)0))); __this->set_m_Title_4(_stringLiteral1347337112); __this->set_m_UserIDs_5(((StringU5BU5D_t3608572874*)SZArrayNew(StringU5BU5D_t3608572874_il2cpp_TypeInfo_var, (uint32_t)0))); return; } } // System.String UnityEngine.SocialPlatforms.Impl.Leaderboard::ToString() extern "C" String_t* Leaderboard_ToString_m3275737436 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Leaderboard_ToString_m3275737436_MetadataUsageId); s_Il2CppMethodInitialized = true; } Range_t2283206190 V_0; memset(&V_0, 0, sizeof(V_0)); Range_t2283206190 V_1; memset(&V_1, 0, sizeof(V_1)); String_t* V_2 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)((int32_t)20))); NullCheck(L_0); ArrayElementTypeCheck (L_0, _stringLiteral3929450208); (L_0)->SetAt(static_cast(0), (RuntimeObject *)_stringLiteral3929450208); ObjectU5BU5D_t3885370135* L_1 = L_0; String_t* L_2 = Leaderboard_get_id_m2059568589(__this, /*hidden argument*/NULL); NullCheck(L_1); ArrayElementTypeCheck (L_1, L_2); (L_1)->SetAt(static_cast(1), (RuntimeObject *)L_2); ObjectU5BU5D_t3885370135* L_3 = L_1; NullCheck(L_3); ArrayElementTypeCheck (L_3, _stringLiteral1966556228); (L_3)->SetAt(static_cast(2), (RuntimeObject *)_stringLiteral1966556228); ObjectU5BU5D_t3885370135* L_4 = L_3; String_t* L_5 = __this->get_m_Title_4(); NullCheck(L_4); ArrayElementTypeCheck (L_4, L_5); (L_4)->SetAt(static_cast(3), (RuntimeObject *)L_5); ObjectU5BU5D_t3885370135* L_6 = L_4; NullCheck(L_6); ArrayElementTypeCheck (L_6, _stringLiteral2019217056); (L_6)->SetAt(static_cast(4), (RuntimeObject *)_stringLiteral2019217056); ObjectU5BU5D_t3885370135* L_7 = L_6; bool L_8 = __this->get_m_Loading_0(); bool L_9 = L_8; RuntimeObject * L_10 = Box(Boolean_t1642230456_il2cpp_TypeInfo_var, &L_9); NullCheck(L_7); ArrayElementTypeCheck (L_7, L_10); (L_7)->SetAt(static_cast(5), (RuntimeObject *)L_10); ObjectU5BU5D_t3885370135* L_11 = L_7; NullCheck(L_11); ArrayElementTypeCheck (L_11, _stringLiteral1977467422); (L_11)->SetAt(static_cast(6), (RuntimeObject *)_stringLiteral1977467422); ObjectU5BU5D_t3885370135* L_12 = L_11; Range_t2283206190 L_13 = Leaderboard_get_range_m224007063(__this, /*hidden argument*/NULL); V_0 = L_13; int32_t L_14 = (&V_0)->get_from_0(); int32_t L_15 = L_14; RuntimeObject * L_16 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_15); NullCheck(L_12); ArrayElementTypeCheck (L_12, L_16); (L_12)->SetAt(static_cast(7), (RuntimeObject *)L_16); ObjectU5BU5D_t3885370135* L_17 = L_12; NullCheck(L_17); ArrayElementTypeCheck (L_17, _stringLiteral3610780097); (L_17)->SetAt(static_cast(8), (RuntimeObject *)_stringLiteral3610780097); ObjectU5BU5D_t3885370135* L_18 = L_17; Range_t2283206190 L_19 = Leaderboard_get_range_m224007063(__this, /*hidden argument*/NULL); V_1 = L_19; int32_t L_20 = (&V_1)->get_count_1(); int32_t L_21 = L_20; RuntimeObject * L_22 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_21); NullCheck(L_18); ArrayElementTypeCheck (L_18, L_22); (L_18)->SetAt(static_cast(((int32_t)9)), (RuntimeObject *)L_22); ObjectU5BU5D_t3885370135* L_23 = L_18; NullCheck(L_23); ArrayElementTypeCheck (L_23, _stringLiteral3368200717); (L_23)->SetAt(static_cast(((int32_t)10)), (RuntimeObject *)_stringLiteral3368200717); ObjectU5BU5D_t3885370135* L_24 = L_23; uint32_t L_25 = __this->get_m_MaxRange_2(); uint32_t L_26 = L_25; RuntimeObject * L_27 = Box(UInt32_t2977936117_il2cpp_TypeInfo_var, &L_26); NullCheck(L_24); ArrayElementTypeCheck (L_24, L_27); (L_24)->SetAt(static_cast(((int32_t)11)), (RuntimeObject *)L_27); ObjectU5BU5D_t3885370135* L_28 = L_24; NullCheck(L_28); ArrayElementTypeCheck (L_28, _stringLiteral1214608949); (L_28)->SetAt(static_cast(((int32_t)12)), (RuntimeObject *)_stringLiteral1214608949); ObjectU5BU5D_t3885370135* L_29 = L_28; IScoreU5BU5D_t519731081* L_30 = __this->get_m_Scores_3(); NullCheck(L_30); int32_t L_31 = (((int32_t)((int32_t)(((RuntimeArray *)L_30)->max_length)))); RuntimeObject * L_32 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_31); NullCheck(L_29); ArrayElementTypeCheck (L_29, L_32); (L_29)->SetAt(static_cast(((int32_t)13)), (RuntimeObject *)L_32); ObjectU5BU5D_t3885370135* L_33 = L_29; NullCheck(L_33); ArrayElementTypeCheck (L_33, _stringLiteral3699080494); (L_33)->SetAt(static_cast(((int32_t)14)), (RuntimeObject *)_stringLiteral3699080494); ObjectU5BU5D_t3885370135* L_34 = L_33; int32_t L_35 = Leaderboard_get_userScope_m3174579800(__this, /*hidden argument*/NULL); int32_t L_36 = L_35; RuntimeObject * L_37 = Box(UserScope_t788576880_il2cpp_TypeInfo_var, &L_36); NullCheck(L_34); ArrayElementTypeCheck (L_34, L_37); (L_34)->SetAt(static_cast(((int32_t)15)), (RuntimeObject *)L_37); ObjectU5BU5D_t3885370135* L_38 = L_34; NullCheck(L_38); ArrayElementTypeCheck (L_38, _stringLiteral3585726162); (L_38)->SetAt(static_cast(((int32_t)16)), (RuntimeObject *)_stringLiteral3585726162); ObjectU5BU5D_t3885370135* L_39 = L_38; int32_t L_40 = Leaderboard_get_timeScope_m2393285066(__this, /*hidden argument*/NULL); int32_t L_41 = L_40; RuntimeObject * L_42 = Box(TimeScope_t4070455592_il2cpp_TypeInfo_var, &L_41); NullCheck(L_39); ArrayElementTypeCheck (L_39, L_42); (L_39)->SetAt(static_cast(((int32_t)17)), (RuntimeObject *)L_42); ObjectU5BU5D_t3885370135* L_43 = L_39; NullCheck(L_43); ArrayElementTypeCheck (L_43, _stringLiteral2256614753); (L_43)->SetAt(static_cast(((int32_t)18)), (RuntimeObject *)_stringLiteral2256614753); ObjectU5BU5D_t3885370135* L_44 = L_43; StringU5BU5D_t3608572874* L_45 = __this->get_m_UserIDs_5(); NullCheck(L_45); int32_t L_46 = (((int32_t)((int32_t)(((RuntimeArray *)L_45)->max_length)))); RuntimeObject * L_47 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_46); NullCheck(L_44); ArrayElementTypeCheck (L_44, L_47); (L_44)->SetAt(static_cast(((int32_t)19)), (RuntimeObject *)L_47); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_48 = String_Concat_m2150944860(NULL /*static, unused*/, L_44, /*hidden argument*/NULL); V_2 = L_48; goto IL_0104; } IL_0104: { String_t* L_49 = V_2; return L_49; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetLocalUserScore(UnityEngine.SocialPlatforms.IScore) extern "C" void Leaderboard_SetLocalUserScore_m2947022105 (Leaderboard_t3315266811 * __this, RuntimeObject* ___score0, const RuntimeMethod* method) { { RuntimeObject* L_0 = ___score0; __this->set_m_LocalUserScore_1(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetMaxRange(System.UInt32) extern "C" void Leaderboard_SetMaxRange_m1441382126 (Leaderboard_t3315266811 * __this, uint32_t ___maxRange0, const RuntimeMethod* method) { { uint32_t L_0 = ___maxRange0; __this->set_m_MaxRange_2(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetScores(UnityEngine.SocialPlatforms.IScore[]) extern "C" void Leaderboard_SetScores_m1863945428 (Leaderboard_t3315266811 * __this, IScoreU5BU5D_t519731081* ___scores0, const RuntimeMethod* method) { { IScoreU5BU5D_t519731081* L_0 = ___scores0; __this->set_m_Scores_3(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::SetTitle(System.String) extern "C" void Leaderboard_SetTitle_m4254570531 (Leaderboard_t3315266811 * __this, String_t* ___title0, const RuntimeMethod* method) { { String_t* L_0 = ___title0; __this->set_m_Title_4(L_0); return; } } // System.String[] UnityEngine.SocialPlatforms.Impl.Leaderboard::GetUserFilter() extern "C" StringU5BU5D_t3608572874* Leaderboard_GetUserFilter_m3311896502 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { StringU5BU5D_t3608572874* V_0 = NULL; { StringU5BU5D_t3608572874* L_0 = __this->get_m_UserIDs_5(); V_0 = L_0; goto IL_000d; } IL_000d: { StringU5BU5D_t3608572874* L_1 = V_0; return L_1; } } // System.String UnityEngine.SocialPlatforms.Impl.Leaderboard::get_id() extern "C" String_t* Leaderboard_get_id_m2059568589 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_U3CidU3Ek__BackingField_6(); V_0 = L_0; goto IL_000c; } IL_000c: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_id(System.String) extern "C" void Leaderboard_set_id_m819788632 (Leaderboard_t3315266811 * __this, String_t* ___value0, const RuntimeMethod* method) { { String_t* L_0 = ___value0; __this->set_U3CidU3Ek__BackingField_6(L_0); return; } } // UnityEngine.SocialPlatforms.UserScope UnityEngine.SocialPlatforms.Impl.Leaderboard::get_userScope() extern "C" int32_t Leaderboard_get_userScope_m3174579800 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_U3CuserScopeU3Ek__BackingField_7(); V_0 = L_0; goto IL_000c; } IL_000c: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_userScope(UnityEngine.SocialPlatforms.UserScope) extern "C" void Leaderboard_set_userScope_m1110642206 (Leaderboard_t3315266811 * __this, int32_t ___value0, const RuntimeMethod* method) { { int32_t L_0 = ___value0; __this->set_U3CuserScopeU3Ek__BackingField_7(L_0); return; } } // UnityEngine.SocialPlatforms.Range UnityEngine.SocialPlatforms.Impl.Leaderboard::get_range() extern "C" Range_t2283206190 Leaderboard_get_range_m224007063 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { Range_t2283206190 V_0; memset(&V_0, 0, sizeof(V_0)); { Range_t2283206190 L_0 = __this->get_U3CrangeU3Ek__BackingField_8(); V_0 = L_0; goto IL_000c; } IL_000c: { Range_t2283206190 L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_range(UnityEngine.SocialPlatforms.Range) extern "C" void Leaderboard_set_range_m4172403679 (Leaderboard_t3315266811 * __this, Range_t2283206190 ___value0, const RuntimeMethod* method) { { Range_t2283206190 L_0 = ___value0; __this->set_U3CrangeU3Ek__BackingField_8(L_0); return; } } // UnityEngine.SocialPlatforms.TimeScope UnityEngine.SocialPlatforms.Impl.Leaderboard::get_timeScope() extern "C" int32_t Leaderboard_get_timeScope_m2393285066 (Leaderboard_t3315266811 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_U3CtimeScopeU3Ek__BackingField_9(); V_0 = L_0; goto IL_000c; } IL_000c: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Leaderboard::set_timeScope(UnityEngine.SocialPlatforms.TimeScope) extern "C" void Leaderboard_set_timeScope_m1140780687 (Leaderboard_t3315266811 * __this, int32_t ___value0, const RuntimeMethod* method) { { int32_t L_0 = ___value0; __this->set_U3CtimeScopeU3Ek__BackingField_9(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::.ctor() extern "C" void LocalUser__ctor_m928281921 (LocalUser_t2155741069 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (LocalUser__ctor_m928281921_MetadataUsageId); s_Il2CppMethodInitialized = true; } { UserProfile__ctor_m2050922054(__this, /*hidden argument*/NULL); __this->set_m_Friends_5((IUserProfileU5BU5D_t3867243727*)((UserProfileU5BU5D_t3377267652*)SZArrayNew(UserProfileU5BU5D_t3377267652_il2cpp_TypeInfo_var, (uint32_t)0))); __this->set_m_Authenticated_6((bool)0); __this->set_m_Underage_7((bool)0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetFriends(UnityEngine.SocialPlatforms.IUserProfile[]) extern "C" void LocalUser_SetFriends_m2359410273 (LocalUser_t2155741069 * __this, IUserProfileU5BU5D_t3867243727* ___friends0, const RuntimeMethod* method) { { IUserProfileU5BU5D_t3867243727* L_0 = ___friends0; __this->set_m_Friends_5(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetAuthenticated(System.Boolean) extern "C" void LocalUser_SetAuthenticated_m85368100 (LocalUser_t2155741069 * __this, bool ___value0, const RuntimeMethod* method) { { bool L_0 = ___value0; __this->set_m_Authenticated_6(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.LocalUser::SetUnderage(System.Boolean) extern "C" void LocalUser_SetUnderage_m192521804 (LocalUser_t2155741069 * __this, bool ___value0, const RuntimeMethod* method) { { bool L_0 = ___value0; __this->set_m_Underage_7(L_0); return; } } // System.Boolean UnityEngine.SocialPlatforms.Impl.LocalUser::get_authenticated() extern "C" bool LocalUser_get_authenticated_m1333358728 (LocalUser_t2155741069 * __this, const RuntimeMethod* method) { bool V_0 = false; { bool L_0 = __this->get_m_Authenticated_6(); V_0 = L_0; goto IL_000d; } IL_000d: { bool L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Score::.ctor(System.String,System.Int64) extern "C" void Score__ctor_m1838853748 (Score_t671349143 * __this, String_t* ___leaderboardID0, int64_t ___value1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Score__ctor_m1838853748_MetadataUsageId); s_Il2CppMethodInitialized = true; } { String_t* L_0 = ___leaderboardID0; int64_t L_1 = ___value1; IL2CPP_RUNTIME_CLASS_INIT(DateTime_t1205928702_il2cpp_TypeInfo_var); DateTime_t1205928702 L_2 = DateTime_get_Now_m2497775987(NULL /*static, unused*/, /*hidden argument*/NULL); Score__ctor_m1424242054(__this, L_0, L_1, _stringLiteral1666647875, L_2, _stringLiteral4212843024, (-1), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.Score::.ctor(System.String,System.Int64,System.String,System.DateTime,System.String,System.Int32) extern "C" void Score__ctor_m1424242054 (Score_t671349143 * __this, String_t* ___leaderboardID0, int64_t ___value1, String_t* ___userID2, DateTime_t1205928702 ___date3, String_t* ___formattedValue4, int32_t ___rank5, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); String_t* L_0 = ___leaderboardID0; Score_set_leaderboardID_m2411520823(__this, L_0, /*hidden argument*/NULL); int64_t L_1 = ___value1; Score_set_value_m2819979283(__this, L_1, /*hidden argument*/NULL); String_t* L_2 = ___userID2; __this->set_m_UserID_2(L_2); DateTime_t1205928702 L_3 = ___date3; __this->set_m_Date_0(L_3); String_t* L_4 = ___formattedValue4; __this->set_m_FormattedValue_1(L_4); int32_t L_5 = ___rank5; __this->set_m_Rank_3(L_5); return; } } // System.String UnityEngine.SocialPlatforms.Impl.Score::ToString() extern "C" String_t* Score_ToString_m1928919354 (Score_t671349143 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Score_ToString_m1928919354_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)((int32_t)10))); NullCheck(L_0); ArrayElementTypeCheck (L_0, _stringLiteral713862236); (L_0)->SetAt(static_cast(0), (RuntimeObject *)_stringLiteral713862236); ObjectU5BU5D_t3885370135* L_1 = L_0; int32_t L_2 = __this->get_m_Rank_3(); int32_t L_3 = L_2; RuntimeObject * L_4 = Box(Int32_t2185247404_il2cpp_TypeInfo_var, &L_3); NullCheck(L_1); ArrayElementTypeCheck (L_1, L_4); (L_1)->SetAt(static_cast(1), (RuntimeObject *)L_4); ObjectU5BU5D_t3885370135* L_5 = L_1; NullCheck(L_5); ArrayElementTypeCheck (L_5, _stringLiteral2308931076); (L_5)->SetAt(static_cast(2), (RuntimeObject *)_stringLiteral2308931076); ObjectU5BU5D_t3885370135* L_6 = L_5; int64_t L_7 = Score_get_value_m1477333616(__this, /*hidden argument*/NULL); int64_t L_8 = L_7; RuntimeObject * L_9 = Box(Int64_t3954580378_il2cpp_TypeInfo_var, &L_8); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_9); (L_6)->SetAt(static_cast(3), (RuntimeObject *)L_9); ObjectU5BU5D_t3885370135* L_10 = L_6; NullCheck(L_10); ArrayElementTypeCheck (L_10, _stringLiteral2339561701); (L_10)->SetAt(static_cast(4), (RuntimeObject *)_stringLiteral2339561701); ObjectU5BU5D_t3885370135* L_11 = L_10; String_t* L_12 = Score_get_leaderboardID_m4172359465(__this, /*hidden argument*/NULL); NullCheck(L_11); ArrayElementTypeCheck (L_11, L_12); (L_11)->SetAt(static_cast(5), (RuntimeObject *)L_12); ObjectU5BU5D_t3885370135* L_13 = L_11; NullCheck(L_13); ArrayElementTypeCheck (L_13, _stringLiteral753814197); (L_13)->SetAt(static_cast(6), (RuntimeObject *)_stringLiteral753814197); ObjectU5BU5D_t3885370135* L_14 = L_13; String_t* L_15 = __this->get_m_UserID_2(); NullCheck(L_14); ArrayElementTypeCheck (L_14, L_15); (L_14)->SetAt(static_cast(7), (RuntimeObject *)L_15); ObjectU5BU5D_t3885370135* L_16 = L_14; NullCheck(L_16); ArrayElementTypeCheck (L_16, _stringLiteral3809495824); (L_16)->SetAt(static_cast(8), (RuntimeObject *)_stringLiteral3809495824); ObjectU5BU5D_t3885370135* L_17 = L_16; DateTime_t1205928702 L_18 = __this->get_m_Date_0(); DateTime_t1205928702 L_19 = L_18; RuntimeObject * L_20 = Box(DateTime_t1205928702_il2cpp_TypeInfo_var, &L_19); NullCheck(L_17); ArrayElementTypeCheck (L_17, L_20); (L_17)->SetAt(static_cast(((int32_t)9)), (RuntimeObject *)L_20); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_21 = String_Concat_m2150944860(NULL /*static, unused*/, L_17, /*hidden argument*/NULL); V_0 = L_21; goto IL_0078; } IL_0078: { String_t* L_22 = V_0; return L_22; } } // System.String UnityEngine.SocialPlatforms.Impl.Score::get_leaderboardID() extern "C" String_t* Score_get_leaderboardID_m4172359465 (Score_t671349143 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_U3CleaderboardIDU3Ek__BackingField_4(); V_0 = L_0; goto IL_000c; } IL_000c: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Score::set_leaderboardID(System.String) extern "C" void Score_set_leaderboardID_m2411520823 (Score_t671349143 * __this, String_t* ___value0, const RuntimeMethod* method) { { String_t* L_0 = ___value0; __this->set_U3CleaderboardIDU3Ek__BackingField_4(L_0); return; } } // System.Int64 UnityEngine.SocialPlatforms.Impl.Score::get_value() extern "C" int64_t Score_get_value_m1477333616 (Score_t671349143 * __this, const RuntimeMethod* method) { int64_t V_0 = 0; { int64_t L_0 = __this->get_U3CvalueU3Ek__BackingField_5(); V_0 = L_0; goto IL_000c; } IL_000c: { int64_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Impl.Score::set_value(System.Int64) extern "C" void Score_set_value_m2819979283 (Score_t671349143 * __this, int64_t ___value0, const RuntimeMethod* method) { { int64_t L_0 = ___value0; __this->set_U3CvalueU3Ek__BackingField_5(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::.ctor() extern "C" void UserProfile__ctor_m2050922054 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (UserProfile__ctor_m2050922054_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); __this->set_m_UserName_0(_stringLiteral1411782842); __this->set_m_ID_1(_stringLiteral1666647875); __this->set_m_IsFriend_2((bool)0); __this->set_m_State_3(3); Texture2D_t1384570725 * L_0 = (Texture2D_t1384570725 *)il2cpp_codegen_object_new(Texture2D_t1384570725_il2cpp_TypeInfo_var); Texture2D__ctor_m400428107(L_0, ((int32_t)32), ((int32_t)32), /*hidden argument*/NULL); __this->set_m_Image_4(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::.ctor(System.String,System.String,System.Boolean,UnityEngine.SocialPlatforms.UserState,UnityEngine.Texture2D) extern "C" void UserProfile__ctor_m3004638010 (UserProfile_t2942407481 * __this, String_t* ___name0, String_t* ___id1, bool ___friend2, int32_t ___state3, Texture2D_t1384570725 * ___image4, const RuntimeMethod* method) { { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); String_t* L_0 = ___name0; __this->set_m_UserName_0(L_0); String_t* L_1 = ___id1; __this->set_m_ID_1(L_1); bool L_2 = ___friend2; __this->set_m_IsFriend_2(L_2); int32_t L_3 = ___state3; __this->set_m_State_3(L_3); Texture2D_t1384570725 * L_4 = ___image4; __this->set_m_Image_4(L_4); return; } } // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::ToString() extern "C" String_t* UserProfile_ToString_m383837202 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (UserProfile_ToString_m383837202_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; { ObjectU5BU5D_t3885370135* L_0 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)7)); String_t* L_1 = UserProfile_get_id_m2069338772(__this, /*hidden argument*/NULL); NullCheck(L_0); ArrayElementTypeCheck (L_0, L_1); (L_0)->SetAt(static_cast(0), (RuntimeObject *)L_1); ObjectU5BU5D_t3885370135* L_2 = L_0; NullCheck(L_2); ArrayElementTypeCheck (L_2, _stringLiteral41011391); (L_2)->SetAt(static_cast(1), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_3 = L_2; String_t* L_4 = UserProfile_get_userName_m3008791783(__this, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_4); (L_3)->SetAt(static_cast(2), (RuntimeObject *)L_4); ObjectU5BU5D_t3885370135* L_5 = L_3; NullCheck(L_5); ArrayElementTypeCheck (L_5, _stringLiteral41011391); (L_5)->SetAt(static_cast(3), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_6 = L_5; bool L_7 = UserProfile_get_isFriend_m1328512851(__this, /*hidden argument*/NULL); bool L_8 = L_7; RuntimeObject * L_9 = Box(Boolean_t1642230456_il2cpp_TypeInfo_var, &L_8); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_9); (L_6)->SetAt(static_cast(4), (RuntimeObject *)L_9); ObjectU5BU5D_t3885370135* L_10 = L_6; NullCheck(L_10); ArrayElementTypeCheck (L_10, _stringLiteral41011391); (L_10)->SetAt(static_cast(5), (RuntimeObject *)_stringLiteral41011391); ObjectU5BU5D_t3885370135* L_11 = L_10; int32_t L_12 = UserProfile_get_state_m735841295(__this, /*hidden argument*/NULL); int32_t L_13 = L_12; RuntimeObject * L_14 = Box(UserState_t2255672114_il2cpp_TypeInfo_var, &L_13); NullCheck(L_11); ArrayElementTypeCheck (L_11, L_14); (L_11)->SetAt(static_cast(6), (RuntimeObject *)L_14); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_15 = String_Concat_m2150944860(NULL /*static, unused*/, L_11, /*hidden argument*/NULL); V_0 = L_15; goto IL_0058; } IL_0058: { String_t* L_16 = V_0; return L_16; } } // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetUserName(System.String) extern "C" void UserProfile_SetUserName_m3129419512 (UserProfile_t2942407481 * __this, String_t* ___name0, const RuntimeMethod* method) { { String_t* L_0 = ___name0; __this->set_m_UserName_0(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetUserID(System.String) extern "C" void UserProfile_SetUserID_m836273895 (UserProfile_t2942407481 * __this, String_t* ___id0, const RuntimeMethod* method) { { String_t* L_0 = ___id0; __this->set_m_ID_1(L_0); return; } } // System.Void UnityEngine.SocialPlatforms.Impl.UserProfile::SetImage(UnityEngine.Texture2D) extern "C" void UserProfile_SetImage_m4145629067 (UserProfile_t2942407481 * __this, Texture2D_t1384570725 * ___image0, const RuntimeMethod* method) { { Texture2D_t1384570725 * L_0 = ___image0; __this->set_m_Image_4(L_0); return; } } // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::get_userName() extern "C" String_t* UserProfile_get_userName_m3008791783 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_UserName_0(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.String UnityEngine.SocialPlatforms.Impl.UserProfile::get_id() extern "C" String_t* UserProfile_get_id_m2069338772 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = __this->get_m_ID_1(); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.Boolean UnityEngine.SocialPlatforms.Impl.UserProfile::get_isFriend() extern "C" bool UserProfile_get_isFriend_m1328512851 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { bool V_0 = false; { bool L_0 = __this->get_m_IsFriend_2(); V_0 = L_0; goto IL_000d; } IL_000d: { bool L_1 = V_0; return L_1; } } // UnityEngine.SocialPlatforms.UserState UnityEngine.SocialPlatforms.Impl.UserProfile::get_state() extern "C" int32_t UserProfile_get_state_m735841295 (UserProfile_t2942407481 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = __this->get_m_State_3(); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.SocialPlatforms.Range::.ctor(System.Int32,System.Int32) extern "C" void Range__ctor_m3029477343 (Range_t2283206190 * __this, int32_t ___fromValue0, int32_t ___valueCount1, const RuntimeMethod* method) { { int32_t L_0 = ___fromValue0; __this->set_from_0(L_0); int32_t L_1 = ___valueCount1; __this->set_count_1(L_1); return; } } extern "C" void Range__ctor_m3029477343_AdjustorThunk (RuntimeObject * __this, int32_t ___fromValue0, int32_t ___valueCount1, const RuntimeMethod* method) { Range_t2283206190 * _thisAdjusted = reinterpret_cast(__this + 1); Range__ctor_m3029477343(_thisAdjusted, ___fromValue0, ___valueCount1, method); } // System.Int32 UnityEngine.SortingLayer::GetLayerValueFromID(System.Int32) extern "C" int32_t SortingLayer_GetLayerValueFromID_m1093666524 (RuntimeObject * __this /* static, unused */, int32_t ___id0, const RuntimeMethod* method) { typedef int32_t (*SortingLayer_GetLayerValueFromID_m1093666524_ftn) (int32_t); static SortingLayer_GetLayerValueFromID_m1093666524_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SortingLayer_GetLayerValueFromID_m1093666524_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SortingLayer::GetLayerValueFromID(System.Int32)"); int32_t retVal = _il2cpp_icall_func(___id0); return retVal; } // System.Void UnityEngine.SpaceAttribute::.ctor() extern "C" void SpaceAttribute__ctor_m23427159 (SpaceAttribute_t1419322499 * __this, const RuntimeMethod* method) { { PropertyAttribute__ctor_m1537537891(__this, /*hidden argument*/NULL); __this->set_height_0((8.0f)); return; } } // System.Void UnityEngine.SpaceAttribute::.ctor(System.Single) extern "C" void SpaceAttribute__ctor_m3496678365 (SpaceAttribute_t1419322499 * __this, float ___height0, const RuntimeMethod* method) { { PropertyAttribute__ctor_m1537537891(__this, /*hidden argument*/NULL); float L_0 = ___height0; __this->set_height_0(L_0); return; } } // System.Void UnityEngine.SphereCollider::.ctor() extern "C" void SphereCollider__ctor_m543920664 (SphereCollider_t2896221692 * __this, const RuntimeMethod* method) { { Collider__ctor_m3904369873(__this, /*hidden argument*/NULL); return; } } // UnityEngine.Vector3 UnityEngine.SphereCollider::get_center() extern "C" Vector3_t67624592 SphereCollider_get_center_m3039278529 (SphereCollider_t2896221692 * __this, const RuntimeMethod* method) { Vector3_t67624592 V_0; memset(&V_0, 0, sizeof(V_0)); Vector3_t67624592 V_1; memset(&V_1, 0, sizeof(V_1)); { SphereCollider_INTERNAL_get_center_m1829176733(__this, (&V_0), /*hidden argument*/NULL); Vector3_t67624592 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector3_t67624592 L_1 = V_1; return L_1; } } // System.Void UnityEngine.SphereCollider::set_center(UnityEngine.Vector3) extern "C" void SphereCollider_set_center_m3931328636 (SphereCollider_t2896221692 * __this, Vector3_t67624592 ___value0, const RuntimeMethod* method) { { SphereCollider_INTERNAL_set_center_m338109470(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SphereCollider::INTERNAL_get_center(UnityEngine.Vector3&) extern "C" void SphereCollider_INTERNAL_get_center_m1829176733 (SphereCollider_t2896221692 * __this, Vector3_t67624592 * ___value0, const RuntimeMethod* method) { typedef void (*SphereCollider_INTERNAL_get_center_m1829176733_ftn) (SphereCollider_t2896221692 *, Vector3_t67624592 *); static SphereCollider_INTERNAL_get_center_m1829176733_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SphereCollider_INTERNAL_get_center_m1829176733_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SphereCollider::INTERNAL_get_center(UnityEngine.Vector3&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.SphereCollider::INTERNAL_set_center(UnityEngine.Vector3&) extern "C" void SphereCollider_INTERNAL_set_center_m338109470 (SphereCollider_t2896221692 * __this, Vector3_t67624592 * ___value0, const RuntimeMethod* method) { typedef void (*SphereCollider_INTERNAL_set_center_m338109470_ftn) (SphereCollider_t2896221692 *, Vector3_t67624592 *); static SphereCollider_INTERNAL_set_center_m338109470_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SphereCollider_INTERNAL_set_center_m338109470_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SphereCollider::INTERNAL_set_center(UnityEngine.Vector3&)"); _il2cpp_icall_func(__this, ___value0); } // System.Single UnityEngine.SphereCollider::get_radius() extern "C" float SphereCollider_get_radius_m2964120565 (SphereCollider_t2896221692 * __this, const RuntimeMethod* method) { typedef float (*SphereCollider_get_radius_m2964120565_ftn) (SphereCollider_t2896221692 *); static SphereCollider_get_radius_m2964120565_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SphereCollider_get_radius_m2964120565_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SphereCollider::get_radius()"); float retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.SphereCollider::set_radius(System.Single) extern "C" void SphereCollider_set_radius_m3265963779 (SphereCollider_t2896221692 * __this, float ___value0, const RuntimeMethod* method) { typedef void (*SphereCollider_set_radius_m3265963779_ftn) (SphereCollider_t2896221692 *, float); static SphereCollider_set_radius_m3265963779_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SphereCollider_set_radius_m3265963779_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SphereCollider::set_radius(System.Single)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Rect UnityEngine.Sprite::get_rect() extern "C" Rect_t3345319094 Sprite_get_rect_m2355604598 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_INTERNAL_get_rect_m3872599290(__this, (&V_0), /*hidden argument*/NULL); Rect_t3345319094 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Rect_t3345319094 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Sprite::INTERNAL_get_rect(UnityEngine.Rect&) extern "C" void Sprite_INTERNAL_get_rect_m3872599290 (Sprite_t3419621700 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) { typedef void (*Sprite_INTERNAL_get_rect_m3872599290_ftn) (Sprite_t3419621700 *, Rect_t3345319094 *); static Sprite_INTERNAL_get_rect_m3872599290_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_INTERNAL_get_rect_m3872599290_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::INTERNAL_get_rect(UnityEngine.Rect&)"); _il2cpp_icall_func(__this, ___value0); } // System.Single UnityEngine.Sprite::get_pixelsPerUnit() extern "C" float Sprite_get_pixelsPerUnit_m2835939234 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { typedef float (*Sprite_get_pixelsPerUnit_m2835939234_ftn) (Sprite_t3419621700 *); static Sprite_get_pixelsPerUnit_m2835939234_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_get_pixelsPerUnit_m2835939234_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::get_pixelsPerUnit()"); float retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Texture2D UnityEngine.Sprite::get_texture() extern "C" Texture2D_t1384570725 * Sprite_get_texture_m2121757581 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { typedef Texture2D_t1384570725 * (*Sprite_get_texture_m2121757581_ftn) (Sprite_t3419621700 *); static Sprite_get_texture_m2121757581_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_get_texture_m2121757581_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::get_texture()"); Texture2D_t1384570725 * retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Texture2D UnityEngine.Sprite::get_associatedAlphaSplitTexture() extern "C" Texture2D_t1384570725 * Sprite_get_associatedAlphaSplitTexture_m169587792 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { typedef Texture2D_t1384570725 * (*Sprite_get_associatedAlphaSplitTexture_m169587792_ftn) (Sprite_t3419621700 *); static Sprite_get_associatedAlphaSplitTexture_m169587792_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_get_associatedAlphaSplitTexture_m169587792_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::get_associatedAlphaSplitTexture()"); Texture2D_t1384570725 * retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Rect UnityEngine.Sprite::get_textureRect() extern "C" Rect_t3345319094 Sprite_get_textureRect_m255598562 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_INTERNAL_get_textureRect_m2787057290(__this, (&V_0), /*hidden argument*/NULL); Rect_t3345319094 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Rect_t3345319094 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Sprite::INTERNAL_get_textureRect(UnityEngine.Rect&) extern "C" void Sprite_INTERNAL_get_textureRect_m2787057290 (Sprite_t3419621700 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) { typedef void (*Sprite_INTERNAL_get_textureRect_m2787057290_ftn) (Sprite_t3419621700 *, Rect_t3345319094 *); static Sprite_INTERNAL_get_textureRect_m2787057290_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_INTERNAL_get_textureRect_m2787057290_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::INTERNAL_get_textureRect(UnityEngine.Rect&)"); _il2cpp_icall_func(__this, ___value0); } // System.Boolean UnityEngine.Sprite::get_packed() extern "C" bool Sprite_get_packed_m2782072222 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { typedef bool (*Sprite_get_packed_m2782072222_ftn) (Sprite_t3419621700 *); static Sprite_get_packed_m2782072222_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_get_packed_m2782072222_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::get_packed()"); bool retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Vector4 UnityEngine.Sprite::get_border() extern "C" Vector4_t4108915337 Sprite_get_border_m2635530827 (Sprite_t3419621700 * __this, const RuntimeMethod* method) { Vector4_t4108915337 V_0; memset(&V_0, 0, sizeof(V_0)); Vector4_t4108915337 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_INTERNAL_get_border_m499630133(__this, (&V_0), /*hidden argument*/NULL); Vector4_t4108915337 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector4_t4108915337 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Sprite::INTERNAL_get_border(UnityEngine.Vector4&) extern "C" void Sprite_INTERNAL_get_border_m499630133 (Sprite_t3419621700 * __this, Vector4_t4108915337 * ___value0, const RuntimeMethod* method) { typedef void (*Sprite_INTERNAL_get_border_m499630133_ftn) (Sprite_t3419621700 *, Vector4_t4108915337 *); static Sprite_INTERNAL_get_border_m499630133_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Sprite_INTERNAL_get_border_m499630133_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprite::INTERNAL_get_border(UnityEngine.Vector4&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.SpriteRenderer::set_sprite(UnityEngine.Sprite) extern "C" void SpriteRenderer_set_sprite_m3337771916 (SpriteRenderer_t1459332486 * __this, Sprite_t3419621700 * ___value0, const RuntimeMethod* method) { { Sprite_t3419621700 * L_0 = ___value0; SpriteRenderer_SetSprite_INTERNAL_m1476729322(__this, L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.SpriteRenderer::SetSprite_INTERNAL(UnityEngine.Sprite) extern "C" void SpriteRenderer_SetSprite_INTERNAL_m1476729322 (SpriteRenderer_t1459332486 * __this, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) { typedef void (*SpriteRenderer_SetSprite_INTERNAL_m1476729322_ftn) (SpriteRenderer_t1459332486 *, Sprite_t3419621700 *); static SpriteRenderer_SetSprite_INTERNAL_m1476729322_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SpriteRenderer_SetSprite_INTERNAL_m1476729322_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SpriteRenderer::SetSprite_INTERNAL(UnityEngine.Sprite)"); _il2cpp_icall_func(__this, ___sprite0); } // UnityEngine.Vector4 UnityEngine.Sprites.DataUtility::GetInnerUV(UnityEngine.Sprite) extern "C" Vector4_t4108915337 DataUtility_GetInnerUV_m1858782874 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) { Vector4_t4108915337 V_0; memset(&V_0, 0, sizeof(V_0)); Vector4_t4108915337 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_t3419621700 * L_0 = ___sprite0; DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070(NULL /*static, unused*/, L_0, (&V_0), /*hidden argument*/NULL); Vector4_t4108915337 L_1 = V_0; V_1 = L_1; goto IL_0010; } IL_0010: { Vector4_t4108915337 L_2 = V_1; return L_2; } } // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetInnerUV(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) { typedef void (*DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070_ftn) (Sprite_t3419621700 *, Vector4_t4108915337 *); static DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (DataUtility_INTERNAL_CALL_GetInnerUV_m3118229070_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetInnerUV(UnityEngine.Sprite,UnityEngine.Vector4&)"); _il2cpp_icall_func(___sprite0, ___value1); } // UnityEngine.Vector4 UnityEngine.Sprites.DataUtility::GetOuterUV(UnityEngine.Sprite) extern "C" Vector4_t4108915337 DataUtility_GetOuterUV_m111603994 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) { Vector4_t4108915337 V_0; memset(&V_0, 0, sizeof(V_0)); Vector4_t4108915337 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_t3419621700 * L_0 = ___sprite0; DataUtility_INTERNAL_CALL_GetOuterUV_m230980969(NULL /*static, unused*/, L_0, (&V_0), /*hidden argument*/NULL); Vector4_t4108915337 L_1 = V_0; V_1 = L_1; goto IL_0010; } IL_0010: { Vector4_t4108915337 L_2 = V_1; return L_2; } } // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetOuterUV(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetOuterUV_m230980969 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) { typedef void (*DataUtility_INTERNAL_CALL_GetOuterUV_m230980969_ftn) (Sprite_t3419621700 *, Vector4_t4108915337 *); static DataUtility_INTERNAL_CALL_GetOuterUV_m230980969_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (DataUtility_INTERNAL_CALL_GetOuterUV_m230980969_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetOuterUV(UnityEngine.Sprite,UnityEngine.Vector4&)"); _il2cpp_icall_func(___sprite0, ___value1); } // UnityEngine.Vector4 UnityEngine.Sprites.DataUtility::GetPadding(UnityEngine.Sprite) extern "C" Vector4_t4108915337 DataUtility_GetPadding_m1519381867 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) { Vector4_t4108915337 V_0; memset(&V_0, 0, sizeof(V_0)); Vector4_t4108915337 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_t3419621700 * L_0 = ___sprite0; DataUtility_INTERNAL_CALL_GetPadding_m440627081(NULL /*static, unused*/, L_0, (&V_0), /*hidden argument*/NULL); Vector4_t4108915337 L_1 = V_0; V_1 = L_1; goto IL_0010; } IL_0010: { Vector4_t4108915337 L_2 = V_1; return L_2; } } // System.Void UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetPadding(UnityEngine.Sprite,UnityEngine.Vector4&) extern "C" void DataUtility_INTERNAL_CALL_GetPadding_m440627081 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector4_t4108915337 * ___value1, const RuntimeMethod* method) { typedef void (*DataUtility_INTERNAL_CALL_GetPadding_m440627081_ftn) (Sprite_t3419621700 *, Vector4_t4108915337 *); static DataUtility_INTERNAL_CALL_GetPadding_m440627081_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (DataUtility_INTERNAL_CALL_GetPadding_m440627081_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprites.DataUtility::INTERNAL_CALL_GetPadding(UnityEngine.Sprite,UnityEngine.Vector4&)"); _il2cpp_icall_func(___sprite0, ___value1); } // UnityEngine.Vector2 UnityEngine.Sprites.DataUtility::GetMinSize(UnityEngine.Sprite) extern "C" Vector2_t3854014517 DataUtility_GetMinSize_m1802152380 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { Sprite_t3419621700 * L_0 = ___sprite0; DataUtility_Internal_GetMinSize_m928418521(NULL /*static, unused*/, L_0, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_1 = V_0; V_1 = L_1; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_2 = V_1; return L_2; } } // System.Void UnityEngine.Sprites.DataUtility::Internal_GetMinSize(UnityEngine.Sprite,UnityEngine.Vector2&) extern "C" void DataUtility_Internal_GetMinSize_m928418521 (RuntimeObject * __this /* static, unused */, Sprite_t3419621700 * ___sprite0, Vector2_t3854014517 * ___output1, const RuntimeMethod* method) { typedef void (*DataUtility_Internal_GetMinSize_m928418521_ftn) (Sprite_t3419621700 *, Vector2_t3854014517 *); static DataUtility_Internal_GetMinSize_m928418521_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (DataUtility_Internal_GetMinSize_m928418521_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Sprites.DataUtility::Internal_GetMinSize(UnityEngine.Sprite,UnityEngine.Vector2&)"); _il2cpp_icall_func(___sprite0, ___output1); } // System.Void UnityEngine.StackTraceUtility::SetProjectFolder(System.String) extern "C" void StackTraceUtility_SetProjectFolder_m865009452 (RuntimeObject * __this /* static, unused */, String_t* ___folder0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_SetProjectFolder_m865009452_MetadataUsageId); s_Il2CppMethodInitialized = true; } { String_t* L_0 = ___folder0; NullCheck(L_0); String_t* L_1 = String_Replace_m212902530(L_0, _stringLiteral3572222939, _stringLiteral3343446928, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->set_projectFolder_0(L_1); return; } } // System.String UnityEngine.StackTraceUtility::ExtractStackTrace() extern "C" String_t* StackTraceUtility_ExtractStackTrace_m2121576629 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_ExtractStackTrace_m2121576629_MetadataUsageId); s_Il2CppMethodInitialized = true; } StackTrace_t798888381 * V_0 = NULL; String_t* V_1 = NULL; String_t* V_2 = NULL; { StackTrace_t798888381 * L_0 = (StackTrace_t798888381 *)il2cpp_codegen_object_new(StackTrace_t798888381_il2cpp_TypeInfo_var); StackTrace__ctor_m3377607597(L_0, 1, (bool)1, /*hidden argument*/NULL); V_0 = L_0; StackTrace_t798888381 * L_1 = V_0; IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); String_t* L_2 = StackTraceUtility_ExtractFormattedStackTrace_m2265662347(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); NullCheck(L_2); String_t* L_3 = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, L_2); V_1 = L_3; String_t* L_4 = V_1; V_2 = L_4; goto IL_001c; } IL_001c: { String_t* L_5 = V_2; return L_5; } } // System.Boolean UnityEngine.StackTraceUtility::IsSystemStacktraceType(System.Object) extern "C" bool StackTraceUtility_IsSystemStacktraceType_m70277135 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___name0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_IsSystemStacktraceType_m70277135_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; bool V_1 = false; int32_t G_B7_0 = 0; { RuntimeObject * L_0 = ___name0; V_0 = ((String_t*)CastclassSealed((RuntimeObject*)L_0, String_t_il2cpp_TypeInfo_var)); String_t* L_1 = V_0; NullCheck(L_1); bool L_2 = String_StartsWith_m2227418833(L_1, _stringLiteral676969769, /*hidden argument*/NULL); if (L_2) { goto IL_0065; } } { String_t* L_3 = V_0; NullCheck(L_3); bool L_4 = String_StartsWith_m2227418833(L_3, _stringLiteral155130972, /*hidden argument*/NULL); if (L_4) { goto IL_0065; } } { String_t* L_5 = V_0; NullCheck(L_5); bool L_6 = String_StartsWith_m2227418833(L_5, _stringLiteral2311935814, /*hidden argument*/NULL); if (L_6) { goto IL_0065; } } { String_t* L_7 = V_0; NullCheck(L_7); bool L_8 = String_StartsWith_m2227418833(L_7, _stringLiteral2930130424, /*hidden argument*/NULL); if (L_8) { goto IL_0065; } } { String_t* L_9 = V_0; NullCheck(L_9); bool L_10 = String_StartsWith_m2227418833(L_9, _stringLiteral2902902247, /*hidden argument*/NULL); if (L_10) { goto IL_0065; } } { String_t* L_11 = V_0; NullCheck(L_11); bool L_12 = String_StartsWith_m2227418833(L_11, _stringLiteral1845300824, /*hidden argument*/NULL); G_B7_0 = ((int32_t)(L_12)); goto IL_0066; } IL_0065: { G_B7_0 = 1; } IL_0066: { V_1 = (bool)G_B7_0; goto IL_006c; } IL_006c: { bool L_13 = V_1; return L_13; } } // System.Void UnityEngine.StackTraceUtility::ExtractStringFromExceptionInternal(System.Object,System.String&,System.String&) extern "C" void StackTraceUtility_ExtractStringFromExceptionInternal_m1435564516 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___exceptiono0, String_t** ___message1, String_t** ___stackTrace2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_ExtractStringFromExceptionInternal_m1435564516_MetadataUsageId); s_Il2CppMethodInitialized = true; } Exception_t3285241636 * V_0 = NULL; StringBuilder_t313129557 * V_1 = NULL; String_t* V_2 = NULL; String_t* V_3 = NULL; String_t* V_4 = NULL; StackTrace_t798888381 * V_5 = NULL; int32_t G_B7_0 = 0; { RuntimeObject * L_0 = ___exceptiono0; if (L_0) { goto IL_0012; } } { ArgumentException_t270170821 * L_1 = (ArgumentException_t270170821 *)il2cpp_codegen_object_new(ArgumentException_t270170821_il2cpp_TypeInfo_var); ArgumentException__ctor_m3557549525(L_1, _stringLiteral696031758, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_1); } IL_0012: { RuntimeObject * L_2 = ___exceptiono0; V_0 = ((Exception_t3285241636 *)IsInstClass((RuntimeObject*)L_2, Exception_t3285241636_il2cpp_TypeInfo_var)); Exception_t3285241636 * L_3 = V_0; if (L_3) { goto IL_002a; } } { ArgumentException_t270170821 * L_4 = (ArgumentException_t270170821 *)il2cpp_codegen_object_new(ArgumentException_t270170821_il2cpp_TypeInfo_var); ArgumentException__ctor_m3557549525(L_4, _stringLiteral1197065091, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_4); } IL_002a: { Exception_t3285241636 * L_5 = V_0; NullCheck(L_5); String_t* L_6 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Exception::get_StackTrace() */, L_5); if (L_6) { goto IL_003f; } } { G_B7_0 = ((int32_t)512); goto IL_004c; } IL_003f: { Exception_t3285241636 * L_7 = V_0; NullCheck(L_7); String_t* L_8 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Exception::get_StackTrace() */, L_7); NullCheck(L_8); int32_t L_9 = String_get_Length_m38839245(L_8, /*hidden argument*/NULL); G_B7_0 = ((int32_t)((int32_t)L_9*(int32_t)2)); } IL_004c: { StringBuilder_t313129557 * L_10 = (StringBuilder_t313129557 *)il2cpp_codegen_object_new(StringBuilder_t313129557_il2cpp_TypeInfo_var); StringBuilder__ctor_m3754152305(L_10, G_B7_0, /*hidden argument*/NULL); V_1 = L_10; String_t** L_11 = ___message1; *((RuntimeObject **)(L_11)) = (RuntimeObject *)_stringLiteral4212843024; Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_11), (RuntimeObject *)_stringLiteral4212843024); V_2 = _stringLiteral4212843024; goto IL_0106; } IL_0064: { String_t* L_12 = V_2; NullCheck(L_12); int32_t L_13 = String_get_Length_m38839245(L_12, /*hidden argument*/NULL); if (L_13) { goto IL_007c; } } { Exception_t3285241636 * L_14 = V_0; NullCheck(L_14); String_t* L_15 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Exception::get_StackTrace() */, L_14); V_2 = L_15; goto IL_008e; } IL_007c: { Exception_t3285241636 * L_16 = V_0; NullCheck(L_16); String_t* L_17 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Exception::get_StackTrace() */, L_16); String_t* L_18 = V_2; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_19 = String_Concat_m4226800250(NULL /*static, unused*/, L_17, _stringLiteral162306806, L_18, /*hidden argument*/NULL); V_2 = L_19; } IL_008e: { Exception_t3285241636 * L_20 = V_0; NullCheck(L_20); Type_t * L_21 = Exception_GetType_m4106188822(L_20, /*hidden argument*/NULL); NullCheck(L_21); String_t* L_22 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_21); V_3 = L_22; V_4 = _stringLiteral4212843024; Exception_t3285241636 * L_23 = V_0; NullCheck(L_23); String_t* L_24 = VirtFuncInvoker0< String_t* >::Invoke(6 /* System.String System.Exception::get_Message() */, L_23); if (!L_24) { goto IL_00b4; } } { Exception_t3285241636 * L_25 = V_0; NullCheck(L_25); String_t* L_26 = VirtFuncInvoker0< String_t* >::Invoke(6 /* System.String System.Exception::get_Message() */, L_25); V_4 = L_26; } IL_00b4: { String_t* L_27 = V_4; NullCheck(L_27); String_t* L_28 = String_Trim_m2409528586(L_27, /*hidden argument*/NULL); NullCheck(L_28); int32_t L_29 = String_get_Length_m38839245(L_28, /*hidden argument*/NULL); if (!L_29) { goto IL_00dc; } } { String_t* L_30 = V_3; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_31 = String_Concat_m3797386145(NULL /*static, unused*/, L_30, _stringLiteral2733268254, /*hidden argument*/NULL); V_3 = L_31; String_t* L_32 = V_3; String_t* L_33 = V_4; String_t* L_34 = String_Concat_m3797386145(NULL /*static, unused*/, L_32, L_33, /*hidden argument*/NULL); V_3 = L_34; } IL_00dc: { String_t** L_35 = ___message1; String_t* L_36 = V_3; *((RuntimeObject **)(L_35)) = (RuntimeObject *)L_36; Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_35), (RuntimeObject *)L_36); Exception_t3285241636 * L_37 = V_0; NullCheck(L_37); Exception_t3285241636 * L_38 = Exception_get_InnerException_m3140938854(L_37, /*hidden argument*/NULL); if (!L_38) { goto IL_00fe; } } { String_t* L_39 = V_3; String_t* L_40 = V_2; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_41 = String_Concat_m3900126850(NULL /*static, unused*/, _stringLiteral1964127969, L_39, _stringLiteral162306806, L_40, /*hidden argument*/NULL); V_2 = L_41; } IL_00fe: { Exception_t3285241636 * L_42 = V_0; NullCheck(L_42); Exception_t3285241636 * L_43 = Exception_get_InnerException_m3140938854(L_42, /*hidden argument*/NULL); V_0 = L_43; } IL_0106: { Exception_t3285241636 * L_44 = V_0; if (L_44) { goto IL_0064; } } { StringBuilder_t313129557 * L_45 = V_1; String_t* L_46 = V_2; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_47 = String_Concat_m3797386145(NULL /*static, unused*/, L_46, _stringLiteral162306806, /*hidden argument*/NULL); NullCheck(L_45); StringBuilder_Append_m1092472320(L_45, L_47, /*hidden argument*/NULL); StackTrace_t798888381 * L_48 = (StackTrace_t798888381 *)il2cpp_codegen_object_new(StackTrace_t798888381_il2cpp_TypeInfo_var); StackTrace__ctor_m3377607597(L_48, 1, (bool)1, /*hidden argument*/NULL); V_5 = L_48; StringBuilder_t313129557 * L_49 = V_1; StackTrace_t798888381 * L_50 = V_5; IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); String_t* L_51 = StackTraceUtility_ExtractFormattedStackTrace_m2265662347(NULL /*static, unused*/, L_50, /*hidden argument*/NULL); NullCheck(L_49); StringBuilder_Append_m1092472320(L_49, L_51, /*hidden argument*/NULL); String_t** L_52 = ___stackTrace2; StringBuilder_t313129557 * L_53 = V_1; NullCheck(L_53); String_t* L_54 = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, L_53); *((RuntimeObject **)(L_52)) = (RuntimeObject *)L_54; Il2CppCodeGenWriteBarrier((RuntimeObject **)(L_52), (RuntimeObject *)L_54); return; } } // System.String UnityEngine.StackTraceUtility::PostprocessStacktrace(System.String,System.Boolean) extern "C" String_t* StackTraceUtility_PostprocessStacktrace_m2698903637 (RuntimeObject * __this /* static, unused */, String_t* ___oldString0, bool ___stripEngineInternalInformation1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_PostprocessStacktrace_m2698903637_MetadataUsageId); s_Il2CppMethodInitialized = true; } String_t* V_0 = NULL; StringU5BU5D_t3608572874* V_1 = NULL; StringBuilder_t313129557 * V_2 = NULL; int32_t V_3 = 0; int32_t V_4 = 0; String_t* V_5 = NULL; int32_t V_6 = 0; int32_t V_7 = 0; int32_t V_8 = 0; int32_t V_9 = 0; { String_t* L_0 = ___oldString0; if (L_0) { goto IL_0012; } } { IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = ((String_t_StaticFields*)il2cpp_codegen_static_fields_for(String_t_il2cpp_TypeInfo_var))->get_Empty_2(); V_0 = L_1; goto IL_02a4; } IL_0012: { String_t* L_2 = ___oldString0; CharU5BU5D_t1522321484* L_3 = ((CharU5BU5D_t1522321484*)SZArrayNew(CharU5BU5D_t1522321484_il2cpp_TypeInfo_var, (uint32_t)1)); NullCheck(L_3); (L_3)->SetAt(static_cast(0), (Il2CppChar)((int32_t)10)); NullCheck(L_2); StringU5BU5D_t3608572874* L_4 = String_Split_m3520467407(L_2, L_3, /*hidden argument*/NULL); V_1 = L_4; String_t* L_5 = ___oldString0; NullCheck(L_5); int32_t L_6 = String_get_Length_m38839245(L_5, /*hidden argument*/NULL); StringBuilder_t313129557 * L_7 = (StringBuilder_t313129557 *)il2cpp_codegen_object_new(StringBuilder_t313129557_il2cpp_TypeInfo_var); StringBuilder__ctor_m3754152305(L_7, L_6, /*hidden argument*/NULL); V_2 = L_7; V_3 = 0; goto IL_0046; } IL_0037: { StringU5BU5D_t3608572874* L_8 = V_1; int32_t L_9 = V_3; StringU5BU5D_t3608572874* L_10 = V_1; int32_t L_11 = V_3; NullCheck(L_10); int32_t L_12 = L_11; String_t* L_13 = (L_10)->GetAt(static_cast(L_12)); NullCheck(L_13); String_t* L_14 = String_Trim_m2409528586(L_13, /*hidden argument*/NULL); NullCheck(L_8); ArrayElementTypeCheck (L_8, L_14); (L_8)->SetAt(static_cast(L_9), (String_t*)L_14); int32_t L_15 = V_3; V_3 = ((int32_t)((int32_t)L_15+(int32_t)1)); } IL_0046: { int32_t L_16 = V_3; StringU5BU5D_t3608572874* L_17 = V_1; NullCheck(L_17); if ((((int32_t)L_16) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_17)->max_length))))))) { goto IL_0037; } } { V_4 = 0; goto IL_028e; } IL_0057: { StringU5BU5D_t3608572874* L_18 = V_1; int32_t L_19 = V_4; NullCheck(L_18); int32_t L_20 = L_19; String_t* L_21 = (L_18)->GetAt(static_cast(L_20)); V_5 = L_21; String_t* L_22 = V_5; NullCheck(L_22); int32_t L_23 = String_get_Length_m38839245(L_22, /*hidden argument*/NULL); if (!L_23) { goto IL_0079; } } { String_t* L_24 = V_5; NullCheck(L_24); Il2CppChar L_25 = String_get_Chars_m1295159314(L_24, 0, /*hidden argument*/NULL); if ((!(((uint32_t)L_25) == ((uint32_t)((int32_t)10))))) { goto IL_007e; } } IL_0079: { goto IL_0288; } IL_007e: { String_t* L_26 = V_5; NullCheck(L_26); bool L_27 = String_StartsWith_m2227418833(L_26, _stringLiteral1537213814, /*hidden argument*/NULL); if (!L_27) { goto IL_0094; } } { goto IL_0288; } IL_0094: { bool L_28 = ___stripEngineInternalInformation1; if (!L_28) { goto IL_00b0; } } { String_t* L_29 = V_5; NullCheck(L_29); bool L_30 = String_StartsWith_m2227418833(L_29, _stringLiteral1742707595, /*hidden argument*/NULL); if (!L_30) { goto IL_00b0; } } { goto IL_0298; } IL_00b0: { bool L_31 = ___stripEngineInternalInformation1; if (!L_31) { goto IL_0107; } } { int32_t L_32 = V_4; StringU5BU5D_t3608572874* L_33 = V_1; NullCheck(L_33); if ((((int32_t)L_32) >= ((int32_t)((int32_t)((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_33)->max_length))))-(int32_t)1))))) { goto IL_0107; } } { String_t* L_34 = V_5; IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); bool L_35 = StackTraceUtility_IsSystemStacktraceType_m70277135(NULL /*static, unused*/, L_34, /*hidden argument*/NULL); if (!L_35) { goto IL_0107; } } { StringU5BU5D_t3608572874* L_36 = V_1; int32_t L_37 = V_4; NullCheck(L_36); int32_t L_38 = ((int32_t)((int32_t)L_37+(int32_t)1)); String_t* L_39 = (L_36)->GetAt(static_cast(L_38)); IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); bool L_40 = StackTraceUtility_IsSystemStacktraceType_m70277135(NULL /*static, unused*/, L_39, /*hidden argument*/NULL); if (!L_40) { goto IL_00e4; } } { goto IL_0288; } IL_00e4: { String_t* L_41 = V_5; NullCheck(L_41); int32_t L_42 = String_IndexOf_m1185123121(L_41, _stringLiteral1361813893, /*hidden argument*/NULL); V_6 = L_42; int32_t L_43 = V_6; if ((((int32_t)L_43) == ((int32_t)(-1)))) { goto IL_0106; } } { String_t* L_44 = V_5; int32_t L_45 = V_6; NullCheck(L_44); String_t* L_46 = String_Substring_m659618115(L_44, 0, L_45, /*hidden argument*/NULL); V_5 = L_46; } IL_0106: { } IL_0107: { String_t* L_47 = V_5; NullCheck(L_47); int32_t L_48 = String_IndexOf_m1185123121(L_47, _stringLiteral800780832, /*hidden argument*/NULL); if ((((int32_t)L_48) == ((int32_t)(-1)))) { goto IL_011e; } } { goto IL_0288; } IL_011e: { String_t* L_49 = V_5; NullCheck(L_49); int32_t L_50 = String_IndexOf_m1185123121(L_49, _stringLiteral3450408964, /*hidden argument*/NULL); if ((((int32_t)L_50) == ((int32_t)(-1)))) { goto IL_0135; } } { goto IL_0288; } IL_0135: { String_t* L_51 = V_5; NullCheck(L_51); int32_t L_52 = String_IndexOf_m1185123121(L_51, _stringLiteral1173566749, /*hidden argument*/NULL); if ((((int32_t)L_52) == ((int32_t)(-1)))) { goto IL_014c; } } { goto IL_0288; } IL_014c: { bool L_53 = ___stripEngineInternalInformation1; if (!L_53) { goto IL_0179; } } { String_t* L_54 = V_5; NullCheck(L_54); bool L_55 = String_StartsWith_m2227418833(L_54, _stringLiteral1427619272, /*hidden argument*/NULL); if (!L_55) { goto IL_0179; } } { String_t* L_56 = V_5; NullCheck(L_56); bool L_57 = String_EndsWith_m2914504526(L_56, _stringLiteral1109926636, /*hidden argument*/NULL); if (!L_57) { goto IL_0179; } } { goto IL_0288; } IL_0179: { String_t* L_58 = V_5; NullCheck(L_58); bool L_59 = String_StartsWith_m2227418833(L_58, _stringLiteral3731977866, /*hidden argument*/NULL); if (!L_59) { goto IL_0197; } } { String_t* L_60 = V_5; NullCheck(L_60); String_t* L_61 = String_Remove_m2484650411(L_60, 0, 3, /*hidden argument*/NULL); V_5 = L_61; } IL_0197: { String_t* L_62 = V_5; NullCheck(L_62); int32_t L_63 = String_IndexOf_m1185123121(L_62, _stringLiteral3979129001, /*hidden argument*/NULL); V_7 = L_63; V_8 = (-1); int32_t L_64 = V_7; if ((((int32_t)L_64) == ((int32_t)(-1)))) { goto IL_01c0; } } { String_t* L_65 = V_5; int32_t L_66 = V_7; NullCheck(L_65); int32_t L_67 = String_IndexOf_m3631343126(L_65, _stringLiteral1109926636, L_66, /*hidden argument*/NULL); V_8 = L_67; } IL_01c0: { int32_t L_68 = V_7; if ((((int32_t)L_68) == ((int32_t)(-1)))) { goto IL_01e5; } } { int32_t L_69 = V_8; int32_t L_70 = V_7; if ((((int32_t)L_69) <= ((int32_t)L_70))) { goto IL_01e5; } } { String_t* L_71 = V_5; int32_t L_72 = V_7; int32_t L_73 = V_8; int32_t L_74 = V_7; NullCheck(L_71); String_t* L_75 = String_Remove_m2484650411(L_71, L_72, ((int32_t)((int32_t)((int32_t)((int32_t)L_73-(int32_t)L_74))+(int32_t)1)), /*hidden argument*/NULL); V_5 = L_75; } IL_01e5: { String_t* L_76 = V_5; NullCheck(L_76); String_t* L_77 = String_Replace_m212902530(L_76, _stringLiteral675700299, _stringLiteral4212843024, /*hidden argument*/NULL); V_5 = L_77; String_t* L_78 = V_5; NullCheck(L_78); String_t* L_79 = String_Replace_m212902530(L_78, _stringLiteral3572222939, _stringLiteral3343446928, /*hidden argument*/NULL); V_5 = L_79; String_t* L_80 = V_5; IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); String_t* L_81 = ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->get_projectFolder_0(); NullCheck(L_80); String_t* L_82 = String_Replace_m212902530(L_80, L_81, _stringLiteral4212843024, /*hidden argument*/NULL); V_5 = L_82; String_t* L_83 = V_5; NullCheck(L_83); String_t* L_84 = String_Replace_m4026310352(L_83, ((int32_t)92), ((int32_t)47), /*hidden argument*/NULL); V_5 = L_84; String_t* L_85 = V_5; NullCheck(L_85); int32_t L_86 = String_LastIndexOf_m2697281871(L_85, _stringLiteral1328470161, /*hidden argument*/NULL); V_9 = L_86; int32_t L_87 = V_9; if ((((int32_t)L_87) == ((int32_t)(-1)))) { goto IL_0274; } } { String_t* L_88 = V_5; int32_t L_89 = V_9; NullCheck(L_88); String_t* L_90 = String_Remove_m2484650411(L_88, L_89, 5, /*hidden argument*/NULL); V_5 = L_90; String_t* L_91 = V_5; int32_t L_92 = V_9; NullCheck(L_91); String_t* L_93 = String_Insert_m1241113509(L_91, L_92, _stringLiteral1284737963, /*hidden argument*/NULL); V_5 = L_93; String_t* L_94 = V_5; String_t* L_95 = V_5; NullCheck(L_95); int32_t L_96 = String_get_Length_m38839245(L_95, /*hidden argument*/NULL); NullCheck(L_94); String_t* L_97 = String_Insert_m1241113509(L_94, L_96, _stringLiteral2696783159, /*hidden argument*/NULL); V_5 = L_97; } IL_0274: { StringBuilder_t313129557 * L_98 = V_2; String_t* L_99 = V_5; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_100 = String_Concat_m3797386145(NULL /*static, unused*/, L_99, _stringLiteral162306806, /*hidden argument*/NULL); NullCheck(L_98); StringBuilder_Append_m1092472320(L_98, L_100, /*hidden argument*/NULL); } IL_0288: { int32_t L_101 = V_4; V_4 = ((int32_t)((int32_t)L_101+(int32_t)1)); } IL_028e: { int32_t L_102 = V_4; StringU5BU5D_t3608572874* L_103 = V_1; NullCheck(L_103); if ((((int32_t)L_102) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_103)->max_length))))))) { goto IL_0057; } } IL_0298: { StringBuilder_t313129557 * L_104 = V_2; NullCheck(L_104); String_t* L_105 = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, L_104); V_0 = L_105; goto IL_02a4; } IL_02a4: { String_t* L_106 = V_0; return L_106; } } // System.String UnityEngine.StackTraceUtility::ExtractFormattedStackTrace(System.Diagnostics.StackTrace) extern "C" String_t* StackTraceUtility_ExtractFormattedStackTrace_m2265662347 (RuntimeObject * __this /* static, unused */, StackTrace_t798888381 * ___stackTrace0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility_ExtractFormattedStackTrace_m2265662347_MetadataUsageId); s_Il2CppMethodInitialized = true; } StringBuilder_t313129557 * V_0 = NULL; int32_t V_1 = 0; StackFrame_t2547199141 * V_2 = NULL; MethodBase_t710954372 * V_3 = NULL; Type_t * V_4 = NULL; String_t* V_5 = NULL; int32_t V_6 = 0; ParameterInfoU5BU5D_t2585026604* V_7 = NULL; bool V_8 = false; String_t* V_9 = NULL; bool V_10 = false; int32_t V_11 = 0; String_t* V_12 = NULL; int32_t G_B27_0 = 0; int32_t G_B29_0 = 0; { StringBuilder_t313129557 * L_0 = (StringBuilder_t313129557 *)il2cpp_codegen_object_new(StringBuilder_t313129557_il2cpp_TypeInfo_var); StringBuilder__ctor_m3754152305(L_0, ((int32_t)255), /*hidden argument*/NULL); V_0 = L_0; V_1 = 0; goto IL_02ba; } IL_0013: { StackTrace_t798888381 * L_1 = ___stackTrace0; int32_t L_2 = V_1; NullCheck(L_1); StackFrame_t2547199141 * L_3 = VirtFuncInvoker1< StackFrame_t2547199141 *, int32_t >::Invoke(5 /* System.Diagnostics.StackFrame System.Diagnostics.StackTrace::GetFrame(System.Int32) */, L_1, L_2); V_2 = L_3; StackFrame_t2547199141 * L_4 = V_2; NullCheck(L_4); MethodBase_t710954372 * L_5 = VirtFuncInvoker0< MethodBase_t710954372 * >::Invoke(7 /* System.Reflection.MethodBase System.Diagnostics.StackFrame::GetMethod() */, L_4); V_3 = L_5; MethodBase_t710954372 * L_6 = V_3; if (L_6) { goto IL_002e; } } { goto IL_02b6; } IL_002e: { MethodBase_t710954372 * L_7 = V_3; NullCheck(L_7); Type_t * L_8 = VirtFuncInvoker0< Type_t * >::Invoke(6 /* System.Type System.Reflection.MemberInfo::get_DeclaringType() */, L_7); V_4 = L_8; Type_t * L_9 = V_4; if (L_9) { goto IL_0042; } } { goto IL_02b6; } IL_0042: { Type_t * L_10 = V_4; NullCheck(L_10); String_t* L_11 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_10); V_5 = L_11; String_t* L_12 = V_5; if (!L_12) { goto IL_0075; } } { String_t* L_13 = V_5; NullCheck(L_13); int32_t L_14 = String_get_Length_m38839245(L_13, /*hidden argument*/NULL); if (!L_14) { goto IL_0075; } } { StringBuilder_t313129557 * L_15 = V_0; String_t* L_16 = V_5; NullCheck(L_15); StringBuilder_Append_m1092472320(L_15, L_16, /*hidden argument*/NULL); StringBuilder_t313129557 * L_17 = V_0; NullCheck(L_17); StringBuilder_Append_m1092472320(L_17, _stringLiteral257692189, /*hidden argument*/NULL); } IL_0075: { StringBuilder_t313129557 * L_18 = V_0; Type_t * L_19 = V_4; NullCheck(L_19); String_t* L_20 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_19); NullCheck(L_18); StringBuilder_Append_m1092472320(L_18, L_20, /*hidden argument*/NULL); StringBuilder_t313129557 * L_21 = V_0; NullCheck(L_21); StringBuilder_Append_m1092472320(L_21, _stringLiteral3341918290, /*hidden argument*/NULL); StringBuilder_t313129557 * L_22 = V_0; MethodBase_t710954372 * L_23 = V_3; NullCheck(L_23); String_t* L_24 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_23); NullCheck(L_22); StringBuilder_Append_m1092472320(L_22, L_24, /*hidden argument*/NULL); StringBuilder_t313129557 * L_25 = V_0; NullCheck(L_25); StringBuilder_Append_m1092472320(L_25, _stringLiteral2063084106, /*hidden argument*/NULL); V_6 = 0; MethodBase_t710954372 * L_26 = V_3; NullCheck(L_26); ParameterInfoU5BU5D_t2585026604* L_27 = VirtFuncInvoker0< ParameterInfoU5BU5D_t2585026604* >::Invoke(14 /* System.Reflection.ParameterInfo[] System.Reflection.MethodBase::GetParameters() */, L_26); V_7 = L_27; V_8 = (bool)1; goto IL_00f4; } IL_00bb: { bool L_28 = V_8; if (L_28) { goto IL_00d4; } } { StringBuilder_t313129557 * L_29 = V_0; NullCheck(L_29); StringBuilder_Append_m1092472320(L_29, _stringLiteral3525100246, /*hidden argument*/NULL); goto IL_00d7; } IL_00d4: { V_8 = (bool)0; } IL_00d7: { StringBuilder_t313129557 * L_30 = V_0; ParameterInfoU5BU5D_t2585026604* L_31 = V_7; int32_t L_32 = V_6; NullCheck(L_31); int32_t L_33 = L_32; ParameterInfo_t1917333745 * L_34 = (L_31)->GetAt(static_cast(L_33)); NullCheck(L_34); Type_t * L_35 = VirtFuncInvoker0< Type_t * >::Invoke(6 /* System.Type System.Reflection.ParameterInfo::get_ParameterType() */, L_34); NullCheck(L_35); String_t* L_36 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_35); NullCheck(L_30); StringBuilder_Append_m1092472320(L_30, L_36, /*hidden argument*/NULL); int32_t L_37 = V_6; V_6 = ((int32_t)((int32_t)L_37+(int32_t)1)); } IL_00f4: { int32_t L_38 = V_6; ParameterInfoU5BU5D_t2585026604* L_39 = V_7; NullCheck(L_39); if ((((int32_t)L_38) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_39)->max_length))))))) { goto IL_00bb; } } { StringBuilder_t313129557 * L_40 = V_0; NullCheck(L_40); StringBuilder_Append_m1092472320(L_40, _stringLiteral2696783159, /*hidden argument*/NULL); StackFrame_t2547199141 * L_41 = V_2; NullCheck(L_41); String_t* L_42 = VirtFuncInvoker0< String_t* >::Invoke(5 /* System.String System.Diagnostics.StackFrame::GetFileName() */, L_41); V_9 = L_42; String_t* L_43 = V_9; if (!L_43) { goto IL_02a9; } } { Type_t * L_44 = V_4; NullCheck(L_44); String_t* L_45 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_44); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_46 = String_op_Equality_m767991535(NULL /*static, unused*/, L_45, _stringLiteral2622672072, /*hidden argument*/NULL); if (!L_46) { goto IL_0147; } } { Type_t * L_47 = V_4; NullCheck(L_47); String_t* L_48 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_47); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_49 = String_op_Equality_m767991535(NULL /*static, unused*/, L_48, _stringLiteral1864495309, /*hidden argument*/NULL); if (L_49) { goto IL_020c; } } IL_0147: { Type_t * L_50 = V_4; NullCheck(L_50); String_t* L_51 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_50); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_52 = String_op_Equality_m767991535(NULL /*static, unused*/, L_51, _stringLiteral3096061537, /*hidden argument*/NULL); if (!L_52) { goto IL_0173; } } { Type_t * L_53 = V_4; NullCheck(L_53); String_t* L_54 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_53); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_55 = String_op_Equality_m767991535(NULL /*static, unused*/, L_54, _stringLiteral1864495309, /*hidden argument*/NULL); if (L_55) { goto IL_020c; } } IL_0173: { Type_t * L_56 = V_4; NullCheck(L_56); String_t* L_57 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_56); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_58 = String_op_Equality_m767991535(NULL /*static, unused*/, L_57, _stringLiteral1633200396, /*hidden argument*/NULL); if (!L_58) { goto IL_019f; } } { Type_t * L_59 = V_4; NullCheck(L_59); String_t* L_60 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_59); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_61 = String_op_Equality_m767991535(NULL /*static, unused*/, L_60, _stringLiteral1864495309, /*hidden argument*/NULL); if (L_61) { goto IL_020c; } } IL_019f: { Type_t * L_62 = V_4; NullCheck(L_62); String_t* L_63 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_62); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_64 = String_op_Equality_m767991535(NULL /*static, unused*/, L_63, _stringLiteral3230881341, /*hidden argument*/NULL); if (!L_64) { goto IL_01cb; } } { Type_t * L_65 = V_4; NullCheck(L_65); String_t* L_66 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_65); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_67 = String_op_Equality_m767991535(NULL /*static, unused*/, L_66, _stringLiteral2222186932, /*hidden argument*/NULL); if (L_67) { goto IL_020c; } } IL_01cb: { MethodBase_t710954372 * L_68 = V_3; NullCheck(L_68); String_t* L_69 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_68); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_70 = String_op_Equality_m767991535(NULL /*static, unused*/, L_69, _stringLiteral1917672447, /*hidden argument*/NULL); if (!L_70) { goto IL_0209; } } { Type_t * L_71 = V_4; NullCheck(L_71); String_t* L_72 = VirtFuncInvoker0< String_t* >::Invoke(8 /* System.String System.Reflection.MemberInfo::get_Name() */, L_71); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_73 = String_op_Equality_m767991535(NULL /*static, unused*/, L_72, _stringLiteral2694655422, /*hidden argument*/NULL); if (!L_73) { goto IL_0209; } } { Type_t * L_74 = V_4; NullCheck(L_74); String_t* L_75 = VirtFuncInvoker0< String_t* >::Invoke(34 /* System.String System.Type::get_Namespace() */, L_74); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_76 = String_op_Equality_m767991535(NULL /*static, unused*/, L_75, _stringLiteral1864495309, /*hidden argument*/NULL); G_B27_0 = ((int32_t)(L_76)); goto IL_020a; } IL_0209: { G_B27_0 = 0; } IL_020a: { G_B29_0 = G_B27_0; goto IL_020d; } IL_020c: { G_B29_0 = 1; } IL_020d: { V_10 = (bool)G_B29_0; bool L_77 = V_10; if (L_77) { goto IL_02a8; } } { StringBuilder_t313129557 * L_78 = V_0; NullCheck(L_78); StringBuilder_Append_m1092472320(L_78, _stringLiteral1284737963, /*hidden argument*/NULL); String_t* L_79 = V_9; NullCheck(L_79); String_t* L_80 = String_Replace_m212902530(L_79, _stringLiteral3572222939, _stringLiteral3343446928, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); String_t* L_81 = ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->get_projectFolder_0(); NullCheck(L_80); bool L_82 = String_StartsWith_m2227418833(L_80, L_81, /*hidden argument*/NULL); if (!L_82) { goto IL_026a; } } { String_t* L_83 = V_9; IL2CPP_RUNTIME_CLASS_INIT(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var); String_t* L_84 = ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->get_projectFolder_0(); NullCheck(L_84); int32_t L_85 = String_get_Length_m38839245(L_84, /*hidden argument*/NULL); String_t* L_86 = V_9; NullCheck(L_86); int32_t L_87 = String_get_Length_m38839245(L_86, /*hidden argument*/NULL); String_t* L_88 = ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->get_projectFolder_0(); NullCheck(L_88); int32_t L_89 = String_get_Length_m38839245(L_88, /*hidden argument*/NULL); NullCheck(L_83); String_t* L_90 = String_Substring_m659618115(L_83, L_85, ((int32_t)((int32_t)L_87-(int32_t)L_89)), /*hidden argument*/NULL); V_9 = L_90; } IL_026a: { StringBuilder_t313129557 * L_91 = V_0; String_t* L_92 = V_9; NullCheck(L_91); StringBuilder_Append_m1092472320(L_91, L_92, /*hidden argument*/NULL); StringBuilder_t313129557 * L_93 = V_0; NullCheck(L_93); StringBuilder_Append_m1092472320(L_93, _stringLiteral3341918290, /*hidden argument*/NULL); StringBuilder_t313129557 * L_94 = V_0; StackFrame_t2547199141 * L_95 = V_2; NullCheck(L_95); int32_t L_96 = VirtFuncInvoker0< int32_t >::Invoke(4 /* System.Int32 System.Diagnostics.StackFrame::GetFileLineNumber() */, L_95); V_11 = L_96; String_t* L_97 = Int32_ToString_m1159740622((&V_11), /*hidden argument*/NULL); NullCheck(L_94); StringBuilder_Append_m1092472320(L_94, L_97, /*hidden argument*/NULL); StringBuilder_t313129557 * L_98 = V_0; NullCheck(L_98); StringBuilder_Append_m1092472320(L_98, _stringLiteral2696783159, /*hidden argument*/NULL); } IL_02a8: { } IL_02a9: { StringBuilder_t313129557 * L_99 = V_0; NullCheck(L_99); StringBuilder_Append_m1092472320(L_99, _stringLiteral162306806, /*hidden argument*/NULL); } IL_02b6: { int32_t L_100 = V_1; V_1 = ((int32_t)((int32_t)L_100+(int32_t)1)); } IL_02ba: { int32_t L_101 = V_1; StackTrace_t798888381 * L_102 = ___stackTrace0; NullCheck(L_102); int32_t L_103 = VirtFuncInvoker0< int32_t >::Invoke(4 /* System.Int32 System.Diagnostics.StackTrace::get_FrameCount() */, L_102); if ((((int32_t)L_101) < ((int32_t)L_103))) { goto IL_0013; } } { StringBuilder_t313129557 * L_104 = V_0; NullCheck(L_104); String_t* L_105 = VirtFuncInvoker0< String_t* >::Invoke(3 /* System.String System.Object::ToString() */, L_104); V_12 = L_105; goto IL_02d3; } IL_02d3: { String_t* L_106 = V_12; return L_106; } } // System.Void UnityEngine.StackTraceUtility::.cctor() extern "C" void StackTraceUtility__cctor_m2051063265 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (StackTraceUtility__cctor_m2051063265_MetadataUsageId); s_Il2CppMethodInitialized = true; } { ((StackTraceUtility_t1534026680_StaticFields*)il2cpp_codegen_static_fields_for(StackTraceUtility_t1534026680_il2cpp_TypeInfo_var))->set_projectFolder_0(_stringLiteral4212843024); return; } } // System.Void UnityEngine.StateMachineBehaviour::.ctor() extern "C" void StateMachineBehaviour__ctor_m1629655286 (StateMachineBehaviour_t2091767483 * __this, const RuntimeMethod* method) { { ScriptableObject__ctor_m3935827375(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateEnter(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32) extern "C" void StateMachineBehaviour_OnStateEnter_m2392832795 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateUpdate(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32) extern "C" void StateMachineBehaviour_OnStateUpdate_m4017265790 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateExit(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32) extern "C" void StateMachineBehaviour_OnStateExit_m1788743454 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMove(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32) extern "C" void StateMachineBehaviour_OnStateMove_m2512939908 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateIK(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32) extern "C" void StateMachineBehaviour_OnStateIK_m735645240 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMachineEnter(UnityEngine.Animator,System.Int32) extern "C" void StateMachineBehaviour_OnStateMachineEnter_m3635469714 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, int32_t ___stateMachinePathHash1, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMachineExit(UnityEngine.Animator,System.Int32) extern "C" void StateMachineBehaviour_OnStateMachineExit_m1686688589 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, int32_t ___stateMachinePathHash1, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateEnter(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateEnter_m37543043 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, AnimatorControllerPlayable_t3898188599 ___controller3, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateUpdate(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateUpdate_m3820310185 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, AnimatorControllerPlayable_t3898188599 ___controller3, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateExit(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateExit_m2656655813 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, AnimatorControllerPlayable_t3898188599 ___controller3, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMove(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateMove_m3003839180 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, AnimatorControllerPlayable_t3898188599 ___controller3, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateIK(UnityEngine.Animator,UnityEngine.AnimatorStateInfo,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateIK_m3036912078 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, AnimatorStateInfo_t3042152932 ___stateInfo1, int32_t ___layerIndex2, AnimatorControllerPlayable_t3898188599 ___controller3, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMachineEnter(UnityEngine.Animator,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateMachineEnter_m249635709 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, int32_t ___stateMachinePathHash1, AnimatorControllerPlayable_t3898188599 ___controller2, const RuntimeMethod* method) { { return; } } // System.Void UnityEngine.StateMachineBehaviour::OnStateMachineExit(UnityEngine.Animator,System.Int32,UnityEngine.Animations.AnimatorControllerPlayable) extern "C" void StateMachineBehaviour_OnStateMachineExit_m2625462685 (StateMachineBehaviour_t2091767483 * __this, Animator_t3669487027 * ___animator0, int32_t ___stateMachinePathHash1, AnimatorControllerPlayable_t3898188599 ___controller2, const RuntimeMethod* method) { { return; } } // UnityEngine.OperatingSystemFamily UnityEngine.SystemInfo::get_operatingSystemFamily() extern "C" int32_t SystemInfo_get_operatingSystemFamily_m1305796766 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef int32_t (*SystemInfo_get_operatingSystemFamily_m1305796766_ftn) (); static SystemInfo_get_operatingSystemFamily_m1305796766_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SystemInfo_get_operatingSystemFamily_m1305796766_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SystemInfo::get_operatingSystemFamily()"); int32_t retVal = _il2cpp_icall_func(); return retVal; } // System.Void UnityEngine.TextAreaAttribute::.ctor(System.Int32,System.Int32) extern "C" void TextAreaAttribute__ctor_m2561858287 (TextAreaAttribute_t2984524453 * __this, int32_t ___minLines0, int32_t ___maxLines1, const RuntimeMethod* method) { { PropertyAttribute__ctor_m1537537891(__this, /*hidden argument*/NULL); int32_t L_0 = ___minLines0; __this->set_minLines_0(L_0); int32_t L_1 = ___maxLines1; __this->set_maxLines_1(L_1); return; } } // System.String UnityEngine.TextAsset::get_text() extern "C" String_t* TextAsset_get_text_m3742127726 (TextAsset_t2643108631 * __this, const RuntimeMethod* method) { typedef String_t* (*TextAsset_get_text_m3742127726_ftn) (TextAsset_t2643108631 *); static TextAsset_get_text_m3742127726_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextAsset_get_text_m3742127726_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextAsset::get_text()"); String_t* retVal = _il2cpp_icall_func(__this); return retVal; } // System.String UnityEngine.TextAsset::ToString() extern "C" String_t* TextAsset_ToString_m1805285601 (TextAsset_t2643108631 * __this, const RuntimeMethod* method) { String_t* V_0 = NULL; { String_t* L_0 = TextAsset_get_text_m3742127726(__this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000d; } IL_000d: { String_t* L_1 = V_0; return L_1; } } // System.Void UnityEngine.TextEditor::.ctor() extern "C" void TextEditor__ctor_m1004933930 (TextEditor_t876577383 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextEditor__ctor_m1004933930_MetadataUsageId); s_Il2CppMethodInitialized = true; } { __this->set_keyboardOnScreen_0((TouchScreenKeyboard_t1595360201 *)NULL); __this->set_controlID_1(0); IL2CPP_RUNTIME_CLASS_INIT(GUIStyle_t4033995491_il2cpp_TypeInfo_var); GUIStyle_t4033995491 * L_0 = GUIStyle_get_none_m4014421518(NULL /*static, unused*/, /*hidden argument*/NULL); __this->set_style_2(L_0); __this->set_multiline_3((bool)0); __this->set_hasHorizontalCursorPos_4((bool)0); __this->set_isPasswordField_5((bool)0); IL2CPP_RUNTIME_CLASS_INIT(Vector2_t3854014517_il2cpp_TypeInfo_var); Vector2_t3854014517 L_1 = Vector2_get_zero_m1977254044(NULL /*static, unused*/, /*hidden argument*/NULL); __this->set_scrollOffset_6(L_1); GUIContent_t3165057865 * L_2 = (GUIContent_t3165057865 *)il2cpp_codegen_object_new(GUIContent_t3165057865_il2cpp_TypeInfo_var); GUIContent__ctor_m3699292156(L_2, /*hidden argument*/NULL); __this->set_m_Content_7(L_2); __this->set_m_CursorIndex_8(0); __this->set_m_SelectIndex_9(0); __this->set_m_RevealCursor_10((bool)0); __this->set_m_MouseDragSelectsWholeWords_11((bool)0); __this->set_m_DblClickInitPos_12(0); __this->set_m_DblClickSnap_13(0); __this->set_m_bJustSelected_14((bool)0); __this->set_m_iAltCursorPos_15((-1)); Object__ctor_m1196001181(__this, /*hidden argument*/NULL); return; } } // Conversion methods for marshalling of: UnityEngine.TextGenerationSettings extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke(const TextGenerationSettings_t2955391441& unmarshaled, TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___font_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'font' of type 'TextGenerationSettings': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___font_0Exception); } extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke_back(const TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled, TextGenerationSettings_t2955391441& unmarshaled) { Il2CppCodeGenException* ___font_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'font' of type 'TextGenerationSettings': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___font_0Exception); } // Conversion method for clean up from marshalling of: UnityEngine.TextGenerationSettings extern "C" void TextGenerationSettings_t2955391441_marshal_pinvoke_cleanup(TextGenerationSettings_t2955391441_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.TextGenerationSettings extern "C" void TextGenerationSettings_t2955391441_marshal_com(const TextGenerationSettings_t2955391441& unmarshaled, TextGenerationSettings_t2955391441_marshaled_com& marshaled) { Il2CppCodeGenException* ___font_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'font' of type 'TextGenerationSettings': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___font_0Exception); } extern "C" void TextGenerationSettings_t2955391441_marshal_com_back(const TextGenerationSettings_t2955391441_marshaled_com& marshaled, TextGenerationSettings_t2955391441& unmarshaled) { Il2CppCodeGenException* ___font_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'font' of type 'TextGenerationSettings': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___font_0Exception); } // Conversion method for clean up from marshalling of: UnityEngine.TextGenerationSettings extern "C" void TextGenerationSettings_t2955391441_marshal_com_cleanup(TextGenerationSettings_t2955391441_marshaled_com& marshaled) { } // System.Boolean UnityEngine.TextGenerationSettings::CompareColors(UnityEngine.Color,UnityEngine.Color) extern "C" bool TextGenerationSettings_CompareColors_m4161672168 (TextGenerationSettings_t2955391441 * __this, Color_t267620335 ___left0, Color_t267620335 ___right1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerationSettings_CompareColors_m4161672168_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; int32_t G_B5_0 = 0; { float L_0 = (&___left0)->get_r_0(); float L_1 = (&___right1)->get_r_0(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_2 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_005e; } } { float L_3 = (&___left0)->get_g_1(); float L_4 = (&___right1)->get_g_1(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_5 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); if (!L_5) { goto IL_005e; } } { float L_6 = (&___left0)->get_b_2(); float L_7 = (&___right1)->get_b_2(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_8 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_6, L_7, /*hidden argument*/NULL); if (!L_8) { goto IL_005e; } } { float L_9 = (&___left0)->get_a_3(); float L_10 = (&___right1)->get_a_3(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_11 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_9, L_10, /*hidden argument*/NULL); G_B5_0 = ((int32_t)(L_11)); goto IL_005f; } IL_005e: { G_B5_0 = 0; } IL_005f: { V_0 = (bool)G_B5_0; goto IL_0065; } IL_0065: { bool L_12 = V_0; return L_12; } } extern "C" bool TextGenerationSettings_CompareColors_m4161672168_AdjustorThunk (RuntimeObject * __this, Color_t267620335 ___left0, Color_t267620335 ___right1, const RuntimeMethod* method) { TextGenerationSettings_t2955391441 * _thisAdjusted = reinterpret_cast(__this + 1); return TextGenerationSettings_CompareColors_m4161672168(_thisAdjusted, ___left0, ___right1, method); } // System.Boolean UnityEngine.TextGenerationSettings::CompareVector2(UnityEngine.Vector2,UnityEngine.Vector2) extern "C" bool TextGenerationSettings_CompareVector2_m2697891872 (TextGenerationSettings_t2955391441 * __this, Vector2_t3854014517 ___left0, Vector2_t3854014517 ___right1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerationSettings_CompareVector2_m2697891872_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; int32_t G_B3_0 = 0; { float L_0 = (&___left0)->get_x_0(); float L_1 = (&___right1)->get_x_0(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_2 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_002e; } } { float L_3 = (&___left0)->get_y_1(); float L_4 = (&___right1)->get_y_1(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_5 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_3, L_4, /*hidden argument*/NULL); G_B3_0 = ((int32_t)(L_5)); goto IL_002f; } IL_002e: { G_B3_0 = 0; } IL_002f: { V_0 = (bool)G_B3_0; goto IL_0035; } IL_0035: { bool L_6 = V_0; return L_6; } } extern "C" bool TextGenerationSettings_CompareVector2_m2697891872_AdjustorThunk (RuntimeObject * __this, Vector2_t3854014517 ___left0, Vector2_t3854014517 ___right1, const RuntimeMethod* method) { TextGenerationSettings_t2955391441 * _thisAdjusted = reinterpret_cast(__this + 1); return TextGenerationSettings_CompareVector2_m2697891872(_thisAdjusted, ___left0, ___right1, method); } // System.Boolean UnityEngine.TextGenerationSettings::Equals(UnityEngine.TextGenerationSettings) extern "C" bool TextGenerationSettings_Equals_m872373524 (TextGenerationSettings_t2955391441 * __this, TextGenerationSettings_t2955391441 ___other0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerationSettings_Equals_m872373524_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; int32_t G_B21_0 = 0; { Color_t267620335 L_0 = __this->get_color_1(); Color_t267620335 L_1 = (&___other0)->get_color_1(); bool L_2 = TextGenerationSettings_CompareColors_m4161672168(__this, L_0, L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_0187; } } { int32_t L_3 = __this->get_fontSize_2(); int32_t L_4 = (&___other0)->get_fontSize_2(); if ((!(((uint32_t)L_3) == ((uint32_t)L_4)))) { goto IL_0187; } } { float L_5 = __this->get_scaleFactor_5(); float L_6 = (&___other0)->get_scaleFactor_5(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_7 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_5, L_6, /*hidden argument*/NULL); if (!L_7) { goto IL_0187; } } { int32_t L_8 = __this->get_resizeTextMinSize_10(); int32_t L_9 = (&___other0)->get_resizeTextMinSize_10(); if ((!(((uint32_t)L_8) == ((uint32_t)L_9)))) { goto IL_0187; } } { int32_t L_10 = __this->get_resizeTextMaxSize_11(); int32_t L_11 = (&___other0)->get_resizeTextMaxSize_11(); if ((!(((uint32_t)L_10) == ((uint32_t)L_11)))) { goto IL_0187; } } { float L_12 = __this->get_lineSpacing_3(); float L_13 = (&___other0)->get_lineSpacing_3(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_t2756327229_il2cpp_TypeInfo_var); bool L_14 = Mathf_Approximately_m2771810637(NULL /*static, unused*/, L_12, L_13, /*hidden argument*/NULL); if (!L_14) { goto IL_0187; } } { int32_t L_15 = __this->get_fontStyle_6(); int32_t L_16 = (&___other0)->get_fontStyle_6(); if ((!(((uint32_t)L_15) == ((uint32_t)L_16)))) { goto IL_0187; } } { bool L_17 = __this->get_richText_4(); bool L_18 = (&___other0)->get_richText_4(); if ((!(((uint32_t)L_17) == ((uint32_t)L_18)))) { goto IL_0187; } } { int32_t L_19 = __this->get_textAnchor_7(); int32_t L_20 = (&___other0)->get_textAnchor_7(); if ((!(((uint32_t)L_19) == ((uint32_t)L_20)))) { goto IL_0187; } } { bool L_21 = __this->get_alignByGeometry_8(); bool L_22 = (&___other0)->get_alignByGeometry_8(); if ((!(((uint32_t)L_21) == ((uint32_t)L_22)))) { goto IL_0187; } } { bool L_23 = __this->get_resizeTextForBestFit_9(); bool L_24 = (&___other0)->get_resizeTextForBestFit_9(); if ((!(((uint32_t)L_23) == ((uint32_t)L_24)))) { goto IL_0187; } } { int32_t L_25 = __this->get_resizeTextMinSize_10(); int32_t L_26 = (&___other0)->get_resizeTextMinSize_10(); if ((!(((uint32_t)L_25) == ((uint32_t)L_26)))) { goto IL_0187; } } { int32_t L_27 = __this->get_resizeTextMaxSize_11(); int32_t L_28 = (&___other0)->get_resizeTextMaxSize_11(); if ((!(((uint32_t)L_27) == ((uint32_t)L_28)))) { goto IL_0187; } } { bool L_29 = __this->get_resizeTextForBestFit_9(); bool L_30 = (&___other0)->get_resizeTextForBestFit_9(); if ((!(((uint32_t)L_29) == ((uint32_t)L_30)))) { goto IL_0187; } } { bool L_31 = __this->get_updateBounds_12(); bool L_32 = (&___other0)->get_updateBounds_12(); if ((!(((uint32_t)L_31) == ((uint32_t)L_32)))) { goto IL_0187; } } { int32_t L_33 = __this->get_horizontalOverflow_14(); int32_t L_34 = (&___other0)->get_horizontalOverflow_14(); if ((!(((uint32_t)L_33) == ((uint32_t)L_34)))) { goto IL_0187; } } { int32_t L_35 = __this->get_verticalOverflow_13(); int32_t L_36 = (&___other0)->get_verticalOverflow_13(); if ((!(((uint32_t)L_35) == ((uint32_t)L_36)))) { goto IL_0187; } } { Vector2_t3854014517 L_37 = __this->get_generationExtents_15(); Vector2_t3854014517 L_38 = (&___other0)->get_generationExtents_15(); bool L_39 = TextGenerationSettings_CompareVector2_m2697891872(__this, L_37, L_38, /*hidden argument*/NULL); if (!L_39) { goto IL_0187; } } { Vector2_t3854014517 L_40 = __this->get_pivot_16(); Vector2_t3854014517 L_41 = (&___other0)->get_pivot_16(); bool L_42 = TextGenerationSettings_CompareVector2_m2697891872(__this, L_40, L_41, /*hidden argument*/NULL); if (!L_42) { goto IL_0187; } } { Font_t1580130639 * L_43 = __this->get_font_0(); Font_t1580130639 * L_44 = (&___other0)->get_font_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_45 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_43, L_44, /*hidden argument*/NULL); G_B21_0 = ((int32_t)(L_45)); goto IL_0188; } IL_0187: { G_B21_0 = 0; } IL_0188: { V_0 = (bool)G_B21_0; goto IL_018e; } IL_018e: { bool L_46 = V_0; return L_46; } } extern "C" bool TextGenerationSettings_Equals_m872373524_AdjustorThunk (RuntimeObject * __this, TextGenerationSettings_t2955391441 ___other0, const RuntimeMethod* method) { TextGenerationSettings_t2955391441 * _thisAdjusted = reinterpret_cast(__this + 1); return TextGenerationSettings_Equals_m872373524(_thisAdjusted, ___other0, method); } // Conversion methods for marshalling of: UnityEngine.TextGenerator extern "C" void TextGenerator_t1838611233_marshal_pinvoke(const TextGenerator_t1838611233& unmarshaled, TextGenerator_t1838611233_marshaled_pinvoke& marshaled) { Il2CppCodeGenException* ___m_LastSettings_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_LastSettings' of type 'TextGenerator'."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_LastSettings_2Exception); } extern "C" void TextGenerator_t1838611233_marshal_pinvoke_back(const TextGenerator_t1838611233_marshaled_pinvoke& marshaled, TextGenerator_t1838611233& unmarshaled) { Il2CppCodeGenException* ___m_LastSettings_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_LastSettings' of type 'TextGenerator'."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_LastSettings_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.TextGenerator extern "C" void TextGenerator_t1838611233_marshal_pinvoke_cleanup(TextGenerator_t1838611233_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.TextGenerator extern "C" void TextGenerator_t1838611233_marshal_com(const TextGenerator_t1838611233& unmarshaled, TextGenerator_t1838611233_marshaled_com& marshaled) { Il2CppCodeGenException* ___m_LastSettings_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_LastSettings' of type 'TextGenerator'."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_LastSettings_2Exception); } extern "C" void TextGenerator_t1838611233_marshal_com_back(const TextGenerator_t1838611233_marshaled_com& marshaled, TextGenerator_t1838611233& unmarshaled) { Il2CppCodeGenException* ___m_LastSettings_2Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_LastSettings' of type 'TextGenerator'."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_LastSettings_2Exception); } // Conversion method for clean up from marshalling of: UnityEngine.TextGenerator extern "C" void TextGenerator_t1838611233_marshal_com_cleanup(TextGenerator_t1838611233_marshaled_com& marshaled) { } // System.Void UnityEngine.TextGenerator::.ctor() extern "C" void TextGenerator__ctor_m2719349404 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { { TextGenerator__ctor_m3315225751(__this, ((int32_t)50), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.TextGenerator::.ctor(System.Int32) extern "C" void TextGenerator__ctor_m3315225751 (TextGenerator_t1838611233 * __this, int32_t ___initialCapacity0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator__ctor_m3315225751_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Object__ctor_m1196001181(__this, /*hidden argument*/NULL); int32_t L_0 = ___initialCapacity0; List_1_t2359577098 * L_1 = (List_1_t2359577098 *)il2cpp_codegen_object_new(List_1_t2359577098_il2cpp_TypeInfo_var); List_1__ctor_m2525236808(L_1, ((int32_t)((int32_t)((int32_t)((int32_t)L_0+(int32_t)1))*(int32_t)4)), /*hidden argument*/List_1__ctor_m2525236808_RuntimeMethod_var); __this->set_m_Verts_5(L_1); int32_t L_2 = ___initialCapacity0; List_1_t369525373 * L_3 = (List_1_t369525373 *)il2cpp_codegen_object_new(List_1_t369525373_il2cpp_TypeInfo_var); List_1__ctor_m691252865(L_3, ((int32_t)((int32_t)L_2+(int32_t)1)), /*hidden argument*/List_1__ctor_m691252865_RuntimeMethod_var); __this->set_m_Characters_6(L_3); List_1_t1470875743 * L_4 = (List_1_t1470875743 *)il2cpp_codegen_object_new(List_1_t1470875743_il2cpp_TypeInfo_var); List_1__ctor_m581423473(L_4, ((int32_t)20), /*hidden argument*/List_1__ctor_m581423473_RuntimeMethod_var); __this->set_m_Lines_7(L_4); TextGenerator_Init_m2835255125(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.TextGenerator::Finalize() extern "C" void TextGenerator_Finalize_m3033244656 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator_Finalize_m3033244656_MetadataUsageId); s_Il2CppMethodInitialized = true; } Exception_t3285241636 * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t3285241636 * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = 0; NO_UNUSED_WARNING (__leave_target); { } IL_0001: try { // begin try (depth: 1) InterfaceActionInvoker0::Invoke(0 /* System.Void System.IDisposable::Dispose() */, IDisposable_t971480393_il2cpp_TypeInfo_var, __this); IL2CPP_LEAVE(0x13, FINALLY_000c); } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t3285241636 *)e.ex; goto FINALLY_000c; } FINALLY_000c: { // begin finally (depth: 1) Object_Finalize_m3696538117(__this, /*hidden argument*/NULL); IL2CPP_END_FINALLY(12) } // end finally (depth: 1) IL2CPP_CLEANUP(12) { IL2CPP_JUMP_TBL(0x13, IL_0013) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t3285241636 *) } IL_0013: { return; } } // System.Void UnityEngine.TextGenerator::System.IDisposable.Dispose() extern "C" void TextGenerator_System_IDisposable_Dispose_m1341300146 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { { TextGenerator_Dispose_cpp_m3624568491(__this, /*hidden argument*/NULL); return; } } // UnityEngine.TextGenerationSettings UnityEngine.TextGenerator::ValidatedSettings(UnityEngine.TextGenerationSettings) extern "C" TextGenerationSettings_t2955391441 TextGenerator_ValidatedSettings_m3744012953 (TextGenerator_t1838611233 * __this, TextGenerationSettings_t2955391441 ___settings0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator_ValidatedSettings_m3744012953_MetadataUsageId); s_Il2CppMethodInitialized = true; } TextGenerationSettings_t2955391441 V_0; memset(&V_0, 0, sizeof(V_0)); { Font_t1580130639 * L_0 = (&___settings0)->get_font_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_002b; } } { Font_t1580130639 * L_2 = (&___settings0)->get_font_0(); NullCheck(L_2); bool L_3 = Font_get_dynamic_m1368413874(L_2, /*hidden argument*/NULL); if (!L_3) { goto IL_002b; } } { TextGenerationSettings_t2955391441 L_4 = ___settings0; V_0 = L_4; goto IL_00e2; } IL_002b: { int32_t L_5 = (&___settings0)->get_fontSize_2(); if (L_5) { goto IL_0043; } } { int32_t L_6 = (&___settings0)->get_fontStyle_6(); if (!L_6) { goto IL_008d; } } IL_0043: { Font_t1580130639 * L_7 = (&___settings0)->get_font_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_8 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_7, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_8) { goto IL_007c; } } { Font_t1580130639 * L_9 = (&___settings0)->get_font_0(); ObjectU5BU5D_t3885370135* L_10 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)1)); Font_t1580130639 * L_11 = (&___settings0)->get_font_0(); NullCheck(L_11); String_t* L_12 = Object_get_name_m1438513735(L_11, /*hidden argument*/NULL); NullCheck(L_10); ArrayElementTypeCheck (L_10, L_12); (L_10)->SetAt(static_cast(0), (RuntimeObject *)L_12); IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogWarningFormat_m4125348817(NULL /*static, unused*/, L_9, _stringLiteral2266523459, L_10, /*hidden argument*/NULL); } IL_007c: { (&___settings0)->set_fontSize_2(0); (&___settings0)->set_fontStyle_6(0); } IL_008d: { bool L_13 = (&___settings0)->get_resizeTextForBestFit_9(); if (!L_13) { goto IL_00db; } } { Font_t1580130639 * L_14 = (&___settings0)->get_font_0(); IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_15 = Object_op_Inequality_m68474028(NULL /*static, unused*/, L_14, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_15) { goto IL_00d2; } } { Font_t1580130639 * L_16 = (&___settings0)->get_font_0(); ObjectU5BU5D_t3885370135* L_17 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)1)); Font_t1580130639 * L_18 = (&___settings0)->get_font_0(); NullCheck(L_18); String_t* L_19 = Object_get_name_m1438513735(L_18, /*hidden argument*/NULL); NullCheck(L_17); ArrayElementTypeCheck (L_17, L_19); (L_17)->SetAt(static_cast(0), (RuntimeObject *)L_19); IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogWarningFormat_m4125348817(NULL /*static, unused*/, L_16, _stringLiteral1956399547, L_17, /*hidden argument*/NULL); } IL_00d2: { (&___settings0)->set_resizeTextForBestFit_9((bool)0); } IL_00db: { TextGenerationSettings_t2955391441 L_20 = ___settings0; V_0 = L_20; goto IL_00e2; } IL_00e2: { TextGenerationSettings_t2955391441 L_21 = V_0; return L_21; } } // System.Void UnityEngine.TextGenerator::Invalidate() extern "C" void TextGenerator_Invalidate_m1307583196 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { { __this->set_m_HasGenerated_3((bool)0); return; } } // System.Void UnityEngine.TextGenerator::GetCharacters(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetCharacters_m3070669632 (TextGenerator_t1838611233 * __this, List_1_t369525373 * ___characters0, const RuntimeMethod* method) { { List_1_t369525373 * L_0 = ___characters0; TextGenerator_GetCharactersInternal_m2640027672(__this, L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.TextGenerator::GetLines(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetLines_m4086371989 (TextGenerator_t1838611233 * __this, List_1_t1470875743 * ___lines0, const RuntimeMethod* method) { { List_1_t1470875743 * L_0 = ___lines0; TextGenerator_GetLinesInternal_m4053054016(__this, L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.TextGenerator::GetVertices(System.Collections.Generic.List`1) extern "C" void TextGenerator_GetVertices_m2648380066 (TextGenerator_t1838611233 * __this, List_1_t2359577098 * ___vertices0, const RuntimeMethod* method) { { List_1_t2359577098 * L_0 = ___vertices0; TextGenerator_GetVerticesInternal_m937574849(__this, L_0, /*hidden argument*/NULL); return; } } // System.Single UnityEngine.TextGenerator::GetPreferredWidth(System.String,UnityEngine.TextGenerationSettings) extern "C" float TextGenerator_GetPreferredWidth_m2494406489 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); float V_1 = 0.0f; { (&___settings1)->set_horizontalOverflow_14(1); (&___settings1)->set_verticalOverflow_13(1); (&___settings1)->set_updateBounds_12((bool)1); String_t* L_0 = ___str0; TextGenerationSettings_t2955391441 L_1 = ___settings1; TextGenerator_Populate_m614341003(__this, L_0, L_1, /*hidden argument*/NULL); Rect_t3345319094 L_2 = TextGenerator_get_rectExtents_m128057140(__this, /*hidden argument*/NULL); V_0 = L_2; float L_3 = Rect_get_width_m1618071060((&V_0), /*hidden argument*/NULL); V_1 = L_3; goto IL_0036; } IL_0036: { float L_4 = V_1; return L_4; } } // System.Single UnityEngine.TextGenerator::GetPreferredHeight(System.String,UnityEngine.TextGenerationSettings) extern "C" float TextGenerator_GetPreferredHeight_m3668791684 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); float V_1 = 0.0f; { (&___settings1)->set_verticalOverflow_13(1); (&___settings1)->set_updateBounds_12((bool)1); String_t* L_0 = ___str0; TextGenerationSettings_t2955391441 L_1 = ___settings1; TextGenerator_Populate_m614341003(__this, L_0, L_1, /*hidden argument*/NULL); Rect_t3345319094 L_2 = TextGenerator_get_rectExtents_m128057140(__this, /*hidden argument*/NULL); V_0 = L_2; float L_3 = Rect_get_height_m2713477301((&V_0), /*hidden argument*/NULL); V_1 = L_3; goto IL_002e; } IL_002e: { float L_4 = V_1; return L_4; } } // System.Boolean UnityEngine.TextGenerator::PopulateWithErrors(System.String,UnityEngine.TextGenerationSettings,UnityEngine.GameObject) extern "C" bool TextGenerator_PopulateWithErrors_m2106001595 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, GameObject_t2923855588 * ___context2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator_PopulateWithErrors_m2106001595_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; bool V_1 = false; { String_t* L_0 = ___str0; TextGenerationSettings_t2955391441 L_1 = ___settings1; int32_t L_2 = TextGenerator_PopulateWithError_m1090609619(__this, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; int32_t L_3 = V_0; if (L_3) { goto IL_0017; } } { V_1 = (bool)1; goto IL_0064; } IL_0017: { int32_t L_4 = V_0; if (!((int32_t)((int32_t)L_4&(int32_t)1))) { goto IL_003a; } } { GameObject_t2923855588 * L_5 = ___context2; ObjectU5BU5D_t3885370135* L_6 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)1)); Font_t1580130639 * L_7 = (&___settings1)->get_font_0(); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_7); (L_6)->SetAt(static_cast(0), (RuntimeObject *)L_7); IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogErrorFormat_m242749776(NULL /*static, unused*/, L_5, _stringLiteral475378281, L_6, /*hidden argument*/NULL); } IL_003a: { int32_t L_8 = V_0; if (!((int32_t)((int32_t)L_8&(int32_t)2))) { goto IL_005d; } } { GameObject_t2923855588 * L_9 = ___context2; ObjectU5BU5D_t3885370135* L_10 = ((ObjectU5BU5D_t3885370135*)SZArrayNew(ObjectU5BU5D_t3885370135_il2cpp_TypeInfo_var, (uint32_t)1)); Font_t1580130639 * L_11 = (&___settings1)->get_font_0(); NullCheck(L_10); ArrayElementTypeCheck (L_10, L_11); (L_10)->SetAt(static_cast(0), (RuntimeObject *)L_11); IL2CPP_RUNTIME_CLASS_INIT(Debug_t2324836986_il2cpp_TypeInfo_var); Debug_LogErrorFormat_m242749776(NULL /*static, unused*/, L_9, _stringLiteral2537927702, L_10, /*hidden argument*/NULL); } IL_005d: { V_1 = (bool)0; goto IL_0064; } IL_0064: { bool L_12 = V_1; return L_12; } } // System.Boolean UnityEngine.TextGenerator::Populate(System.String,UnityEngine.TextGenerationSettings) extern "C" bool TextGenerator_Populate_m614341003 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) { int32_t V_0 = 0; bool V_1 = false; { String_t* L_0 = ___str0; TextGenerationSettings_t2955391441 L_1 = ___settings1; int32_t L_2 = TextGenerator_PopulateWithError_m1090609619(__this, L_0, L_1, /*hidden argument*/NULL); V_0 = L_2; int32_t L_3 = V_0; V_1 = (bool)((((int32_t)L_3) == ((int32_t)0))? 1 : 0); goto IL_0014; } IL_0014: { bool L_4 = V_1; return L_4; } } // UnityEngine.TextGenerationError UnityEngine.TextGenerator::PopulateWithError(System.String,UnityEngine.TextGenerationSettings) extern "C" int32_t TextGenerator_PopulateWithError_m1090609619 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator_PopulateWithError_m1090609619_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; { bool L_0 = __this->get_m_HasGenerated_3(); if (!L_0) { goto IL_003b; } } { String_t* L_1 = ___str0; String_t* L_2 = __this->get_m_LastString_1(); IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); bool L_3 = String_op_Equality_m767991535(NULL /*static, unused*/, L_1, L_2, /*hidden argument*/NULL); if (!L_3) { goto IL_003b; } } { TextGenerationSettings_t2955391441 L_4 = __this->get_m_LastSettings_2(); bool L_5 = TextGenerationSettings_Equals_m872373524((&___settings1), L_4, /*hidden argument*/NULL); if (!L_5) { goto IL_003b; } } { int32_t L_6 = __this->get_m_LastValid_4(); V_0 = L_6; goto IL_0055; } IL_003b: { String_t* L_7 = ___str0; TextGenerationSettings_t2955391441 L_8 = ___settings1; int32_t L_9 = TextGenerator_PopulateAlways_m980987704(__this, L_7, L_8, /*hidden argument*/NULL); __this->set_m_LastValid_4(L_9); int32_t L_10 = __this->get_m_LastValid_4(); V_0 = L_10; goto IL_0055; } IL_0055: { int32_t L_11 = V_0; return L_11; } } // UnityEngine.TextGenerationError UnityEngine.TextGenerator::PopulateAlways(System.String,UnityEngine.TextGenerationSettings) extern "C" int32_t TextGenerator_PopulateAlways_m980987704 (TextGenerator_t1838611233 * __this, String_t* ___str0, TextGenerationSettings_t2955391441 ___settings1, const RuntimeMethod* method) { TextGenerationSettings_t2955391441 V_0; memset(&V_0, 0, sizeof(V_0)); int32_t V_1 = 0; int32_t V_2 = 0; { String_t* L_0 = ___str0; __this->set_m_LastString_1(L_0); __this->set_m_HasGenerated_3((bool)1); __this->set_m_CachedVerts_8((bool)0); __this->set_m_CachedCharacters_9((bool)0); __this->set_m_CachedLines_10((bool)0); TextGenerationSettings_t2955391441 L_1 = ___settings1; __this->set_m_LastSettings_2(L_1); TextGenerationSettings_t2955391441 L_2 = ___settings1; TextGenerationSettings_t2955391441 L_3 = TextGenerator_ValidatedSettings_m3744012953(__this, L_2, /*hidden argument*/NULL); V_0 = L_3; String_t* L_4 = ___str0; Font_t1580130639 * L_5 = (&V_0)->get_font_0(); Color_t267620335 L_6 = (&V_0)->get_color_1(); int32_t L_7 = (&V_0)->get_fontSize_2(); float L_8 = (&V_0)->get_scaleFactor_5(); float L_9 = (&V_0)->get_lineSpacing_3(); int32_t L_10 = (&V_0)->get_fontStyle_6(); bool L_11 = (&V_0)->get_richText_4(); bool L_12 = (&V_0)->get_resizeTextForBestFit_9(); int32_t L_13 = (&V_0)->get_resizeTextMinSize_10(); int32_t L_14 = (&V_0)->get_resizeTextMaxSize_11(); int32_t L_15 = (&V_0)->get_verticalOverflow_13(); int32_t L_16 = (&V_0)->get_horizontalOverflow_14(); bool L_17 = (&V_0)->get_updateBounds_12(); int32_t L_18 = (&V_0)->get_textAnchor_7(); Vector2_t3854014517 L_19 = (&V_0)->get_generationExtents_15(); Vector2_t3854014517 L_20 = (&V_0)->get_pivot_16(); bool L_21 = (&V_0)->get_generateOutOfBounds_17(); bool L_22 = (&V_0)->get_alignByGeometry_8(); TextGenerator_Populate_Internal_m93079026(__this, L_4, L_5, L_6, L_7, L_8, L_9, L_10, L_11, L_12, L_13, L_14, L_15, L_16, L_17, L_18, L_19, L_20, L_21, L_22, (&V_1), /*hidden argument*/NULL); int32_t L_23 = V_1; __this->set_m_LastValid_4(L_23); int32_t L_24 = V_1; V_2 = L_24; goto IL_00c9; } IL_00c9: { int32_t L_25 = V_2; return L_25; } } // System.Collections.Generic.IList`1 UnityEngine.TextGenerator::get_verts() extern "C" RuntimeObject* TextGenerator_get_verts_m2493230849 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { RuntimeObject* V_0 = NULL; { bool L_0 = __this->get_m_CachedVerts_8(); if (L_0) { goto IL_0021; } } { List_1_t2359577098 * L_1 = __this->get_m_Verts_5(); TextGenerator_GetVertices_m2648380066(__this, L_1, /*hidden argument*/NULL); __this->set_m_CachedVerts_8((bool)1); } IL_0021: { List_1_t2359577098 * L_2 = __this->get_m_Verts_5(); V_0 = (RuntimeObject*)L_2; goto IL_002d; } IL_002d: { RuntimeObject* L_3 = V_0; return L_3; } } // System.Collections.Generic.IList`1 UnityEngine.TextGenerator::get_characters() extern "C" RuntimeObject* TextGenerator_get_characters_m4169986014 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { RuntimeObject* V_0 = NULL; { bool L_0 = __this->get_m_CachedCharacters_9(); if (L_0) { goto IL_0021; } } { List_1_t369525373 * L_1 = __this->get_m_Characters_6(); TextGenerator_GetCharacters_m3070669632(__this, L_1, /*hidden argument*/NULL); __this->set_m_CachedCharacters_9((bool)1); } IL_0021: { List_1_t369525373 * L_2 = __this->get_m_Characters_6(); V_0 = (RuntimeObject*)L_2; goto IL_002d; } IL_002d: { RuntimeObject* L_3 = V_0; return L_3; } } // System.Collections.Generic.IList`1 UnityEngine.TextGenerator::get_lines() extern "C" RuntimeObject* TextGenerator_get_lines_m1377364226 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { RuntimeObject* V_0 = NULL; { bool L_0 = __this->get_m_CachedLines_10(); if (L_0) { goto IL_0021; } } { List_1_t1470875743 * L_1 = __this->get_m_Lines_7(); TextGenerator_GetLines_m4086371989(__this, L_1, /*hidden argument*/NULL); __this->set_m_CachedLines_10((bool)1); } IL_0021: { List_1_t1470875743 * L_2 = __this->get_m_Lines_7(); V_0 = (RuntimeObject*)L_2; goto IL_002d; } IL_002d: { RuntimeObject* L_3 = V_0; return L_3; } } // System.Void UnityEngine.TextGenerator::Init() extern "C" void TextGenerator_Init_m2835255125 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { typedef void (*TextGenerator_Init_m2835255125_ftn) (TextGenerator_t1838611233 *); static TextGenerator_Init_m2835255125_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_Init_m2835255125_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::Init()"); _il2cpp_icall_func(__this); } // System.Void UnityEngine.TextGenerator::Dispose_cpp() extern "C" void TextGenerator_Dispose_cpp_m3624568491 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { typedef void (*TextGenerator_Dispose_cpp_m3624568491_ftn) (TextGenerator_t1838611233 *); static TextGenerator_Dispose_cpp_m3624568491_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_Dispose_cpp_m3624568491_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::Dispose_cpp()"); _il2cpp_icall_func(__this); } // System.Boolean UnityEngine.TextGenerator::Populate_Internal(System.String,UnityEngine.Font,UnityEngine.Color,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,UnityEngine.VerticalWrapMode,UnityEngine.HorizontalWrapMode,System.Boolean,UnityEngine.TextAnchor,UnityEngine.Vector2,UnityEngine.Vector2,System.Boolean,System.Boolean,UnityEngine.TextGenerationError&) extern "C" bool TextGenerator_Populate_Internal_m93079026 (TextGenerator_t1838611233 * __this, String_t* ___str0, Font_t1580130639 * ___font1, Color_t267620335 ___color2, int32_t ___fontSize3, float ___scaleFactor4, float ___lineSpacing5, int32_t ___style6, bool ___richText7, bool ___resizeTextForBestFit8, int32_t ___resizeTextMinSize9, int32_t ___resizeTextMaxSize10, int32_t ___verticalOverFlow11, int32_t ___horizontalOverflow12, bool ___updateBounds13, int32_t ___anchor14, Vector2_t3854014517 ___extents15, Vector2_t3854014517 ___pivot16, bool ___generateOutOfBounds17, bool ___alignByGeometry18, int32_t* ___error19, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (TextGenerator_Populate_Internal_m93079026_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint32_t V_0 = 0; bool V_1 = false; bool V_2 = false; { V_0 = 0; Font_t1580130639 * L_0 = ___font1; IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_m1674932247(NULL /*static, unused*/, L_0, (Object_t1332387349 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_001b; } } { int32_t* L_2 = ___error19; *((int32_t*)(L_2)) = (int32_t)4; V_1 = (bool)0; goto IL_006b; } IL_001b: { String_t* L_3 = ___str0; Font_t1580130639 * L_4 = ___font1; Color_t267620335 L_5 = ___color2; int32_t L_6 = ___fontSize3; float L_7 = ___scaleFactor4; float L_8 = ___lineSpacing5; int32_t L_9 = ___style6; bool L_10 = ___richText7; bool L_11 = ___resizeTextForBestFit8; int32_t L_12 = ___resizeTextMinSize9; int32_t L_13 = ___resizeTextMaxSize10; int32_t L_14 = ___verticalOverFlow11; int32_t L_15 = ___horizontalOverflow12; bool L_16 = ___updateBounds13; int32_t L_17 = ___anchor14; float L_18 = (&___extents15)->get_x_0(); float L_19 = (&___extents15)->get_y_1(); float L_20 = (&___pivot16)->get_x_0(); float L_21 = (&___pivot16)->get_y_1(); bool L_22 = ___generateOutOfBounds17; bool L_23 = ___alignByGeometry18; bool L_24 = TextGenerator_Populate_Internal_cpp_m2278858808(__this, L_3, L_4, L_5, L_6, L_7, L_8, L_9, L_10, L_11, L_12, L_13, L_14, L_15, L_16, L_17, L_18, L_19, L_20, L_21, L_22, L_23, (&V_0), /*hidden argument*/NULL); V_2 = L_24; int32_t* L_25 = ___error19; uint32_t L_26 = V_0; *((int32_t*)(L_25)) = (int32_t)L_26; bool L_27 = V_2; V_1 = L_27; goto IL_006b; } IL_006b: { bool L_28 = V_1; return L_28; } } // System.Boolean UnityEngine.TextGenerator::Populate_Internal_cpp(System.String,UnityEngine.Font,UnityEngine.Color,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.Boolean,UnityEngine.TextAnchor,System.Single,System.Single,System.Single,System.Single,System.Boolean,System.Boolean,System.UInt32&) extern "C" bool TextGenerator_Populate_Internal_cpp_m2278858808 (TextGenerator_t1838611233 * __this, String_t* ___str0, Font_t1580130639 * ___font1, Color_t267620335 ___color2, int32_t ___fontSize3, float ___scaleFactor4, float ___lineSpacing5, int32_t ___style6, bool ___richText7, bool ___resizeTextForBestFit8, int32_t ___resizeTextMinSize9, int32_t ___resizeTextMaxSize10, int32_t ___verticalOverFlow11, int32_t ___horizontalOverflow12, bool ___updateBounds13, int32_t ___anchor14, float ___extentsX15, float ___extentsY16, float ___pivotX17, float ___pivotY18, bool ___generateOutOfBounds19, bool ___alignByGeometry20, uint32_t* ___error21, const RuntimeMethod* method) { bool V_0 = false; { String_t* L_0 = ___str0; Font_t1580130639 * L_1 = ___font1; int32_t L_2 = ___fontSize3; float L_3 = ___scaleFactor4; float L_4 = ___lineSpacing5; int32_t L_5 = ___style6; bool L_6 = ___richText7; bool L_7 = ___resizeTextForBestFit8; int32_t L_8 = ___resizeTextMinSize9; int32_t L_9 = ___resizeTextMaxSize10; int32_t L_10 = ___verticalOverFlow11; int32_t L_11 = ___horizontalOverflow12; bool L_12 = ___updateBounds13; int32_t L_13 = ___anchor14; float L_14 = ___extentsX15; float L_15 = ___extentsY16; float L_16 = ___pivotX17; float L_17 = ___pivotY18; bool L_18 = ___generateOutOfBounds19; bool L_19 = ___alignByGeometry20; uint32_t* L_20 = ___error21; bool L_21 = TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204(NULL /*static, unused*/, __this, L_0, L_1, (&___color2), L_2, L_3, L_4, L_5, L_6, L_7, L_8, L_9, L_10, L_11, L_12, L_13, L_14, L_15, L_16, L_17, L_18, L_19, L_20, /*hidden argument*/NULL); V_0 = L_21; goto IL_0037; } IL_0037: { bool L_22 = V_0; return L_22; } } // System.Boolean UnityEngine.TextGenerator::INTERNAL_CALL_Populate_Internal_cpp(UnityEngine.TextGenerator,System.String,UnityEngine.Font,UnityEngine.Color&,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.Boolean,UnityEngine.TextAnchor,System.Single,System.Single,System.Single,System.Single,System.Boolean,System.Boolean,System.UInt32&) extern "C" bool TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204 (RuntimeObject * __this /* static, unused */, TextGenerator_t1838611233 * ___self0, String_t* ___str1, Font_t1580130639 * ___font2, Color_t267620335 * ___color3, int32_t ___fontSize4, float ___scaleFactor5, float ___lineSpacing6, int32_t ___style7, bool ___richText8, bool ___resizeTextForBestFit9, int32_t ___resizeTextMinSize10, int32_t ___resizeTextMaxSize11, int32_t ___verticalOverFlow12, int32_t ___horizontalOverflow13, bool ___updateBounds14, int32_t ___anchor15, float ___extentsX16, float ___extentsY17, float ___pivotX18, float ___pivotY19, bool ___generateOutOfBounds20, bool ___alignByGeometry21, uint32_t* ___error22, const RuntimeMethod* method) { typedef bool (*TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204_ftn) (TextGenerator_t1838611233 *, String_t*, Font_t1580130639 *, Color_t267620335 *, int32_t, float, float, int32_t, bool, bool, int32_t, int32_t, int32_t, int32_t, bool, int32_t, float, float, float, float, bool, bool, uint32_t*); static TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_INTERNAL_CALL_Populate_Internal_cpp_m2391936204_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::INTERNAL_CALL_Populate_Internal_cpp(UnityEngine.TextGenerator,System.String,UnityEngine.Font,UnityEngine.Color&,System.Int32,System.Single,System.Single,UnityEngine.FontStyle,System.Boolean,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.Boolean,UnityEngine.TextAnchor,System.Single,System.Single,System.Single,System.Single,System.Boolean,System.Boolean,System.UInt32&)"); bool retVal = _il2cpp_icall_func(___self0, ___str1, ___font2, ___color3, ___fontSize4, ___scaleFactor5, ___lineSpacing6, ___style7, ___richText8, ___resizeTextForBestFit9, ___resizeTextMinSize10, ___resizeTextMaxSize11, ___verticalOverFlow12, ___horizontalOverflow13, ___updateBounds14, ___anchor15, ___extentsX16, ___extentsY17, ___pivotX18, ___pivotY19, ___generateOutOfBounds20, ___alignByGeometry21, ___error22); return retVal; } // UnityEngine.Rect UnityEngine.TextGenerator::get_rectExtents() extern "C" Rect_t3345319094 TextGenerator_get_rectExtents_m128057140 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { Rect_t3345319094 V_0; memset(&V_0, 0, sizeof(V_0)); Rect_t3345319094 V_1; memset(&V_1, 0, sizeof(V_1)); { TextGenerator_INTERNAL_get_rectExtents_m4191808009(__this, (&V_0), /*hidden argument*/NULL); Rect_t3345319094 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Rect_t3345319094 L_1 = V_1; return L_1; } } // System.Void UnityEngine.TextGenerator::INTERNAL_get_rectExtents(UnityEngine.Rect&) extern "C" void TextGenerator_INTERNAL_get_rectExtents_m4191808009 (TextGenerator_t1838611233 * __this, Rect_t3345319094 * ___value0, const RuntimeMethod* method) { typedef void (*TextGenerator_INTERNAL_get_rectExtents_m4191808009_ftn) (TextGenerator_t1838611233 *, Rect_t3345319094 *); static TextGenerator_INTERNAL_get_rectExtents_m4191808009_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_INTERNAL_get_rectExtents_m4191808009_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::INTERNAL_get_rectExtents(UnityEngine.Rect&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.TextGenerator::GetVerticesInternal(System.Object) extern "C" void TextGenerator_GetVerticesInternal_m937574849 (TextGenerator_t1838611233 * __this, RuntimeObject * ___vertices0, const RuntimeMethod* method) { typedef void (*TextGenerator_GetVerticesInternal_m937574849_ftn) (TextGenerator_t1838611233 *, RuntimeObject *); static TextGenerator_GetVerticesInternal_m937574849_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_GetVerticesInternal_m937574849_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::GetVerticesInternal(System.Object)"); _il2cpp_icall_func(__this, ___vertices0); } // System.Int32 UnityEngine.TextGenerator::get_characterCount() extern "C" int32_t TextGenerator_get_characterCount_m3131948647 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { typedef int32_t (*TextGenerator_get_characterCount_m3131948647_ftn) (TextGenerator_t1838611233 *); static TextGenerator_get_characterCount_m3131948647_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_get_characterCount_m3131948647_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::get_characterCount()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Int32 UnityEngine.TextGenerator::get_characterCountVisible() extern "C" int32_t TextGenerator_get_characterCountVisible_m3955448162 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = TextGenerator_get_characterCount_m3131948647(__this, /*hidden argument*/NULL); V_0 = ((int32_t)((int32_t)L_0-(int32_t)1)); goto IL_000f; } IL_000f: { int32_t L_1 = V_0; return L_1; } } // System.Void UnityEngine.TextGenerator::GetCharactersInternal(System.Object) extern "C" void TextGenerator_GetCharactersInternal_m2640027672 (TextGenerator_t1838611233 * __this, RuntimeObject * ___characters0, const RuntimeMethod* method) { typedef void (*TextGenerator_GetCharactersInternal_m2640027672_ftn) (TextGenerator_t1838611233 *, RuntimeObject *); static TextGenerator_GetCharactersInternal_m2640027672_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_GetCharactersInternal_m2640027672_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::GetCharactersInternal(System.Object)"); _il2cpp_icall_func(__this, ___characters0); } // System.Int32 UnityEngine.TextGenerator::get_lineCount() extern "C" int32_t TextGenerator_get_lineCount_m2861967458 (TextGenerator_t1838611233 * __this, const RuntimeMethod* method) { typedef int32_t (*TextGenerator_get_lineCount_m2861967458_ftn) (TextGenerator_t1838611233 *); static TextGenerator_get_lineCount_m2861967458_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_get_lineCount_m2861967458_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::get_lineCount()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.TextGenerator::GetLinesInternal(System.Object) extern "C" void TextGenerator_GetLinesInternal_m4053054016 (TextGenerator_t1838611233 * __this, RuntimeObject * ___lines0, const RuntimeMethod* method) { typedef void (*TextGenerator_GetLinesInternal_m4053054016_ftn) (TextGenerator_t1838611233 *, RuntimeObject *); static TextGenerator_GetLinesInternal_m4053054016_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextGenerator_GetLinesInternal_m4053054016_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextGenerator::GetLinesInternal(System.Object)"); _il2cpp_icall_func(__this, ___lines0); } // System.Void UnityEngine.TextMesh::set_text(System.String) extern "C" void TextMesh_set_text_m3108628191 (TextMesh_t2729623642 * __this, String_t* ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_set_text_m3108628191_ftn) (TextMesh_t2729623642 *, String_t*); static TextMesh_set_text_m3108628191_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_set_text_m3108628191_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::set_text(System.String)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Font UnityEngine.TextMesh::get_font() extern "C" Font_t1580130639 * TextMesh_get_font_m2863180815 (TextMesh_t2729623642 * __this, const RuntimeMethod* method) { typedef Font_t1580130639 * (*TextMesh_get_font_m2863180815_ftn) (TextMesh_t2729623642 *); static TextMesh_get_font_m2863180815_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_get_font_m2863180815_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::get_font()"); Font_t1580130639 * retVal = _il2cpp_icall_func(__this); return retVal; } // System.Void UnityEngine.TextMesh::set_font(UnityEngine.Font) extern "C" void TextMesh_set_font_m1802478126 (TextMesh_t2729623642 * __this, Font_t1580130639 * ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_set_font_m1802478126_ftn) (TextMesh_t2729623642 *, Font_t1580130639 *); static TextMesh_set_font_m1802478126_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_set_font_m1802478126_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::set_font(UnityEngine.Font)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.TextMesh::set_fontSize(System.Int32) extern "C" void TextMesh_set_fontSize_m2737382977 (TextMesh_t2729623642 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_set_fontSize_m2737382977_ftn) (TextMesh_t2729623642 *, int32_t); static TextMesh_set_fontSize_m2737382977_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_set_fontSize_m2737382977_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::set_fontSize(System.Int32)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.TextMesh::set_anchor(UnityEngine.TextAnchor) extern "C" void TextMesh_set_anchor_m3847081119 (TextMesh_t2729623642 * __this, int32_t ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_set_anchor_m3847081119_ftn) (TextMesh_t2729623642 *, int32_t); static TextMesh_set_anchor_m3847081119_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_set_anchor_m3847081119_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::set_anchor(UnityEngine.TextAnchor)"); _il2cpp_icall_func(__this, ___value0); } // UnityEngine.Color UnityEngine.TextMesh::get_color() extern "C" Color_t267620335 TextMesh_get_color_m1387888700 (TextMesh_t2729623642 * __this, const RuntimeMethod* method) { Color_t267620335 V_0; memset(&V_0, 0, sizeof(V_0)); Color_t267620335 V_1; memset(&V_1, 0, sizeof(V_1)); { TextMesh_INTERNAL_get_color_m2101696051(__this, (&V_0), /*hidden argument*/NULL); Color_t267620335 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Color_t267620335 L_1 = V_1; return L_1; } } // System.Void UnityEngine.TextMesh::set_color(UnityEngine.Color) extern "C" void TextMesh_set_color_m3708437087 (TextMesh_t2729623642 * __this, Color_t267620335 ___value0, const RuntimeMethod* method) { { TextMesh_INTERNAL_set_color_m3627446082(__this, (&___value0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.TextMesh::INTERNAL_get_color(UnityEngine.Color&) extern "C" void TextMesh_INTERNAL_get_color_m2101696051 (TextMesh_t2729623642 * __this, Color_t267620335 * ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_INTERNAL_get_color_m2101696051_ftn) (TextMesh_t2729623642 *, Color_t267620335 *); static TextMesh_INTERNAL_get_color_m2101696051_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_INTERNAL_get_color_m2101696051_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::INTERNAL_get_color(UnityEngine.Color&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.TextMesh::INTERNAL_set_color(UnityEngine.Color&) extern "C" void TextMesh_INTERNAL_set_color_m3627446082 (TextMesh_t2729623642 * __this, Color_t267620335 * ___value0, const RuntimeMethod* method) { typedef void (*TextMesh_INTERNAL_set_color_m3627446082_ftn) (TextMesh_t2729623642 *, Color_t267620335 *); static TextMesh_INTERNAL_set_color_m3627446082_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (TextMesh_INTERNAL_set_color_m3627446082_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.TextMesh::INTERNAL_set_color(UnityEngine.Color&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.Texture::.ctor() extern "C" void Texture__ctor_m3948473377 (Texture_t2354860603 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Texture__ctor_m3948473377_MetadataUsageId); s_Il2CppMethodInitialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Object_t1332387349_il2cpp_TypeInfo_var); Object__ctor_m1201776117(__this, /*hidden argument*/NULL); return; } } // System.Int32 UnityEngine.Texture::Internal_GetWidth(UnityEngine.Texture) extern "C" int32_t Texture_Internal_GetWidth_m1728621115 (RuntimeObject * __this /* static, unused */, Texture_t2354860603 * ___t0, const RuntimeMethod* method) { typedef int32_t (*Texture_Internal_GetWidth_m1728621115_ftn) (Texture_t2354860603 *); static Texture_Internal_GetWidth_m1728621115_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture_Internal_GetWidth_m1728621115_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture::Internal_GetWidth(UnityEngine.Texture)"); int32_t retVal = _il2cpp_icall_func(___t0); return retVal; } // System.Int32 UnityEngine.Texture::Internal_GetHeight(UnityEngine.Texture) extern "C" int32_t Texture_Internal_GetHeight_m2677419952 (RuntimeObject * __this /* static, unused */, Texture_t2354860603 * ___t0, const RuntimeMethod* method) { typedef int32_t (*Texture_Internal_GetHeight_m2677419952_ftn) (Texture_t2354860603 *); static Texture_Internal_GetHeight_m2677419952_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture_Internal_GetHeight_m2677419952_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture::Internal_GetHeight(UnityEngine.Texture)"); int32_t retVal = _il2cpp_icall_func(___t0); return retVal; } // System.Int32 UnityEngine.Texture::get_width() extern "C" int32_t Texture_get_width_m3222511853 (Texture_t2354860603 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = Texture_Internal_GetWidth_m1728621115(NULL /*static, unused*/, __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // System.Int32 UnityEngine.Texture::get_height() extern "C" int32_t Texture_get_height_m2661125960 (Texture_t2354860603 * __this, const RuntimeMethod* method) { int32_t V_0 = 0; { int32_t L_0 = Texture_Internal_GetHeight_m2677419952(NULL /*static, unused*/, __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000d; } IL_000d: { int32_t L_1 = V_0; return L_1; } } // UnityEngine.TextureWrapMode UnityEngine.Texture::get_wrapMode() extern "C" int32_t Texture_get_wrapMode_m3905008577 (Texture_t2354860603 * __this, const RuntimeMethod* method) { typedef int32_t (*Texture_get_wrapMode_m3905008577_ftn) (Texture_t2354860603 *); static Texture_get_wrapMode_m3905008577_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture_get_wrapMode_m3905008577_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture::get_wrapMode()"); int32_t retVal = _il2cpp_icall_func(__this); return retVal; } // UnityEngine.Vector2 UnityEngine.Texture::get_texelSize() extern "C" Vector2_t3854014517 Texture_get_texelSize_m1064583269 (Texture_t2354860603 * __this, const RuntimeMethod* method) { Vector2_t3854014517 V_0; memset(&V_0, 0, sizeof(V_0)); Vector2_t3854014517 V_1; memset(&V_1, 0, sizeof(V_1)); { Texture_INTERNAL_get_texelSize_m1640036898(__this, (&V_0), /*hidden argument*/NULL); Vector2_t3854014517 L_0 = V_0; V_1 = L_0; goto IL_0010; } IL_0010: { Vector2_t3854014517 L_1 = V_1; return L_1; } } // System.Void UnityEngine.Texture::INTERNAL_get_texelSize(UnityEngine.Vector2&) extern "C" void Texture_INTERNAL_get_texelSize_m1640036898 (Texture_t2354860603 * __this, Vector2_t3854014517 * ___value0, const RuntimeMethod* method) { typedef void (*Texture_INTERNAL_get_texelSize_m1640036898_ftn) (Texture_t2354860603 *, Vector2_t3854014517 *); static Texture_INTERNAL_get_texelSize_m1640036898_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture_INTERNAL_get_texelSize_m1640036898_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture::INTERNAL_get_texelSize(UnityEngine.Vector2&)"); _il2cpp_icall_func(__this, ___value0); } // System.Void UnityEngine.Texture2D::.ctor(System.Int32,System.Int32) extern "C" void Texture2D__ctor_m400428107 (Texture2D_t1384570725 * __this, int32_t ___width0, int32_t ___height1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Texture2D__ctor_m400428107_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Texture__ctor_m3948473377(__this, /*hidden argument*/NULL); int32_t L_0 = ___width0; int32_t L_1 = ___height1; IntPtr_t L_2 = ((IntPtr_t_StaticFields*)il2cpp_codegen_static_fields_for(IntPtr_t_il2cpp_TypeInfo_var))->get_Zero_1(); Texture2D_Internal_Create_m2456905009(NULL /*static, unused*/, __this, L_0, L_1, 4, (bool)1, (bool)0, L_2, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.Texture2D::Internal_Create(UnityEngine.Texture2D,System.Int32,System.Int32,UnityEngine.TextureFormat,System.Boolean,System.Boolean,System.IntPtr) extern "C" void Texture2D_Internal_Create_m2456905009 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___mono0, int32_t ___width1, int32_t ___height2, int32_t ___format3, bool ___mipmap4, bool ___linear5, IntPtr_t ___nativeTex6, const RuntimeMethod* method) { typedef void (*Texture2D_Internal_Create_m2456905009_ftn) (Texture2D_t1384570725 *, int32_t, int32_t, int32_t, bool, bool, IntPtr_t); static Texture2D_Internal_Create_m2456905009_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture2D_Internal_Create_m2456905009_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture2D::Internal_Create(UnityEngine.Texture2D,System.Int32,System.Int32,UnityEngine.TextureFormat,System.Boolean,System.Boolean,System.IntPtr)"); _il2cpp_icall_func(___mono0, ___width1, ___height2, ___format3, ___mipmap4, ___linear5, ___nativeTex6); } // UnityEngine.Texture2D UnityEngine.Texture2D::get_whiteTexture() extern "C" Texture2D_t1384570725 * Texture2D_get_whiteTexture_m3889823561 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { typedef Texture2D_t1384570725 * (*Texture2D_get_whiteTexture_m3889823561_ftn) (); static Texture2D_get_whiteTexture_m3889823561_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture2D_get_whiteTexture_m3889823561_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture2D::get_whiteTexture()"); Texture2D_t1384570725 * retVal = _il2cpp_icall_func(); return retVal; } // UnityEngine.Color UnityEngine.Texture2D::GetPixelBilinear(System.Single,System.Single) extern "C" Color_t267620335 Texture2D_GetPixelBilinear_m4026853624 (Texture2D_t1384570725 * __this, float ___u0, float ___v1, const RuntimeMethod* method) { Color_t267620335 V_0; memset(&V_0, 0, sizeof(V_0)); Color_t267620335 V_1; memset(&V_1, 0, sizeof(V_1)); { float L_0 = ___u0; float L_1 = ___v1; Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901(NULL /*static, unused*/, __this, L_0, L_1, (&V_0), /*hidden argument*/NULL); Color_t267620335 L_2 = V_0; V_1 = L_2; goto IL_0012; } IL_0012: { Color_t267620335 L_3 = V_1; return L_3; } } // System.Void UnityEngine.Texture2D::INTERNAL_CALL_GetPixelBilinear(UnityEngine.Texture2D,System.Single,System.Single,UnityEngine.Color&) extern "C" void Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901 (RuntimeObject * __this /* static, unused */, Texture2D_t1384570725 * ___self0, float ___u1, float ___v2, Color_t267620335 * ___value3, const RuntimeMethod* method) { typedef void (*Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901_ftn) (Texture2D_t1384570725 *, float, float, Color_t267620335 *); static Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (Texture2D_INTERNAL_CALL_GetPixelBilinear_m1520279901_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Texture2D::INTERNAL_CALL_GetPixelBilinear(UnityEngine.Texture2D,System.Single,System.Single,UnityEngine.Color&)"); _il2cpp_icall_func(___self0, ___u1, ___v2, ___value3); } // System.Void UnityEngine.ThreadAndSerializationSafeAttribute::.ctor() extern "C" void ThreadAndSerializationSafeAttribute__ctor_m3729301985 (ThreadAndSerializationSafeAttribute_t669741721 * __this, const RuntimeMethod* method) { { Attribute__ctor_m574845334(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif BasiliskII/src/macos_util.cpp /* * macos_util.cpp - MacOS definitions/utility functions * * Basilisk II (C) 1997-2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "sysdeps.h" #include "cpu_emulation.h" #include "adb.h" #include "main.h" #include "sony.h" #include "disk.h" #include "cdrom.h" #include "macos_util.h" #define DEBUG 0 #include "debug.h" /* * Enqueue QElem to list */ void EnqueueMac(uint32 elem, uint32 list) { WriteMacInt32(elem + qLink, 0); if (!ReadMacInt32(list + qTail)) { WriteMacInt32(list + qHead, elem); WriteMacInt32(list + qTail, elem); } else { WriteMacInt32(ReadMacInt32(list + qTail) + qLink, elem); WriteMacInt32(list + qTail, elem); } } /* * Find first free drive number, starting at num */ static bool is_drive_number_free(int num) { uint32 e = ReadMacInt32(0x308 + qHead); while (e) { uint32 d = e - dsQLink; if ((int)ReadMacInt16(d + dsQDrive) == num) return false; e = ReadMacInt32(e + qLink); } return true; } int FindFreeDriveNumber(int num) { while (!is_drive_number_free(num)) num++; return num; } /* * Mount volume with given file handle (call this function when you are unable to * do automatic media change detection and the user has to press a special key * or something to mount a volume; this function will check if there's really a * volume in the drive with SysIsDiskInserted(); volumes which are present on startup * are automatically mounted) */ void MountVolume(void *fh) { SonyMountVolume(fh) || DiskMountVolume(fh) || CDROMMountVolume(fh); } /* * Calculate disk image file layout given file size and first 256 data bytes */ void FileDiskLayout(loff_t size, uint8 *data, loff_t &start_byte, loff_t &real_size) { if (size == 419284 || size == 838484) { // 400K/800K DiskCopy image, 84 byte header start_byte = 84; real_size = (size - 84) & ~0x1ff; } else { // 0..511 byte header start_byte = size & 0x1ff; real_size = size - start_byte; } } uint32 DebugUtil(uint32 Selector) { switch (Selector) { case duDebuggerGetMax: return 3; case duDebuggerEnter: return 0; case duDebuggerExit: return 0; case duDebuggerPoll: ADBInterrupt(); return 0; default: return (uint32) paramErr; } } /* * Convert time_t value to MacOS time (seconds since 1.1.1904) */ uint32 TimeToMacTime(time_t t) { // This code is taken from glibc 2.2 // Convert to number of seconds elapsed since 1-Jan-1904 struct tm *local = localtime(&t); const int TM_EPOCH_YEAR = 1900; const int MAC_EPOCH_YEAR = 1904; int a4 = ((local->tm_year + TM_EPOCH_YEAR) >> 2) - !(local->tm_year & 3); int b4 = (MAC_EPOCH_YEAR >> 2) - !(MAC_EPOCH_YEAR & 3); int a100 = a4 / 25 - (a4 % 25 < 0); int b100 = b4 / 25 - (b4 % 25 < 0); int a400 = a100 >> 2; int b400 = b100 >> 2; int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400); uint32 days = local->tm_yday + 365 * (local->tm_year - 4) + intervening_leap_days; return local->tm_sec + 60 * (local->tm_min + 60 * (local->tm_hour + 24 * days)); } /* * Convert MacOS time to time_t (seconds since 1.1.1970) */ time_t MacTimeToTime(uint32 t) { // simply subtract number of seconds between 1.1.1904 and 1.1.1970 return t - 2082826800; } sltn011/OpenGL-Learning1-10 /** * @file ShadowMap.hpp */ #ifndef OGL_SHADOWMAP_H #define OGL_SHADOWMAP_H #include "FrameBufferObject.hpp" namespace OGL { /** * @brief Class that stores shadows created by DirectionalLight or SpotLight */ class ShadowMap { /// FrameBufferObject that stores depth values FrameBufferObject m_fbo; /// Texture unit assigned to ShadowMap texture GL_TEXTURE{N} GLenum m_mapTextureUnit; /// Size of ShadowMap int m_mapSize; /// Projection*View matrix of CameraShadowMap used to render ShadowMap glm::mat4 m_lightProjView; public: /** * @brief ShadowMap constructor * @param mapTextureUnit Texture unit assigned to ShadowCubemap texture GL_TEXTURE{N} * @param mapSize Size of ShadowMap * @param lightProjViewMatrix Projection*View matrix of CameraShadowMap used to render ShadowMap */ ShadowMap( GLenum mapTextureUnit, int mapSize, glm::mat4 lightProjViewMatrix ); ShadowMap( ShadowMap const &rhs ) = delete; ShadowMap( ShadowMap &&rhs ) = default; ShadowMap &operator=( ShadowMap const &rhs ) = delete; ShadowMap &operator=( ShadowMap &&rhs ) = default; /** * @brief Binds ShadowMap as FrameBufferObject GL_FRAMEBUFFER */ void bindFramebuffer( ) const; /** * @brief Unbinds ShadowMap FrameBufferObject and sets FrameBufferObject GL_FRAMEBUFFER to default */ static void unbindFramebuffer( ); /** * @brief Binds ShadowMap as texture to its texture unit */ void bindTexture( ); /** * @brief Unbinds ShadowMap as texture */ static void unbindTexture( ); /** * @brief Get ShadowMap ID * @return ShadowMap ID */ unsigned int value( ); /** * @brief Get ShadowMap texture unit * @return ShadowMap texture unit */ GLenum textureUnit( ) const; /** * @brief Get size of ShadowMap * @return Size of ShadowMap */ int mapSize( ) const; /** * @brief Get Projection*View matrix of CameraShadowMap used to render ShadowMap * @return Projection*View matrix of CameraShadowMap used to render ShadowMap */ glm::mat4 lightProjView( ) const; }; } #endif // OGL_SHADOWMAP_H #include "HierarchyWindow.h" #include "Editor.h" #include "ApplicationInfoWindow.h" #include #include #include #include #include #include #include #include namespace Lumos { ApplicationInfoWindow::ApplicationInfoWindow() { m_Name = "ApplicationInfo"; m_SimpleName = "ApplicationInfo"; } void ApplicationInfoWindow::OnImGui() { auto flags = ImGuiWindowFlags_NoCollapse; ImGui::Begin(m_Name.c_str(), &m_Active, flags); { if(ImGui::TreeNode("Application")) { auto systems = Application::Get().GetSystemManager(); if(ImGui::TreeNode("Systems")) { systems->OnImGui(); ImGui::TreePop(); } auto renderGraph = Application::Get().GetRenderGraph(); if(ImGui::TreeNode("RenderGraph")) { renderGraph->OnImGui(); ImGui::TreePop(); } ImGui::NewLine(); ImGui::Text("FPS : %5.2i", Engine::Get().Statistics().FramesPerSecond); ImGui::Text("UPS : %5.2i", Engine::Get().Statistics().UpdatesPerSecond); ImGui::Text("Frame Time : %5.2f ms", Engine::Get().Statistics().FrameTime); ImGui::NewLine(); ImGui::Text("Scene : %s", Application::Get().GetSceneManager()->GetCurrentScene()->GetSceneName().c_str()); if(ImGui::TreeNode("GBuffer")) { if(ImGui::TreeNode("Colour Texture")) { ImGuiHelpers::Image(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_COLOUR), Maths::Vector2(128.0f, 128.0f)); ImGuiHelpers::Tooltip(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_COLOUR), Maths::Vector2(256.0f, 256.0f)); ImGui::TreePop(); } if(ImGui::TreeNode("Normal Texture")) { ImGuiHelpers::Image(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_NORMALS), Maths::Vector2(128.0f, 128.0f)); ImGuiHelpers::Tooltip(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_NORMALS), Maths::Vector2(256.0f, 256.0f)); ImGui::TreePop(); } if(ImGui::TreeNode("PBR Texture")) { ImGuiHelpers::Image(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_PBR), Maths::Vector2(128.0f, 128.0f)); ImGuiHelpers::Tooltip(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_PBR), Maths::Vector2(256.0f, 256.0f)); ImGui::TreePop(); } if(ImGui::TreeNode("Position Texture")) { ImGuiHelpers::Image(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_POSITION), Maths::Vector2(128.0f, 128.0f)); ImGuiHelpers::Tooltip(Application::Get().GetRenderGraph()->GetGBuffer()->GetTexture(Graphics::SCREENTEX_POSITION), Maths::Vector2(256.0f, 256.0f)); ImGui::TreePop(); } ImGui::TreePop(); } ImGui::TreePop(); }; } ImGui::End(); } } // Ogonek // // Written in 2012-2013 by <> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see . // Decomposing iterator #ifndef OGONEK_DETAIL_DECOMPOSING_ITERATOR_HPP #define OGONEK_DETAIL_DECOMPOSING_ITERATOR_HPP #include #include #include #include #include #include #include namespace ogonek { namespace detail { template using vector_type = detail::small_vector; template struct ordered_decomposing_iterator; template struct decomposing_iterator : boost::iterator_facade< decomposing_iterator, code_point, std::forward_iterator_tag, // TODO code_point > { public: decomposing_iterator(Iterator first, Iterator last) : first(std::move(first)), last(std::move(last)) { if(this->first != this->last) { increment(); } } code_point dereference() const { return current[position]; } bool equal(decomposing_iterator const& that) const { return (first == that.first && position == that.position) || (exhausted() && that.exhausted()); } void increment() { ++position; if(static_cast(position) < current.size()) return; if(first == last) { current = {}; position = depleted; return; } auto u = *first++; if(Compatibility) { current = ucd::get_compatibility_decomposition_mapping(u); } else if(ucd::get_decomposition_type(u) == ucd::decomposition_type::can) { current = ucd::get_canonical_decomposition_mapping(u); } else { current = { u }; } position = 0; } private: friend class ordered_decomposing_iterator; static constexpr int depleted = -1; bool exhausted() const { return position == depleted; } Iterator first, last; int position = depleted; vector_type current; }; } // namespace detail } // namespace ogonek #endif // OGONEK_DETAIL_DECOMPOSING_ITERATOR_HPP // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License. #pragma once #include #include "touca/lib_api.hpp" #ifndef DOXYGEN_SHOULD_SKIP_THIS #if (__cplusplus >= 201703L) #define MAYBE_UNUSED [[maybe_unused]] #else #define MAYBE_UNUSED #endif #endif /** * @def TOUCA_SCOPED_TIMER * @brief convenience macro for logging performance of a function * as a performance metric. */ #define TOUCA_SCOPED_TIMER \ MAYBE_UNUSED const touca::scoped_timer touca_scoped_timer(__FUNCTION__); \ std::ignore = touca_scoped_timer; namespace touca { /** * @brief a simple class that helps clients log the duration between * its instantiation and destruction as a performance metric. */ class TOUCA_CLIENT_API scoped_timer { public: explicit scoped_timer(const std::string& name); ~scoped_timer(); private: std::string _name; }; } // namespace touca 0 // balcl_constraint.t.cpp -*-C++-*- #include #include #include // 'bsls::Types::Int64' #include // 'bsl::atoi' #include #include // 'bsl::operator<<' using namespace BloombergLP; using namespace bsl; // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // ---------------------------------------------------------------------------- // TYPES // [ 1] struct Constraint // // ---------------------------------------------------------------------------- // [ 7] USAGE EXAMPLE // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; } // close unnamed namespace // ============================================================================ // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING // ---------------------------------------------------------------------------- typedef balcl::Constraint Constraint; // ========================= // functions test*Constraint // ========================= // BDE_VERIFY pragma: -FABC01 // Function ... not in alphabetic order bool testCharConstraint (const char * , bsl::ostream&) // Return 'true'. { return true; } bool testIntConstraint (const int * , bsl::ostream&) // Return 'true'. { return true; } bool testInt64Constraint (const bsls::Types::Int64 *, bsl::ostream&) // Return 'true'. { return true; } bool testDoubleConstraint (const double * , bsl::ostream&) // Return 'true'. { return true; } bool testStringConstraint (const bsl::string * , bsl::ostream&) // Return 'true'. { return true; } bool testDatetimeConstraint(const bdlt::Datetime * , bsl::ostream&) // Return 'true'. { return true; } bool testDateConstraint (const bdlt::Date * , bsl::ostream&) // Return 'true'. { return true; } bool testTimeConstraint (const bdlt::Time * , bsl::ostream&) // Return 'true'. { return true; } // These functions, never invoked, provide a default value for the // 'balcl::Constraint' nested 'typedef's. // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { const int test = argc > 1 ? atoi(argv[1]) : 0; const bool verbose = argc > 2; cout << "TEST " << __FILE__ << " CASE " << test << endl; switch (test) { case 0: case 1: { // -------------------------------------------------------------------- // TESTING 'balcl::Constraint' // // Concerns: //: 1 This class provides a namespace for a set of useful constraints //: for each of the 'balcl::OptionType' element types. We need only //: make sure that the types correspond to the expected function //: types. // // Plan: //: 1 Instantiate a constraint for each type, and load a function //: pointer of the appropriate prototype. // // Testing: // struct Constraint // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'balcl::Constraint'" << endl << "===========================" << endl; Constraint::CharConstraint charF(&testCharConstraint); Constraint::IntConstraint intF(&testIntConstraint); Constraint::Int64Constraint int64F(&testInt64Constraint); Constraint::DoubleConstraint doubleF(&testDoubleConstraint); Constraint::StringConstraint stringF(&testStringConstraint); Constraint::DatetimeConstraint datetimeF(&testDatetimeConstraint); Constraint::DateConstraint dateF(&testDateConstraint); Constraint::TimeConstraint timeF(&testTimeConstraint); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2020 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- Medusa/Medusa/Application/FrameAutoStopWatch.cpp // Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #include "MedusaPreCompiled.h" #include "FrameAutoStopWatch.h" #include "Core/Chrono/StopWatch.h" #include "Application/ApplicationStatics.h" MEDUSA_BEGIN; FrameAutoStopWatch::FrameAutoStopWatch(StopWatch& watch, FrameStep step) :mStopWatch(watch), mStep(step) { mStopWatch.Start(); } FrameAutoStopWatch::~FrameAutoStopWatch() { mStopWatch.Shot(); ApplicationStatics::Instance().SetElpased(mStep, mStopWatch.ElapsedMilliseconds()); } MEDUSA_END;#include "dataflow_analysis/processing/processing.h" #include "dataflow_analysis/common/grouping.h" #include "dataflow_analysis/common/netlist_abstraction.h" #include "dataflow_analysis/processing/configuration.h" #include "dataflow_analysis/processing/context.h" #include "dataflow_analysis/processing/pass_collection.h" #include "dataflow_analysis/processing/result.h" #include "dataflow_analysis/utils/progress_printer.h" #include "dataflow_analysis/utils/timing_utils.h" #include "hal_core/netlist/gate.h" #include "hal_core/netlist/netlist.h" #include "hal_core/utilities/log.h" #include #include #include namespace hal { namespace dataflow { namespace processing { namespace { progress_printer m_progress_printer; void process_pass_configuration(const Configuration& config, Context& ctx) { u32 num_passes = ctx.current_passes.size(); while (true) { u32 start_id; u32 end_id; // fetch next work package { std::lock_guard guard(ctx.progress_mutex); if (ctx.done) { break; } // adaptive workload: // every thread gets between 1 and 20 passes, depending on the number of remaining passes // this improves cpu utilization and reduces number of mutex locks start_id = ctx.pass_counter; u32 remaining_passes = num_passes - start_id; u32 work = 20; if (remaining_passes < config.num_threads * work / 2) { work = std::max(1u, remaining_passes / config.num_threads); } end_id = std::min(start_id + work, (u32)num_passes); ctx.pass_counter = end_id; if (ctx.pass_counter >= num_passes) { ctx.done = true; } } for (u32 current_id = start_id; current_id < end_id; ++current_id) { const auto& [current_state, current_pass] = ctx.current_passes[current_id]; if (auto it = ctx.pass_outcome.find({current_state, current_pass.id}); it != ctx.pass_outcome.end()) { // early exit, outcome is already known std::lock_guard guard(ctx.result_mutex); ctx.new_recurring_results.emplace_back(current_state, current_pass.id, it->second); ctx.finished_passes++; m_progress_printer.print_progress((float)ctx.finished_passes / ctx.current_passes.size(), std::to_string(ctx.finished_passes) + "\\" + std::to_string(ctx.current_passes.size()) + " (" + std::to_string(ctx.new_unique_groupings.size()) + " new results)"); continue; } // process work auto new_state = current_pass.function(current_state); // aggregate result std::shared_ptr duplicate = nullptr; for (const auto& other : ctx.result.unique_groupings) { if (*new_state == *other) { duplicate = other; break; } } { std::lock_guard guard(ctx.result_mutex); if (duplicate == nullptr) { ctx.new_unique_groupings.emplace_back(current_state, current_pass.id, new_state); } else { ctx.new_recurring_results.emplace_back(current_state, current_pass.id, duplicate); } ctx.finished_passes++; m_progress_printer.print_progress((float)ctx.finished_passes / ctx.current_passes.size(), std::to_string(ctx.finished_passes) + "\\" + std::to_string(ctx.current_passes.size()) + " (" + std::to_string(ctx.new_unique_groupings.size()) + " new results)"); } } } } std::vector, PassConfiguration>> generate_pass_combinations(Context& ctx, const std::shared_ptr& initial_grouping) { // create current layer of pass combinations; std::vector, PassConfiguration>> output; if (initial_grouping != nullptr) { for (const auto& pass : pass_collection::get_passes(ctx.result.pass_combinations_leading_to_grouping[initial_grouping])) { output.emplace_back(initial_grouping, pass); } } else { for (const auto& state : ctx.result.unique_groupings) { for (const auto& pass : pass_collection::get_passes(ctx.result.pass_combinations_leading_to_grouping[state])) { output.emplace_back(state, pass); } } } return output; } } // namespace Result run(const Configuration& config, const std::shared_ptr& initial_grouping) { log_info("dataflow", "starting pipeline with {} threads", config.num_threads); Context ctx; ctx.num_iterations = 0; ctx.phase = 0; ctx.end_reached = false; for (u32 layer = 0; layer < config.pass_layers; layer++) { log_info("dataflow", "start processing layer {}", layer); auto begin_time = std::chrono::high_resolution_clock::now(); // get all pass combinations of layer ctx.current_passes = generate_pass_combinations(ctx, (layer == 0) ? initial_grouping : nullptr); // preparations ctx.done = false; ctx.pass_counter = 0; ctx.finished_passes = 0; m_progress_printer = progress_printer(30); // spawn threads std::vector workers; for (u32 t = 0; t < config.num_threads - 1; ++t) { workers.emplace_back([&]() { process_pass_configuration(config, ctx); }); } process_pass_configuration(config, ctx); // wait for threads to finish for (auto& worker : workers) { worker.join(); } m_progress_printer.clear(); log_info("dataflow", " finished in {:3.2f}s, processed {} passes, filtering results...", seconds_since(begin_time), ctx.finished_passes, ctx.new_unique_groupings.size()); auto all_new_results = ctx.new_recurring_results; begin_time = std::chrono::high_resolution_clock::now(); // filter same results of different threads u32 num_unique_filtered = 0; std::vector do_not_consider(ctx.new_unique_groupings.size(), false); for (u32 i = 0; i < ctx.new_unique_groupings.size(); ++i) { if (do_not_consider[i]) { continue; } const auto& [start_state_i, pass_i, new_state_i] = ctx.new_unique_groupings[i]; for (u32 j = i + 1; j < ctx.new_unique_groupings.size(); ++j) { if (do_not_consider[j]) { continue; } const auto& [start_state_j, pass_j, new_state_j] = ctx.new_unique_groupings[j]; // j is a duplicate of i if (*new_state_i == *new_state_j) { do_not_consider[j] = true; all_new_results.emplace_back(start_state_j, pass_j, new_state_i); } } ctx.result.unique_groupings.push_back(new_state_i); all_new_results.push_back(ctx.new_unique_groupings[i]); num_unique_filtered++; } log_info("dataflow", " filtered results in {:3.2f}s, got {} new unique results", seconds_since(begin_time), num_unique_filtered); begin_time = std::chrono::high_resolution_clock::now(); ctx.new_recurring_results.clear(); ctx.new_unique_groupings.clear(); // fill results: compute path by appending pass id to the path of the prev round for (const auto& [start_state, pass, new_state] : all_new_results) { ctx.pass_outcome[{start_state, pass}] = new_state; const auto& start_pass_combinations = ctx.result.pass_combinations_leading_to_grouping[start_state]; auto& new_pass_combinations = ctx.result.pass_combinations_leading_to_grouping[new_state]; if (start_pass_combinations.empty()) { std::vector path{pass}; new_pass_combinations.push_back(path); ctx.result.groupings[path] = new_state; } else { std::vector> new_paths; // temporary memory to avoid modification while looping new_paths.reserve(start_pass_combinations.size()); for (const auto& path : start_pass_combinations) { if (path.size() != layer) { continue; } std::vector new_path(path); new_path.push_back(pass); new_paths.push_back(new_path); ctx.result.groupings[new_path] = new_state; } new_pass_combinations.insert(new_pass_combinations.end(), new_paths.begin(), new_paths.end()); } } log_info("dataflow", " total: {} unique states", ctx.result.unique_groupings.size()); } return ctx.result; } } // namespace processing } // namespace dataflow } // namespace halSunguckLee/real-mongodbsrc/mongo/dbtests/query_stage_cached_plan.cpp /** * Copyright (C) 2015 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/bson/bsonobjbuilder.h" #include "mongo/db/catalog/collection.h" #include "mongo/db/catalog/database.h" #include "mongo/db/catalog/database_holder.h" #include "mongo/db/client.h" #include "mongo/db/db_raii.h" #include "mongo/db/exec/cached_plan.h" #include "mongo/db/exec/queued_data_stage.h" #include "mongo/db/jsobj.h" #include "mongo/db/json.h" #include "mongo/db/matcher/extensions_callback_disallow_extensions.h" #include "mongo/db/query/canonical_query.h" #include "mongo/db/query/get_executor.h" #include "mongo/db/query/plan_cache.h" #include "mongo/db/query/plan_yield_policy.h" #include "mongo/db/query/query_knobs.h" #include "mongo/db/query/query_planner_params.h" #include "mongo/dbtests/dbtests.h" #include "mongo/stdx/memory.h" namespace QueryStageCachedPlan { static const NamespaceString nss("unittests.QueryStageCachedPlan"); class QueryStageCachedPlanBase { public: QueryStageCachedPlanBase() { // If collection exists already, we need to drop it. dropCollection(); // Add indices. addIndex(BSON("a" << 1)); addIndex(BSON("b" << 1)); OldClientWriteContext ctx(&_txn, nss.ns()); Collection* collection = ctx.getCollection(); ASSERT(collection); // Add data. for (int i = 0; i < 10; i++) { insertDocument(collection, BSON("_id" << i << "a" << i << "b" << 1)); } } void addIndex(const BSONObj& obj) { ASSERT_OK(dbtests::createIndex(&_txn, nss.ns(), obj)); } void dropCollection() { ScopedTransaction transaction(&_txn, MODE_X); Lock::DBLock dbLock(_txn.lockState(), nss.db(), MODE_X); Database* database = dbHolder().get(&_txn, nss.db()); if (!database) { return; } WriteUnitOfWork wuow(&_txn); database->dropCollection(&_txn, nss.ns()); wuow.commit(); } void insertDocument(Collection* collection, BSONObj obj) { WriteUnitOfWork wuow(&_txn); const bool enforceQuota = false; OpDebug* const nullOpDebug = nullptr; ASSERT_OK(collection->insertDocument(&_txn, obj, nullOpDebug, enforceQuota)); wuow.commit(); } OperationContext* txn() { return &_txn; } protected: const ServiceContext::UniqueOperationContext _txnPtr = cc().makeOperationContext(); OperationContext& _txn = *_txnPtr; WorkingSet _ws; }; /** * Test that on failure, the cached plan stage replans the query but does not create a new cache * entry. */ class QueryStageCachedPlanFailure : public QueryStageCachedPlanBase { public: void run() { AutoGetCollectionForRead ctx(&_txn, nss.ns()); Collection* collection = ctx.getCollection(); ASSERT(collection); // Query can be answered by either index on "a" or index on "b". auto qr = stdx::make_unique(nss); qr->setFilter(fromjson("{a: {$gte: 8}, b: 1}")); auto statusWithCQ = CanonicalQuery::canonicalize( txn(), std::move(qr), ExtensionsCallbackDisallowExtensions()); ASSERT_OK(statusWithCQ.getStatus()); const std::unique_ptr cq = std::move(statusWithCQ.getValue()); // We shouldn't have anything in the plan cache for this shape yet. PlanCache* cache = collection->infoCache()->getPlanCache(); ASSERT(cache); CachedSolution* rawCachedSolution; ASSERT_NOT_OK(cache->get(*cq, &rawCachedSolution)); // Get planner params. QueryPlannerParams plannerParams; fillOutPlannerParams(&_txn, collection, cq.get(), &plannerParams); // Queued data stage will return a failure during the cached plan trial period. auto mockChild = stdx::make_unique(&_txn, &_ws); mockChild->pushBack(PlanStage::FAILURE); // High enough so that we shouldn't trigger a replan based on works. const size_t decisionWorks = 50; CachedPlanStage cachedPlanStage( &_txn, collection, &_ws, cq.get(), plannerParams, decisionWorks, mockChild.release()); // This should succeed after triggering a replan. PlanYieldPolicy yieldPolicy(PlanExecutor::YIELD_MANUAL, _txn.getServiceContext()->getFastClockSource()); ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy)); // Make sure that we get 2 legit results back. size_t numResults = 0; PlanStage::StageState state = PlanStage::NEED_TIME; while (state != PlanStage::IS_EOF) { WorkingSetID id = WorkingSet::INVALID_ID; state = cachedPlanStage.work(&id); ASSERT_NE(state, PlanStage::FAILURE); ASSERT_NE(state, PlanStage::DEAD); if (state == PlanStage::ADVANCED) { WorkingSetMember* member = _ws.get(id); ASSERT(cq->root()->matchesBSON(member->obj.value())); numResults++; } } ASSERT_EQ(numResults, 2U); // Plan cache should still be empty, as we don't write to it when we replan a failed // query. ASSERT_NOT_OK(cache->get(*cq, &rawCachedSolution)); } }; /** * Test that hitting the cached plan stage trial period's threshold for work cycles causes the * query to be replanned. Also verify that the replanning results in a new plan cache entry. */ class QueryStageCachedPlanHitMaxWorks : public QueryStageCachedPlanBase { public: void run() { AutoGetCollectionForRead ctx(&_txn, nss.ns()); Collection* collection = ctx.getCollection(); ASSERT(collection); // Query can be answered by either index on "a" or index on "b". auto qr = stdx::make_unique(nss); qr->setFilter(fromjson("{a: {$gte: 8}, b: 1}")); auto statusWithCQ = CanonicalQuery::canonicalize( txn(), std::move(qr), ExtensionsCallbackDisallowExtensions()); ASSERT_OK(statusWithCQ.getStatus()); const std::unique_ptr cq = std::move(statusWithCQ.getValue()); // We shouldn't have anything in the plan cache for this shape yet. PlanCache* cache = collection->infoCache()->getPlanCache(); ASSERT(cache); CachedSolution* rawCachedSolution; ASSERT_NOT_OK(cache->get(*cq, &rawCachedSolution)); // Get planner params. QueryPlannerParams plannerParams; fillOutPlannerParams(&_txn, collection, cq.get(), &plannerParams); // Set up queued data stage to take a long time before returning EOF. Should be long // enough to trigger a replan. const size_t decisionWorks = 10; const size_t mockWorks = 1U + static_cast(internalQueryCacheEvictionRatio * decisionWorks); auto mockChild = stdx::make_unique(&_txn, &_ws); for (size_t i = 0; i < mockWorks; i++) { mockChild->pushBack(PlanStage::NEED_TIME); } CachedPlanStage cachedPlanStage( &_txn, collection, &_ws, cq.get(), plannerParams, decisionWorks, mockChild.release()); // This should succeed after triggering a replan. PlanYieldPolicy yieldPolicy(PlanExecutor::YIELD_MANUAL, _txn.getServiceContext()->getFastClockSource()); ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy)); // Make sure that we get 2 legit results back. size_t numResults = 0; PlanStage::StageState state = PlanStage::NEED_TIME; while (state != PlanStage::IS_EOF) { WorkingSetID id = WorkingSet::INVALID_ID; state = cachedPlanStage.work(&id); ASSERT_NE(state, PlanStage::FAILURE); ASSERT_NE(state, PlanStage::DEAD); if (state == PlanStage::ADVANCED) { WorkingSetMember* member = _ws.get(id); ASSERT(cq->root()->matchesBSON(member->obj.value())); numResults++; } } ASSERT_EQ(numResults, 2U); // This time we expect to find something in the plan cache. Replans after hitting the // works threshold result in a cache entry. ASSERT_OK(cache->get(*cq, &rawCachedSolution)); const std::unique_ptr cachedSolution(rawCachedSolution); } }; class All : public Suite { public: All() : Suite("query_stage_cached_plan") {} void setupTests() { add(); add(); } }; SuiteInstance all; } // namespace QueryStageCachedPlan #include "glviewer.h" #include "ui_glviewer.h" #include #include #include //process mouse event #include //process wheel event #include #include #include GLViewer::GLViewer(QWidget *parent) : QOpenGLWidget(parent), ui(new Ui::GLViewer) { ui->setupUi(this); camera = new GLCamera(); } GLViewer::~GLViewer() { delete ui; } void GLViewer::drawShaded() { setDrawMode(0); } void GLViewer::drawWireframe() { setDrawMode(1); } void GLViewer::setDrawMode(int mode) { drawMode = mode; update(); //refresh display } void GLViewer::setProjectionMode(int mode) { projMode = mode; update(); } void GLViewer::drawNodes() { initializeOpenGLFunctions(); for(auto& node : nodes) { QMatrix4x4 trans; trans.translate(node); nodeModel->draw(view, projection, camera->model*trans); } } void GLViewer::initializeGL() { initializeOpenGLFunctions(); // glClearColor(0.2f, 0.3f, 0.3f, 1.0f); //default background glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //default background // backdrop = new Backdrop(); coordinate = new GLCoordinate(); nodeModel = new GLModel(QFileInfo("./sphere.dae").absoluteFilePath().toStdString()); ndiModel = new GLModel(QFileInfo("./ndi.stl").absoluteFilePath().toStdString()); ndiModel->setColor(QVector4D(1.0f, 1.0f, 1.0f, 1.0f)); loadTools(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [=]{update();}); timer->start(10); /*** test nodes ***/ // QTimer *genNodesTimer = new QTimer(this); // connect(genNodesTimer, &QTimer::timeout, this, [=]{ // nodes.clear(); // int sum = rand()%20; // for(int i = 0; i < sum; i++) // nodes << QVector3D((rand()%1000 -500.0)/1000.0, rand()%300/300.0, (rand()%1000 -500.0)/1000.0); // }); // genNodesTimer->start(2000); } void GLViewer::paintGL() { if(drawMode == 1) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } if(projMode == 1) { projection.setToIdentity(); // same as view projection.ortho(-1.0f*camera->zoom, 1.0f*camera->zoom, -1.0f*height()/(float)width()*camera->zoom, 1.0f*height()/(float)width()*camera->zoom, 0.1, 100); // projection.perspective(camera->zoom, (float)width()/height(), 0.1, 100); } else { projection.setToIdentity(); // same as view projection.perspective(camera->fov, (float)width()/height(), 0.1, 100); } // glClearColor(0.2f, 0.3f, 0.3f, 1.0f); //default background glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //default background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); //enable depth test glDisable(GL_CULL_FACE); glEnable(GL_BLEND); /*** view and projection matrix ***/ view = camera->getViewMatrix(); // projection.setToIdentity(); // same as view // projection.ortho(0.0f, (float)width()/height()*fov, 0.0f, (float)fov, 0.1, 100); //正交投影 // projection.perspective(camera->zoom, (float)width()/height(), 0.1, 100); /*** background ***/ // backdrop->draw(); /*** axis ***/ QMatrix4x4 model; coordinate->draw(view, projection, camera->model* model); /*** nodes ***/ // nodes.clear(); // nodes << QVector3D(0,0,0)<< QVector3D(-0.3,-0.3,-0.3) << QVector3D(0.3,-0.3,-0.3) << QVector3D(-0.3,0.3,-0.3) << QVector3D(-0.3,-0.3,0.3); // nodes << QVector3D((rand()%1000 -500.0)/1000.0, rand()%300/300.0, (rand()%1000 -500.0)/1000.0); drawNodes(); /*** ndi ***/ model.scale(0.001); ndiModel->draw(view, projection, camera->model*model); /*** tools ***/ for(auto& tool : existTools) { QMatrix4x4 model; model.scale(tool.scale); qDebug() << tool.scale; model = tool.SetCoordination(tool.getIndexAndCoordinate()) * model; toolModels[tool.name]->draw(view, projection, camera->model* model); } /*** status ***/ QString s1 = QString("Status: Dectected %1 nodes.").arg(nodes.size()); QString s2 = QString(" Phased %1 tools.").arg(existTools.size()); QStringList ss; ss << s1 << s2; setStatus(ss); drawStatus(); //draw status text on viewport } void GLViewer::resizeGL(int w, int h) { glViewport(0, 0, w, h); } void GLViewer::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { _mouse_pos = event->pos(); //store the mouse pos when pressed } else if(event->button() == Qt::RightButton) { _mouse_pos = event->pos(); setCursor(Qt::SizeAllCursor); } else if(event->button() == Qt::MidButton) { _mouse_pos = event->pos(); setCursor(Qt::ClosedHandCursor); //set cursor style } } void GLViewer::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton || event->button() == Qt::RightButton || Qt::MidButton) { unsetCursor(); //reset cursor style } } void GLViewer::mouseMoveEvent(QMouseEvent *event) { auto p = event->pos(); //current mouse pos auto d = p - _mouse_pos; //move distance between mouse pressed and current // qDebug() <buttons() & Qt::LeftButton) //left button -> rotation { camera->cameraRotate(d); // qDebug() << QString("yaw: %1, tilt: %2").arg(yaw).arg(tilt).toStdString().c_str(); update(); } else if(event->buttons() & Qt::RightButton) //right button -> translation { camera->cameraTranslate(d); } else if(event->buttons() & Qt::MidButton) { camera->modelRot(d); } _mouse_pos = p; } void GLViewer::wheelEvent(QWheelEvent *event) { auto p = event->pos(); // qDebug() << event->delta(); //每次delta都是+/- 120,每滚动一格都会进入,+1即可 if(event->delta() < 0) { // camera->zoom = camera->zoom * 1.13 > 150 ? 150 : camera->zoom * 1.13; camera->cameraZoom(0.2f); } else if(event->delta() > 0) { // camera->zoom = camera->zoom * 0.885 < 0.1 ? 0.1 : camera->zoom * 0.885; camera->cameraZoom(-0.2f); } update(); } void GLViewer::setStatus(QStringList &lst) { status = lst; } void GLViewer::addStatus(QString &s) { status << s; } void GLViewer::clearStatus() { status.clear(); } void GLViewer::drawStatus() { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //需要恢复成GL_FILL模式,否则显示的文字看不清 QPainter painter(this); painter.setPen(Qt::white); painter.setRenderHint(QPainter::Antialiasing); for(int i = 0; i < status.size(); i++) { painter.drawText(5, 15+20*i, status[i]); } } void GLViewer::dataProc(const QVector &data) { nodes = data; for(auto& node : nodes) { node *= 0.001; } } void GLViewer::toolProc(const QVector &data) { existTools = data; } void GLViewer::toolsLoaded(const QVector &tools) { for(auto& tool : tools) { toolModels[tool.name] = new GLModel(QFileInfo(tool.modelPath).absoluteFilePath().toStdString()); toolModels[tool.name]->setColor(QVector4D(131.0f/255.0,111.0f/255.0, 255.0f/255.0, 1.0f)); } } void GLViewer::loadTools() { tools = XmlParser::getToolsByDistancesFromXml("./tooldef.xml"); toolsLoaded(tools); } /* * @lc app=leetcode id=101 lang=cpp * * [101] Symmetric Tree */ // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; // @lc code=start #include class Solution { public: using Node = std::pair; bool isSymmetric(TreeNode *root) { std::stack stack; stack.push({root->left, root->right}); while (!stack.empty()) { const auto node = stack.top(); stack.pop(); if ((node.first == nullptr && node.second != nullptr) || (node.first != nullptr && node.second == nullptr)) { return false; } if (node.first == nullptr && node.second == nullptr) { continue; } if (node.first->val != node.second->val) { return false; } stack.push({node.first->left, node.second->right}); stack.push({node.first->right, node.second->left}); } return true; } }; // @lc code=end 0 /*************************************************************************** qgsgenericfeatureselectionmanager.cpp -------------------------------------- Date : 11.6.2013 Copyright : (C) 2013 Email : matthias at opengis dot ch *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsgenericfeatureselectionmanager.h" QgsGenericFeatureSelectionManager::QgsGenericFeatureSelectionManager( QObject *parent ) : QgsIFeatureSelectionManager( parent ) { } QgsGenericFeatureSelectionManager::QgsGenericFeatureSelectionManager( const QgsFeatureIds &initialSelection, QObject *parent ) : QgsIFeatureSelectionManager( parent ) , mSelectedFeatures( initialSelection ) { } int QgsGenericFeatureSelectionManager::selectedFeatureCount() { return mSelectedFeatures.size(); } void QgsGenericFeatureSelectionManager::select( const QgsFeatureIds &ids ) { mSelectedFeatures += ids; emit selectionChanged( ids, QgsFeatureIds(), false ); } void QgsGenericFeatureSelectionManager::deselect( const QgsFeatureIds &ids ) { mSelectedFeatures -= ids; emit selectionChanged( QgsFeatureIds(), ids, false ); } void QgsGenericFeatureSelectionManager::setSelectedFeatures( const QgsFeatureIds &ids ) { QgsFeatureIds selected = mSelectedFeatures - ids; QgsFeatureIds deselected = ids - mSelectedFeatures; mSelectedFeatures = ids; emit selectionChanged( selected, deselected, true ); } const QgsFeatureIds &QgsGenericFeatureSelectionManager::selectedFeatureIds() const { return mSelectedFeatures; } rockeet/terark-zipsrc/terark/fsa/crit_bit_trie.cpp #include "crit_bit_trie.hpp" #include #include namespace { static constexpr uint32_t invalid_pos = uint32_t(-1); } // namespace namespace terark { class SortedUintVec; CritBitTriePackedBuilder::CritBitTriePackedBuilder(size_t numKeys, size_t entryPerTrie, size_t sumKeyLen, bool isReverse, uint8_t hash_bit_num) : entry_per_trie_(entryPerTrie), trie_nums_((numKeys + entryPerTrie - 1) / entryPerTrie), num_words_(numKeys), total_key_size_(sumKeyLen), hash_bit_num_(hash_bit_num), is_reverse_(isReverse) { CritBitTrieBuilder init(isReverse, hash_bit_num); builder_list_.resize(trie_nums_, init); if (hash_bit_num_ != 0) { for (auto& builder : builder_list_) { builder.hash_vec_.resize_with_uintbits(0, hash_bit_num_); } } } void CritBitTriePackedBuilder::insert(fstring key, size_t pos) { builder_list_[pos].insert(key); } CritBitTriePacked* CritBitTriePackedBuilder::newcbt() { std::unique_ptr builder( SortedUintVec::createBuilder(false, 64)); std::unique_ptr trie(new CritBitTriePacked); trie->trie_list_.resize(trie_nums_); trie->max_layer_ = 0; // 0 num_words builder->push_back(num_words_); trie->num_words_ = num_words_; // 1 trie_nums builder->push_back(trie_nums_); trie->trie_nums_ = trie_nums_; // 2 entry per trie builder->push_back(entry_per_trie_); trie->entry_per_trie_ = entry_per_trie_; // 3 hash_bit_num builder->push_back(hash_bit_num_); trie->hash_bit_num_ = hash_bit_num_; for (size_t i = 0; i < trie_nums_; ++i) { auto& b = builder_list_[i]; b.largest_key_.swap(b.prev_key_); if (is_reverse_) { b.largest_key_.swap(b.smallest_key_); } // max_layer_ isn't saved trie->max_layer_ = std::max(trie->max_layer_, b.layer_); auto& cbt = (*trie)[i]; // 4 base bit num cbt.base_bit_num_ = b.base_bit_num_; builder->push_back(cbt.base_bit_num_); // 5 extra bit num cbt.extra_bit_num_ = b.extra_bit_num_; builder->push_back(cbt.extra_bit_num_); // 6 layer cbt.layer_ = b.layer_; builder->push_back(cbt.layer_); // 7 encoded trie mem size cbt.encoded_trie_.swap(b.encoded_trie_); builder->push_back(cbt.encoded_trie_.mem_size()); // 8 base size and mem_size cbt.base_.swap(b.base_); builder->push_back(cbt.base_.mem_size()); // 9 bitmap mem size cbt.bitmap_.swap(b.bitmap_); builder->push_back(cbt.bitmap_.mem_size()); // 10 mem_size (extra size = bitmap.max_rank1()) b.extra_.shrink_to_fit(); cbt.extra_.swap(b.extra_); builder->push_back(cbt.extra_.mem_size()); // 11 hash vec mem_size (size = base.size()) if (hash_bit_num_ != 0) { if (is_reverse_) { cbt.hash_vec_.resize_with_uintbits(b.hash_vec_.size(), hash_bit_num_); for (size_t i = 0, j = b.hash_vec_.size() - 1; i < b.hash_vec_.size(); ++i, --j) { cbt.hash_vec_.set_wire(j, b.hash_vec_[i]); } } else { b.hash_vec_.shrink_to_fit(); cbt.hash_vec_.swap(b.hash_vec_); } } builder->push_back(cbt.hash_vec_.mem_size()); cbt.calculat_layer_pos(); } builder->finish(&header_vec); trie->header_vec.swap(header_vec); return trie.release(); } void CritBitTriePackedBuilder::get_bounds(bool reverse, fstrvec* bounds) { bounds->erase_all(); for (size_t i = 0; i < trie_nums_; ++i) { auto& b = builder_list_[i]; if (reverse) { bounds->push_back(b.smallest_key_); } else { bounds->push_back(b.largest_key_); } } } void CritBitTriePacked::clear() { header_vec.clear(); trie_list_.clear(); } void CritBitTriePacked::risk_release() { header_vec.risk_release_ownership(); for (auto& trie : trie_list_) { trie.risk_release_ownership(); } trie_list_.clear(); } uint64_t CritBitTriePacked::get_largest_id(size_t trie_index) const { uint64_t rank = entry_per_trie_ * (trie_index + 1) - 1; return std::min(rank, num_words_ - 1); } CritBitTriePackedBuilder::~CritBitTriePackedBuilder() {} void CritBitTriePackedBuilder::encode() { max_layer_ = 0; for (auto& builder : builder_list_) { builder.node_storage_.pop_back(); builder.encode(); builder.compress_diff_bit_array(); max_layer_ = std::max(max_layer_, builder.layer_); } } void CritBitTriePacked::save( std::function append) const { IndexCBTPrefixHeader header; memset(&header, 0, sizeof header); header.header_size = header_vec.mem_size(); header.magic = 0; header.version = 0; header.header_crc16 = Crc16c_update(0, header_vec.data(), header_vec.mem_size()); header.extra_header = 0; header.reserve_bits = 0; append(&header, sizeof header); append(header_vec.data(), header_vec.mem_size()); for (auto& trie : trie_list_) { append(trie.encoded_trie_.data(), trie.encoded_trie_.mem_size()); append(trie.base_.data(), trie.base_.mem_size()); append(trie.bitmap_.data(), trie.bitmap_.mem_size()); append(trie.extra_.data(), trie.extra_.mem_size()); append(trie.hash_vec_.data(), trie.hash_vec_.mem_size()); } } /** * 0 num_words * 1 trie_nums * 2 entry per trie * 3 hash bit number * 4 ~ 11 base_bit_num extra_bit_num layer succient_mem_size base_mem_size * bitmap_mem_size extra_mem_size hash_mem_size */ void CritBitTriePacked::load(fstring mem) { const int mem_index_begin = 4; const int num_each_group = 8; const IndexCBTPrefixHeader* header = reinterpret_cast(mem.data()); header_vec.risk_set_data((byte_t*)mem.data() + sizeof(IndexCBTPrefixHeader), header->header_size); num_words_ = header_vec.get(0); trie_nums_ = header_vec.get(1); entry_per_trie_ = header_vec.get(2); hash_bit_num_ = header_vec.get(3); max_layer_ = 0; // init CritBitTriePacked trie_list_.resize(trie_nums_); byte_t* data_ptr = (byte_t*)mem.data() + sizeof(*header) + header_vec.mem_size(); for (size_t i = 0; i < trie_nums_; ++i) { size_t begin = mem_index_begin + i * num_each_group; uint64_t base_size = i + 1 < trie_nums_ ? entry_per_trie_ : num_words_ % entry_per_trie_; auto& t = trie_list_[i]; t.base_bit_num_ = header_vec.get(begin++); t.extra_bit_num_ = header_vec.get(begin++); t.layer_ = header_vec.get(begin++); max_layer_ = std::max(max_layer_, t.layer_); size_t encoded_trie_mem_size = header_vec.get(begin++); size_t base_mem_size = header_vec.get(begin++); size_t bitmap_mem_size = header_vec.get(begin++); size_t extra_mem_size = header_vec.get(begin++); size_t hash_vec_mem_size = header_vec.get(begin++); assert((hash_bit_num_ != 0 && hash_vec_mem_size != 0) || (hash_bit_num_ == 0 && hash_vec_mem_size == 0)); t.encoded_trie_.risk_mmap_from(data_ptr, encoded_trie_mem_size); data_ptr += encoded_trie_mem_size; t.base_.risk_set_data(data_ptr, base_size - 1, t.base_bit_num_); data_ptr += base_mem_size; t.bitmap_.risk_mmap_from(data_ptr, bitmap_mem_size); data_ptr += bitmap_mem_size; t.extra_.risk_set_data(data_ptr, t.bitmap_.max_rank1(), t.extra_bit_num_); data_ptr += extra_mem_size; if (hash_bit_num_ != 0) { t.hash_vec_.risk_set_data(data_ptr, base_size, hash_bit_num_); data_ptr += hash_vec_mem_size; } t.calculat_layer_pos(); } } CritBitTrieBuilder::~CritBitTrieBuilder() {} void CritBitTrieBuilder::compress_diff_bit_array() { Uint64Histogram hist_delta; // 1st isn't used if (!diff_bit_array_.empty()) { // fill the diff_bit_delta_ and hist_delta diff_bit_delta_.push_back(diff_bit_array_[0]); hist_delta[diff_bit_array_[0]]++; } for (size_t i = 0; i < diff_bit_array_.size(); ++i) { uint64_t parent_rank = i; uint64_t child_pos = parent_rank * 2; if (encoded_trie_.is1(child_pos)) { uint64_t child_rank = encoded_trie_.rank1(child_pos + 1); assert(diff_bit_array_[child_rank] >= diff_bit_array_[parent_rank]); uint64_t delta = diff_bit_array_[child_rank] - diff_bit_array_[parent_rank]; diff_bit_delta_.push_back(delta); hist_delta[delta]++; } child_pos = parent_rank * 2 + 1; if (encoded_trie_.is1(child_pos)) { uint64_t child_rank = encoded_trie_.rank1(child_pos + 1); assert(diff_bit_array_[child_rank] >= diff_bit_array_[parent_rank]); uint64_t delta = diff_bit_array_[child_rank] - diff_bit_array_[parent_rank]; diff_bit_delta_.push_back(delta); hist_delta[delta]++; } } hist_delta.finish(); uint64_t max_delta = hist_delta.m_max_key_len; uint64_t total_storage_size = uint64_t(-1); uint64_t max_delta_bit_num = UintVecMin0::compute_uintbits(max_delta); base_bit_num_ = 0; extra_bit_num_ = 0; // make out the base_bit_num for (size_t i = 1; i <= max_delta_bit_num; ++i) { // i is the bit num of base_ uint64_t max_base = uint64_t(-1) >> (64 - i); uint64_t below_num = 0; auto below_sum = [&below_num, &max_base](uint64_t key, size_t num) { if (key < max_base) below_num += num; }; hist_delta.for_each(below_sum); uint64_t upper_num = hist_delta.m_cnt_sum - below_num; uint64_t tmp = hist_delta.m_cnt_sum * i + upper_num * (max_delta_bit_num - i); if (tmp < total_storage_size) { total_storage_size = tmp; base_bit_num_ = i; } } extra_bit_num_ = max_delta_bit_num - base_bit_num_; uint64_t base_max = uint64_t(-1) >> (64 - base_bit_num_); base_.resize_with_uintbits(diff_bit_delta_.size(), base_bit_num_); extra_.resize_with_uintbits(0, extra_bit_num_); bitmap_.resize(diff_bit_delta_.size()); for (size_t i = 0; i < diff_bit_delta_.size(); ++i) { uint64_t delta = diff_bit_delta_[i]; if (delta <= base_max) { base_.set_wire(i, delta); bitmap_.set0(i); } else { base_.set_wire(i, delta & base_max); bitmap_.set1(i); extra_.push_back(delta >> base_bit_num_); } } bitmap_.build_cache(false, false); } uint64_t CritBitTrieBuilder::comp_key(fstring key, fstring key2) { size_t min_len = std::min(key.size(), key2.size()); size_t diff_byte; for (diff_byte = 0; diff_byte < min_len; ++diff_byte) { if (key[diff_byte] != key2[diff_byte]) { break; } } if (diff_byte == min_len) { // key is sub_str of prev_key(vice versa) // byte * 9 + 0 return diff_byte * 9; } else { assert(diff_byte < min_len); // byte * 9 + diff_bit_in_byte uint32_t b = uint32_t(uint8_t(key[diff_byte] ^ key2[diff_byte])) << 23; assert(b > 0); return diff_byte * 9 + fast_clz32(b); } } void CritBitTrieBuilder::encode() { /** * each node has 2 bit * add 1 bit to support encoded_trie_.rank0(encoded_trie_.size()) */ encoded_trie_.resize(node_storage_.size() * 2 + 1); std::queue pos_queue; if (!node_storage_.empty()) { pos_queue.push(root_pos_); } uint32_t bit_pos = 0; layer_ = 0; while (!pos_queue.empty()) { uint32_t queue_size = pos_queue.size(); for (uint32_t i = 0; i < queue_size; ++i) { uint32_t front = pos_queue.front(); diff_bit_array_.push_back(node_storage_[front].diff_bit); pos_queue.pop(); for (auto& child_pos : node_storage_[front].child) { if (child_pos != invalid_pos) { encoded_trie_.set(bit_pos, 1); pos_queue.push(child_pos); } else { encoded_trie_.set(bit_pos, 0); } ++bit_pos; } } ++layer_; } encoded_trie_.build_cache(false, false); // release memory valvec().swap(node_storage_); } void CritBitTrieBuilder::insert(fstring key) { if (hash_bit_num_ != 0) { hash_vec_.push_back(std::hash()(key) & hash_mask_); } if (node_storage_.empty()) { prev_key_.assign(key.data(), key.size()); smallest_key_.assign(key.data(), key.size()); node_storage_.emplace_back(); return; } assert(prev_key_ != key); uint32_t new_node_pos = node_storage_.size() - 1; Node* new_node = &node_storage_.back(); new_node->diff_bit = comp_key(key, prev_key_); new_node->child[0] = new_node->child[1] = invalid_pos; if (root_pos_ == invalid_pos) { root_pos_ = new_node_pos; prev_key_.assign(key.data(), key.size()); node_storage_.emplace_back(); return; } /** * 1-2 A = 10 A B B B B * 2-3 B = 4 1 2 -> / 3 -> / \ -> / \ -> / \ * 3-4 C = 15 A A C A D A D * 4-5 D = 8 1 2 1 2 3 4 1 2 / 5 1 2 / \ * 5-6 E = 12 C C E * 3 4 3 4 5 6 * * 1-2 A = 10 A B C C C * 2-3 B = 7 1 2 -> / 3 -> / 4 -> / \ -> / \ * 3-4 C = 3 A B B D B E * 4-5 D = 12 1 2 / 3 / 3 4 5 / 3 / 6 * 5-6 E = 8 A A A D * 1 2 1 2 1 2 4 5 */ uint32_t parent = invalid_pos; uint32_t child = root_pos_; bool is_leaf; while (true) { Node* node = at(child); if (new_node->diff_bit < node->diff_bit) { is_leaf = false; break; } uint32_t next_child = node->child[!is_reverse_]; if (next_child == invalid_pos) { is_leaf = true; break; } parent = child; child = next_child; } if (is_leaf) { at(child)->child[!is_reverse_] = new_node_pos; } else { if (parent == invalid_pos) { root_pos_ = new_node_pos; } else { at(parent)->child[!is_reverse_] = new_node_pos; } new_node->child[is_reverse_] = child; } // preserve the last key prev_key_.assign(key.data(), key.size()); node_storage_.emplace_back(); } void CritBitTrie::risk_release_ownership() { encoded_trie_.risk_release_ownership(); base_.risk_release_ownership(); bitmap_.risk_release_ownership(); extra_.risk_release_ownership(); hash_vec_.risk_release_ownership(); } /** * ? * | * -1 * bit 0 * * ? * | * 5 * / \ * -1 -1 * bit 1 0 0 * * * ? * | * 3 * / \ * 4 6 * / \ / \ * 5 -1 10 -1 * / \ / \ * -1 -1 -1 -1 * pos 0 1 2 3 4 5 6 7 8 9 * diff 3 4 6 5 10 * bits 1 1 1 1 0 1 0 0 0 0 0 * rank1 0 1 2 3 4 4 5 5 5 5 5 5 * rank0 0 0 0 0 0 1 1 2 3 4 5 6 */ void CritBitTrie::calculat_layer_pos() { // the last is leaf layer and layer + 1 layer_id_.reserve((layer_ + 1) * 2); layer_id_.risk_set_size(layer_ + 1); layer_rank_ = layer_id_.data() + layer_id_.size(); layer_id_[0] = 0; layer_rank_[0] = 0; if (encoded_trie_.size() == 0) { return; } uint64_t id = 0; uint64_t rank = 0; for (size_t layer = 1; layer < layer_id_.size(); ++layer) { uint64_t pos = (id + 1) * 2; rank = encoded_trie_.rank0(pos); id = pos - rank; layer_id_[layer] = id; layer_rank_[layer] = rank; } } bool CritBitTrie::test_key(fstring key, uint64_t bit_pos) { auto div_result = std::div(bit_pos, 9); if (size_t(div_result.quot) >= key.size()) { return false; } if (div_result.rem == 0) { return true; } return (uint32_t(key[div_result.quot]) >> (8 - div_result.rem)) & 1; } uint64_t CritBitTrie::make_diff_bit(uint64_t rank, uint64_t diff_base) const { uint64_t base_val = base_.get(rank) + diff_base; if (bitmap_.is0(rank)) { return base_val; } else { size_t idx = bitmap_.rank1(rank); return (extra_.get(idx) << base_bit_num_) + base_val; } } bool CritBitTrie::hash_match(fstring key, uint64_t id, uint8_t hash_bit_num) const { assert(hash_bit_num <= 64); uint64_t hash_mask = uint64_t(-1) >> (64 - hash_bit_num); return (std::hash()(key) & hash_mask) == hash_vec_.get(id); } /** * 3 * / \ * 4 6 * / \ / \ * 5 -1 10 -1 * / \ / \ * -1 -1 -1 -1 * * pos 0 1 2 3 4 5 6 7 8 9 * bits 1 1 1 0 1 0 0 0 0 0 * rank1 * rank0 * * 3 * / \ * 4 6 * / \ / \ * 5 7 10 -1 * / \ / \ / \ * -1 -1 -1 -1 -1 -1 * * pos 0 1 2 3 4 5 6 7 8 9 * bits 1 1 1 1 1 0 0 0 0 0 0 0 * rank1 * rank0 * * 3 * / \ * 4 6 * / \ / \ * -1 7 10 -1 * / \ / \ * -1 -1 -1 -1 * * pos 0 1 2 3 4 5 6 7 8 9 * bits 1 1 0 1 1 0 0 0 0 0 * rank1 * rank0 * id pos rank * 1 1 0 0 * 2 2 2 0 * break * 3 4 5 0 * * * -1 * bit * * * 5 * / \ * -1 -1 * bit 0 0 * */ size_t CritBitTrie::index(fstring key, Path* vec) const { if (vec != nullptr) { vec->risk_set_size(0); } if (base_.size() == 0) { return 0; } uint64_t pos; uint64_t id = 0; uint64_t rank = 0; uint64_t diff_base = 0; size_t layer = 0; while (true) { #if 0 uint64_t diff_bit = make_diff_bit(id, diff_base); #else // manual inline make_diff_bit uint64_t diff_bit = base_.get(id) + diff_base; if (bitmap_.is1(id)) { diff_bit += extra_.get(bitmap_.rank1(id)) << base_bit_num_; } #endif diff_base = diff_bit; size_t is_right = test_key(key, diff_bit); if (vec != nullptr) { assert(vec->size() < vec->capacity()); PathElement e; e.is_right = is_right; e.id = id; vec->unchecked_push_back(e); } pos = id * 2 + is_right; rank += encoded_trie_.rank0(pos) - layer_rank_[layer]; if (encoded_trie_.is0(pos)) { id = encoded_trie_.rank1(pos); break; } ++layer; id = encoded_trie_.rank1(pos + 1); } while (id != layer_id_[layer++]) { pos = (id + 1) * 2; id = encoded_trie_.rank1(pos); rank += encoded_trie_.rank0(pos) - layer_rank_[layer]; } return rank; } /** * 7 * / \ * 9 -1 * / \ * -1 16 * / \ * 18 18 * / \ / \ * -1 -1 -1 26 * / \ * -1 27 * / \ * -1 -1 * * * * 7 * / \ * 9 9 * / \ / \ * -1 15 -1 16 * / \ / \ * 16 -1 -1 18 * / \ / \ * -1 18 -1 -1 * / \ * -1 27 * / \ * -1 -1 * * diff bit array : 7 9 9 15 16 16 18 18 27 * diff bit delta : 7 2 2 6 7 1 2 2 9 * layer id : 0 2 4 6 7 8 8 * layer rank : 0 0 2 4 7 8 10 * succient :1 1 0 1 0 1 1 0 0 1 0 1 0 0 0 1 0 0 * * * 7 * / \ * 9 9 * / \ / \ * -1 15 -1 16 * / \ / \ * 16 -1 -1 18 * / \ / \ * -1 18 -1 -1 * / \ * 27 -1 * / \ * -1 -1 * * pos 0 2 4 6 8 10 12 14 16 18 * bits 1 1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0 0 * rank0 0 0 0 1 1 2 2 2 3 4 4 5 5 6 7 7 8 9 10 * rank1 0 1 2 2 3 3 4 5 5 5 6 6 7 7 7 8 8 8 8 * layer | | | | | | | * l_id 0 2 4 6 7 8 8 * l_rank 0 0 2 4 7 8 10 * * * step id pos rank * 1 1 0 0 * 2 2 2 0 * 3 3 5 * 4 5 6 * 5 7 11 * 6 8 14 * break * 1 18 * * */ /** * 7 * / \ * 9 -1 * / \ * -1 15 * / \ * 16 -1 * / \ * 18 17 * / \ / \ * -1 -1 18 -1 * / \ * -1 26 * / \ * -1 27 * / \ * -1 -1 * */ size_t CritBitTrie::lower_bound(fstring key, fstring best_match_key, const Path& path, int c) const { size_t common_bits = CritBitTrieBuilder::comp_key(key, best_match_key); uint64_t rank_inc = c > 0; if (path.empty()) { return rank_inc; } uint64_t id = (assert(path[0].id == 0), 0); uint64_t rank = 0; uint64_t diff_base = 0; size_t layer = 0; while (true) { #if 0 uint64_t diff_bit = make_diff_bit(id, diff_base); #else // manual inline make_diff_bit uint64_t diff_bit = base_.get(id) + diff_base; if (bitmap_.is1(id)) { diff_bit += extra_.get(bitmap_.rank1(id)) << base_bit_num_; } #endif diff_base = diff_bit; if (diff_bit > common_bits) { while (true) { uint64_t pos = id * 2 + rank_inc; id = encoded_trie_.rank1(pos + 1); rank += encoded_trie_.rank0(pos) - layer_rank_[layer]; if (encoded_trie_.is0(pos)) { break; } ++layer; } break; } else { uint64_t pos = id * 2 + path[layer].is_right; rank += encoded_trie_.rank0(pos) - layer_rank_[layer]; if (layer + 1 == path.size()) { assert(encoded_trie_.is0(pos)); id = encoded_trie_.rank1(pos); break; } } id = path[++layer].id; } while (id != layer_id_[layer++]) { uint64_t pos = (id + 1) * 2; id = encoded_trie_.rank1(pos); rank += encoded_trie_.rank0(pos) - layer_rank_[layer]; } return rank + rank_inc; } } // namespace terark 100-1000 #include #include namespace Gwk { // namespace ControlFactory // { // class TextBox_Factory : public Gwk::ControlFactory::Base // { // public: // // GWK_CONTROL_FACTORY_FOR(TextBox, Label) // { // } // // Gwk::Controls::Base* CreateInstance(Gwk::Controls::Base* parent) override // { // Gwk::Controls::TextBox* control = new Gwk::Controls::TextBox(parent); // control->SetSize(100, 20); // control->SetText(""); // return control; // } // // }; // // // class TextBoxMultiline_Factory : public Gwk::ControlFactory::Base // { // public: // // GWK_CONTROL_FACTORY_FOR(TextBoxMultiline, TextBox) // { // } // // Gwk::Controls::Base* CreateInstance(Gwk::Controls::Base* parent) override // { // Gwk::Controls::TextBoxMultiline* control = // new Gwk::Controls::TextBoxMultiline(parent); // control->SetSize(100, 50); // control->SetText(""); // return control; // } // // }; // // // GWK_CONTROL_FACTORY(TextBox_Factory); // GWK_CONTROL_FACTORY(TextBoxMultiline_Factory); // // } } #include "BuildingData.h" using namespace BOSS; BuildingStatus::BuildingStatus() : _type(ActionTypes::None) , _timeRemaining(0) , _isConstructing(ActionTypes::None) , _addon(ActionTypes::None) { } BuildingStatus::BuildingStatus(const ActionType & action, const ActionType & addon) : _type(action) , _timeRemaining(0) , _isConstructing(ActionTypes::None) , _addon(addon) { } BuildingStatus::BuildingStatus(const ActionType & action, FrameCountType time, const ActionType & constructing, const ActionType & addon) : _type(action) , _timeRemaining(time) , _isConstructing(constructing) , _addon(addon) { } const bool BuildingStatus::canBuildEventually(const ActionType & action) const { if (!_type.canBuild(action)) { return false; } // if the type is an addon if (action.isAddon()) { // if we already have an addon we can't build it if (_addon != ActionTypes::None) { return false; } // if we are building an addon we can't ever build it if (_timeRemaining > 0 && _isConstructing.isAddon()) { return false; } } if (action.requiresAddon() && (_addon != action.requiredAddonType())) { if (_isConstructing != action.requiredAddonType()) { return false; } } // if the built type is morphed and we are morphing something, we won't be able to build it if (action.isMorphed() && (_timeRemaining > 0) && (_isConstructing.isMorphed())) { return false; } return true; } const bool BuildingStatus::canBuildNow(const ActionType & action) const { if (_timeRemaining > 0) { return false; } if (!_type.canBuild(action)) { return false; } if (action.isAddon() && (_addon != ActionTypes::None)) { return false; } if (action.requiresAddon() && (_addon != action.requiredAddonType())) { return false; } return true; } void BuildingStatus::queueActionType(const ActionType & action) { _timeRemaining = action.buildTime(); _isConstructing = action; } void BuildingStatus::fastForward(const FrameCountType frames) { // if we fastforward more than the current time remaining, we will complete the action bool willComplete = _timeRemaining <= frames; int timeWasRemaining = _timeRemaining; const std::string & name = _type.getName(); if ((_timeRemaining > 0) && willComplete) { BOSS_ASSERT(_isConstructing != ActionTypes::None, "We can't be building a unit without a type %s %d", _type.getName().c_str(), timeWasRemaining); _timeRemaining = 0; // if it's building an addon, add it if (_isConstructing.isAddon()) { _addon = _isConstructing; } // if we are finishing a morphed type, it becomes that type if (_isConstructing.isMorphed()) { _type = _isConstructing; } _isConstructing = ActionTypes::None; } else if (_timeRemaining > 0) { _timeRemaining -= frames; } } BuildingData::BuildingData() { } const size_t & BuildingData::size() const { return _buildings.size(); } void BuildingData::addBuilding(const ActionType & action, const ActionType & addon) { BOSS_ASSERT(action.isBuilding(), "Trying to add a non-building to the building data"); _buildings.push_back(BuildingStatus(action, addon)); } void BuildingData::removeBuilding(const ActionType & action, const ActionType & addon) { BOSS_ASSERT(action.isBuilding(), "Trying to remove a non-building from the building data"); for (size_t i = 0; i < _buildings.size(); i++) { if (_buildings[i]._type == action) { _buildings.remove(i); break; } } } void BuildingData::addBuilding(const ActionType & action, const FrameCountType timeUntilFree, const ActionType & constructing, const ActionType & addon) { BOSS_ASSERT(action.isBuilding(), "Trying to add a non-building to the building data"); _buildings.push_back(BuildingStatus(action, timeUntilFree, constructing, addon)); } const BuildingStatus & BuildingData::getBuilding(const UnitCountType i) const { return _buildings[i]; } // how long from now until we can build the given action const FrameCountType BuildingData::getTimeUntilCanBuild(const ActionType & action) const { bool minset = false; FrameCountType min = 0; for (size_t i=0; i<_buildings.size(); ++i) { if (_buildings[i].canBuildEventually(action)) { if (!minset || _buildings[i]._timeRemaining < min) { minset = true; min = _buildings[i]._timeRemaining; } } } BOSS_ASSERT(minset, "Min was not set"); return min; } void BuildingData::queueAction(const ActionType & action) { for (size_t i=0; i<_buildings.size(); ++i) { if (_buildings[i].canBuildNow(action)) { _buildings[i].queueActionType(action); return; } } // this method should always work since we have fast forwarded to the correct point in time BOSS_ASSERT(false, "Didn't find a building to queue this type of unit in: %s", action.getName().c_str()); } // fast forward all the building states by amount: frames void BuildingData::fastForwardBuildings(const FrameCountType frames) { for (size_t i=0; i<_buildings.size(); ++i) { _buildings[i].fastForward(frames); } } std::string BuildingData::toString() const { std::stringstream ss; ss << "Buildings\n\n"; for (size_t i=0; i<_buildings.size(); ++i) { const BuildingStatus & b = _buildings[i]; ss << b._type.getName() << " "; ss << b._timeRemaining << " "; ss << (b._isConstructing != ActionTypes::None ? b._isConstructing.getName() : "None") << " "; ss << (b._addon != ActionTypes::None ? b._addon.getName() : "None") << "\n"; } return ss.str(); } const bool BuildingData::canBuildNow(const ActionType & action) const { for (size_t i=0; i<_buildings.size(); ++i) { if (_buildings[i].canBuildNow(action)) { return true; } } return false; } const bool BuildingData::canBuildEventually(const ActionType & action) const { for (size_t i=0; i<_buildings.size(); ++i) { if (_buildings[i].canBuildEventually(action)) { return true; } } return false; } void BuildingData::printBuildingInformation() const { for (size_t i=0; i<_buildings.size(); ++i) { if (_buildings[i]._timeRemaining == 0) { printf("BUILDING INFO: %s is free to assign\n", _buildings[i]._type.getName().c_str()); } else { printf("BUILDING INFO: %s will be free in %d frames\n", _buildings[i]._type.getName().c_str(), _buildings[i]._timeRemaining); } } printf("-----------------------------------------------------------\n\n"); }// Copyright 2019 DeepMind Technologies Ltd. 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. // testing #include "open_spiel/games/amazons.h" #include #include #include #include #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/spiel_utils.h" #include "open_spiel/utils/tensor_view.h" namespace open_spiel { namespace amazons { namespace { // Facts about the game. const GameType kGameType{ /*short_name=*/"amazons", /*long_name=*/"Amazons", GameType::Dynamics::kSequential, GameType::ChanceMode::kDeterministic, GameType::Information::kPerfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/false, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, /*parameter_specification=*/{} // no parameters }; std::shared_ptr Factory(const GameParameters ¶ms) { return std::shared_ptr(new AmazonsGame(params)); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace CellState PlayerToState(Player player) { switch (player) { case 0: return CellState::kCross; case 1: return CellState::kNought; default: SpielFatalError(absl::StrCat("Invalid player id ", player)); return CellState::kEmpty; } } std::string StateToString(CellState state) { switch (state) { case CellState::kEmpty: return "."; case CellState::kNought: return "O"; case CellState::kCross: return "X"; case CellState::kBlock: return "#"; default: SpielFatalError("Unknown state."); } } /* Move generation functions */ std::vector AmazonsState::GetHorizontalMoves(Action cell) const { std::vector horizontalMoves; unsigned char col = cell % kNumRows; // The column the cell is in unsigned char left = col; // The maximum amount of spaces to check left of given cell unsigned char right = kNumCols - col - 1; // The maximal amount of spaces to check right of given cell Action focus; // <-----X // Walk until we encounter a blocking piece or end of row int count = 1; while (count <= left) { focus = cell - count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X----> // Walk until we encounter a blocking piece or end of row count = 1; while (count <= right) { focus = cell + count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return horizontalMoves; } std::vector AmazonsState::GetVerticalMoves(Action cell) const { std::vector verticalMoves; unsigned char row = cell / kNumRows; // The row the cell is in unsigned char up = row; // The maximum amount of spaces to check up of given cell unsigned char down = kNumRows - row - 1; // The maximal amount of spaces to check down of given cell Action focus; // ^ // | // | // X // Walk until we encounter a blocking piece or end of column int count = 1; focus = cell; while (count <= up) { focus -= kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X // | // | // V // Walk until we encounter a blocking piece or end of column count = 1; focus = cell; while (count <= down) { focus += kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return verticalMoves; } std::vector AmazonsState::GetDiagonalMoves(Action cell) const { std::vector diagonalMoves; unsigned char col = cell % kNumCols; // The column the cell is in unsigned char row = cell / kNumRows; // The row the cell is in unsigned char upLeft = std::min( row, col); // The maximum amount of spaces to check up and left of given cell unsigned char upRight = std::min( row, (unsigned char)(kNumCols - col - 1)); // The maximum amount of spaces to // check up and right of given cell // The maximum amount of spaces to check // down and left of given cell unsigned char downLeft = std::min(static_cast(kNumRows - row - 1), col); // The maximum amount of spaces to check down // and right of given cell unsigned char downRight = std::min(static_cast(kNumRows - row - 1), static_cast(kNumCols - col - 1)); Action focus; // Up and left int count = 1; focus = cell; while (count <= upLeft) { focus -= (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Up and right count = 1; focus = cell; while (count <= upRight) { focus -= (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and left count = 1; focus = cell; while (count <= downLeft) { focus += (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and right count = 1; focus = cell; while (count <= downRight) { focus += (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return diagonalMoves; } std::vector AmazonsState::GetAllMoves(Action cell) const { std::vector horizontals = GetHorizontalMoves(cell); std::vector verticals = GetVerticalMoves(cell); std::vector diagonals = GetDiagonalMoves(cell); std::vector acc = horizontals; acc.insert(acc.end(), verticals.begin(), verticals.end()); acc.insert(acc.end(), diagonals.begin(), diagonals.end()); return acc; } void AmazonsState::DoApplyAction(Action action) { switch (state_) { case amazon_select: { SPIEL_CHECK_EQ(board_[action], PlayerToState(CurrentPlayer())); from_ = action; board_[from_] = CellState::kEmpty; state_ = destination_select; } break; case destination_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); to_ = action; board_[to_] = PlayerToState(CurrentPlayer()); state_ = shot_select; break; } case shot_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); shoot_ = action; board_[shoot_] = CellState::kBlock; current_player_ = 1 - current_player_; state_ = amazon_select; // Check if game is over if (LegalActions().empty()) { // outcome = winner outcome_ = 1 - current_player_; } } break; } ++num_moves_; } void AmazonsState::UndoAction(Player player, Action move) { switch (state_) { case amazon_select: { shoot_ = move; board_[shoot_] = CellState::kEmpty; current_player_ = player; outcome_ = kInvalidPlayer; state_ = shot_select; } break; case destination_select: { from_ = move; board_[from_] = PlayerToState(player); state_ = amazon_select; } break; case shot_select: { to_ = move; board_[to_] = CellState::kEmpty; state_ = destination_select; } break; } --num_moves_; --move_number_; history_.pop_back(); } std::vector AmazonsState::LegalActions() const { if (IsTerminal()) return {}; std::vector actions; switch (state_) { case amazon_select: for (int i = 0; i < board_.size(); i++) { if (board_[i] == PlayerToState(CurrentPlayer())) { // check if the selected amazon has a possible move if (GetAllMoves(i).empty()) continue; actions.push_back(i); } } break; case destination_select: actions = GetAllMoves(from_); break; case shot_select: actions = GetAllMoves(to_); break; } sort(actions.begin(), actions.end()); return actions; } std::string AmazonsState::ActionToString(Player player, Action action) const { std::string str = absl::StrCat("(", (action / kNumRows) + 1, ", ", (action % kNumRows) + 1, ")"); switch (state_) { case amazon_select: return absl::StrCat(StateToString(PlayerToState(player)), " From ", str); case destination_select: return absl::StrCat(StateToString(PlayerToState(player)), " To ", str); case shot_select: return absl::StrCat(StateToString(PlayerToState(player)), " Shoot: ", str); } } // Looks okay AmazonsState::AmazonsState(std::shared_ptr game) : State(game) { std::fill(begin(board_), end(board_), CellState::kEmpty); switch (kNumRows) { case 6: board_[1] = board_[4] = board_[6] = board_[11] = CellState::kCross; board_[24] = board_[29] = board_[31] = board_[34] = CellState::kNought; break; case 8: board_[2] = board_[5] = board_[16] = board_[23] = CellState::kCross; board_[40] = board_[47] = board_[58] = board_[61] = CellState::kNought; break; } } void AmazonsState::SetState(int cur_player, MoveState move_state, const std::array& board) { current_player_ = cur_player; state_ = move_state; board_ = board; } std::string AmazonsState::ToString() const { std::string str; for (int r = 0; r < kNumRows; ++r) { for (int c = 0; c < kNumCols; ++c) { absl::StrAppend(&str, StateToString(BoardAt(r, c))); } if (r < (kNumRows - 1)) { absl::StrAppend(&str, "\n"); } } return str; } bool AmazonsState::IsTerminal() const { return outcome_ != kInvalidPlayer; } std::vector AmazonsState::Returns() const { if (outcome_ == (Player{0})) { return {1.0, -1.0}; } else if (outcome_ == (Player{1})) { return {-1.0, 1.0}; } else { return {0.0, 0.0}; } } std::string AmazonsState::InformationStateString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return HistoryString(); } std::string AmazonsState::ObservationString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return ToString(); } void AmazonsState::ObservationTensor(Player player, absl::Span values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // Treat `values` as a 2-d tensor. TensorView<2> view(values, {kCellStates, kNumCells}, true); for (int cell = 0; cell < kNumCells; ++cell) { view[{static_cast(board_[cell]), cell}] = 1.0; } } std::unique_ptr AmazonsState::Clone() const { return std::unique_ptr(new AmazonsState(*this)); } AmazonsGame::AmazonsGame(const GameParameters ¶ms) : Game(kGameType, params) {} } // namespace amazons } // namespace open_spiel #include #define MAXN 100000+5 using namespace std; int n,m; struct SHOP {int i,w,p;}a[MAXN]; bool cmp(SHOP a,SHOP b) { if(a.w/a.p>b.w/b.p)return 1; return a.p>b.p; return 1; } void shop(int k) { int ans=0; for(int i=1;i<=n;i++) { while(k>=a[i].p) { ans+=a[i].w; k=k-a[i].p; } } printf("%d\n",ans); return; } int main() { freopen("shopping.in","r",stdin); freopen("shopping.out","w",stdout); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { a[i].i=i; scanf("%d%d",&a[i].w,&a[i].p); } sort(a+1,a+n+1,cmp); while(m--) { int flag; scanf("%d",&flag); if(flag==1) { int x,w,p; scanf("%d%d%d",&x,&w,&p); for(int i=1;i<=n;i++) { if(a[i].i==x) {a[i].w=w;a[i].p=p;} } sort(a+1,a+n+1,cmp); } else { int k; scanf("%d",&k); shop(k); } } return 0; } /* * CSemaphore.cpp * * Copyright (C) 2015, <>, <> * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. * * encoding: UTF-8 * tab size: 4 * * author: () * created: 11/11/14 * version: 0.2.2 - add semaphore to synchronize the start of the measurements */ #include "CSemaphore.hpp" #include namespace NLibMeasure { CSemaphore::CSemaphore() { sem_init(&mSemID, 0, 0); } CSemaphore::~CSemaphore() { sem_destroy(&mSemID); } void CSemaphore::post(int count) { for(int i = 0; i < count; i++){ sem_post(&mSemID); } } void CSemaphore::wait(void) { sem_wait(&mSemID); } } wlhcode/lscct #include using namespace std; char board[10][10]; int main(){ ios::sync_with_stdio(false); cin.tie(0); int kill=0; for(int i=0;i<10;i++){ for(int j=0;j<10;j++) board[j][i]='.'; } for(int i=1;i<=8;i++){ for(int j=1;j<=8;j++){ cin>>board[j][i]; if(board[j][i]=='P'){ if(board[j-1][i-1]=='p'){ kill++; board[j-1][i-1]='K'; } if(board[j+1][i-1]=='p'){ kill++; board[j+1][i-1]='K'; } } // for(int k=1;k<=8;k++){ // for(int l=1;l<=8;l++) cout<1000+ #ifndef _higan_dsp_h_ #define _higan_dsp_h_ #include "SPC_DSP.h" #include "blargg_common.h" namespace SuperFamicom { struct DSP { int64_t clock; unsigned long removed_samples; inline void step(uint64_t clocks); bool mute(); uint8_t read(uint8_t addr); void write(uint8_t addr, uint8_t data); void enter(); void power(); void reset(); void channel_enable(unsigned channel, bool enable); void disable_surround(bool disable = true); DSP(struct SMP&); ~DSP(); SPC_DSP spc_dsp; private: struct SMP & smp; int16_t * samplebuffer; bool channel_enabled[8]; }; }; #endif wangyang2013/TFMTFM/click-2.0.1/elements/standard/quicknotequeue.cc // -*- c-basic-offset: 4 -*- /* * quicknotequeue.{cc,hh} -- queue element that notifies quickly * * * Copyright (c) 2009 Meraki, Inc. * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include #include "quicknotequeue.hh" CLICK_DECLS QuickNoteQueue::QuickNoteQueue() { } QuickNoteQueue::~QuickNoteQueue() { } void * QuickNoteQueue::cast(const char *n) { if (strcmp(n, "QuickNoteQueue") == 0) return (QuickNoteQueue *)this; else return FullNoteQueue::cast(n); } Packet * QuickNoteQueue::pull(int) { int h = _head, t = _tail; Packet *p; if (h != t) { p = _q[h]; packet_memory_barrier(_q[h], _head); _head = h = next_i(h); _full_note.wake(); } else p = 0; if (h == t) { _empty_note.sleep(); #if HAVE_MULTITHREAD // Work around race condition between push() and pull(). // We might have just undone push()'s Notifier::wake() call. // Easiest lock-free solution: check whether we should wake again! if (size()) _empty_note.wake(); #endif } return p; } CLICK_ENDDECLS ELEMENT_REQUIRES(FullNoteQueue) EXPORT_ELEMENT(QuickNoteQueue) #include "Level.h" #include "Player.h" #include "Resource.h" #include "Rock.h" Level::Level(pa::World& world) : pa::Object(world) , pa::InputHandler(world) { m_background = g_resource.background->createMap(g_resource.backgroundTileMap, 0, 0, false, false, -1); } void Level::onCreate() { getWorld().create()->getPosition().set(320, 320); getWorld().create()->getPosition().set(64, 64); getWorld().create()->getPosition().set(570, 64); getWorld().create()->getPosition().set(570, 570); getWorld().create()->getPosition().set(64, 570); } void Level::onStep(pa::Time deltaTime) { if (getWorld().getList().size() + getWorld().getList().size() == 0) { getWorld().resetNextStep(); } } #ifndef _PADDLE_H_ #define _PADDLE_H_ #include "vrpong.hpp" struct Paddle { Color color; int x, y; int width, height; Paddle(int x1, int y1, int w, int h, Color c = Color(0xFF, 0xFF, 0xFF)) : color(c.r, c.g, c.b), x(x1), y(y1), width(w), height(h) {} }; #endif /* _PADDLE_H_ */ #include "scalar_image.h" bool SCALAR_Image::readImage() { if (nifti_image_load(nim)==-1) { std::cout<<"Cannot read image data from : " << filePath << std::endl; return false; } NiftiDataAccessor *accessor = NULL; switch (nim->datatype) { case 2: accessor = new NiftiDataAccessor_ForType; break; case 4: accessor = new NiftiDataAccessor_ForType; break; case 8: accessor = new NiftiDataAccessor_ForType; break; case 16: accessor = new NiftiDataAccessor_ForType; break; case 64: accessor = new NiftiDataAccessor_ForType; break; case 256: accessor = new NiftiDataAccessor_ForType; break; case 512: accessor = new NiftiDataAccessor_ForType; break; case 768: accessor = new NiftiDataAccessor_ForType; break; case 1024: accessor = new NiftiDataAccessor_ForType; break; case 1280: accessor = new NiftiDataAccessor_ForType; break; case 1536: accessor = new NiftiDataAccessor_ForType; break; } // all zero valued voxels are pointed to here zero = new float[1]; zero[0] = 0; // Copy everything in a float array with dimension 1 data = new float*[sxyz]; MT::MTRUN(sxyz, sxyz/16, MT::maxNumberOfThreads,[&](MTTASK task)->void { data[task.no] = new float[1]; data[task.no][0] = accessor->get(nim->data,task.no); }); nifti_image_unload(nim); delete accessor; nim->nt = 1; //Force the forth dimension to be 1 so indexing will not crash if an 3D image with nim->nt=0 comes this->Image::indexVoxels(); return true; } #include #include #include "gtest/gtest.h" #include "user-thread.hpp" using namespace orks::userthread; namespace { struct TestData { WorkerManager& wm; const int thread_size = 8; std::atomic_int counter {0}; std::atomic_int alive_thread_counter {thread_size}; }; void main_thread_for_test_main_thread(void* arg) { printf("main thread\n"); (*static_cast(arg)) = 1; } void child_thread_for_test(void* arg) { printf("child thread\n"); TestData& args = *reinterpret_cast(arg); ++args.counter; --args.alive_thread_counter; } void main_thread_for_test(void* arg) { printf("main thread\n"); TestData& args = *reinterpret_cast(arg); for (int i = 0; i < args.thread_size; ++i) { args.wm.start_thread(child_thread_for_test, &args); } while (args.alive_thread_counter != 0) { args.wm.scheduling_yield(); } } void child_thread_for_test_yield(void* arg) { printf("child thread\n"); TestData& args = *reinterpret_cast(arg); ++args.counter; args.wm.scheduling_yield(); printf("child thread resumed\n"); ++args.counter; --args.alive_thread_counter; } void main_thread_for_test_yield(void* arg) { printf("main thread\n"); TestData& args = *reinterpret_cast(arg); for (int i = 0; i < args.thread_size; ++i) { args.wm.start_thread(child_thread_for_test_yield, &args); } while (args.alive_thread_counter != 0) { printf("main thread yield\n"); args.wm.scheduling_yield(); } } void rec(unsigned int n) { volatile char c[0x1000] = {}; static_cast(c); if (n == 0) { return; } rec(n - 1); } void rec_thread(WorkerManager* wm, unsigned int n) { volatile char c[0x1000] = {}; static_cast(c); if (n == 0) { return; } detail::create_thread(*wm, rec_thread, wm, n - 1); } } TEST(WorkerManager, TestMainThreadWith1Worker) { WorkerManager wm { 1 }; std::atomic_int i {0}; wm.start_main_thread(main_thread_for_test_main_thread, &i); ASSERT_EQ(i, 1); } TEST(WorkerManager, TestMainThread) { WorkerManager wm { 4 }; std::atomic_int i {0}; wm.start_main_thread(main_thread_for_test_main_thread, &i); ASSERT_EQ(i, 1); } TEST(WorkerManager, TestWith1Worker) { WorkerManager wm { 1 }; TestData args {wm}; wm.start_main_thread(main_thread_for_test, &args); ASSERT_EQ(args.thread_size, args.counter); } TEST(WorkerManager, TestYieldWith1Worker) { WorkerManager wm { 1 }; TestData args {wm}; wm.start_main_thread(main_thread_for_test_yield, &args); ASSERT_EQ(args.thread_size * 2, args.counter); } TEST(WorkerManager, Test) { WorkerManager wm { 4 }; TestData args {wm}; wm.start_main_thread(main_thread_for_test, &args); ASSERT_EQ(args.thread_size, args.counter); } TEST(WorkerManager, TestYield) { WorkerManager wm { 4 }; TestData args {wm}; wm.start_main_thread(main_thread_for_test_yield, &args); ASSERT_EQ(args.thread_size * 2, args.counter); } #ifdef USE_SPLITSTACKS TEST(TestBigLocalArray, RecCallWith1Worker) { WorkerManager wm { 1 }; detail::start_main_thread(wm, rec, 10); } TEST(TestBigLocalArray, RecCall) { WorkerManager wm { 4 }; detail::start_main_thread(wm, rec, 10); } TEST(TestBigLocalArray, RecThreadWith1Worker) { WorkerManager wm { 1 }; detail::start_main_thread(wm, rec_thread, &wm, 10); } TEST(TestBigLocalArray, RecThread) { WorkerManager wm { 4 }; detail::start_main_thread(wm, rec_thread, &wm, 10); } #endif int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } /* * Copyright (c) 2019, the neonavigation authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include namespace planner_cspace { TEST(GridAstar, ParallelSearch) { using Vec = CyclicVecInt<1, 1>; GridAstar<1, 1> as(Vec(16)); as.setSearchTaskNum(8); omp_set_num_threads(2); class Model : public GridAstarModelBase<1, 1> { private: std::vector> search_; public: Model() : search_(16) { // create search table of graph edges (relative vector to the connected grid) // 0: connected to 1-14 // 1-14: connected to 1-15 for (int i = 1; i <= 14; ++i) { search_[0].push_back(Vec(i)); for (int j = 1; j <= 15; ++j) { if (i == j) continue; search_[i].push_back(Vec(j - i)); } } } float cost(const Vec&, const Vec&, const std::vector&, const Vec&) const final { return 1.0; } float costEstim(const Vec& s, const Vec& e) const final { return 0.0; } const std::vector& searchGrids(const Vec& p, const std::vector&, const Vec&) const final { return search_[p[0]]; } }; Model::Ptr model(new Model()); const auto cb_progress = [](const std::list&, const SearchStats&) -> bool { return true; }; for (int i = 0; i < 1000; ++i) { std::list path; std::vector starts; starts.emplace_back(Vec(0)); ASSERT_TRUE( as.search( starts, Vec(15), path, model, cb_progress, 0, 1.0)); ASSERT_EQ(path.size(), 3u); ASSERT_EQ(path.front(), Vec(0)); ASSERT_EQ(path.back(), Vec(15)); } } TEST(GridAstar, TimeoutAbort) { using Vec = CyclicVecInt<1, 1>; GridAstar<1, 1> as(Vec(2)); as.setSearchTaskNum(8); omp_set_num_threads(2); class Model : public GridAstarModelBase<1, 1> { private: std::vector> search_; public: Model() : search_(3) { search_[0].push_back(Vec(1)); search_[1].push_back(Vec(2)); } float cost(const Vec&, const Vec&, const std::vector&, const Vec&) const final { return 1.0; } float costEstim(const Vec& s, const Vec& e) const final { return 0.0; } const std::vector& searchGrids(const Vec& p, const std::vector&, const Vec&) const final { return search_[p[0]]; } }; Model::Ptr model(new Model()); int cnt(0); const auto cb_progress = [&cnt](const std::list& /* path_grid */, const SearchStats& stats) -> bool { switch (cnt++) { case 0: EXPECT_EQ(1u, stats.num_loop); EXPECT_EQ(1u, stats.num_search_queue); EXPECT_EQ(0u, stats.num_prev_updates); EXPECT_EQ(0u, stats.num_total_updates); return true; case 1: EXPECT_EQ(2u, stats.num_loop); EXPECT_EQ(1u, stats.num_search_queue); EXPECT_EQ(1u, stats.num_prev_updates); EXPECT_EQ(1u, stats.num_total_updates); return false; } EXPECT_TRUE(false) << "Search was not aborted"; return false; }; std::list path; std::vector starts; starts.emplace_back(Vec(0)); ASSERT_FALSE(as.search(starts, Vec(2), path, model, cb_progress, 0, 0.0)); } TEST(GridAstar, SearchWithMultipleStarts) { using Vec = CyclicVecInt<1, 1>; GridAstar<1, 1> as(Vec(16)); as.setSearchTaskNum(1); class Model : public GridAstarModelBase<1, 1> { private: std::vector> search_; public: Model() : search_(16) { // create search table of graph edges (relative vector to the connected grid) // 0: connected to 2-14 // 1: connected to 2-14 // 2-14: connected to 2-15 for (int i = 2; i <= 14; ++i) { search_[0].push_back(Vec(i)); search_[1].push_back(Vec(i - 1)); for (int j = 2; j <= 15; ++j) { if (i == j) continue; search_[i].push_back(Vec(j - i)); } } } float cost(const Vec&, const Vec&, const std::vector&, const Vec&) const final { return 1.0; } float costEstim(const Vec& s, const Vec& e) const final { return 0.0; } const std::vector& searchGrids(const Vec& p, const std::vector&, const Vec&) const final { return search_[p[0]]; } }; Model::Ptr model(new Model()); const auto cb_progress = [](const std::list&, const SearchStats&) -> bool { return true; }; for (int add_cost_to = 0; add_cost_to < 2; ++add_cost_to) { std::vector::VecWithCost> starts; starts.emplace_back(Vec(0)); starts.emplace_back(Vec(1)); starts[add_cost_to].c_ = 0.1; std::list path; ASSERT_TRUE( as.search( starts, Vec(15), path, model, cb_progress, 0, 1.0)) << add_cost_to; ASSERT_EQ(path.size(), 3u); ASSERT_EQ(path.back(), Vec(15)); if (add_cost_to == 0) ASSERT_EQ(path.front(), Vec(1)); else ASSERT_EQ(path.front(), Vec(0)); } } class GridAstarTestWrapper : public GridAstar<1, 1> { public: explicit GridAstarTestWrapper(const Vec& size) : GridAstar(size) { } std::unordered_map& parentMap() { return parents_; } bool findPath(const std::vector& ss, const Vec& e, std::list& path) const { return GridAstar::findPath(ss, e, path); } }; TEST(GridAstar, FindPathLooped) { using Vec = GridAstarTestWrapper::Vec; GridAstarTestWrapper as(Vec(4)); as.parentMap()[Vec(3)] = Vec(2); as.parentMap()[Vec(2)] = Vec(1); as.parentMap()[Vec(1)] = Vec(2); std::list path; const auto timeout_func = []() { try { boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); } catch (boost::thread_interrupted&) { return; } EXPECT_TRUE(false) << "Looks entered endless loop. Test will be aborted."; abort(); }; boost::thread timeout(timeout_func); std::vector starts; starts.emplace_back(Vec(0)); ASSERT_FALSE(as.findPath(starts, Vec(3), path)); timeout.interrupt(); } TEST(GridAstar, FindPathUnconnected) { using Vec = GridAstarTestWrapper::Vec; GridAstarTestWrapper as(Vec(3)); as.parentMap()[Vec(2)] = Vec(1); std::list path; std::vector starts; starts.emplace_back(Vec(0)); ASSERT_FALSE(as.findPath(starts, Vec(2), path)); } TEST(GridAstar, FindPath) { using Vec = GridAstarTestWrapper::Vec; GridAstarTestWrapper as(Vec(3)); as.parentMap()[Vec(2)] = Vec(1); as.parentMap()[Vec(1)] = Vec(0); // findPath must return same result for multiple calls for (int i = 0; i < 2; ++i) { std::list path; std::vector starts; starts.emplace_back(Vec(0)); ASSERT_TRUE(as.findPath(starts, Vec(2), path)); ASSERT_EQ(path.size(), 3u); auto it = path.cbegin(); ASSERT_EQ(*(it++), Vec(0)); ASSERT_EQ(*(it++), Vec(1)); ASSERT_EQ(*it, Vec(2)); } } } // namespace planner_cspace int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } 1-10 /* * \file tcs3414_impl.hpp * \date 2 Mar 2013 * \author */ #ifndef XPCC__TCS3414_HPP # error "Don't include this file directly, use 'software_i2c.hpp' instead!" #endif template xpcc::i2c::WriteReadAdapter xpcc::Tcs3414::i2cWRadapter; template typename xpcc::Tcs3414::Data xpcc::Tcs3414::data; template typename xpcc::tcs3414::Rgb xpcc::Tcs3414::color; template xpcc::tcs3414::OperationSuccess xpcc::Tcs3414::configure(const Gain gain, const Prescaler prescaler, const IntegrationMode mode, const uint8_t time) { if(!setGain(gain, prescaler)) { return false; } return setIntegrationTime(mode, time); } template xpcc::tcs3414::OperationSuccess xpcc::Tcs3414::writeRegister( const RegisterAddress address, const uint8_t value) { uint8_t buffer_write[3] = { 0, 1 }; // set the number of bytes to 1 buffer_write[0] = 0x80 // write command | 0x40 // with SMB read/write protocol | static_cast(address); // at this address buffer_write[2] = value; i2cWRadapter.initialize(ADDRESS, buffer_write, 3, NULL, 0); if(!I2cMaster::startSync(&i2cWRadapter)) return false; if(i2cWRadapter.getState() != xpcc::i2c::adapter::State::NO_ERROR) return false; return true; } template xpcc::tcs3414::OperationSuccess xpcc::Tcs3414::readRegisters( const RegisterAddress address, uint8_t* const values, const uint8_t count) { const uint8_t buffer_write = static_cast(0x80) // write command | static_cast(0x40) // with SMB read/write protocol | static_cast(address); // at this address i2cWRadapter.initialize(&buffer_write, 1, values, count); // read registers if(!I2cMaster::startSync(&i2cWRadapter)) return false; if(i2cWRadapter.getState() != xpcc::i2c::adapter::State::NO_ERROR) return false; return true; } 1-10 //********************************************************* // Speed_Bins.cpp - distribute speed bin data //********************************************************* #include "Emissions.hpp" //--------------------------------------------------------- // Speed_Bin_Distribution //--------------------------------------------------------- int Emissions::Speed_Bin_Distribution (int group) { int i, speed_bin, bin_id, num_out; double vmt, vmt2, vht, vht2, bin_wt; Value_Map *bin_map; //---- TRANSIMS speed bin loop ---- num_out = 0; if (smooth_flag) { //---- exclude stop time from the smoothing ---- vht = spd_bin [0] - spd_bin [1]; if (vht < 0) vht = 0; smooth_data.Input (1, (spd_bin [0] - vht)); for (i=1; i < num_bins; i++) { smooth_data.Input (i+1, spd_bin [i]); } smooth_data.Smooth (); vht = MIN (smooth_data.Output (1) + vht, spd_bin [0]); smooth_data.Output (1, vht); //---- calculate VMT and VHT ---- if (moves_bin_flag) { for (i=1; i <= smooth_data.Num_Output (); i += 2) { bin_id = (i + 1) / 2; vht = smooth_data.Output (i); if (i == 1) { vmt = 0.0; vht += vht2 = smooth_data.Output (i + 1) / 2.0; vmt += vht2 * i * bin_size; } else { vmt = vht * (i - 1) * bin_size; if (i < smooth_data.Num_Output () + 1) { vht += vht2 = smooth_data.Output (i + 1) / 2.0; vmt += vht2 * i * bin_size; } else if (i < smooth_data.Num_Output ()) { vht += vht2 = smooth_data.Output (i + 1); vmt += vht2 * i * bin_size; } vht += vht2 = smooth_data.Output (i - 1) / 2.0; vmt += vht2 * (i - 2) * bin_size; } if (bin_id > max_bin) { vmt_bin [max_bin] += vmt; vht_bin [max_bin] += vht; num_out = max_bin; } else { vmt_bin [bin_id] = vmt; vht_bin [bin_id] = vht; if (bin_id > num_out) num_out = bin_id; } } } else { for (bin_id=1; bin_id <= smooth_data.Num_Output (); bin_id++) { vht = smooth_data.Output (bin_id); if (bin_id == 1) { vmt = 0.0; } else { vmt = vht * (bin_id - 1) * bin_size; } if (bin_id > max_bin) { vmt_bin [max_bin] += vmt; vht_bin [max_bin] += vht; num_out = max_bin; } else { vmt_bin [bin_id] = vmt; vht_bin [bin_id] = vht; if (bin_id > num_out) num_out = bin_id; } } } } else { memset (vmt_bin, '\0', sizeof (vmt_bin)); memset (vht_bin, '\0', sizeof (vht_bin)); for (i=0; i < num_bins; i++) { //---- get the speed summary record ---- vht = spd_bin [i]; if (vht == 0.0) continue; vmt = i * UnRound (cell_size) * vht; //---- speed bin ---- speed_bin = i + 1; for (bin_id = 0; ; bin_id++) { if (bin_id == 0) { bin_map = bin_ptr->First_Member (speed_bin, group); } else { bin_map = bin_ptr->Next_Member (speed_bin, group); if (bin_map == NULL) break; } if (bin_map == NULL) { bin_id = speed_bin; bin_wt = 1.0; } else { bin_id = bin_map->Value (); bin_wt = bin_map->Weight (); } vmt_bin [bin_id] += vmt * bin_wt; vht_bin [bin_id] += vht * bin_wt; if (bin_id > num_out) num_out = bin_id; } } } //---- normalized the total vht ---- vht = vmt = vht2 = vmt2 = 0.0; bin_wt = UnRound (cell_size); for (i=0; i < num_bins; i++) { vht += spd_bin [i]; vmt += spd_bin [i] * i * bin_wt; } for (i=1; i <= num_out; i++) { vht2 += vht_bin [i]; vmt2 += vmt_bin [i]; } vht = (vht2 > 0) ? vht / vht2 : 1.0; vmt = (vmt2 > 0) ? vmt / vmt2 : 1.0; for (i=1; i <= num_out; i++) { vht_bin [i] *= vht; vmt_bin [i] *= vmt; } //---- output the smooth sample ---- if (sample_flag) { if (random.Probability () < sample_size) { for (i=1; i <= num_bins; i++) { sample_file.Put_Field (i, spd_bin [i-1]); } for (bin_id=1; bin_id <= max_bin; bin_id++, i++) { vht = (bin_id <= num_out) ? vht_bin [bin_id] : 0.0; sample_file.Put_Field (i, vht); } if (!sample_file.Write ()) { Error ("Writing %s", sample_file.File_Type ()); } num_sample++; } } return (num_out); } rpuntaie/c-examplescpp/io_c_feof.cpp0 /* g++ --std=c++20 -pthread -o ../_build/cpp/io_c_feof.exe ./cpp/io_c_feof.cpp && (cd ../_build/cpp/;./io_c_feof.exe) || true https://en.cppreference.com/w/cpp/io/c/feof */ #include #include int main() { int is_ok = EXIT_FAILURE; FILE* fp = std::fopen("/tmp/test.txt", "w+"); if(!fp) { std::perror("File opening failed"); return is_ok; } int c; // note: int, not char, required to handle EOF while ((c = std::fgetc(fp)) != EOF) { // standard C I/O file reading loop std::putchar(c); } if (std::ferror(fp)) { std::puts("I/O error when reading"); } else if (std::feof(fp)) { std::puts("End of file reached successfully"); is_ok = EXIT_SUCCESS; } std::fclose(fp); return is_ok; } sotaoverride/ot3-firmwarre-sotainclude/common/firmware/uart_comms.hpp #pragma once #include #include "stm32g4xx_hal_conf.h" namespace uart_comms { class Uart { public: explicit Uart(UART_HandleTypeDef *handle) : handle{handle} {} void read(std::span &buff); void write(const std::span &buff); private: static constexpr auto timeout = 0xFFFF; UART_HandleTypeDef *handle; }; } // namespace uart_comms// Name: SeaOfThieves, Version: 2.0.23 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_Potion_Reroll_ShopDisplay.BP_Potion_Reroll_ShopDisplay_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_Potion_Reroll_ShopDisplay_C::UserConstructionScript() { static auto fn = UObject::FindObject("Function BP_Potion_Reroll_ShopDisplay.BP_Potion_Reroll_ShopDisplay_C.UserConstructionScript"); ABP_Potion_Reroll_ShopDisplay_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; } void ABP_Potion_Reroll_ShopDisplay_C::AfterRead() { AModalInteractionProxy::AfterRead(); READ_PTR_FULL(InspectDialog, UNPCDialogComponent); READ_PTR_FULL(vfx_Tendrils, UStaticMeshComponent); READ_PTR_FULL(vfx_rerollBottle, UParticleSystemComponent); READ_PTR_FULL(Potion_Reroll, UStaticMeshComponent); READ_PTR_FULL(DefaultSceneRoot, USceneComponent); } void ABP_Potion_Reroll_ShopDisplay_C::BeforeDelete() { AModalInteractionProxy::BeforeDelete(); DELE_PTR_FULL(InspectDialog); DELE_PTR_FULL(vfx_Tendrils); DELE_PTR_FULL(vfx_rerollBottle); DELE_PTR_FULL(Potion_Reroll); DELE_PTR_FULL(DefaultSceneRoot); } } #ifdef _MSC_VER #pragma pack(pop) #endif lhmouse/asteria100-1000 // This file is part of Asteria. // Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved. #ifndef ASTERIA_LIBRARY_JSON_HPP_ #define ASTERIA_LIBRARY_JSON_HPP_ #include "../fwd.hpp" namespace asteria { // `std.json.format` V_string std_json_format(Value value, optV_string indent); V_string std_json_format(Value value, V_integer indent); // `std.json.format5` V_string std_json_format5(Value value, optV_string indent); V_string std_json_format5(Value value, V_integer indent); // `std.json.parse` Value std_json_parse(V_string text); // `std.json.parse_file` Value std_json_parse_file(V_string path); // Create an object that is to be referenced as `std.json`. void create_bindings_json(V_object& result, API_Version version); } // namespace asteria #endif class Solution { public: vector> subsetsWithDup(vector& nums) { std::sort(nums.begin(), nums.end()); std::vector> ret; std::vector cur; recur(ret, 0, nums, cur); return ret; } private: void recur(std::vector>& ret, int index, std::vector& nums, std::vector& cur) { ret.emplace_back(cur); for (int i = index; i < nums.size(); ++i) { if (i != index && nums[i] == nums[i-1]) continue; cur.emplace_back(nums[i]); recur(ret, i+1, nums, cur); cur.pop_back(); } return; } }; /** * @file SedError.cpp * @brief Implementation of the SedError class. * @author DEVISER * * */ #include #include #include #include #include #include #include /** @cond doxygenIgnored */ using namespace std; /** @endcond */ LIBSEDML_CPP_NAMESPACE_BEGIN #ifdef __cplusplus /** @cond doxygenLibsedmlInternal **/ /** * Helper function for SedError(). Takes an index, SED-ML level and version, * and returns the appropriate field for the severity code out of the sedmlErrorTable entry. */ static const unsigned int getSeverityForEntry(unsigned int index, unsigned int level, unsigned int version) { if ( level == 1 ) { switch (version) { case 1: default: return sedmlErrorTable[index].l1v1_severity; } } else { return sedmlErrorTable[index].l1v1_severity; } } /* * @return the severity as a string for the given @n code. */ std::string SedError::stringForSeverity(unsigned int code) const { /* it should never happen that an error ends up with a severity * that is not in the XMLSeverity_t enumeration * but just in case: */ if (code < LIBSEDML_SEV_SCHEMA_ERROR) { return XMLError::stringForSeverity(code); } else { switch (code) { case LIBSEDML_SEV_SCHEMA_ERROR: return "Schema error"; case LIBSEDML_SEV_GENERAL_WARNING: return "General warning"; case LIBSEDML_SEV_NOT_APPLICABLE: return "Not applicable"; default: return ""; } } } /* * Table of strings corresponding to the values from SedErrorCategory_t. * The enumeration starts at a number higher than 0, so each entry is keyed * by its enum value. * * A similar table for severity strings is currently unnecessary because * libSEDML never returns anything more than the XMLSeverityCode_t values. */ static struct sedmlCategoryString { unsigned int catCode; const char * catString; } sedmlCategoryStringTable[] = { { LIBSEDML_CAT_SEDML, "General SED-ML conformance" }, { LIBSEDML_CAT_GENERAL_CONSISTENCY, "SED-ML component consistency" }, { LIBSEDML_CAT_IDENTIFIER_CONSISTENCY, "SED-ML identifier consistency" }, { LIBSEDML_CAT_MATHML_CONSISTENCY, "MathML consistency" }, { LIBSEDML_CAT_INTERNAL_CONSISTENCY, "Internal consistency" } }; static unsigned int sedmlCategoryStringTableSize = sizeof(sedmlCategoryStringTable)/sizeof(sedmlCategoryStringTable[0]); /* * @return the category as a string for the given @n code. */ std::string SedError::stringForCategory(unsigned int code) const { if ( code >= LIBSEDML_CAT_SEDML ) { for ( unsigned int i = 0; i < sedmlCategoryStringTableSize; i++ ) if ( sedmlCategoryStringTable[i].catCode == code ) return sedmlCategoryStringTable[i].catString; } return XMLError::stringForCategory(code); } /** @endcond **/ SedError::SedError ( const unsigned int errorId , const unsigned int level , const unsigned int version , const std::string& details , const unsigned int line , const unsigned int column , const unsigned int severity , const unsigned int category) : XMLError((int)errorId, details, line, column, severity, category) { // Check if the given @p id is one we have in our table of error codes. If // it is, fill in the fields of the error object with the appropriate // content. If it's not in the table, take the content as-is. if ( /*mErrorId >= 0 &&*/ mErrorId < XMLErrorCodesUpperBound ) { // The error was caught during the XML read and the XMLError // constructor will have filled in all the right pieces. return; } else if ( mErrorId > XMLErrorCodesUpperBound && mErrorId < SedCodesUpperBound ) { unsigned int tableSize = sizeof(sedmlErrorTable)/sizeof(sedmlErrorTable[0]); unsigned int index = 0; for ( unsigned int i = 0; i < tableSize; i++ ) { if ( mErrorId == sedmlErrorTable[i].code ) { index = i; break; } } if ( index == 0 && mErrorId != SedUnknown ) { // The id is in the range of error numbers that are supposed to be in // the SED-ML layer, but it's NOT in our table. This is an internal error. // Unfortunately, we don't have an error log or anywhere to report it // except the measure of last resort: the standard error output. //cerr << "Internal error: unknown error code '" << mErrorId // << "' encountered while processing error." << endl; //return; // Changed this behaviour // Now we log the error as an UnKnown Error and mark it as invalid mValidError = false; } // The rest of this block massages the results to account for how some // internal bookkeeping is done in libSEDML 3, and also to provide // additional info in the messages. mCategory = sedmlErrorTable[index].category; mShortMessage = sedmlErrorTable[index].shortMessage; ostringstream newMsg; mSeverity = getSeverityForEntry(index, level, version); if (mValidError == false) mSeverity = LIBSEDML_SEV_WARNING; if (mSeverity == LIBSEDML_SEV_SCHEMA_ERROR) { mErrorId = SedNotSchemaConformant; mSeverity = LIBSEDML_SEV_ERROR; newMsg << sedmlErrorTable[3].message << " "; // FIXME } else if (mSeverity == LIBSEDML_SEV_GENERAL_WARNING) { mSeverity = LIBSEDML_SEV_WARNING; newMsg << "[Although SED-ML Level " << level << " Version " << version << " does not explicitly define the " << "following as an error, other Levels and/or Versions " << "of SED-ML do.] " << endl; } // Finish updating the (full) error message. if (!((string)sedmlErrorTable[index].message).empty()) { newMsg << sedmlErrorTable[index].message << endl; } // look for individual references // if the code for this error does not yet exist skip if (sedmlErrorTable[index].reference.ref_l1v1 != NULL) { std::string ref; switch(level) { case 1: default: switch(version) { case 1: default: ref = sedmlErrorTable[index].reference.ref_l1v1; break; } break; } if (!ref.empty()) { newMsg << "Reference: " << ref << endl; } } if (!details.empty()) { newMsg << " " << details; if (details[details.size()-1] != '\n') { newMsg << endl; } } mMessage = newMsg.str(); // We mucked around with the severity code and (maybe) category code // after creating the XMLError object, so we may have to update the // corresponding strings. mSeverityString = stringForSeverity(mSeverity); mCategoryString = stringForCategory(mCategory); return; } // It's not an error code in the SED-ML layer, so assume the caller has // filled in all the relevant additional data. (If they didn't, the // following merely assigns the defaults.) mMessage = details; mSeverity = severity; mCategory = category; mSeverityString = stringForSeverity(mSeverity); mCategoryString = stringForCategory(mCategory); } /* * Copy Constructor */ SedError::SedError(const SedError& orig) : XMLError(orig) { } SedError& SedError::operator=(const SedError& rhs) { if (&rhs != this) { XMLError::operator=(rhs); } return *this; } /* * Destroys this SedError. */ SedError::~SedError () { } /** @cond doxygenLibsedmlInternal **/ /* * clone function */ SedError* SedError::clone() const { return new SedError(*this); } /** @endcond **/ /** @cond doxygenLibsedmlInternal **/ /* * Outputs this SedError to stream in the following format (and followed by * a newline): * * line: (error_id [severity]) message */ void SedError::print(ostream& s) const { s << "line " << getLine() << ": (" << setfill('0') << setw(5) << getErrorId() << " [" << getSeverityAsString() << "]) " << getMessage() << endl; } /** @endcond **/ #endif /* __cplusplus */ LIBSEDML_CPP_NAMESPACE_END SaLeeC/Fiu-FunctionGeneratorFiuDDS-Platformio/AD9833-SCU-VFO-r00/lib/main.cpp #include #include #include //#include #include //#include #include #include "Wire.h" //Si5351 HSClockGen; Adafruit_SI5351 HSClockGen = Adafruit_SI5351(); #define PLLB_FREQ 87600000000 uint32_t HSCFrequency; uint32_t HSCIfFrequency; /* Il processo di controllo del DDS gira autonomamente nel core 1 mentre tutti i rimanenti processi girano nel core 0. Questo consente di ottenere la massima velocità nella gestione del DDS riducendo le interferenze fra i processi di servizio e il processo di controllo del DDS */ TaskHandle_t DDSManagement; void sweepgenCreate(float TSweep, uint8_t SweepMode); void DACIncrementStep(uint16_t ii); void DACDecrementStep(uint16_t ii); void DDSManagementCode(void * pvParameters); //Blocco variabili di controllo dei processi //DDSGenMode //128 = Frequenza fissa // 0 = Rampa Ascendente // 1 = Rampa discendente // 2 = trinagolare (simmetrica) // 4 = sinusoidale // 16 = andamento logaritmico uint8_t DDSGenMode = 128; float FL, FH; //DDSWave //0 = Sinusoide //1 = Triangolare //2 = Quadra uint8_t DDSWave = 0; //#define freqSerieMaxLeng 2048 #define freqSerieMaxLeng 2048 //uint32_t freqSerie[freqSerieMaxLeng];//Sequenza di frequenze per lo sweep float freqSerie[freqSerieMaxLeng];//Sequenza di frequenze per lo sweep uint16_t freqSerieNumActiveElement = 0;//Numero degli elementi caricati per lo sweep uint32_t freqSerieTStep = 0;//Tempo in uS fra uno step e il successivo #define DACResolution 256 float DACSerieStep; float DACCurrentProg; //il numero di elementi dellArray del DAC è uguale al numero di elementi dell'Array //delle frequenze. //Il numero di celle utilizzate rimarà uguale a quello delle frequenze uint16_t DACSerie[freqSerieMaxLeng]; // Pins for SPI comm with the AD9833 IC #define FSYNC 10 ///< SPI Load pin number (FSYNC in AD9833 usage) MD_AD9833 DDS9833_0(FSYNC); // DDS AD9833 via Hardware SPI ESP32DMASPI::Slave rxSPI; static const uint32_t BUFFER_SIZE = 70; uint8_t* spi_slave_tx_buf; uint8_t* spi_slave_rx_buf; void set_buffer() { for (uint32_t i = 0; i < BUFFER_SIZE; i++) { // spi_master_tx_buf[i] = i & 0xFF; spi_slave_tx_buf[i] = (0xFF - i) & 0xFF; } // memset(spi_master_rx_buf, 0, BUFFER_SIZE); memset(spi_slave_rx_buf, 0, BUFFER_SIZE); } constexpr uint8_t CORE_TASK_SPI_SLAVE {0}; constexpr uint8_t CORE_TASK_PROCESS_BUFFER {0}; static TaskHandle_t task_handle_wait_spi = 0; static TaskHandle_t task_handle_process_buffer = 0; void task_wait_spi(void *pvParameters) { while(1) { ulTaskNotifyTake(pdTRUE, portMAX_DELAY); rxSPI.wait(spi_slave_rx_buf, spi_slave_tx_buf, BUFFER_SIZE); String taskMessage = "SPI wait running on core "; taskMessage = taskMessage + xPortGetCoreID(); Serial.println(taskMessage); xTaskNotifyGive(task_handle_process_buffer); } } void task_process_buffer(void *pvParameters) { while(1) { ulTaskNotifyTake(pdTRUE, portMAX_DELAY); String taskMessage = "Buffer print running on core "; taskMessage = taskMessage + xPortGetCoreID(); Serial.println(taskMessage); // show received data for (size_t i = 0; i < BUFFER_SIZE; ++i) { printf("%c", spi_slave_rx_buf[i]); //spi_slave_tx_buf[i] = ++spi_slave_rx_buf[i]; } printf("\n"); rxSPI.pop(); xTaskNotifyGive(task_handle_wait_spi); } } void sweepgenCreate(float TSweep, uint8_t SweepMode) /* ---------------------------------------------------------------------------------------- Genera la sequenza di frequenze per far sweepare il DDS Le sequenze di frequenze limite sono FL e FH le quali sono espresse in Hz. Il tempo di ciclo è definito da TSweep il quale è espresso in uS. La sequenza è salvata nell'array freqSerie[] che può avere sino a 2048 elementi Il numero di elementi utilizzato per descrivere la serie è in freqSerieNumActiveElement Il tempo fra uno step e il successivo è in freqSerieTStep ed è espresso in uS ---------------------------------------------------------------------------------------- SweepMode definisce la tipologia di distribuzione delle frequenze durante lo sweep 0 = Rampa Ascendente 1 = Rampa discendente 2 = trinagolare (simmetrica) 4 = sinusoidale 16 = andamento logaritmico ---------------------------------------------------------------------------------------- Viene anche generata la sequenza di valori per la generazione di una tensione con la stessa forma d-onda dello sweep. Questa tensione pu; essere utilizzata come asse X di un oscilloscopio per visualizzazione sincronizzata rispetto allo sweep dei segnali. La tensione viene generata con un DAC da 256 passi. I passi sono normalizzati in maniera da coprire sempre tutta l-escursione dello sweep. */ { uint32_t deltaF; //Inizializza il numero di elementi utilizzati dell'array delle frequenze pari alla dimensione //dellArray. //Lo stesso valore è utilizzato per gestire lArray del DAC principale freqSerieNumActiveElement = freqSerieMaxLeng; //Calcola il deltaF deltaF = FH - FL; //Se deltaF espresso in Hz è inferiore a freqSerieMaxLeng i valori della serie //dello sweep sono inferiori alla dimensione dell'Array. //Fissa il numero di celle dell'Array utilizzate if (deltaF < freqSerieMaxLeng) { freqSerieNumActiveElement = deltaF; } //calcola il rapporto fra i passi F e i passi V (passi del DAC) DACSerieStep = freqSerieNumActiveElement/DACResolution; //Inizializza la prima casella della serie //e calcola lo step di avanzamento per la frequenza nei casi in //cui il processo sia lineare deltaF /= freqSerieNumActiveElement; //Se la ssequenza e inversa fa partire la serie dal valire massimo if (SweepMode & B00000001) { freqSerie[0] = FH;//Inizia dal valore massimo DACSerie[0] = DACResolution;//Inizia dal valore massimo } //altrimenti parte dal valire minimo else { freqSerie[0] = FL;//Inizia dal valore minimo DACSerie[0] = 0;//Inizia dal valore minimo } //Calcola il passo angolare in frazioni di 2Pigreco per la sinusoide float passoAngolare = (2.0 * PI) / freqSerieNumActiveElement; //Se è richiesta la triangolare raddoppia il passo if((SweepMode & B00000010) != 0) { deltaF += deltaF;//Raddopia il passo DACSerieStep += DACSerieStep;//Raddopia il passo } //Controlla se è richiesta la sinusoide nel qual caso setta deltaF a delta/2 per //snellire il calcolo if((SweepMode & B00000100) != 0) { deltaF = (FH - FL) / 2.0; DACSerieStep = freqSerieNumActiveElement / 2;//????????? } //Inizializza i riferimenti per la curva logaritmica float stepLog = (log10(FH) - log10(FL)) / freqSerieNumActiveElement;//calcola il passo per coprire l'intero sweep //Inizializza laccumulatore per il controllo del passo del DAC DACCurrentProg = DACSerie[0]; //Apre il loop di popolamento degli Array (frequenza e DAC) for(int32_t ii = 1; ii < freqSerieNumActiveElement; ii++)//per tutte le celle dell'Array { //Sceglie il processo di popolamento dell'Array switch (SweepMode) { case 0://Rampa ascendente-popola per somma con andamento lineare freqSerie[ii] = freqSerie[ii - 1] + deltaF; DACIncrementStep(ii); break; case 1://Rampa discendente-popola per differenza freqSerie[ii] = freqSerie[ii - 1] - deltaF; DACDecrementStep(ii); break; case 2://Triangolare (simmetrica)-popola con un doppio passo //Per la prima metà dei passi va in salita if (ii <= (freqSerieNumActiveElement/2)) { freqSerie[ii] = freqSerie[ii-1] + deltaF; DACIncrementStep(ii); } //Per la seconda metà dei passi va in discesa else { freqSerie[ii] = freqSerie[ii-1] - deltaF; DACDecrementStep(ii); } break; case 4://Sinusoidale //In questa modalità deltaF vale delta/2 //Lo split di (freqSerieNumActiveElement/4) serve a ritardare di 90° la simulazione //della sinusoide così da partire dal valore minimo (FL) freqSerie[ii] = (FL + deltaF) + (deltaF * sin((float(ii) - (freqSerieNumActiveElement/4.0)) * passoAngolare)); DACIncrementStep(ii); break; case 16://Rampa ascendente-popola per somma con andamento logaritmico freqSerie[ii] = pow(10,(log10(freqSerie[ii-1]) + stepLog)); DACIncrementStep(ii); break; default: break; } } } void DACIncrementStep(uint16_t ii) { DACCurrentProg += DACSerieStep;//incrementa del passo di avanzamento del DAC //Se laccumulatore di passi ha superato lunità (il DAC lavora per numeri interi) if(int(DACCurrentProg) >= 1) { //Incrementa il contenuto della cella corrente dellArray del DAC della parte intera //dell'accumulatore di passo DACSerie[ii] = DACSerie[ii-1] + int(DACCurrentProg); //Elimina la parte intera dallaccumulatore di passo lasciando la parte decimale DACCurrentProg -= int(DACCurrentProg); } //Se l'accumulatore di passo non ha ancora superato l'unità else { //Conferma il valore precedente nella cella corrente dell'Array del DAC DACSerie[ii] = DACSerie[ii-1]; } } void DACDecrementStep(uint16_t ii) { DACCurrentProg += DACSerieStep;//incrementa del passo di avanzamento del DAC //Se laccumulatore di passi ha superato lunità (il DAC lavora per numeri interi) if(int(DACCurrentProg) >= 1) { //Incrementa il contenuto della cella corrente dellArray del DAC della parte intera //dell'accumulatore di passo DACSerie[ii] = DACSerie[ii-1] - int(DACCurrentProg); //Elimina la parte intera dallaccumulatore di passo lasciando la parte decimale DACCurrentProg -= int(DACCurrentProg); } //Se l'accumulatore di passo non ha ancora superato l'unità else { //Conferma il valore precedente nella cella corrente dell'Array del DAC DACSerie[ii] = DACSerie[ii-1]; } } void DDSManagementCode(void * pvParameters) { uint32_t iii = 0;//Puntatore per lo Sweep //Genera uno sweep sino a quando non viene richiesta una frequenza fissa while ((DDSGenMode & B01000000) == 0) { //Imposta la frequenza corrente DDS9833_0.setFrequency(MD_AD9833::CHAN_0, freqSerie[iii]); //Imposta la tensione corrente per il DAC DACSerie[iii]; //Aspetta il tempo di step delayMicroseconds(freqSerieTStep); //Aggiorna il puntatore iii++; //controlla che non abbia superato il limite iii %= freqSerieNumActiveElement; } //Se è stato richiesto un cambio frequenza provvede, diversamente salta if((DDSGenMode & B10000000) !=0) { //Imposta la frequenza fissa DDS9833_0.setFrequency(MD_AD9833::CHAN_0, FL); //Azzera il flag di "cambia frequenza fissa" bitClear(DDSGenMode,7); } } //Attua la sequenza sweep void sweepgen() { } void setup() { // Start serial and initialize the Si5351 Serial.begin(115200); Serial.print("Init result "); Serial.println("Si5351 Clockgen Test"); Serial.println(""); /* Initialise the sensor */ if (HSClockGen.begin() != ERROR_NONE) { /* There was a problem detecting the IC ... check your connections */ Serial.print("Ooops, no Si5351 detected ... Check your wiring or I2C ADDR!"); while(1); } Serial.println("OK!"); /* INTEGER ONLY MODE --> most accurate output */ /* Setup PLLA to integer only mode @ 900MHz (must be 600..900MHz) */ /* Set Multisynth 0 to 112.5MHz using integer only mode (div by 4/6/8) */ /* 25MHz * 36 = 900 MHz, then 900 MHz / 8 = 112.5 MHz */ Serial.println("Set PLLA to 900MHz"); HSClockGen.setupPLLInt(SI5351_PLL_A, 36); Serial.println("Set Output #0 to 112.5MHz"); HSClockGen.setupMultisynthInt(0, SI5351_PLL_A, SI5351_MULTISYNTH_DIV_8); /* FRACTIONAL MODE --> More flexible but introduce clock jitter */ /* Setup PLLB to fractional mode @616.66667MHz (XTAL * 24 + 2/3) */ /* Setup Multisynth 1 to 13.55311MHz (PLLB/45.5) */ HSClockGen.setupPLL(SI5351_PLL_B, 35, 1, 1); Serial.println("Set Output #1 to 13.553115MHz"); // HSClockGen.setupMultisynth(1, SI5351_PLL_B, 33, 3704, 10000); HSClockGen.setupMultisynth(1, SI5351_PLL_B, 33, 3704, 10000); /* Multisynth 2 is not yet used and won't be enabled, but can be */ /* Use PLLB @ 616.66667MHz, then divide by 900 -> 685.185 KHz */ /* then divide by 64 for 10.706 KHz */ /* configured using either PLL in either integer or fractional mode */ Serial.println("Set Output #2 to 10.706 KHz"); HSClockGen.setupMultisynth(2, SI5351_PLL_B, 900, 0, 1); HSClockGen.setupRdiv(2, SI5351_R_DIV_64); /* Enable the clocks */ HSClockGen.enableOutputs(true); Serial.println("\nI2C Scanner"); byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for(address = 1; address < 127; address++ ) { Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address<16) { Serial.print("0"); } Serial.println(address,HEX); nDevices++; } else if (error==4) { Serial.print("Unknow error at address 0x"); if (address<16) { Serial.print("0"); } Serial.println(address,HEX); } } if (nDevices == 0) { Serial.println("No I2C devices found\n"); } else { Serial.println("done\n"); } delay(5000); // //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0 // xTaskCreatePinnedToCore( // DDSManagementCode, /* Task function. */ // "DDSManagement", /* name of task. */ // 10000, /* Stack size of task */ // NULL, /* parameter of the task */ // 1, /* priority of the task */ // &DDSManagement, /* Task handle to keep track of created task */ // 0); /* pin task to core 0 */ // // put your setup code here, to run once: // Serial.begin(115200); // Serial.println(micros()); // sweepgenCreate(2000, 0); // Serial.println(micros()); // Serial.println(micros()); // sweepgenCreate(2000, 1); // Serial.println(micros()); // Serial.println(micros()); // sweepgenCreate(2000, 2); // Serial.println(micros()); // Serial.println(micros()); // sweepgenCreate(2000, 4); // Serial.println(micros()); // Serial.println(micros()); // sweepgenCreate(2000, 16); // Serial.println(micros()); // // to use DMA buffer, use these methods to allocate buffer // spi_slave_tx_buf = rxSPI.allocDMABuffer(BUFFER_SIZE); // spi_slave_rx_buf = rxSPI.allocDMABuffer(BUFFER_SIZE); // set_buffer(); // delay(5000); // rxSPI.setDataMode(SPI_MODE1); // for DMA, only 1 or 3 is available // rxSPI.setMaxTransferSize(BUFFER_SIZE); // rxSPI.setDMAChannel(2); // 1 or 2 only // rxSPI.setQueueSize(1); // transaction queue size // // begin() after setting // // HSPI = CS: 15, CLK: 14, MOSI: 13, MISO: 12 // rxSPI.begin(HSPI); // printf("Main code running on core : %d\n", xPortGetCoreID()); // xTaskCreatePinnedToCore(task_wait_spi, "task_wait_spi", 2048, NULL, 2, &task_handle_wait_spi, CORE_TASK_SPI_SLAVE); // xTaskNotifyGive(task_handle_wait_spi); // xTaskCreatePinnedToCore(task_process_buffer, "task_process_buffer", 2048, NULL, 2, &task_handle_process_buffer, CORE_TASK_PROCESS_BUFFER); } void loop() { HSCFrequency = 27000000; HSCIfFrequency = 455000; HSCFrequency -= HSCIfFrequency; for (uint32_t ii=1000;ii<1000000;ii+=1000) { HSCFrequency+=1000; HSClockGen.setupMultisynth(1, SI5351_PLL_B, int(900000000/HSCFrequency), ((900000000/HSCFrequency) - int((900000000/HSCFrequency)))/100000, 100000); HSClockGen.enableOutputs(true); Serial.println(HSCFrequency + HSCIfFrequency); delay(500); } // Read the Status Register and print it every 10 seconds // Serial.println(HSCFrequency); // HSClockGen.set_freq((HSCFrequency * SI5351_FREQ_MULT), SI5351_PLL_FIXED, SI5351_CLK1); // HSClockGen.set_freq(HSCFrequency, SI5351_CLK0); // HSClockGen.update_status(); // Serial.print("corr: "); // // Serial.print(HSClockGen.get_correction()); // Serial.print(" SYS_INIT: "); // Serial.print(HSClockGen.dev_status.SYS_INIT); // Serial.print(" LOL_A: "); // Serial.print(HSClockGen.dev_status.LOL_A); // Serial.print(" LOL_B: "); // Serial.print(HSClockGen.dev_status.LOL_B); // Serial.print(" LOS: "); // Serial.print(HSClockGen.dev_status.LOS); // Serial.print(" REVID: "); // Serial.println(HSClockGen.dev_status.REVID); // delay(10000); // if (HSCFrequency>1000000) // { // HSCFrequency=80000; // } // else // { // HSCFrequency=144000000; // } // HSCFrequency += 1000; // Serial.println("ESP32"); // put your main code here, to run repeatedly: }1-10 /* * Copyright (C) 2010, 2011, 2012 Research In Motion Limited. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "GeolocationClientBlackBerry.h" #include "Chrome.h" #include "Frame.h" #include "Geolocation.h" #include "GeolocationController.h" #include "GeolocationError.h" #include "GeolocationPosition.h" #include "Page.h" #include "SecurityOrigin.h" #include "WebPage_p.h" #include using namespace WebCore; static String getOrigin(Frame* frame) { String origin; SecurityOrigin* securityOrigin = frame->document()->securityOrigin(); // Special case for file. if (securityOrigin->protocol() == "file") origin = securityOrigin->fileSystemPath(); else origin = securityOrigin->toString(); return origin; } GeolocationClientBlackBerry::GeolocationClientBlackBerry(BlackBerry::WebKit::WebPagePrivate* webPagePrivate) : m_webPagePrivate(webPagePrivate) , m_accuracy(false) , m_isActive(false) { } void GeolocationClientBlackBerry::geolocationDestroyed() { BlackBerry::Platform::GeolocationHandler::instance()->unregisterFromPermissionTracking(this); delete this; } void GeolocationClientBlackBerry::startUpdating() { if (!m_isActive) BlackBerry::Platform::GeolocationHandler::instance()->addListener(this); m_isActive = true; } void GeolocationClientBlackBerry::stopUpdating() { if (m_isActive) BlackBerry::Platform::GeolocationHandler::instance()->removeListener(this); m_isActive = false; } GeolocationPosition* GeolocationClientBlackBerry::lastPosition() { return m_lastPosition.get(); } void GeolocationClientBlackBerry::requestPermission(Geolocation* location) { Frame* frame = location->frame(); if (!frame) return; if (!m_webPagePrivate->m_webSettings->isGeolocationEnabled()) { location->setIsAllowed(false); return; } const String origin = getOrigin(frame); // Special case for documents with the isUnique flag on. (ie. sandboxed iframes) if (origin == "null") location->setIsAllowed(false); // Check global location setting, if it is off then we request an infobar that invokes a location settings card. // If it's on, then we request an infobar that allows the site to have permission to use geolocation. if (!BlackBerry::Platform::GeolocationHandler::instance()->isGlobalServiceActive()) { // We only want to ask them once per session. If we get here again, automatically fail the request. if (!BlackBerry::Platform::GeolocationHandler::instance()->didAskUserForGlobalPermission()) { m_webPagePrivate->m_client->requestGlobalLocalServicePermission(this, origin); BlackBerry::Platform::GeolocationHandler::instance()->setAskedUserForGlobalPermission(); } else location->setIsAllowed(false); return; } // Register the listener with the GeolocationHandler to receive permissions. if (m_geolocationRequestMap.isEmpty()) BlackBerry::Platform::GeolocationHandler::instance()->registerPermissionTracking(this); // Add this geolocation permission request to our request map. Vector > geoRequestsForOrigin; HashMap > >::AddResult result = m_geolocationRequestMap.add(origin, geoRequestsForOrigin); result.iterator->value.append(location); // Avoid sending another request if the vector already has another geolocation pending for this origin in this page. if (result.isNewEntry) m_webPagePrivate->m_client->requestGeolocationPermission(this, origin); } void GeolocationClientBlackBerry::cancelPermissionRequest(Geolocation* location) { Frame* frame = location->frame(); if (!frame) return; const String origin = getOrigin(frame); // Remove the geolocation from the pending permission map. HashMap > >::iterator it = m_geolocationRequestMap.find(origin); if (it == m_geolocationRequestMap.end()) return; Vector >* result = &(it->value); size_t geolocationCount = result->size(); for (size_t i = 0; i < geolocationCount; ++i) { if ((*result)[i].get() == location) { result->remove(i); // Remove this vector from the pending permission map is it doesn't contain anymore geo objects if (result->isEmpty()) m_geolocationRequestMap.remove(origin); break; } } if (m_geolocationRequestMap.isEmpty()) BlackBerry::Platform::GeolocationHandler::instance()->unregisterFromPermissionTracking(this); m_webPagePrivate->m_client->cancelGeolocationPermission(); } void GeolocationClientBlackBerry::onLocationUpdate(double timestamp, double latitude, double longitude, double accuracy, double altitude, bool altitudeValid, double altitudeAccuracy, bool altitudeAccuracyValid, double speed, bool speedValid, double heading, bool headingValid) { m_lastPosition = GeolocationPosition::create(timestamp, latitude, longitude, accuracy, altitudeValid, altitude, altitudeAccuracyValid, altitudeAccuracy, headingValid, heading, speedValid, speed); GeolocationController::from(m_webPagePrivate->m_page)->positionChanged(m_lastPosition.get()); } void GeolocationClientBlackBerry::onLocationError(const char* errorStr) { RefPtr error = GeolocationError::create(GeolocationError::PositionUnavailable, String::fromUTF8(errorStr)); GeolocationController::from(m_webPagePrivate->m_page)->errorOccurred(error.get()); } void GeolocationClientBlackBerry::onPermission(const BlackBerry::Platform::String& origin, bool isAllowed) { Vector > pendingPermissionGeolocation = m_geolocationRequestMap.get(origin); if (pendingPermissionGeolocation.isEmpty()) return; size_t numberOfGeolocations = pendingPermissionGeolocation.size(); for (size_t i = 0; i < numberOfGeolocations; ++i) pendingPermissionGeolocation[i]->setIsAllowed(isAllowed); m_geolocationRequestMap.remove(origin); if (m_geolocationRequestMap.isEmpty()) BlackBerry::Platform::GeolocationHandler::instance()->unregisterFromPermissionTracking(this); } void GeolocationClientBlackBerry::setEnableHighAccuracy(bool newAccuracy) { if (m_accuracy != newAccuracy) { m_accuracy = newAccuracy; BlackBerry::Platform::GeolocationHandler::instance()->switchAccuracy(this); } } sample_loader_app/main.cpp #include #include "render/raytracing.h" #include "render/image_save.h" std::vector rayTraceCPU(std::shared_ptr pRayTracer, int width, int height) { std::vector raytracedImageData(width * height, 0u); #pragma omp parallel for default(none) shared(height, width, raytracedImageData, pRayTracer) for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { pRayTracer->CastSingleRay(i, j, raytracedImageData.data()); } } return raytracedImageData; } int main() { constexpr uint32_t WIDTH = 1024; constexpr uint32_t HEIGHT = 1024; auto pRayTracerCPU = std::make_shared(WIDTH, HEIGHT); auto loaded = pRayTracerCPU->LoadScene("../01_simple_scenes/instanced_objects.xml"); if(!loaded) return -1; auto image = rayTraceCPU(pRayTracerCPU, WIDTH, HEIGHT); saveImageLDR("output.png", image, WIDTH, HEIGHT, 4); return 0; } Neozaru/cpp-netlib-urisrc/detail/uri_normalize.cpp // Copyright 2013-2016 . // 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) #include #include #include #include "../boost/algorithm/string/split.hpp" #include "../boost/algorithm/string/join.hpp" #include "uri_normalize.hpp" #include "uri_percent_encode.hpp" #include "algorithm.hpp" namespace network { namespace detail { std::string normalize_path_segments(string_view path) { std::string result; if (!path.empty()) { std::vector path_segments; network_boost::split(path_segments, path, [](char ch) { return ch == '/'; }); // remove single dot segments detail::remove_erase_if( path_segments, [](const std::string& s) { return (s == "."); }); // remove double dot segments std::vector normalized_segments; for (auto& segment : path_segments) { if (segment == "..") { if (normalized_segments.size() <= 1) { throw uri_builder_error(); } normalized_segments.pop_back(); } else { normalized_segments.push_back(segment); } } // remove adjacent slashes optional prev_segment; detail::remove_erase_if( normalized_segments, [&prev_segment](const std::string& segment) { bool has_adjacent_slash = ((prev_segment && prev_segment->empty()) && segment.empty()); if (!has_adjacent_slash) { prev_segment = segment; } return has_adjacent_slash; }); result = network_boost::join(normalized_segments, "/"); } if (result.empty()) { result = "/"; } return result; } std::string normalize_path(string_view path, uri_comparison_level level) { auto result = path.to_string(); if (uri_comparison_level::syntax_based == level) { // case normalization detail::for_each(result, percent_encoded_to_upper()); // % encoding normalization result.erase( detail::decode_encoded_unreserved_chars(std::begin(result), std::end(result)), std::end(result)); // % path segment normalization result = normalize_path_segments(result); } return result; } } // namespace detail } // namespace network class Solution { private: vector tmp; vector> res; int N; public: void backtrack(int step,vector& nums) { if(step == N) res.push_back(tmp); else { backtrack(step+1, nums); tmp.push_back(nums[step]); backtrack(step+1, nums); tmp.pop_back(); } } vector> subsets(vector& nums) { N = nums.size(); backtrack(0, nums); return res; } };#include "sphere.cpp" #include #include #include int main(int argc, char ** argv) { // Set up MPI MPI_Init(&argc, &argv); int rank; int size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // Generate points int npts = 1000000; int dim = 4; double r = 5; double *buf = mpi_gene_4dsphere_bcast(&npts, &r, MPI_COMM_WORLD); // Write metadata to file const int64_t endiancheck = 0x1234ABCD; std::ofstream ofile("data.bin", std::ofstream::binary); ofile.write((char*)&endiancheck, sizeof(endiancheck)); ofile.close(); // Write points to file for(int i = 0; i < size; i++) { if(rank == i) { std::ofstream ofile("data.bin", std::ofstream::binary | std::ofstream::app); ofile.write((char*)buf, npts * dim * sizeof(double)); ofile.close(); std::cout << "Rank " << i << " successfully wrote to file." << std::endl; std::cout.flush(); } MPI_Barrier(MPI_COMM_WORLD); } delete[] buf; MPI_Finalize(); return 0; } #include "gtest.h" namespace testing { namespace internal { UnitTest::UnitTest() : m_first(0) { } void UnitTest::addTestInfo(TestInfo *info) { if (!m_first) m_first = info; else { TestInfo* iter = m_first; while (iter->m_next) iter = iter->m_next; iter->m_next = info; } } int UnitTest::runAllTests() { TestInfo* iter = m_first; while (iter) { printf("%s %s\n", iter->test_case_name(), iter->name()); iter->Run(); iter = iter->m_next; } return 0; } UnitTest* UnitTest::instance() { static UnitTest instance; return &instance; } // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name, const char* type_param, const char* value_param, int /*TypeId*/ fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_case_name, name, type_param, value_param, factory); UnitTest::instance()->addTestInfo(test_info); return test_info; } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template Result HandleExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag // after the exception is caught and either report or re-throw the // exception based on the flag's value: // // try { // // Perform the test method. // } catch (...) { // if (GTEST_FLAG(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. // } // // However, the purpose of this flag is to allow the program to drop into // the debugger when the exception is thrown. On most platforms, once the // control enters the catch block, the exception origin information is // lost and the debugger will stop the program at the point of the // re-throw in this function -- instead of at the point of the original // throw statement in the code under test. For this reason, we perform // the check early, sacrificing the ability to affect Google Test's // exception handling in the method where the exception is thrown. if (1) {// if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return (object->*method)(); } catch (const GoogleTestFailureException&) { // NOLINT // This exception doesn't originate in code under test. It makes no // sense to report it as a test failure. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(NULL, location)); } return static_cast(0); #else return (object->*method)(); #endif // GTEST_HAS_EXCEPTIONS } else { return (object->*method)(); } } } // namespace internal // ----=====================================================================---- // TestResult // ----=====================================================================---- #if 0 // Creates an empty TestResult. TestResult::TestResult() : elapsed_time_(0) { } // D'tor. TestResult::~TestResult() { } // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } // Clears the object. void TestResult::Clear() { test_part_results_.clear(); elapsed_time_ = 0; } // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { return static_cast(test_part_results_.size()); } #endif // ----=====================================================================---- // TestInfo // ----=====================================================================---- // Constructs a TestInfo object. It assumes ownership of the test factory // object. TestInfo::TestInfo(const char* a_test_case_name, const char* a_name, const char* a_type_param, const char* a_value_param, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), //type_param_(a_type_param ? new std::string(a_type_param) : NULL), //value_param_(a_value_param ? new std::string(a_value_param) : NULL), factory_(factory), m_next(0) { } // Destructs a TestInfo object. TestInfo::~TestInfo() { delete factory_; } void TestInfo::Run() { #if 0 // Tells UnitTest where to store test result. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_info(this); TestEventListener* listener = UnitTest::GetInstance()->listener(); // Notifies the unit test event listeners that a test is about to start. listener->OnTestStart(*this); const TimeInMillis start = internal::GetTimeInMillis(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); // Runs the test only if the test object was created and its // constructor didn't generate a fatal failure. if ((test != NULL) && !Test::HasFatalFailure()) { // This doesn't throw as all user code that can throw are wrapped into // exception handling code. test->Run(); } // Deletes the test object. internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. listener->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(NULL); #endif Test* const test = factory_->CreateTest(); test->Run(); test->DeleteSelf_(); } // ----=====================================================================---- // Test // ----=====================================================================---- // Runs the test and updates the test result. void Test::Run() { this->SetUp(); this->TestBody(); this->TearDown(); /* if (!HasSameFixtureClass()) return; internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { internal::HandleExceptionsInMethodIfSupported( this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. internal::HandleExceptionsInMethodIfSupported( this, &Test::TearDown, "TearDown()"); */ } } // namespace testing // | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: // // // Project includes #include "testing/testing.h" #include "containers/model.h" #include "includes/checks.h" #include "geometries/triangle_2d_3.h" #include "geometries/tetrahedra_3d_4.h" #include "utilities/discont_utils.h" namespace Kratos { namespace Testing { KRATOS_TEST_CASE_IN_SUITE(TriangleHorizontalDiscontUtils, KratosCoreFastSuite) { Model current_model; // Generate a model part with the previous ModelPart& base_model_part = current_model.CreateModelPart("Triangle"); base_model_part.AddNodalSolutionStepVariable(DISTANCE); // Fill the model part geometry data base_model_part.CreateNewNode(1, 0.0, 0.0, 0.0); base_model_part.CreateNewNode(2, 1.0, 0.0, 0.0); base_model_part.CreateNewNode(3, 0.0, 1.0, 0.0); Properties::Pointer p_properties(new Properties(0)); base_model_part.CreateNewElement("Element2D3N", 1, {1, 2, 3}, p_properties); // Set the DISTANCE field base_model_part.Nodes()[1].FastGetSolutionStepValue(DISTANCE) = -1.0; base_model_part.Nodes()[2].FastGetSolutionStepValue(DISTANCE) = -1.0; base_model_part.Nodes()[3].FastGetSolutionStepValue(DISTANCE) = 1.0; // Compute the triangle intersection BoundedMatrix point_coordinates; BoundedMatrix continuous_N_gradients; array_1d nodal_distances; array_1d partition_volumes; BoundedMatrix gauss_pt_continuous_N_values; array_1d partition_signs; std::vector enriched_N_gradients_values(3); BoundedMatrix enriched_N_values; array_1d edge_areas; auto rGeom = base_model_part.Elements()[1].GetGeometry(); for (unsigned int inode=0; inode point_coordinates; BoundedMatrix continuous_N_gradients; array_1d nodal_distances; array_1d partition_volumes; BoundedMatrix gauss_pt_continuous_N_values; array_1d partition_signs; std::vector enriched_N_gradients_values(3); BoundedMatrix enriched_N_values; array_1d edge_areas; auto rGeom = base_model_part.Elements()[1].GetGeometry(); for (unsigned int inode=0; inode point_coordinates; BoundedMatrix continuous_N_gradients; array_1d nodal_distances; array_1d partition_volumes; BoundedMatrix gauss_pt_continuous_N_values; array_1d partition_signs; std::vector enriched_N_gradients_values(3); BoundedMatrix enriched_N_values; array_1d edge_areas; auto rGeom = base_model_part.Elements()[1].GetGeometry(); for (unsigned int inode=0; inode #include #include int main() { int a,b; scanf("%d %d",&a,&b); printf("%d\n",a+b); fork(); a=b; b=2; //printf("hello world\n"); return 0; } 1-10 /* * Copyright (c) 2020 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #pragma once #ifdef HT_WINDOWS #include #endif // HT_WINDOWS #include #include #include #include #ifdef HT_OPENGL #include "platform/opengl/GL.hpp" #endif // HT_OPENGL #include "core/Internal.hpp" #if defined(HT_WINDOWS) #define HT_LEVEL_FATAL 0xC0 #define HT_LEVEL_ERROR 0x0C #define HT_LEVEL_WARNING 0x0E #define HT_LEVEL_INFO 0x0F #define HT_LEVEL_MSG 0x07 #elif defined(HT_LINUX) #define HT_LEVEL_FATAL "\033[0;31m" #define HT_LEVEL_ERROR "\033[1;31m" #define HT_LEVEL_WARNING "\033[1;33m" #define HT_LEVEL_INFO "\033[0;37m" #define HT_LEVEL_MSG "\033[1;37m" #endif // HT_WINDOWS #define HT_LOG_LEVEL_FATAL 0 #define HT_LOG_LEVEL_ERROR 1 #define HT_LOG_LEVEL_WARNING 2 #define HT_LOG_LEVEL_INFO 3 #define HT_LOG_LEVEL_MSG 4 #if defined(HT_DEBUG) && !defined(HT_LOG_LEVEL) # define HT_LOG_LEVEL 4 #else # define HT_LOG_LEVEL 2 #endif // HT_DEBUG #if HT_LOG_LEVEL_FATAL <= HT_LOG_LEVEL #define HT_FATAL(format, ...) ht::utils::Log(HT_LEVEL_FATAL, true, format, __VA_ARGS__) #define _HT_FATAL(format, ...) ht::utils::Log(HT_LEVEL_FATAL, false, format, __VA_ARGS__) #else #define HT_FATAL(format, ...) #define _HT_FATAL(format, ...) #endif // HT_LOG_LEVEL_FATAL #if HT_LOG_LEVEL_ERROR <= HT_LOG_LEVEL #define HT_ERROR(format, ...) ht::utils::Log(HT_LEVEL_ERROR, true, format, __VA_ARGS__) #define _HT_ERROR(format, ...) ht::utils::Log(HT_LEVEL_ERROR, false, format, __VA_ARGS__) #else #define HT_ERROR(format, ...) #define _HT_ERROR(format, ...) #endif // HT_LOG_LEVEL_ERROR #if HT_LOG_LEVEL_WARNING <= HT_LOG_LEVEL #define HT_WARN(format, ...) ht::utils::Log(HT_LEVEL_WARNING, true, format, __VA_ARGS__) #define _HT_WARN(format, ...) ht::utils::Log(HT_LEVEL_WARNING, false, format, __VA_ARGS__) #else #define HT_WARN(format, ...) #define _HT_WARN(format, ...) #endif // HT_LOG_LEVEL_WARNING #if HT_LOG_LEVEL_INFO <= HT_LOG_LEVEL #define HT_INFO(format, ...) ht::utils::Log(HT_LEVEL_INFO, true, format, __VA_ARGS__) #define _HT_INFO(format, ...) ht::utils::Log(HT_LEVEL_INFO, false, format, __VA_ARGS__) #else #define HT_INFO(format, ...) #define _HT_INFO(format, ...) #endif // HT_LOG_LEVEL_INFO #if HT_LOG_LEVEL_MSG <= HT_LOG_LEVEL #define HT_MSG(format, ...) ht::utils::Log(HT_LEVEL_MSG, true, format, __VA_ARGS__) #define _HT_MSG(format, ...) ht::utils::Log(HT_LEVEL_MSG, false, format, __VA_ARGS__) #else #define HT_MSG(format, ...) #define _HT_MSG(format, ...) #endif // HT_LOG_LEVEL_MSG #ifdef HT_DEBUG #define HT_ASSERT(condition, statement) \ if(!(condition)) { \ HT_FATAL("%s", "*******************"); \ HT_FATAL("%s", "ASSERTION FAILED"); \ HT_FATAL("Condition: %s", #condition); \ HT_FATAL("%s", statement); \ HT_FATAL("File: %s, line: %d", __FILE__, __LINE__); \ HT_FATAL("%s", "*******************"); \ int *a = nullptr; \ *a = 1; \ } #else #define HT_ASSERT(condition, statement) #endif // HT_DEBUG #ifdef HT_DEBUG # if defined(HT_OPENGL) # define GL(func) func; ht::utils::GLCallLog(#func, __FILE__, __LINE__) # elif defined(HT_DIRECTX) # define DX(func) ht::utils::DXCall(func, #func, __FILE__, __LINE__) # endif #else #define GL(x) x #define DX(x) x #endif // HT_DEBUG namespace ht { namespace utils { #if defined(HT_WINDOWS) template void Log(unsigned int color, bool newline, First arg, Args... message) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); printf(arg, std::forward(message)...); if (newline) printf("\n"); } #elif defined(HT_LINUX) template void Log(const char* color, bool newline, First arg, Args... message) { printf((std::string(color) + arg).c_str(), std::forward(message)...); if (newline) printf("\n"); } #endif // HT_WINDOWS #ifdef HT_OPENGL inline static void GLCallLog(const char* funcName, const char* file, u32 line) { static std::map glErrors = { { 0x0500, "GL_INVALID_ENUM" }, { 0x0501, "GL_INVALID_VALUE" }, { 0x0502, "GL_INVALID_OPERATION" }, { 0x0503, "GL_STACK_OVERFLOW" }, { 0x0504, "GL_STACK_UNDERFLOW" }, { 0x0505, "GL_OUT_OF_MEMORY" }, { 0x0506, "GL_INVALID_FRAMEBUFFER_OPERATION" }, { 0x0507, "GL_CONTEXT_LOST" }, { 0x8031, "GL_TABLE_TOO_LARGE" }, }; u32 error = 0; while (error = glGetError()) { HT_FATAL("[GL] Error %s, calling %s in %s:%u", glErrors[error], funcName, file, line); int* a = nullptr; *a = 1; } } #elif defined(HT_DIRECTX) inline static void DXCall(HRESULT result, const char* funcName, const char* file, u32 line) { static std::map dxErrors = { { D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD, "D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD" }, { D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS, "D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS" }, { D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS, "D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS" }, { DXGI_ERROR_WAS_STILL_DRAWING, "DXGI_ERROR_WAS_STILL_DRAWING" }, { D3D11_ERROR_FILE_NOT_FOUND, "D3D11_ERROR_FILE_NOT_FOUND" }, { DXGI_ERROR_INVALID_CALL, "DXGI_ERROR_INVALID_CALL" }, { E_OUTOFMEMORY, "E_OUTOFMEMORY" }, { E_INVALIDARG, "E_INVALIDARG" }, { E_NOTIMPL, "E_NOTIMPL" }, { S_FALSE, "S_FALSE" }, { E_FAIL, "E_FAIL" }, }; if (result != S_OK) { HT_FATAL("[DX] Error %s, calling %s in %s:%u", dxErrors[result], funcName, file, line); int* a = nullptr; *a = 1; } } #endif // HT_OPENGL } }1-10 #include "RoadNetworkMesh.h" #include namespace odr { template std::vector get_outline_indices(const std::map& start_indices, const size_t num_vertices) { std::vector out_indices; for (auto idx_val_iter = start_indices.begin(); idx_val_iter != start_indices.end(); idx_val_iter++) { const size_t start_idx = idx_val_iter->first; const size_t end_idx = (std::next(idx_val_iter) == start_indices.end()) ? num_vertices : std::next(idx_val_iter)->first; for (size_t idx = start_idx; idx < end_idx - 2; idx += 2) { out_indices.push_back(idx); out_indices.push_back(idx + 2); } for (size_t idx = start_idx + 1; idx < end_idx - 2; idx += 2) { out_indices.push_back(idx); out_indices.push_back(idx + 2); } out_indices.push_back(start_idx); out_indices.push_back(start_idx + 1); out_indices.push_back(end_idx - 2); out_indices.push_back(end_idx - 1); } return out_indices; } std::string MeshUnion::get_road_id(size_t vert_idx) const { return get_nearest_val(this->road_start_indices, vert_idx); } double MeshUnion::get_lanesec_s0(size_t vert_idx) const { return get_nearest_val(this->lanesec_start_indices, vert_idx); } int MeshUnion::get_lane_id(size_t vert_idx) const { return get_nearest_val(this->lane_start_indices, vert_idx); } std::array MeshUnion::get_idx_interval_road(size_t vert_idx) const { return get_key_interval(this->road_start_indices, vert_idx, this->vertices.size()); } std::array MeshUnion::get_idx_interval_lanesec(size_t vert_idx) const { return get_key_interval(this->lanesec_start_indices, vert_idx, this->vertices.size()); } std::array MeshUnion::get_idx_interval_lane(size_t vert_idx) const { return get_key_interval(this->lane_start_indices, vert_idx, this->vertices.size()); } std::vector LaneMeshUnion::get_lane_outline_indices() const { return get_outline_indices(this->lane_start_indices, this->vertices.size()); } std::string RoadmarkMeshUnion::get_roadmark_type(size_t vert_idx) const { return get_nearest_val(this->roadmark_type_start_indices, vert_idx); } std::array RoadmarkMeshUnion::get_idx_interval_roadmark(size_t vert_idx) const { return get_key_interval(this->roadmark_type_start_indices, vert_idx, this->vertices.size()); } std::vector RoadmarkMeshUnion::get_roadmark_outline_indices() const { return get_outline_indices(this->roadmark_type_start_indices, this->vertices.size()); } } // namespace odr#include "WalkingEnemy.h" #include "App.h" #include "Map.h" #include "PathFinding.h" #include "Log.h" #include "Player.h" #include "p2List.h" #include "Scene.h" #include "Physics.h" #include "Textures.h" #include "Render.h" #include "Window.h" #include "Audio.h" #include #include #include #include #include "SDL/include/SDL.h" WalkingEnemy::WalkingEnemy() { name.Create("walkingenemy"); texture = nullptr; float idleSpeed = 0.4f; float movement1Speed = 0.1f; float movement2Speed = 0.2f; float deathSpeed = 0.1f; // IDLE animation right rightIdleAnim.PushBack({ 326, 51, 20, 15 }); rightIdleAnim.PushBack({ 357, 51, 20, 15 }); rightIdleAnim.PushBack({ 387, 51, 20, 15 }); rightIdleAnim.PushBack({ 420, 51, 20, 15 }); rightIdleAnim.PushBack({ 452, 51, 20, 15 }); rightIdleAnim.PushBack({ 484, 51, 20, 15 }); rightIdleAnim.PushBack({ 517, 51, 20, 15 }); rightIdleAnim.PushBack({ 549, 51, 20, 15 }); rightIdleAnim.PushBack({ 582, 51, 20, 15 }); rightIdleAnim.PushBack({ 614, 51, 20, 15 }); rightIdleAnim.loop = true; rightIdleAnim.speed = idleSpeed; // IDLE animation left leftIdleAnim.PushBack({ 295, 51, 20, 15 }); leftIdleAnim.PushBack({ 264, 51, 20, 15 }); leftIdleAnim.PushBack({ 232, 51, 20, 15 }); leftIdleAnim.PushBack({ 200, 51, 20, 15 }); leftIdleAnim.PushBack({ 168, 51, 20, 15 }); leftIdleAnim.PushBack({ 136, 51, 20, 15 }); leftIdleAnim.PushBack({ 104, 51, 20, 15 }); leftIdleAnim.PushBack({ 71, 51, 20, 15 }); leftIdleAnim.PushBack({ 38, 51, 20, 15 }); leftIdleAnim.PushBack({ 6, 51, 20, 15 }); leftIdleAnim.loop = true; leftIdleAnim.speed = idleSpeed; // WALKING animation right runRigthAnim.PushBack({ 327, 116, 20, 15 }); runRigthAnim.PushBack({ 359, 116, 20, 15 }); runRigthAnim.PushBack({ 393, 116, 20, 15 }); runRigthAnim.PushBack({ 423, 116, 20, 15 }); runRigthAnim.PushBack({ 452, 116, 20, 15 }); runRigthAnim.PushBack({ 483, 116, 20, 15 }); runRigthAnim.PushBack({ 514, 116, 20, 15 }); runRigthAnim.PushBack({ 547, 116, 20, 15 }); runRigthAnim.PushBack({ 581, 116, 20, 15 }); runRigthAnim.PushBack({ 614, 116, 20, 15 }); runRigthAnim.loop = true; runRigthAnim.speed = idleSpeed; // WALKING animation left runLeftAnim.PushBack({ 294, 116, 20, 15 }); runLeftAnim.PushBack({ 262, 116, 20, 15 }); runLeftAnim.PushBack({ 228, 116, 20, 15 }); runLeftAnim.PushBack({ 197, 116, 20, 15 }); runLeftAnim.PushBack({ 168, 116, 20, 15 }); runLeftAnim.PushBack({ 136, 116, 20, 15 }); runLeftAnim.PushBack({ 105, 116, 20, 15 }); runLeftAnim.PushBack({ 73, 116, 20, 15 }); runLeftAnim.PushBack({ 39, 116, 20, 15 }); runLeftAnim.PushBack({ 6, 116, 20, 15 }); runLeftAnim.loop = true; runLeftAnim.speed = idleSpeed; // DEATH animation right deathFromRightAnim.PushBack({ 614, 148, 20, 15 }); deathFromRightAnim.PushBack({ 582, 148, 20, 15 }); deathFromRightAnim.PushBack({ 550, 148, 20, 15 }); deathFromRightAnim.PushBack({ 518, 148, 20, 15 }); deathFromRightAnim.PushBack({ 485, 148, 20, 15 }); deathFromRightAnim.PushBack({ 452, 148, 20, 15 }); deathFromRightAnim.PushBack({ 421, 148, 20, 15 }); deathFromRightAnim.PushBack({ 390, 148, 20, 15 }); deathFromRightAnim.PushBack({ 357, 148, 20, 15 }); deathFromRightAnim.PushBack({ 327, 148, 20, 15 }); deathFromRightAnim.loop = false; deathFromRightAnim.speed = idleSpeed; // DEATH animation left deathFromLeftAnim.PushBack({ 6, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 39, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 71, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 103, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 135, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 167, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 198, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 231, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 262, 148, 20, 15 }); deathFromLeftAnim.PushBack({ 294, 148, 20, 15 }); deathFromLeftAnim.loop = false; deathFromLeftAnim.speed = idleSpeed; } WalkingEnemy::~WalkingEnemy() { } bool WalkingEnemy::Awake() { return true; } // Called before the first frame bool WalkingEnemy::Start() { if (app->currentScene == LEVEL1) { // Textures texture = app->tex->Load("Assets/sprites/Enemies.png"); // Enemy stats startPosX = app->map->MapToWorld(30, 6).x; startPosY = app->map->MapToWorld(30, 6).y; speed = { 1.3f,0 }; // Id's : // 0 Nothing // 1 Player // 2 Water // 3 Holes // 4 Win // 5 Flying Enemy // 6 Walking Enemy ColHitbox = app->physics->CreateCircle(startPosX, startPosY, 6); ColHitbox->id = 6; ColHitbox->listener = app->walkingenemy; int x_ = (int)x; int y_ = (int)y; ColHitbox->GetPosition(x_, y_); actualStates = WALK; isAlive = true; lifes = 2; canJump = true; LOG("Loading Flying Enemy"); } return true; } bool WalkingEnemy::Update(float dt) { if (app->currentScene == LEVEL1) { if (lifes <= 0) { actualStates = DIE; isAlive = false; } if (isAlive == true) { if (METERS_TO_PIXELS(app->player->GetColHitbox()->body->GetPosition().x) > 832) { actualStates = ATTACK; if (app->player->isAlive == false) { actualStates = WALK; } } else { actualStates = WALK; } } if (app->player->GetPlayerWin() == true) { actualStates = WALK; } switch (actualStates) { case WALK: { ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); directionPoint = app->map->WorldToMap(positionOfTheObject.x, positionOfTheObject.y); //iPoint playerPos; //ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); //directionPoint = app->map->WorldToMap(positionOfTheObject.x, positionOfTheObject.y); //playerPos = app->map->WorldToMap(playerPos.x + 15, playerPos.y + 15); app->pathfinding->CreatePath(directionPoint, { 29,6 }); iPoint NextPos; const DynArray* lastPath = app->pathfinding->GetLastPath(); if (lastPath->Count() > 1) { iPoint path(lastPath->At(1)->x, lastPath->At(1)->y); NextPos = path; } directionPoint = NextPos; if (app->physics->debug == true) { const DynArray* path = app->pathfinding->GetLastPath(); for (uint i = 0; i < path->Count(); ++i) { iPoint pos = app->map->MapToWorld(path->At(i)->x, path->At(i)->y); app->render->DrawTexture(app->scene->pathTex, pos.x, pos.y); } } }break; case ATTACK: { ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); directionPoint = app->map->WorldToMap(positionOfTheObject.x, positionOfTheObject.y); iPoint playerPos; app->player->GetColHitbox()->GetPosition(playerPos.x, playerPos.y); ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); directionPoint = app->map->WorldToMap(positionOfTheObject.x, positionOfTheObject.y); playerPos = app->map->WorldToMap(playerPos.x + 15, playerPos.y + 15); app->pathfinding->CreatePath(directionPoint, playerPos); iPoint NextPos; const DynArray* lastPath = app->pathfinding->GetLastPath(); if (lastPath->Count() > 1) { iPoint path(lastPath->At(1)->x, lastPath->At(1)->y); NextPos = path; } directionPoint = NextPos; if (app->physics->debug == true) { const DynArray* path = app->pathfinding->GetLastPath(); for (uint i = 0; i < path->Count(); ++i) { iPoint pos = app->map->MapToWorld(path->At(i)->x, path->At(i)->y); app->render->DrawTexture(app->scene->pathTex, pos.x, pos.y); } } }break; case DIE: { ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); directionPoint = app->map->WorldToMap(positionOfTheObject.x, positionOfTheObject.y); }break; } // Enemy movement if (isAlive == true) { switch (actualStates) { case WALK: { directionPoint = app->map->MapToWorld(directionPoint.x, directionPoint.y); // pixels //directionPoint = app->map->MapToWorld(4, 4); // pixels directionPoint = { directionPoint.x + 13, directionPoint.y + 16 }; ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); // pixels if (directionPoint.x + 16 < positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x > -0.1f) { ColHitbox->body->ApplyLinearImpulse({ -0.1f,0.0f }, ColHitbox->body->GetPosition(), true); } } if (directionPoint.x - 16 > positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x < 0.1f) { ColHitbox->body->ApplyLinearImpulse({ 0.1f,0.0f }, ColHitbox->body->GetPosition(), true); } } }break; case ATTACK: { directionPoint = app->map->MapToWorld(directionPoint.x, directionPoint.y); // pixels //directionPoint = app->map->MapToWorld(4, 4); // pixels directionPoint = { directionPoint.x + 13, directionPoint.y + 16 }; ColHitbox->GetPosition(positionOfTheObject.x, positionOfTheObject.y); // pixels iPoint playerPosition; app->player->GetColHitbox()->GetPosition(playerPosition.x, playerPosition.y); if (playerPosition.x >= positionOfTheObject.x) { if (directionPoint.x + 32 < positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x > -0.1f) { ColHitbox->body->ApplyLinearImpulse({ -0.2f,0.0f }, ColHitbox->body->GetPosition(), true); } } if (directionPoint.x + 16 > positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x < 0.9f) { ColHitbox->body->ApplyLinearImpulse({ 0.2f,0.0f }, ColHitbox->body->GetPosition(), true); } } } else { if (directionPoint.x - 32 < positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x > -0.1f) { ColHitbox->body->ApplyLinearImpulse({ -0.2f,0.0f }, ColHitbox->body->GetPosition(), true); } } if (directionPoint.x - 16 > positionOfTheObject.x) { if (ColHitbox->body->GetLinearVelocity().x < 0.9f) { ColHitbox->body->ApplyLinearImpulse({ 0.2f,0.0f }, ColHitbox->body->GetPosition(), true); } } } if ((directionPoint.y < positionOfTheObject.y) && (canJump == true)) { ColHitbox->body->ApplyLinearImpulse({ 0.0f,-0.12f }, ColHitbox->body->GetPosition(), true); canJump = false; } }break; case DIE: { }break; } } switch (actualStates) { case WALK: { statesInt = 0; }break; case ATTACK: { statesInt = 1; }break; case DIE: { statesInt = 2; } } if (isAlive == true) { if (ColHitbox->body->GetLinearVelocity().x < 0) { direction = 3; } else if (ColHitbox->body->GetLinearVelocity().x > 0) { direction = 2; } else if ((ColHitbox->body->GetLinearVelocity().x == 0)) { if (direction == 2) { direction = 0; } if (direction == 3) { direction = 1; } } } else { if (deathAnimAllowed == true) { if (direction == 0) { direction = 4; } if (direction == 1) { direction = 5; } if (direction == 2) { direction = 4; } if (direction == 3) { direction = 5; } } } if (direction == 0) { currentAnimation = &rightIdleAnim; } else if (direction == 1) { currentAnimation = &leftIdleAnim; } else if (direction == 2) { currentAnimation = &runRigthAnim; } else if (direction == 3) { currentAnimation = &runLeftAnim; } else if (direction == 4) { currentAnimation = &deathFromRightAnim; } else if (direction == 5) { currentAnimation = &deathFromLeftAnim; } currentAnimation->Update(); LOG("%i", lifes); } return true; } bool WalkingEnemy::PostUpdate() { if (app->currentScene == LEVEL1) { app->render->DrawTexture(texture, positionOfTheObject.x - 5, positionOfTheObject.y, ¤tAnimation->GetCurrentFrame()); } return true; } bool WalkingEnemy::CleanUp() { LOG("Unloading Enemy"); return true; } int WalkingEnemy::GetEnemyLifes() { return lifes; } void WalkingEnemy::SetEnemyLifes(int l) { lifes = l; } void WalkingEnemy::SetEnemyState(WALKING_ENEMY_STATE state) { actualStates = state; } bool WalkingEnemy::LoadState(pugi::xml_node& data) { b2Vec2 v = { PIXEL_TO_METERS(data.child("Pos").attribute("x").as_float()), PIXEL_TO_METERS(data.child("Pos").attribute("y").as_float()) }; lifes = data.child("lifes").attribute("value").as_int(); isAlive = data.child("isAlive").attribute("value").as_bool(); deathAnimAllowed = data.child("deathAnimation").attribute("value").as_bool(); statesInt = data.child("deathAnimation").attribute("value").as_int(); switch (statesInt) { case 0: { actualStates = WALK; }break; case 1: { actualStates = ATTACK; }break; case 2: { actualStates = DIE; } } ColHitbox->body->SetTransform(v, 0); return true; } bool WalkingEnemy::SaveState(pugi::xml_node& data) const { LOG("saving enemy "); data.child("Pos").attribute("x").set_value(positionOfTheObject.x); data.child("Pos").attribute("y").set_value(positionOfTheObject.y); data.child("lifes").attribute("value").set_value(lifes); data.child("isAlive").attribute("value").set_value(isAlive); data.child("deathAnimation").attribute("value").set_value(deathAnimAllowed); data.child("state").attribute("value").set_value(statesInt); return true; } void WalkingEnemy::OnCollision(PhysBody* bodyA, PhysBody* bodyB) { // Id's : // 0 Nothing // 1 Player // 2 Water // 3 Holes // 4 Win // 5 Flying Enemy // 6 Walking Enemy if (bodyB == nullptr) { } else { if ((bodyA->id == 6) && (bodyB->id == 0)) { canJump = true; } if ((bodyA->id == 6) && (bodyB->id == 2)) { if (lifes > 0) { //app->audio->PlayFx(app->scene->water_fx); lifes--; bodyA->body->ApplyLinearImpulse({ 0, -0.5f }, ColHitbox->body->GetPosition(), true); app->audio->PlayFx(app->scene->ehit_fx); } else { deathAnimAllowed = true; app->audio->PlayFx(app->scene->edeath_fx); } } if ((bodyA->id == 6) && (bodyB->id == 3)) { if (lifes > 0) { //app->audio->PlayFx(app->scene->fall_fx); lifes--; bodyA->body->ApplyLinearImpulse({ 0, -0.5f }, ColHitbox->body->GetPosition(), true); app->audio->PlayFx(app->scene->ehit_fx); } else { deathAnimAllowed = true; app->audio->PlayFx(app->scene->edeath_fx); } } if ((bodyA->id == 6) && (bodyB->id == 7)) { if (lifes > 0) { //app->audio->PlayFx(app->scene->fall_fx); lifes--; //bodyA->body->ApplyLinearImpulse({ 0, -0.5f }, ColHitbox->body->GetPosition(), true); app->audio->PlayFx(app->scene->ehit_fx); } else { deathAnimAllowed = true; app->audio->PlayFx(app->scene->edeath_fx); } } } }// Copyright (c) 2017-2021, Mudita .o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "Application.hpp" #include "Text.hpp" #include "Image.hpp" #include "ListItem.hpp" #include #include "Interface/SMSRecord.hpp" namespace gui { class SMSInputWidget : public ListItem { app::ApplicationCommon *application = nullptr; HBox *body = nullptr; gui::Image *replyImage = nullptr; public: gui::Text *inputText = nullptr; std::optional draft; // draft message of the thread we are showing, if exists. std::unique_ptr number = nullptr; SMSInputWidget(app::ApplicationCommon *application); ~SMSInputWidget() override = default; void handleDraftMessage(); void clearDraftMessage(); void updateDraftMessage(const UTF8 &inputText); void displayDraftMessage() const; auto handleRequestResize(const Item *, Length request_w, Length request_h) -> Size override; }; } /* namespace gui */ 0 #include #include #include #include #include #include #include "key_value.h" #include "kv.h" class KT:public Key{ public: KT(){} KT(const std::string& str){ content_ = str; } uint32_t Size(){ //add 1 endline character return content_.size()+1; } void Serialize(void * buf){ memcpy(buf, content_.c_str(), Size()); } void Deserialize(void * buf){ //for c++ string this content_ does not point to buf. //a new memory space is allocated for the content and content_ points to it. content_.assign(reinterpret_cast(buf)); } std::string Represent_str(){ return content_; } bool IsEqual(void * key_seri){ return !content_.compare(reinterpret_cast(key_seri)); } private: std::string content_; }; class VT:public Value{ public: VT(){} VT(const std::string& str){ content_ = str; } uint32_t Size(){ //add 1 endline character return content_.size()+1; } void Serialize(void * buf){ memcpy(buf, content_.c_str(), Size()); } void Deserialize(void * buf){ //for c++ string this content_ does not point to buf. //a new memory space is allocated for the content and content_ points to it. content_.assign(reinterpret_cast(buf)); } std::string Represent_str(){ return content_; } private: std::string content_; }; int main(int argc, char **argv){ if (argc!=4){ printf("Usage: input_data_path, output_path, kv_path"); exit(0); } std::string key_str; std::string value_str; std::list keylist; std::ifstream in; in.open(argv[1], std::ios::in); while(getline(in, key_str, ' ')){ getline(in, value_str); keylist.push_back(key_str); } in.close(); KT key; VT value; VT ret; // ///////////////////test reload/////////////////////// // std::ofstream out2; out2.open(argv[2], std::ios::out | std::ios::trunc); KV kv_test2; kv_test2.Initialize(argv[3], 0); kv_test2.SetDefaultHash(); int count = 0; for (auto itr = keylist.begin(); itr != keylist.end(); itr++){ key = KT(*itr); kv_test2.Get(key, ret); out2 << key.Represent_str() << ' ' << ret.Represent_str() << "\n"; } // //////////////////test repeated put and delete /////////////// // // key = KT("1234567890"); // value = VT("99887766554433221100"); kv_test2.Checkpoint(); kv_test2.Close(); out2.close(); return 0; } // Adafruit Circuit Playground speaker library // by / Paint Your Dragon. #include #include "Adafruit_CPlay_Speaker.h" // ------------------------------------------------------------------------- // Sets up Circuit Playground speaker for PWM audio output: enables 48 KHz // high-speed PWM mode, configures Timer/Counter 4, sets PWM duty cycle to // 50% (speaker idle position). void Adafruit_CPlay_Speaker::begin(void) { #ifdef __AVR__ // Set up Timer4 for fast PWM on !OC4A PLLFRQ = (PLLFRQ & 0xCF) | 0x30; // Route PLL to async clk TCCR4A = _BV(COM4A0) | _BV(PWM4A); // Clear on match, PWMA on TCCR4B = _BV(PWM4X) |_BV(CS40); // PWM invert, 1:1 prescale TCCR4D = 0; // Fast PWM mode TCCR4E = 0; // Not enhanced mode TC4H = 0; // Not 10-bit mode DT4 = 0; // No dead time OCR4C = 255; // TOP OCR4A = 127; // 50% duty (idle position) to start started = true; pinMode(5, OUTPUT); // Enable output #else // PWM/timer not needed on CPlay Express, has true analog out. // Set analogWrite resolution to 8 bits to match AVR calls. analogWriteResolution(8); pinMode(A0, OUTPUT); // Enable output #endif } void Adafruit_CPlay_Speaker::enable(boolean e) { #ifdef __AVR__ #else // circuit playground express has nicer amp w/shutdown digitalWrite(CPLAY_SPEAKER_SHUTDOWN, e); #endif } // ------------------------------------------------------------------------- // Turns off PWM output to the speaker. void Adafruit_CPlay_Speaker::end(void) { #ifdef __AVR__ TCCR4A = 0; // PWMA off pinMode(5, INPUT); #else pinMode(A0, INPUT); #endif started = false; } // ------------------------------------------------------------------------- // Sets speaker position (0-255; 127=idle), enables PWM output if needed. void Adafruit_CPlay_Speaker::set(uint8_t value) { if(!started) begin(); #ifdef __AVR__ TCCR4A = value; #else analogWrite(A0, value); #endif } // ------------------------------------------------------------------------- // Plays digitized 8-bit audio (optionally 10 bits on Express board) from // a PROGMEM (flash memory) buffer. Maybe 1-3 seconds tops depending on // sampling rate (e.g. 8000 Hz = 8 Kbytes/second). Max ~20K space avail on // Circuit Playground, lots more on Circuit Playground Express. // This function currently "blocks" -- it will not play sounds in the // background while other code runs. void Adafruit_CPlay_Speaker::playSound( const uint8_t *data, uint32_t len, uint16_t sampleRate, boolean tenBit) { if(!started) begin(); uint32_t i; #ifdef __AVR__ uint16_t interval = 1000000L / sampleRate; #else uint32_t r2 = sampleRate / 2; uint32_t startTime = micros(); #endif if(tenBit) { // 10-bit audio samples? uint8_t loIdx = 4; #ifdef __AVR__ // Because it uses 8-bit PWM for output, the AVR code must filter // 10-bit data down to 8 bits. This is ONLY here for compatibility // with sketches with 10-bit samples. If targeting a project for AVR, // it's best to produce and use optimized 8-bit audio, else it's just // wasted space! Timer/Counter 4 DOES offer a 10-bit mode, but it's // not used in this library, just not worth it in the limited flash // space of the 32U4 chip. uint16_t idx = 0; uint8_t hiBits; for(i=0; i= 4) { hiBits = pgm_read_byte(&data[idx++]); loIdx = 0; } OCR4A = ((hiBits & 0xC0) | (pgm_read_byte(&data[idx++]) >> 2)); hiBits <<= 2; // Do this after write, because of masking op above delayMicroseconds(interval); } OCR4A = 127; #else // Circuit Playground Express -- use 10-bit analogWrite() uint32_t idx = 0; uint16_t hiBits; analogWriteResolution(10); for(i=0; i= 4) { hiBits = (uint16_t)pgm_read_byte(&data[idx++]); loIdx = 0; } hiBits <<= 2; // Do this before write, because of masking op below analogWrite(A0, (hiBits & 0x300) | pgm_read_byte(&data[idx++])); while(((micros()-startTime+50)/100) < ((i*10000UL+r2)/sampleRate)); } analogWriteResolution(8); // Return to 8 bits for set() compatibility analogWrite(A0, 127); #endif } else { // 8-bit audio samples #ifdef __AVR__ for(i=0; inaeioi/octoon #include namespace octoon { OctoonImplementSubClass(SkinnedBoneComponent, SkinnedComponent, "SkinnedBone") SkinnedBoneComponent::SkinnedBoneComponent() noexcept { } SkinnedBoneComponent::SkinnedBoneComponent(math::uint1s&& bones, math::float3s&& position, math::Quaternions&& rotation, float control) noexcept : SkinnedBoneComponent() { bones_ = std::move(bones); position_ = std::move(position); rotation_ = std::move(rotation); } SkinnedBoneComponent::SkinnedBoneComponent(const math::uint1s& bones, const math::float3s& position, const math::Quaternions& rotation, float control) noexcept : SkinnedBoneComponent() { bones_ = bones; position_ = position; rotation_ = rotation; } SkinnedBoneComponent::~SkinnedBoneComponent() noexcept { } void SkinnedBoneComponent::setPosition(math::float3s&& position) noexcept { position_ = std::move(position); } void SkinnedBoneComponent::setPosition(const math::float3s& position) noexcept { position_ = position; } const math::float3s& SkinnedBoneComponent::getPosition() const noexcept { return position_; } void SkinnedBoneComponent::setRotation(math::Quaternions&& rotation) noexcept { rotation_ = std::move(rotation); } void SkinnedBoneComponent::setRotation(const math::Quaternions& rotation) noexcept { rotation_ = rotation; } const math::Quaternions& SkinnedBoneComponent::getRotation() const noexcept { return rotation_; } void SkinnedBoneComponent::setBones(math::uint1s&& bones) noexcept { bones_ = std::move(bones); } void SkinnedBoneComponent::setBones(const math::uint1s& bones) noexcept { bones_ = bones; } const math::uint1s& SkinnedBoneComponent::getBones() const noexcept { return bones_; } GameComponentPtr SkinnedBoneComponent::clone() const noexcept { auto instance = std::make_shared(); instance->setName(this->getName()); instance->setControl(this->getControl()); instance->setBones(this->getBones()); instance->setPosition(this->getPosition()); instance->setRotation(this->getRotation()); return instance; } void SkinnedBoneComponent::onActivate() noexcept { if (!this->getName().empty()) this->addMessageListener(this->getName(), std::bind(&SkinnedBoneComponent::onAnimationUpdate, this, std::placeholders::_1)); } void SkinnedBoneComponent::onDeactivate() noexcept { if (!this->getName().empty()) this->removeMessageListener(this->getName(), std::bind(&SkinnedBoneComponent::onAnimationUpdate, this, std::placeholders::_1)); } void SkinnedBoneComponent::onAnimationUpdate(const runtime::any& value) noexcept { assert(value.type() == typeid(float)); this->setControl(runtime::any_cast(value)); } void SkinnedBoneComponent::onTargetReplace(const std::string& name) noexcept { if (!this->getName().empty()) this->removeMessageListener(this->getName(), std::bind(&SkinnedBoneComponent::onAnimationUpdate, this, std::placeholders::_1)); if (!name.empty()) this->addMessageListener(name, std::bind(&SkinnedBoneComponent::onAnimationUpdate, this, std::placeholders::_1)); } }1000+ //----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include "Constants.h" #include "Path.h" using namespace std; const int Constants::NumberDrivers = 1; const struct InfAndDevNode Constants::InstallerList[Constants::NumberDrivers] = { { L"KtlLogger.inf", L"root\\KtlLogger" }, }; const wstring Constants::FilesToBeSigned = L"KtlLogger.sys"; const wstring Constants::CurrentModulePath = PathHelper::GetDirectoryName(PathHelper::GetModuleLocation()); static const wstring UtilityDirectory; DWORD Constants::ExitCodeOK = 0; DWORD Constants::ExitCodeReboot = 1; DWORD Constants::ExitCodeFail = 2; DWORD Constants::ExitCodeUsage = 3; // Copyright 2014 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 "core/css/parser/MediaQueryParser.h" #include "core/MediaTypeNames.h" #include "core/css/parser/CSSTokenizer.h" #include "platform/wtf/Vector.h" namespace blink { RefPtr MediaQueryParser::ParseMediaQuerySet( const String& query_string) { return ParseMediaQuerySet(CSSTokenizer(query_string).TokenRange()); } RefPtr MediaQueryParser::ParseMediaQuerySet( CSSParserTokenRange range) { return MediaQueryParser(kMediaQuerySetParser).ParseImpl(range); } RefPtr MediaQueryParser::ParseMediaCondition( CSSParserTokenRange range) { return MediaQueryParser(kMediaConditionParser).ParseImpl(range); } const MediaQueryParser::State MediaQueryParser::kReadRestrictor = &MediaQueryParser::ReadRestrictor; const MediaQueryParser::State MediaQueryParser::kReadMediaNot = &MediaQueryParser::ReadMediaNot; const MediaQueryParser::State MediaQueryParser::kReadMediaType = &MediaQueryParser::ReadMediaType; const MediaQueryParser::State MediaQueryParser::kReadAnd = &MediaQueryParser::ReadAnd; const MediaQueryParser::State MediaQueryParser::kReadFeatureStart = &MediaQueryParser::ReadFeatureStart; const MediaQueryParser::State MediaQueryParser::kReadFeature = &MediaQueryParser::ReadFeature; const MediaQueryParser::State MediaQueryParser::kReadFeatureColon = &MediaQueryParser::ReadFeatureColon; const MediaQueryParser::State MediaQueryParser::kReadFeatureValue = &MediaQueryParser::ReadFeatureValue; const MediaQueryParser::State MediaQueryParser::kReadFeatureEnd = &MediaQueryParser::ReadFeatureEnd; const MediaQueryParser::State MediaQueryParser::kSkipUntilComma = &MediaQueryParser::SkipUntilComma; const MediaQueryParser::State MediaQueryParser::kSkipUntilBlockEnd = &MediaQueryParser::SkipUntilBlockEnd; const MediaQueryParser::State MediaQueryParser::kDone = &MediaQueryParser::Done; MediaQueryParser::MediaQueryParser(ParserType parser_type) : parser_type_(parser_type), query_set_(MediaQuerySet::Create()) { if (parser_type == kMediaQuerySetParser) state_ = &MediaQueryParser::ReadRestrictor; else // MediaConditionParser state_ = &MediaQueryParser::ReadMediaNot; } MediaQueryParser::~MediaQueryParser() {} void MediaQueryParser::SetStateAndRestrict( State state, MediaQuery::RestrictorType restrictor) { media_query_data_.SetRestrictor(restrictor); state_ = state; } // State machine member functions start here void MediaQueryParser::ReadRestrictor(CSSParserTokenType type, const CSSParserToken& token) { ReadMediaType(type, token); } void MediaQueryParser::ReadMediaNot(CSSParserTokenType type, const CSSParserToken& token) { if (type == kIdentToken && EqualIgnoringASCIICase(token.Value(), "not")) SetStateAndRestrict(kReadFeatureStart, MediaQuery::kNot); else ReadFeatureStart(type, token); } static bool IsRestrictorOrLogicalOperator(const CSSParserToken& token) { // FIXME: it would be more efficient to use lower-case always for tokenValue. return EqualIgnoringASCIICase(token.Value(), "not") || EqualIgnoringASCIICase(token.Value(), "and") || EqualIgnoringASCIICase(token.Value(), "or") || EqualIgnoringASCIICase(token.Value(), "only"); } void MediaQueryParser::ReadMediaType(CSSParserTokenType type, const CSSParserToken& token) { if (type == kLeftParenthesisToken) { if (media_query_data_.Restrictor() != MediaQuery::kNone) state_ = kSkipUntilComma; else state_ = kReadFeature; } else if (type == kIdentToken) { if (state_ == kReadRestrictor && EqualIgnoringASCIICase(token.Value(), "not")) { SetStateAndRestrict(kReadMediaType, MediaQuery::kNot); } else if (state_ == kReadRestrictor && EqualIgnoringASCIICase(token.Value(), "only")) { SetStateAndRestrict(kReadMediaType, MediaQuery::kOnly); } else if (media_query_data_.Restrictor() != MediaQuery::kNone && IsRestrictorOrLogicalOperator(token)) { state_ = kSkipUntilComma; } else { media_query_data_.SetMediaType(token.Value().ToString()); state_ = kReadAnd; } } else if (type == kEOFToken && (!query_set_->QueryVector().size() || state_ != kReadRestrictor)) { state_ = kDone; } else { state_ = kSkipUntilComma; if (type == kCommaToken) SkipUntilComma(type, token); } } void MediaQueryParser::ReadAnd(CSSParserTokenType type, const CSSParserToken& token) { if (type == kIdentToken && EqualIgnoringASCIICase(token.Value(), "and")) { state_ = kReadFeatureStart; } else if (type == kCommaToken && parser_type_ != kMediaConditionParser) { query_set_->AddMediaQuery(media_query_data_.TakeMediaQuery()); state_ = kReadRestrictor; } else if (type == kEOFToken) { state_ = kDone; } else { state_ = kSkipUntilComma; } } void MediaQueryParser::ReadFeatureStart(CSSParserTokenType type, const CSSParserToken& token) { if (type == kLeftParenthesisToken) state_ = kReadFeature; else state_ = kSkipUntilComma; } void MediaQueryParser::ReadFeature(CSSParserTokenType type, const CSSParserToken& token) { if (type == kIdentToken) { media_query_data_.SetMediaFeature(token.Value().ToString()); state_ = kReadFeatureColon; } else { state_ = kSkipUntilComma; } } void MediaQueryParser::ReadFeatureColon(CSSParserTokenType type, const CSSParserToken& token) { if (type == kColonToken) state_ = kReadFeatureValue; else if (type == kRightParenthesisToken || type == kEOFToken) ReadFeatureEnd(type, token); else state_ = kSkipUntilBlockEnd; } void MediaQueryParser::ReadFeatureValue(CSSParserTokenType type, const CSSParserToken& token) { if (type == kDimensionToken && token.GetUnitType() == CSSPrimitiveValue::UnitType::kUnknown) { state_ = kSkipUntilComma; } else { if (media_query_data_.TryAddParserToken(type, token)) state_ = kReadFeatureEnd; else state_ = kSkipUntilBlockEnd; } } void MediaQueryParser::ReadFeatureEnd(CSSParserTokenType type, const CSSParserToken& token) { if (type == kRightParenthesisToken || type == kEOFToken) { if (media_query_data_.AddExpression()) state_ = kReadAnd; else state_ = kSkipUntilComma; } else if (type == kDelimiterToken && token.Delimiter() == '/') { media_query_data_.TryAddParserToken(type, token); state_ = kReadFeatureValue; } else { state_ = kSkipUntilBlockEnd; } } void MediaQueryParser::SkipUntilComma(CSSParserTokenType type, const CSSParserToken& token) { if ((type == kCommaToken && !block_watcher_.BlockLevel()) || type == kEOFToken) { state_ = kReadRestrictor; media_query_data_.Clear(); query_set_->AddMediaQuery(MediaQuery::CreateNotAll()); } } void MediaQueryParser::SkipUntilBlockEnd(CSSParserTokenType type, const CSSParserToken& token) { if (token.GetBlockType() == CSSParserToken::kBlockEnd && !block_watcher_.BlockLevel()) state_ = kSkipUntilComma; } void MediaQueryParser::Done(CSSParserTokenType type, const CSSParserToken& token) {} void MediaQueryParser::HandleBlocks(const CSSParserToken& token) { if (token.GetBlockType() == CSSParserToken::kBlockStart && (token.GetType() != kLeftParenthesisToken || block_watcher_.BlockLevel())) state_ = kSkipUntilBlockEnd; } void MediaQueryParser::ProcessToken(const CSSParserToken& token) { CSSParserTokenType type = token.GetType(); HandleBlocks(token); block_watcher_.HandleToken(token); // Call the function that handles current state if (type != kWhitespaceToken) ((this)->*(state_))(type, token); } // The state machine loop RefPtr MediaQueryParser::ParseImpl(CSSParserTokenRange range) { while (!range.AtEnd()) ProcessToken(range.Consume()); // FIXME: Can we get rid of this special case? if (parser_type_ == kMediaQuerySetParser) ProcessToken(CSSParserToken(kEOFToken)); if (state_ != kReadAnd && state_ != kReadRestrictor && state_ != kDone && state_ != kReadMediaNot) query_set_->AddMediaQuery(MediaQuery::CreateNotAll()); else if (media_query_data_.CurrentMediaQueryChanged()) query_set_->AddMediaQuery(media_query_data_.TakeMediaQuery()); return query_set_; } MediaQueryData::MediaQueryData() : restrictor_(MediaQuery::kNone), media_type_(MediaTypeNames::all), media_type_set_(false) {} void MediaQueryData::Clear() { restrictor_ = MediaQuery::kNone; media_type_ = MediaTypeNames::all; media_type_set_ = false; media_feature_ = String(); value_list_.clear(); expressions_.clear(); } std::unique_ptr MediaQueryData::TakeMediaQuery() { std::unique_ptr media_query = MediaQuery::Create( restrictor_, std::move(media_type_), std::move(expressions_)); Clear(); return media_query; } bool MediaQueryData::AddExpression() { MediaQueryExp expression = MediaQueryExp::Create(media_feature_, value_list_); expressions_.push_back(expression); value_list_.clear(); return expression.IsValid(); } bool MediaQueryData::TryAddParserToken(CSSParserTokenType type, const CSSParserToken& token) { if (type == kNumberToken || type == kPercentageToken || type == kDimensionToken || type == kDelimiterToken || type == kIdentToken) { value_list_.push_back(token); return true; } return false; } void MediaQueryData::SetMediaType(const String& media_type) { media_type_ = media_type; media_type_set_ = true; } } // namespace blink #include "matrix.h" class myKernel: public kernel_Base { public: virtual double kernel_Func(Point r0, Point r1){ double r = sqrt((r0.x-r1.x)*(r0.x-r1.x) + (r0.y-r1.y)*(r0.y-r1.y)); double t0; //implement your own kernel on the next line t0 = exp(pow(r,1.0/4.0)*(-1.0/3.0E1)); if (mxIsInf(t0)||mxIsNaN(t0)) return 0; else return t0; } }; pierce-m/p4c /* Copyright 2013-present Barefoot Networks, 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. */ #include "local_copyprop.h" #include "has_side_effects.h" #include "expr_uses.h" class P4::DoLocalCopyPropagation::ElimDead : public Transform { DoLocalCopyPropagation &self; const IR::Node *preorder(IR::Declaration_Variable *var) override { if (auto local = ::getref(self.available, var->name)) { BUG_CHECK(local->local, "Non-local local var?"); if (!local->live) { LOG3(" removing dead local " << var->name); return nullptr; } } else { BUG("local %s isn't in available table", var->name); } return var; } IR::AssignmentStatement *postorder(IR::AssignmentStatement *as) override { if (auto dest = as->left->to()) { if (auto var = ::getref(self.available, dest->path->name)) { if (var->local && !var->live) { LOG3(" removing dead assignment to " << dest->path->name); return nullptr; } } } return as; } public: explicit ElimDead(DoLocalCopyPropagation &self) : self(self) {} }; void P4::DoLocalCopyPropagation::flow_merge(Visitor &a_) { auto &a = dynamic_cast(a_); BUG_CHECK(in_action == a.in_action, "inconsitent DoLocalCopyPropagation state on merge"); for (auto &var : available) { if (auto merge = ::getref(a.available, var.first)) { if (merge->val != var.second.val) var.second.val = nullptr; if (merge->live) var.second.live = true; } else { var.second.val = nullptr; } } } void P4::DoLocalCopyPropagation::dropValuesUsing(cstring name) { for (auto &var : available) { if (var.first == name) { LOG4(" dropping " << name << " as it is being assigned to"); var.second.val = nullptr; } else if (var.second.val && exprUses(var.second.val, name)) { LOG4(" dropping " << var.first << " as it is use" << name); var.second.val = nullptr; } } } const IR::Node *P4::DoLocalCopyPropagation::postorder(IR::Declaration_Variable *var) { LOG1("Visiting " << getOriginal()); if (!in_action) return var; if (available.count(var->name)) BUG("duplicate var declaration for %s", var->name); auto &local = available[var->name]; local.local = true; if (var->initializer) { if (!hasSideEffects(var->initializer)) { LOG3(" saving init value for " << var->name); local.val = var->initializer; } else { local.live = true; } } return var; } const IR::Expression *P4::DoLocalCopyPropagation::postorder(IR::PathExpression *path) { if (auto var = ::getref(available, path->path->name)) { if (isWrite()) { return path; } else if (var->val) { LOG3(" propagating value for " << path->path->name); return var->val; } else { LOG4(" using " << path->path->name << " with no propagated value"); var->live = true; } } return path; } IR::AssignmentStatement *P4::DoLocalCopyPropagation::postorder(IR::AssignmentStatement *as) { if (as->left == as->right) { // FIXME -- need deep equals here? LOG3(" removing noop assignment " << *as); return nullptr; } if (!in_action) return as; if (auto dest = as->left->to()) { dropValuesUsing(dest->path->name); if (!hasSideEffects(as->right)) { if (as->right->is()) { /* FIXME -- List Expressions need to be turned into constructor calls before * we can copyprop them */ return as; } LOG3(" saving value for " << dest->path->name); available[dest->path->name].val = as->right; } } return as; } IR::MethodCallExpression *P4::DoLocalCopyPropagation::postorder(IR::MethodCallExpression *mc) { if (!in_action) return mc; auto type = mc->method->type->to(); CHECK_NULL(type); int idx = 0; for (auto param : *type->parameters->parameters) { if (param->direction == IR::Direction::Out || param->direction == IR::Direction::InOut) { if (auto arg = mc->arguments->at(idx)->to()) { dropValuesUsing(arg->path->name); } } ++idx; } return mc; } IR::Primitive *P4::DoLocalCopyPropagation::postorder(IR::Primitive *prim) { if (!in_action) return prim; for (unsigned idx = 0; idx < prim->operands.size(); ++idx) { if (prim->isOutput(idx)) { dropValuesUsing(prim->operands.at(idx)->toString()); } } return prim; } IR::P4Action *P4::DoLocalCopyPropagation::preorder(IR::P4Action *act) { in_action = true; if (!available.empty()) BUG("corrupt internal data struct"); LOG2("DoLocalCopyPropagation working on action " << act->name); LOG4(act); return act; } IR::P4Action *P4::DoLocalCopyPropagation::postorder(IR::P4Action *act) { LOG5("DoLocalCopyPropagation before ElimDead " << act->name); LOG5(act); act->body = act->body->apply(ElimDead(*this))->to(); in_action = false; available.clear(); LOG3("DoLocalCopyPropagation finished action " << act->name); LOG4(act); return act; } /* MIT License Copyright (c) 2017 FMI Open Development / , 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. */ /* Part of Rack development has been done in the BALTRAD projects part-financed by the European Union (European Regional Development Fund and European Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013) */ /* * RackLet.cpp * * Created on: Nov 17, 2014 * Author: mpe */ #include #include //#include #include "drain/util/Log.h" #include "drain/util/Input.h" #include "drain/util/Static.h" #include "CommandBank.h" #include "Program.h" namespace drain { //const Flagger::value_t CommandBank::SCRIPT_DEFINED = StatusFlags::add("SCRIPT_DEFINED"); /// Global program command registry. Optional utility. CommandBank & getCommandBank(){ return Static::get(); //static CommandBank commandBank; //return commandBank; } std::set & CommandBank::trimWords(){ static std::set s; if (s.empty()){ s.insert("Cmd"); s.insert("Command"); } return s; } void CommandBank::deriveCmdName(std::string & name, char prefix){ const std::set & trims = trimWords(); Logger mout(__FILE__, __FUNCTION__); std::stringstream sstr; if (prefix) sstr << prefix; // Check initial of the first valid char (after pruning, so possibly i>0) bool checkInitialCase = true; const size_t nameLen = name.size(); size_t i = 0; while (i < nameLen) { //mout.debug(10) << ' ' << i << '\t' << name.at(i) << mout.endl; size_t len = 0; for (std::set::const_iterator it=trims.begin(); it!=trims.end(); ++it){ // std::cerr << " ..." << *it; const std::string & word = *it; len = word.length(); // = chars to skip, potentially if (name.compare(i, len, word) == 0){ // Match // general jump (always) // break; if (i == 0) // and HEAD break; if (i == (nameLen-len)) // and TAIL break; } len = 0; // don't skip any chars, proceed to take the current one. } if (len > 0){ // Skip word i += len; } else { // Copy the current character char c = name.at(i); if (checkInitialCase){ // initial char, ensure ... if (prefix != 0){ // ...Uppercase if ((c>='a') && (c<='z')) c = ('A' + (c-'a')); } else { // ...lowercase if ((c>='A') && (c<='Z')) c = ('a' + (c-'A')); } checkInitialCase = false; } sstr << c; ++i; } //mout.debug() //std::cerr << '\n'; } // mout.warn() << ' ' << prefix << ((int)prefix) << "\t" << name << "\t => "; name = sstr.str(); // mout << name << mout.endl; }; /// Appends program with commands fo the script void CommandBank::append(const Script & script, Context & ctx, Program & prog) const { for (Script::const_iterator it = script.begin(); it!=script.end(); ++it) { if (it->first.size()==1){ static BasicCommand dummy("Marker", "[marker]"); prog.add(it->first, dummy); } else { command_t & cmd = clone(it->first); cmd.setExternalContext(ctx); cmd.setParameters(it->second); prog.add(it->first, cmd); } } } /// Converts linux command line to pairs of strings: (, [params]) /** * Starts from argument 1 instead of 0. */ void CommandBank::scriptify(int argc, const char **argv, Script & script) const { Logger mout(__FILE__, __FUNCTION__); // warning, not initialized //bool PARALLEL = false; for (int i = 1; i < argc; ++i) { const std::string arg(argv[i]); if (arg.empty()){ mout.warn() << "empty arg" << mout.endl; continue; } const std::string argNext((i+1) < argc ? argv[i+1] : ""); bool ARG_TAKEN = scriptify(arg, argNext, script); if (ARG_TAKEN){ // Swallowed argNext as well ++i; if (i == argc){ // Some commands like --help are fine with and without arg (when ending line). //mout.warn() << arg << ": argument missing (premature end of command line), i=" << i << mout.endl; return; } } } } void CommandBank::scriptify(const std::string & line, Script & script) const{ Logger mout(__FILE__, __FUNCTION__); // typedef std::list list_t; list_t l; //drain::StringTools::split(line, l, " "); std::stringstream sstr(line); while (sstr) { l.push_back(""); sstr >> l.back(); } list_t::const_iterator it = l.begin(); while (it != l.end()) { const std::string & arg = *it; ++it; if (it != l.end()){ const std::string & argNext = *it; if (scriptify(arg, argNext, script)) ++it; } else { if (scriptify(arg, "", script)) mout.warn() << arg << ": argument missing (premature end of command line), i=" << mout.endl; } } } bool CommandBank::scriptify(const std::string & arg, const std::string & argNext, Script & script) const { Logger mout(__FILE__, __FUNCTION__); // warning, not initialized if (arg.empty()){ mout.debug() << "empty arg" << mout.endl; return false; } if (arg.at(0) == '-'){ const std::string & key = resolveFull(arg); // handle leading hyphens and aliases if (!key.empty()){ //const drain::ReferenceMap & params = get(key).getParameters(); if (get(key).getParameters().empty()){ script.add(key); return false; } else { script.add(key, argNext); return true; } } else if (!notFoundHandlerCmdKey.empty()){ const Command & cmd = get(notFoundHandlerCmdKey); if (cmd.hasArguments()){ size_t i = arg.find_first_not_of('-'); if (i != std::string::npos){ script.add(notFoundHandlerCmdKey, arg.substr(i)); } else { mout.warn() << "plain dash(es): " << arg << mout.endl; } } else { script.add(notFoundHandlerCmdKey); } } else { mout.warn() << "undefined command: " << arg << " (and no 'notFoundHandlerCmd' set in main program)" << mout.endl; throw std::runtime_error(arg + ": command not found"); } } else if (arg.length() == 1){ // instructions '(', ')' (more in future) script.add(arg); } // Plain argument else if (!defaultCmdKey.empty()){ script.add(defaultCmdKey, arg); } else { mout.error() << "defaultCmd undefined for plain argument (" << arg << ")" << mout.endl; } return false; } void CommandBank::readFile(const std::string & filename, Script & script) const { Logger mout(__FILE__, __FUNCTION__); std::string line; drain::Input ifstr(filename); // mout.note() << "open list: " << filename << mout.endl; // ifstr.open(params.c_str()); while ( std::getline((std::ifstream &)ifstr, line) ){ if (!line.empty()){ mout.debug2() << line << mout.endl; if (line.at(0) != '#') scriptify(line, script); } } } // Future extension. void CommandBank::remove(Program & prog) const { std::cout << "clearing prog: " << '\n'; //prog.toStream(); std::cout << prog << '\n'; for (Program::const_iterator it = prog.begin(); it!=prog.end(); ++it) { } } /// Run a single command void CommandBank::run(const std::string & cmdKey, const std::string & params, Context & ctx){ Logger mout(ctx.log, __FILE__, __FUNCTION__); command_t & cmd = get(cmdKey); //cmd.setKey(cmdKey); if (cmd.contextIsSet()) mout.note() << "replacing original context " << mout.endl; cmd.setExternalContext(ctx); cmd.run(params); } void CommandBank::run(Program & prog, ClonerBase & contextCloner){ // Which log? Perhaps prog first cmd ctx log? //const drain::Flagger::value_t execScript = drain::Static::get().index; bool CREATE_THREADS = false; // std::vector threads; ProgramVector threads; // Iterate commandsconst auto& kv : myMap /* for (auto & entry: prog) { const key_t & key = entry.first; value_t & cmd = entry.second; */ for (Program::iterator it = prog.begin(); it != prog.end(); ++it) { // mout.note() << it->first << mout.endl; const key_t & key = it->first; value_t & cmd = *it->second; // const std::string & cmdName = cmd.getName(); Context & ctx = cmd.getContext<>(); //.log; Log & log = ctx.log; const bool TRIGGER = (cmd.section & this->scriptTriggerFlag); // AND Logger mout(log, __FUNCTION__, __FILE__); // warni //if (TRIGGER) mout.debug() << "TRIGGER? " << cmd.section << '+' << this->scriptTriggerFlag << '=' << sprinter(TRIGGER) << mout.endl; if (cmd.getName().empty()){ mout.warn() << "Command name empty for key='" << key << "', " << cmd << mout.endl; } else if (cmd.getName() == scriptCmd){ // "script" ReferenceMap::const_iterator pit = cmd.getParameters().begin(); mout.warn() << "'" << scriptCmd << "' -> storing routine: '" << pit->second << "'" << mout.endl; scriptify(pit->second.toStr(), prog.routine); //ctx.statusFlags.set(SCRIPT_DEFINED); ctx.setStatus("script", true); //ctx.setStatus(key, value) continue; } // Explicit launch NOT needed, but a passive trigger cmd /* else if (cmd.getName() == execScriptCmd){ // Explicit launch mout.experimental() << "executing script" << mout; Program progSub; append(prog.routine, cmd.getContext(), progSub); // append() has access to command registry (Prog does not) run(progSub, contextCloner); } */ else if (cmd.getName() == execFileCmd){ // "execFile" ReferenceMap::const_iterator pit = cmd.getParameters().begin(); // TODO catch mout.info() << "embedding (inserting commands on-the-fly) from '" << pit->second << "'" << mout; Script script; readFile(pit->second, script); mout.debug() << script << mout.endl; Program::iterator itNext = it; ++itNext; for (Script::value_type & subCmd: script){ mout.debug() << sprinter(subCmd) << mout.endl; command_t & cmd = clone(subCmd.first); cmd.setExternalContext(ctx); cmd.setParameters(subCmd.second); //prog.add(it->first, cmd); prog.insert(itNext, Program::value_type(subCmd.first, &cmd)); //run(subCmd.first, subCmd.second, ctx); } // Debug: print resulting program that contains embedded commands // mout.warn() << sprinter(prog) << mout; continue; } else if (key == "["){ mout.note() << "Switching to parallel mode." << mout.endl; mout.warn() << "Step 1: compose threads." << mout.endl; mout.warn() << "Hey, " << log.getVerbosity() << mout.endl; CREATE_THREADS = true; continue; } else if (key == "]"){ // All the triggering commands collected, run them if (!CREATE_THREADS){ mout.warn() << "Leading brace '[' missing?" << mout.endl; } CREATE_THREADS = false; if (threads.empty()){ mout.warn() << "No threads?" << mout.endl; mout.note() << "No thread-triggering commands inside braces [ ...]. See --help trigger " << mout.endl; //mout.warn() << "No threads defined? Syntax: --script ' ...' [ ...] " << mout.endl; continue; } else { mout.special() << "Start threads" << log.getVerbosity() << mout.endl; #pragma omp parallel for for (size_t i = 0; i < threads.size(); ++i) { // Keep this minimal. (No variable writes here, unless local.) run(threads[i], contextCloner); } mout.special() << "Threads completed." << mout.endl; prog.routine.clear(); // reconsider } } else if (CREATE_THREADS && TRIGGER) { //mout.warn() << "Prepare a new thread: " << key << '(' << cmd << ')' << mout.endl; Context & ctxCloned = contextCloner.getCloned(); ctxCloned.log.setVerbosity(log.getVerbosity()); Program & thread = threads.add(); // Add at least the current command value_t & cmdCloned = clone(key); cmdCloned.setExternalContext(ctxCloned); cmdCloned.setParameters(cmd.getParameters()); thread.add(it->first, cmdCloned); mout.ok() << "Thread #" << threads.size() << "-" << ctxCloned.id << ':' << key << '(' << cmd << ')' << mout.endl; // And also append a script, if defined. if (!prog.routine.empty()){ // Technically unneeded, but for mout... mout.debug() << "routine exists, appending it to thread " << mout.endl; append(prog.routine, ctxCloned, thread); // append } } else if (TRIGGER && !prog.routine.empty()){ // Check here if routine exists (the current cmd may set the routine, and the it should not be run). // First command (cmd) could be run above, but here in prog for debugging (and clarity?) mout.info() << "script triggering command: '" << cmd << mout.endl; Program progSub; progSub.add(key, cmd).section = 0; // execRoutine = false; // COPIES! .setParameters(it->second); append(prog.routine, cmd.getContext(), progSub); // append() has access to command registry (Prog does not) //mout.note() << "Exec routine: " << prog.getContext().id << mout.endl; mout.info() << "running routine: '" << key << ' ' << cmd.getParameters().getValues() << " --" << prog.routine.begin()->first<< " ...'" << mout.endl; //mout.note() << "running routine: " << prog.routine.begin()->first << "..." << mout.endl; run(progSub, contextCloner); // ? prog.routine.clear(); } else { mout.debug() << "Executing: " << key << " = " << cmd << " " << mout.endl; //try { cmd.update(); // --select etc cmd.exec(); ctx.setStatus(key, cmd.getParameters().getValues()); /* } catch (const std::exception & e){ mout.fail() << e.what() << mout.endl; mout.warn() << "stopping" << mout.endl; return; } */ } // TODO: when to explicitly clear routine? } } /** * */ void CommandBank::help(const std::string & key, std::ostream & ostr){ Logger mout(__FILE__, __FUNCTION__); // warning, not initialized if (key.empty()){ //help(0xffffffff, ostr); //help(CommandBank::GENERAL, ostr); help(0, ostr); return; } else if (key == "all"){ help(FlagResolver::ALL, ostr); //help(0xffffffff, ostr); } else { // Try to find the command directly const std::string & fullKey = resolveFull(key); if (!fullKey.empty()){ //mout.warn() << "fullKey: " << key << " -> " << fullKey << mout.endl; try { info(fullKey, get(fullKey), ostr, true); } catch (const std::exception &e) { ostr << "error: " << e.what() << '\n'; } // TODO: "see-also" commands as a list, which is checked. } else { // Or is it a section, or several? Flagger::value_t filter = FlagResolver::getValue(sections, key); // Accepts also numeric strings. //mout.deprecating() << "Flagger: " << sections << " -> " << filter << mout.endl; if (filter > 0){ help(filter, ostr); return; } mout.error() << "not found: " << key << mout.endl; } } } void CommandBank::help(Flagger::value_t sectionFilter, std::ostream & ostr){ ostr << title << '\n' << std::endl; const bool TEST = false; //true; if (sectionFilter > 0){ //Flagger::value_t filter = FlagResolver::getValue(sections, key); //Flagger::value_t filter = 0; //Flagger flagger(filter, sections, ','); //flagger.set(sectionFilter); ostr << "Section: " << FlagResolver::getKeys(sections, sectionFilter) << '\n' << '\n'; for (map_t::const_iterator it = this->begin(); it!=this->end(); ++it){ if ((it->second->getSource().section & sectionFilter) > 0){ try { if (!TEST){ info(it->first, it->second->getSource(), ostr, false); } else { ostr << it->first << '\n'; std::stringstream sstr, sstr2; Command & cmdOrig = it->second->getSource(); Command & cmdCopy = it->second->getCloned(); info(it->first, cmdOrig, sstr, false); info(it->first, cmdCopy, sstr2, false); if (sstr.str() != sstr2.str()){ ostr << sstr.str() << '\n'; ostr << sstr2.str() << '\n'; ostr << "---- ERROR " << '\n'; } sstr.str(" "); sstr2.str(" "); sstr << cmdOrig.getParameters(); sstr2 << cmdCopy.getParameters(); if (sstr.str() != sstr2.str()){ ostr << sstr.str() << '\n'; ostr << sstr2.str() << '\n'; ostr << "---- ERROR " << '\n'; } //cmdCopy.setParameters(cmdOrig.getParameters()); } } catch (const std::exception &e) { ostr << "error: " << e.what() << '\n'; } } } } // else { ? ostr << '\n'; ostr << "For help on a commands, type:\n"; ostr << " --help \n"; ostr << '\n'; ostr << "For help on command sections, type:\n"; ostr << " --help ["; sections.keysToStream(ostr, '|'); if (sections.size() > 2) ostr << '|' << "all"; ostr << "]\n"; /* ostr << "Bonus:\n"; ostr << drain::sprinter(sections); ostr << "Done.\n"; */ //ostr << " --help {" << sections << "}\n"; //std::flush(ostr); } /// Checked key and respective command void CommandBank::info(const std::string & key, const value_t & cmd, std::ostream & ostr, bool detailed) const { Logger mout(__FILE__, __FUNCTION__); /* Dynamic try { cmd.setKey(key); } catch (const std::exception &e) { ostr << "error: " << e.what() << '\n'; return; } */ ostr << "--" << key; char alias = getAlias(key); if (alias) ostr << ", -" << alias; const ReferenceMap & params = cmd.getParameters(); const std::map & units = params.getUnitMap(); const std::list & keys = params.getKeyList(); // To get keys in specified order. ostr << ' ' << ' '; char separator = 0; for (std::list::const_iterator kit = keys.begin(); kit != keys.end(); ++kit){ if (separator) ostr << separator; else separator = params.separator; //','; if (kit->empty()){ ostr << '<' << params.getKeys() << '>'; if (params.size() != 1){ mout.warn() << "the first key empty, but not unique" << mout.endl; //mout.warn() << "the first key empty, but not unique" << mout.endl; } } else { ostr << '<' << *kit << '>'; } } if (detailed) ostr << " (Section: " << FlagResolver::getKeys(sections,cmd.section, ',') << ')'; ostr << '\n'; ostr << ' ' << ' ' << cmd.getDescription() << '\n'; //ostr << cmd.getDescription() << '\n'; /// Iterate variable keys if (detailed){ for (std::list::const_iterator kit = keys.begin(); kit != keys.end(); ++kit){ const std::string & key = *kit; // special: if (keys.size()==1){ if (key.find(',') != std::string::npos){ // Latent-multikey case ostr << '\t' << params.begin()->second << '\n'; return; } } ostr << '\t' << key; // ostr << ' ' << ' ' << key; // ostr << ' ' << ' ' << ' ' << ' ' << key; ReferenceMap::const_iterator rit = params.find(key); // er.. ok.. if (rit == params.end()) throw std::runtime_error(key + ": key listed, but no command found"); else { ostr << '=' << rit->second << ' '; //ostr << 'Q'; std::map::const_iterator uit = units.find(key); if (uit != units.end()) if (!uit->second.empty()) ostr << '[' << uit->second << ']'; } //ostr << 'X'; ostr << '\n'; } } } /// Given alias or long key, possibly prefixed by hyphens, return the long key if a command exists. /** * */ const std::string & CommandBank::resolveFull(const key_t & key) const { Logger mout(__FILE__, __FUNCTION__); // warning, not initialized static const std::string empty; if (key.empty()) return empty; const size_t hyphens = key.find_first_not_of('-'); // Substring starting from first letter (strip leading hyphens) std::string cmd(key, hyphens); if (hyphens>2) mout.warn() << "more than 2 leading hyphens: " << key << mout.endl; else if (hyphens > 0){ if ((hyphens==2) != (cmd.length()>1)) mout.warn() << "mixed type argument (--x or -xx): " << key << mout.endl; } //mout.warn() << "searching for " << cmd << mout.endl; const std::string & cmdFinal = resolve(cmd); const_iterator it = this->find(cmdFinal); if (it != this->end()){ //mout.warn() << "found " << it->first << mout.endl; return it->first; } else { return empty; } } } /* namespace drain */ // Rack // ErrorInformation.h #ifndef INCLUDED_ERRORINFORMATION_H #define INCLUDED_ERRORINFORMATION_H class MyOstream; struct ErrorInformation { char * d_hint; void (*d_f)(void *,MyOstream &); MyOstream * d_os; }; #endif #pragma once #include #include "simeng/MemoryInterface.hh" namespace simeng { /** A memory interface to a flat memory system. */ class FlatMemoryInterface : public MemoryInterface { public: FlatMemoryInterface(char* memory, size_t size); /** Request a read from the supplied target location. * * The caller can optionally provide an ID that will be attached to completed * read results. */ void requestRead(const MemoryAccessTarget& target, uint64_t requestId = 0) override; /** Request a write of `data` to the target location. */ void requestWrite(const MemoryAccessTarget& target, const RegisterValue& data) override; /** Retrieve all completed requests. */ const span getCompletedReads() const override; /** Clear the completed reads. */ void clearCompletedReads() override; /** Returns true if there are any oustanding memory requests in-flight. */ bool hasPendingRequests() const override; /** Tick: do nothing */ void tick() override; private: /** The array representing the flat memory system to access. */ char* memory_; /** The size of accessible memory. */ size_t size_; /** A vector containing all completed read requests. */ std::vector completedReads_; }; } // namespace simeng #include "gtest/gtest.h" #include "templates/struct_templated_type_argument/StructTemplatedTypeArgument.h" namespace templates { namespace struct_templated_type_argument { TEST(StructTemplatedTypeArgumentTest, readWrite) { StructTemplatedTypeArgument structTemplatedTypeArgument; structTemplatedTypeArgument.getParamHolder().setParam(42); Parameterized_uint32& parameterized = structTemplatedTypeArgument.getParameterized(); parameterized.setDescription("description"); parameterized.setId(13); zserio::BitStreamWriter writer; structTemplatedTypeArgument.write(writer); size_t bufferSize = 0; const uint8_t* buffer = writer.getWriteBuffer(bufferSize); zserio::BitStreamReader reader(buffer, bufferSize); StructTemplatedTypeArgument readStructTemplatedTypeArgument(reader); ASSERT_TRUE(structTemplatedTypeArgument == readStructTemplatedTypeArgument); } } // namespace struct_templated_type_argument } // namespace templates /* Copyright (C) 2007 Google Inc. Copyright (C) 2008 MySQL AB Use is subject to license terms 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "semisync.h" const unsigned char Repl_semi_sync_base::k_packet_magic_num= 0xef; const unsigned char Repl_semi_sync_base::k_packet_flag_sync= 0x01; const unsigned long Trace::k_trace_general= 0x0001; const unsigned long Trace::k_trace_detail= 0x0010; const unsigned long Trace::k_trace_net_wait= 0x0020; const unsigned long Trace::k_trace_function= 0x0040; const unsigned char Repl_semi_sync_base::k_sync_header[2]= {Repl_semi_sync_base::k_packet_magic_num, 0}; chessire/blender_with_deeprt0 /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "node_geometry_util.hh" #include "UI_interface.h" #include "UI_resources.h" static bNodeSocketTemplate geo_node_attribute_clamp_in[] = { {SOCK_GEOMETRY, N_("Geometry")}, {SOCK_STRING, N_("Attribute")}, {SOCK_STRING, N_("Result")}, {SOCK_VECTOR, N_("Min"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX}, {SOCK_VECTOR, N_("Max"), 1.0f, 1.0f, 1.0f, 0.0f, -FLT_MAX, FLT_MAX}, {SOCK_FLOAT, N_("Min"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX}, {SOCK_FLOAT, N_("Max"), 1.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX}, {SOCK_INT, N_("Min"), 0.0f, 0.0f, 0.0f, 0.0f, -100000, 100000}, {SOCK_INT, N_("Max"), 100.0f, 0.0f, 0.0f, 0.0f, -100000, 100000}, {SOCK_RGBA, N_("Min"), 0.5, 0.5, 0.5, 1.0}, {SOCK_RGBA, N_("Max"), 0.5, 0.5, 0.5, 1.0}, {-1, ""}, }; static bNodeSocketTemplate geo_node_attribute_clamp_out[] = { {SOCK_GEOMETRY, N_("Geometry")}, {-1, ""}, }; static void geo_node_attribute_clamp_layout(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) { uiItemR(layout, ptr, "data_type", 0, "", ICON_NONE); uiItemR(layout, ptr, "operation", 0, "", ICON_NONE); } static void geo_node_attribute_clamp_init(bNodeTree *UNUSED(tree), bNode *node) { NodeAttributeClamp *data = (NodeAttributeClamp *)MEM_callocN(sizeof(NodeAttributeClamp), __func__); data->data_type = CD_PROP_FLOAT; data->operation = NODE_CLAMP_MINMAX; node->storage = data; } static void geo_node_attribute_clamp_update(bNodeTree *UNUSED(ntree), bNode *node) { bNodeSocket *sock_min_vector = (bNodeSocket *)BLI_findlink(&node->inputs, 3); bNodeSocket *sock_max_vector = sock_min_vector->next; bNodeSocket *sock_min_float = sock_max_vector->next; bNodeSocket *sock_max_float = sock_min_float->next; bNodeSocket *sock_min_int = sock_max_float->next; bNodeSocket *sock_max_int = sock_min_int->next; bNodeSocket *sock_min_color = sock_max_int->next; bNodeSocket *sock_max_color = sock_min_color->next; const NodeAttributeClamp &storage = *(const NodeAttributeClamp *)node->storage; const CustomDataType data_type = static_cast(storage.data_type); nodeSetSocketAvailability(sock_min_vector, data_type == CD_PROP_FLOAT3); nodeSetSocketAvailability(sock_max_vector, data_type == CD_PROP_FLOAT3); nodeSetSocketAvailability(sock_min_float, data_type == CD_PROP_FLOAT); nodeSetSocketAvailability(sock_max_float, data_type == CD_PROP_FLOAT); nodeSetSocketAvailability(sock_min_int, data_type == CD_PROP_INT32); nodeSetSocketAvailability(sock_max_int, data_type == CD_PROP_INT32); nodeSetSocketAvailability(sock_min_color, data_type == CD_PROP_COLOR); nodeSetSocketAvailability(sock_max_color, data_type == CD_PROP_COLOR); } namespace blender::nodes { template T clamp_value(const T val, const T min, const T max); template<> inline float clamp_value(const float val, const float min, const float max) { return std::min(std::max(val, min), max); } template<> inline int clamp_value(const int val, const int min, const int max) { return std::min(std::max(val, min), max); } template<> inline float3 clamp_value(const float3 val, const float3 min, const float3 max) { float3 tmp; tmp.x = std::min(std::max(val.x, min.x), max.x); tmp.y = std::min(std::max(val.y, min.y), max.y); tmp.z = std::min(std::max(val.z, min.z), max.z); return tmp; } template<> inline Color4f clamp_value(const Color4f val, const Color4f min, const Color4f max) { Color4f tmp; tmp.r = std::min(std::max(val.r, min.r), max.r); tmp.g = std::min(std::max(val.g, min.g), max.g); tmp.b = std::min(std::max(val.b, min.b), max.b); tmp.a = std::min(std::max(val.a, min.a), max.a); return tmp; } template static void clamp_attribute(Span read_span, MutableSpan span, const T min, const T max) { for (const int i : span.index_range()) { span[i] = clamp_value(read_span[i], min, max); } } static AttributeDomain get_result_domain(const GeometryComponent &component, StringRef source_name, StringRef result_name) { ReadAttributePtr result_attribute = component.attribute_try_get_for_read(result_name); if (result_attribute) { return result_attribute->domain(); } ReadAttributePtr source_attribute = component.attribute_try_get_for_read(source_name); if (source_attribute) { return source_attribute->domain(); } return ATTR_DOMAIN_POINT; } static void clamp_attribute(GeometryComponent &component, const GeoNodeExecParams ¶ms) { const std::string attribute_name = params.get_input("Attribute"); const std::string result_name = params.get_input("Result"); if (attribute_name.empty() || result_name.empty()) { return; } if (!component.attribute_exists(attribute_name)) { params.error_message_add(NodeWarningType::Error, TIP_("No attribute with name \"") + attribute_name + "\""); return; } const NodeAttributeClamp &storage = *(const NodeAttributeClamp *)params.node().storage; const CustomDataType data_type = static_cast(storage.data_type); const AttributeDomain domain = get_result_domain(component, attribute_name, result_name); const int operation = static_cast(storage.operation); ReadAttributePtr attribute_input = component.attribute_try_get_for_read( attribute_name, domain, data_type); OutputAttributePtr attribute_result = component.attribute_try_get_for_output( result_name, domain, data_type); if (!attribute_result) { params.error_message_add(NodeWarningType::Error, TIP_("Could not find or create attribute with name \"") + result_name + "\""); return; } switch (data_type) { case CD_PROP_FLOAT3: { Span read_span = attribute_input->get_span(); MutableSpan span = attribute_result->get_span_for_write_only(); float3 min = params.get_input("Min"); float3 max = params.get_input("Max"); if (operation == NODE_CLAMP_RANGE) { if (min.x > max.x) { std::swap(min.x, max.x); } if (min.y > max.y) { std::swap(min.y, max.y); } if (min.z > max.z) { std::swap(min.z, max.z); } } clamp_attribute(read_span, span, min, max); break; } case CD_PROP_FLOAT: { Span read_span = attribute_input->get_span(); MutableSpan span = attribute_result->get_span_for_write_only(); const float min = params.get_input("Min_001"); const float max = params.get_input("Max_001"); if (operation == NODE_CLAMP_RANGE && min > max) { clamp_attribute(read_span, span, max, min); } else { clamp_attribute(read_span, span, min, max); } break; } case CD_PROP_INT32: { Span read_span = attribute_input->get_span(); MutableSpan span = attribute_result->get_span_for_write_only(); const int min = params.get_input("Min_002"); const int max = params.get_input("Max_002"); if (operation == NODE_CLAMP_RANGE && min > max) { clamp_attribute(read_span, span, max, min); } else { clamp_attribute(read_span, span, min, max); } break; } case CD_PROP_COLOR: { Span read_span = attribute_input->get_span(); MutableSpan span = attribute_result->get_span_for_write_only(); Color4f min = params.get_input("Min_003"); Color4f max = params.get_input("Max_003"); if (operation == NODE_CLAMP_RANGE) { if (min.r > max.r) { std::swap(min.r, max.r); } if (min.g > max.g) { std::swap(min.g, max.g); } if (min.b > max.b) { std::swap(min.b, max.b); } if (min.a > max.a) { std::swap(min.a, max.a); } } clamp_attribute(read_span, span, min, max); break; } default: { BLI_assert(false); break; } } attribute_result.apply_span_and_save(); } static void geo_node_attribute_clamp_exec(GeoNodeExecParams params) { GeometrySet geometry_set = params.extract_input("Geometry"); geometry_set = geometry_set_realize_instances(geometry_set); if (geometry_set.has()) { clamp_attribute(geometry_set.get_component_for_write(), params); } if (geometry_set.has()) { clamp_attribute(geometry_set.get_component_for_write(), params); } params.set_output("Geometry", geometry_set); } } // namespace blender::nodes void register_node_type_geo_attribute_clamp() { static bNodeType ntype; geo_node_type_base(&ntype, GEO_NODE_ATTRIBUTE_CLAMP, "Attribute Clamp", NODE_CLASS_ATTRIBUTE, 0); node_type_socket_templates(&ntype, geo_node_attribute_clamp_in, geo_node_attribute_clamp_out); node_type_init(&ntype, geo_node_attribute_clamp_init); node_type_update(&ntype, geo_node_attribute_clamp_update); ntype.geometry_node_execute = blender::nodes::geo_node_attribute_clamp_exec; ntype.draw_buttons = geo_node_attribute_clamp_layout; node_type_storage( &ntype, "NodeAttributeClamp", node_free_standard_storage, node_copy_standard_storage); nodeRegisterType(&ntype); } // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "stdafx.h" #include "logger.h" #include #include #include #include #include namespace signalr { #ifdef WIN32 #define GMTIME(r_tm, r_time_t) gmtime_s(r_tm, r_time_t) #else #define GMTIME(r_tm, r_time_t) gmtime_r(r_time_t, r_tm) #endif logger::logger(const std::shared_ptr& log_writer, trace_level trace_level) noexcept : m_log_writer(log_writer), m_trace_level(trace_level) { } void logger::log(trace_level level, const std::string& entry) const { log(level, entry.data(), entry.length()); } void logger::log(trace_level level, const char* entry, size_t entry_count) const { if (level >= m_trace_level && m_log_writer) { try { std::chrono::milliseconds milliseconds = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); std::chrono::seconds seconds = std::chrono::duration_cast(milliseconds); milliseconds = std::chrono::duration_cast(milliseconds - seconds); time_t t = seconds.count(); tm time; // convert time to utc GMTIME(&time, &t); char timeString[sizeof("2019-11-23T13:23:02.000Z")]; // format string to ISO8601 with additional space for 3 digits of millisecond precision std::strftime(timeString, sizeof(timeString), "%FT%T.000Z", &time); // add millisecond part // 5 = 3 digits of millisecond precision + 'Z' + null character ending snprintf(timeString + sizeof(timeString) - 5, 5, "%03dZ", (int)milliseconds.count()); std::stringstream os; os << timeString; write_trace_level(level, os); os.write(entry, (std::streamsize)entry_count) << std::endl; m_log_writer->write(os.str()); } catch (const std::exception &e) { std::cerr << "error occurred when logging: " << e.what() << std::endl << " entry: " << entry << std::endl; } catch (...) { std::cerr << "unknown error occurred when logging" << std::endl << " entry: " << entry << std::endl; } } } void logger::write_trace_level(trace_level trace_level, std::ostream& stream) { switch (trace_level) { case signalr::trace_level::verbose: stream << " [verbose ] "; break; case signalr::trace_level::debug: stream << " [debug ] "; break; case signalr::trace_level::info: stream << " [info ] "; break; case signalr::trace_level::warning: stream << " [warning ] "; break; case signalr::trace_level::error: stream << " [error ] "; break; case signalr::trace_level::critical: stream << " [critical ] "; break; case signalr::trace_level::none: stream << " [none ] "; break; default: assert(false); stream << " [(unknown)] "; break; } } } #ifndef RESOURCE_IDENTIFIERS_HPP #define RESOURCE_IDENTIFIERS_HPP #include #include namespace sf { class Texture; class Font; class SoundBuffer; } namespace Textures { enum ID { WALL, BREAKABLE, BALLOON_0, BALLOON_1, BALLOON_2, SUPER_BALLOON_0, SUPER_BALLOON_1, SUPER_BALLOON_2, C_BALLOON_0, C_BALLOON_1, C_BALLOON_2, C_SUPER_BALLOON_0, C_SUPER_BALLOON_1, C_SUPER_BALLOON_2, PLAYER_ONE, PLAYER_TWO, PLAYER_THREE, PLAYER_FOUR, C_PLAYER_ONE, C_PLAYER_TWO, C_PLAYER_THREE, C_PLAYER_FOUR, SPLOSION_PLUS, SPLOSION_VERT, SPLOSION_HORIZ, BALLOON_UP_0, BALLOON_UP_1, BALLOON_UP_2, RANGE_UP_0, RANGE_UP_1, RANGE_UP_2, SPEED_UP_0, SPEED_UP_1, SPEED_UP_2, KICK_UPGRADE_0, KICK_UPGRADE_1, KICK_UPGRADE_2, RCONTROL_UPGRADE_0, RCONTROL_UPGRADE_1, RCONTROL_UPGRADE_2, SBALLOON_UPGRADE_0, SBALLOON_UPGRADE_1, SBALLOON_UPGRADE_2, PIERCE_UPGRADE_0, PIERCE_UPGRADE_1, PIERCE_UPGRADE_2, SPREAD_UPGRADE_0, SPREAD_UPGRADE_1, SPREAD_UPGRADE_2, GHOST_UPGRADE_0, GHOST_UPGRADE_1, GHOST_UPGRADE_2 }; } namespace Fonts { enum ID { CLEAR_SANS }; } namespace Music { enum ID { }; } namespace Sound { enum ID { BREAKABLE, COUNTDOWN_0, COUNTDOWN_1, DEATH, KICK, SPLOSION, POWERUP, TRY_AGAIN_TUNE, VICTORY_TUNE }; } namespace GameResources { enum LoadingMode { DEFAULT, PACKFILE }; } template class ResourceHolder; typedef ResourceHolder TextureHolder; typedef ResourceHolder FontHolder; typedef ResourceHolder SoundBufferHolder; typedef std::set TextureSet; typedef std::set FontSet; typedef std::set SoundSet; struct ResourcesSet { ResourcesSet(); ResourcesSet(TextureSet& tset, FontSet& fset, SoundSet& sset); TextureSet* tset; FontSet* fset; SoundSet* sset; }; #endif #include "ScreenQuad.h" namespace GameEngine { ScreenQuad::ScreenQuad() { } ScreenQuad::~ScreenQuad() { Dispose(); } void ScreenQuad::Init() { if (m_VAO == 0) { glGenVertexArrays(1, &m_VAO); } if (m_VBO == 0) { glGenBuffers(1, &m_VBO); } if (m_EBO == 0) { glGenBuffers(1, &m_EBO); } GLfloat vertices[] = { // Positions // TexCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), nullptr, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), &vertices[0]); //Upload the position and uv as 1 attribute (vec4) to send all the data in 1 go to the postprocess shader glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glBindVertexArray(0); } void ScreenQuad::Dispose() { //delete the vao's and vbo's and reset them to 0 if (m_VAO != 0) { glDeleteVertexArrays(1, &m_VAO); m_VAO = 0; } if (m_VBO != 0) { glDeleteBuffers(1, &m_VBO); m_VBO = 0; } if (m_EBO != 0) { glDeleteBuffers(1, &m_EBO); m_EBO = 0; } } void ScreenQuad::Render(GLuint _textureID) { glBindVertexArray(m_VAO); /*glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _textureID);*/ glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); } } /* g++ --std=c++20 -pthread -o ../_build/cpp/language_operator_logical.exe ./cpp/language_operator_logical.cpp && (cd ../_build/cpp/;echo quit | ./language_operator_logical.exe) https://en.cppreference.com/w/cpp/language/operator_logical */ #include #include int main() { int n = 2; int* p = &n; // pointers are convertible to bool if( p && *p == 2 // "*p" is safe to use after "p &&" || !p && n != 2 ) // || has lower precedence than && std::cout << "true\n"; // streams are also convertible to bool std::cout << "Enter 'quit' to quit.\n"; for(std::string line; std::cout << "> " && std::getline(std::cin, line) && line != "quit"; ) ; } /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // // <> // // // modified 10/08/15 by <> // #include "AliLog.h" #include "AliTRDdEdxParams.h" ClassImp(AliTRDdEdxParams); AliTRDdEdxParams::AliTRDdEdxParams(const TString name, const TString title): TNamed(name,title) { // //constructor // } Int_t AliTRDdEdxParams::GetIter(const Int_t itype, const Int_t nch, const Int_t ncls, const Bool_t etaCorrection) const { // //return array iterator // Int_t itNch = -999, itNcls = -999, itEtaCorr = -999; //hard coded cuts // <4, 4, 5 or 6 layer if (nch == 6) { itNch = 0; } else if (nch == 5) { itNch = 1; } else if (nch == 4) { itNch = 2; } else if (nch < 4){ itNch = 3; } if (nch != 0 && ncls/nch >= 17) { // QA cut minimum ncls itNcls = 0; } else { itNcls = 1; } if (etaCorrection) { // eta correction itEtaCorr = 0; } else { itEtaCorr = 1; } const Int_t finaliter = itEtaCorr*80 + itNcls*40 + itNch*10 + itype; if (finaliter < 0 || finaliter >= MAXSIZE) { AliError(Form("out of range itype %d, nch %d, ncls %d\n", itype, nch, ncls)); } return finaliter; } const TVectorF& AliTRDdEdxParams::GetParameter(const TVectorF par[], const Int_t itype, const Int_t nch, const Int_t ncls, const Bool_t etaCorrection)const { // //return parameter for particle itype from par[] // const Int_t iter = GetIter(itype, nch, ncls, etaCorrection); return par[iter]; } void AliTRDdEdxParams::SetParameter(TVectorF par[], const Int_t itype, const Int_t nch, const Int_t ncls, const Int_t npar, const Float_t vals[], const Bool_t etaCorrection) { // //set parameter, vals of dimension npar, for particle itype // const Int_t iter = GetIter(itype, nch, ncls, etaCorrection); TVectorF p2(npar, vals); par[iter].ResizeTo(p2); par[iter] = p2; } void AliTRDdEdxParams::Print(Option_t* option) const { // //print all members // TObject::Print(option); printf("\n======================= Mean ========================\n"); for(Int_t ii = 0; ii < MAXSIZE; ii++){ printf("%d: Nrows() %d\n",ii, fMeanPar[ii].GetNrows()); if(fMeanPar[ii].GetNrows()) fMeanPar[ii].Print(); } printf("\n======================= Sigma ========================\n"); for(Int_t ii = 0; ii < MAXSIZE; ii++){ printf("%d: Nrows() %d\n",ii, fSigmaPar[ii].GetNrows()); if(fSigmaPar[ii].GetNrows()) fSigmaPar[ii].Print(); } printf("AliTRDdEdxParams::Print done.\n\n"); } #include using namespace std; void insert(int *array, int element, int size) { for (int i = size; i > 0; --i) { int *temp = array; cout << *array << endl; --array; if (*array > element) { *temp = *array; } else { *temp = element; break; } } } int main(int argc, char const *argv[]) { int array[] = {1, 2, 3, 5, 6, 7, 8, 9, 10, 0}; int element = 4; int size = 10; insert(&array[9], element, size); for (int i : array) { cout << i << " "; } cout << endl; return 0; }#pragma once #include "seqdb-3/sequence.hh" namespace acmacs::seqdb::inline v3 { enum class hamming_distance_by_shortest { no, yes }; template inline dist_t hamming_distance(std::string_view s1, std::string_view s2, hamming_distance_by_shortest shortest = hamming_distance_by_shortest::no) { auto f1 = std::begin(s1); auto f2 = std::begin(s2); dist_t dist = 0; for (; f1 != std::end(s1) && f2 != std::end(s2); ++f1, ++f2) { if (*f1 != *f2) ++dist; } if (shortest == hamming_distance_by_shortest::no) dist += static_cast(std::end(s1) - f1) + static_cast(std::end(s2) - f2); return dist; } inline size_t hamming_distance(sequence_aligned_ref_t s1, sequence_aligned_ref_t s2) { return hamming_distance(*s1, *s2); } inline size_t hamming_distance(sequence_with_alignment_ref_t s1, sequence_with_alignment_ref_t s2) { return hamming_distance(s1.aligned(), s2.aligned()); } } // namespace acmacs::seqdb::inlinev3 // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: #include "Set.hpp" #include #include #include #include #include #include #include namespace SetReplace { class Set::Implementation { private: // Rules fundamentally cannot be changed during evaluation, don't try to remove const. // If rules do need to be changed, create another instance of Set and copy the expressions over. const std::vector rules_; // Determines the limiting conditions for the evaluation. StepSpecification stepSpec_; TerminationReason terminationReason_ = TerminationReason::NotTerminated; std::unordered_map expressions_; std::vector eventRuleIDs_ = {-1}; Atom nextAtom_ = 1; ExpressionID nextExpressionID_ = 0; int64_t destroyedExpressionsCount_ = 0; // In another words, expressions counts by atom. // Note, we cannot use atomsIndex_, because it does not keep last generation expressions. std::unordered_map atomDegrees_; // Largest generation produced so far. // Note, this is not the same as max of generations of all expressions, // because there might exist an event that deletes expressions, but does not create any new ones. Generation largestGeneration_ = 0; AtomsIndex atomsIndex_; Matcher matcher_; std::vector unindexedExpressions_; public: Implementation(const std::vector& rules, const std::vector& initialExpressions, const Matcher::OrderingSpec& orderingSpec, const unsigned int randomSeed) : Implementation(rules, initialExpressions, orderingSpec, randomSeed, [this](const int64_t expressionID) { return expressions_.at(expressionID).atoms; }) {} int64_t replaceOnce(const std::function shouldAbort) { terminationReason_ = TerminationReason::NotTerminated; if (eventRuleIDs_.size() > static_cast(stepSpec_.maxEvents)) { terminationReason_ = TerminationReason::MaxEvents; return 0; } indexNewExpressions([this, &shouldAbort]() { const bool isAborted = shouldAbort(); if (isAborted) terminationReason_ = TerminationReason::Aborted; return isAborted; }); if (matcher_.empty()) { if (largestGeneration_ == stepSpec_.maxGenerationsLocal) { terminationReason_ = TerminationReason::MaxGenerationsLocal; } else { terminationReason_ = TerminationReason::FixedPoint; } return 0; } const MatchPtr match = matcher_.nextMatch(); const auto& ruleInputs = rules_[match->rule].inputs; std::vector inputExpressions; inputExpressions.reserve(match->inputExpressions.size()); for (const auto& expressionID : match->inputExpressions) { inputExpressions.emplace_back(expressions_.at(expressionID).atoms); } auto explicitRuleInputs = ruleInputs; Matcher::substituteMissingAtomsIfPossible(ruleInputs, inputExpressions, &explicitRuleInputs); // Identify output atoms that appear in the input, that still leaves newly created atoms as patterns. auto explicitRuleOutputs = rules_[match->rule].outputs; Matcher::substituteMissingAtomsIfPossible(ruleInputs, inputExpressions, &explicitRuleOutputs); for (const auto function : {&Implementation::willExceedAtomLimits, &Implementation::willExceedExpressionsLimit}) { const auto willExceedAtomLimitsStatus = (this->*function)(explicitRuleInputs, explicitRuleOutputs); if (willExceedAtomLimitsStatus != TerminationReason::NotTerminated) { terminationReason_ = willExceedAtomLimitsStatus; return 0; } } // At this point, we are committed to modifying the set. // Name newly created atoms as well, now all atoms in the output are explicitly named. const auto namedRuleOutputs = nameAnonymousAtoms(explicitRuleOutputs); matcher_.removeMatchesInvolvingExpressions(match->inputExpressions); atomsIndex_.removeExpressions(match->inputExpressions); Generation outputGeneration = 0; for (const auto& inputExpression : match->inputExpressions) { outputGeneration = std::max(outputGeneration, expressions_[inputExpression].generation + 1); } largestGeneration_ = std::max(largestGeneration_, outputGeneration); const EventID eventID = static_cast(eventRuleIDs_.size()); addExpressions(namedRuleOutputs, eventID, outputGeneration); assignDestroyerEvent(match->inputExpressions, eventID); eventRuleIDs_.push_back(match->rule); return 1; } int64_t replace(const StepSpecification stepSpec, const std::function& shouldAbort) { updateStepSpec(stepSpec); int64_t count = 0; while (true) { if (replaceOnce(shouldAbort)) { ++count; } else { return count; } } } std::vector expressions() const { std::vector> idsAndExpressions(expressions_.begin(), expressions_.end()); std::sort(idsAndExpressions.begin(), idsAndExpressions.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); std::vector result; result.reserve(idsAndExpressions.size()); for (const auto& idAndExpression : idsAndExpressions) { result.emplace_back(idAndExpression.second); } return result; } Generation maxCompleteGeneration(const std::function& shouldAbort) { indexNewExpressions(shouldAbort); return std::min(smallestGeneration(matcher_.allMatches()), largestGeneration_); } TerminationReason terminationReason() const { return terminationReason_; } const std::vector& eventRuleIDs() const { return eventRuleIDs_; } private: Implementation(std::vector rules, const std::vector& initialExpressions, const Matcher::OrderingSpec& orderingSpec, const unsigned int randomSeed, const std::function& getAtomsVector) : rules_(std::move(rules)), atomsIndex_(getAtomsVector), matcher_(rules_, &atomsIndex_, getAtomsVector, orderingSpec, randomSeed) { for (const auto& expression : initialExpressions) { for (const auto& atom : expression) { if (atom <= 0) throw Error::NonPositiveAtoms; nextAtom_ = std::max(nextAtom_ - 1, atom); incrementNextAtom(); } } addExpressions(initialExpressions, initialConditionEvent, initialGeneration); } Atom incrementNextAtom() { if (nextAtom_ == std::numeric_limits::max()) { throw Error::AtomCountOverflow; } return ++nextAtom_; } void updateStepSpec(const StepSpecification newStepSpec) { const auto previousMaxGeneration = stepSpec_.maxGenerationsLocal; stepSpec_ = newStepSpec; if (newStepSpec.maxGenerationsLocal > previousMaxGeneration) { for (const auto& idAndExpression : expressions_) { if (idAndExpression.second.generation == previousMaxGeneration) { unindexedExpressions_.push_back(idAndExpression.first); } } } } void indexNewExpressions(const std::function& shouldAbort) { // Atoms index must be updated first, because the matcher uses it to discover expressions. atomsIndex_.addExpressions(unindexedExpressions_); matcher_.addMatchesInvolvingExpressions(unindexedExpressions_, shouldAbort); unindexedExpressions_.clear(); } TerminationReason willExceedAtomLimits(const std::vector& explicitRuleInputs, const std::vector& explicitRuleOutputs) const { const int64_t currentAtomsCount = static_cast(atomDegrees_.size()); std::unordered_map atomDegreeDeltas; updateAtomDegrees(&atomDegreeDeltas, explicitRuleInputs, -1, false); updateAtomDegrees(&atomDegreeDeltas, explicitRuleOutputs, +1, false); int64_t newAtomsCount = currentAtomsCount; for (const auto& atomAndDegreeDelta : atomDegreeDeltas) { const Atom atom = atomAndDegreeDelta.first; const int64_t degreeDelta = atomAndDegreeDelta.second; const int64_t currentDegree = static_cast(atomDegrees_.count(atom)) ? atomDegrees_.at(atom) : 0; if (currentDegree == 0 && degreeDelta > 0) { ++newAtomsCount; } else if (currentDegree > 0 && currentDegree + degreeDelta == 0) { --newAtomsCount; } // Check atom degree. if (currentDegree + degreeDelta > stepSpec_.maxFinalAtomDegree) { return TerminationReason::MaxFinalAtomDegree; } } if (newAtomsCount > stepSpec_.maxFinalAtoms) { return TerminationReason::MaxFinalAtoms; } else { return TerminationReason::NotTerminated; } } static void updateAtomDegrees(std::unordered_map* atomDegrees, const std::vector& deltaExpressions, const int64_t deltaCount, bool deleteIfZero = true) { for (const auto& expression : deltaExpressions) { const std::unordered_set expressionAtoms(expression.begin(), expression.end()); for (const auto& atom : expressionAtoms) { (*atomDegrees)[atom] += deltaCount; if (deleteIfZero && (*atomDegrees)[atom] == 0) { atomDegrees->erase(atom); } } } } TerminationReason willExceedExpressionsLimit(const std::vector& explicitRuleInputs, const std::vector& explicitRuleOutputs) const { const int64_t currentExpressionsCount = nextExpressionID_ - destroyedExpressionsCount_; const int64_t newExpressionsCount = currentExpressionsCount - static_cast(explicitRuleInputs.size()) + static_cast(explicitRuleOutputs.size()); if (newExpressionsCount > stepSpec_.maxFinalExpressions) { return TerminationReason::MaxFinalExpressions; } else { return TerminationReason::NotTerminated; } } std::vector nameAnonymousAtoms(const std::vector& atomVectors) { std::unordered_map names; std::vector result = atomVectors; for (auto& expression : result) { for (auto& atom : expression) { if (atom < 0 && names.count(atom) == 0) { names[atom] = incrementNextAtom(); } if (atom < 0) { atom = names[atom]; } } } return result; } std::vector addExpressions(const std::vector& expressions, const EventID creatorEvent, const Generation generation) { auto ids = assignExpressionIDs(expressions, creatorEvent, generation); // If generation is at least maxGeneration_, we will never use these expressions as inputs, so no need adding them // to the index. if (generation < stepSpec_.maxGenerationsLocal) { unindexedExpressions_.insert(unindexedExpressions_.end(), ids.begin(), ids.end()); } updateAtomDegrees(&atomDegrees_, expressions, +1); return ids; } std::vector assignExpressionIDs(const std::vector& expressions, const EventID creatorEvent, const Generation generation) { std::vector ids; ids.reserve(expressions.size()); for (const auto& expression : expressions) { ids.push_back(nextExpressionID_); expressions_.insert( std::make_pair(nextExpressionID_++, SetExpression{expression, creatorEvent, finalStateEvent, generation})); } return ids; } void assignDestroyerEvent(const std::vector& expressions, const EventID destroyerEvent) { for (const auto id : expressions) { if (expressions_.at(id).destroyerEvent == finalStateEvent) { ++destroyedExpressionsCount_; } expressions_.at(id).destroyerEvent = destroyerEvent; } updateAtomDegrees(&atomDegrees_, expressions, -1); } void updateAtomDegrees(std::unordered_map* atomDegrees, const std::vector& deltaExpressionIDs, const int64_t deltaCount) const { std::vector expressions; expressions.reserve(deltaExpressionIDs.size()); for (const auto id : deltaExpressionIDs) { expressions.emplace_back(expressions_.at(id).atoms); } updateAtomDegrees(atomDegrees, expressions, deltaCount); } Generation smallestGeneration(const std::vector& matches) const { Generation smallestSoFar = std::numeric_limits::max(); for (const auto& match : matches) { Generation largestForTheMatch = 0; for (const ExpressionID id : match->inputExpressions) { largestForTheMatch = std::max(largestForTheMatch, expressions_.at(id).generation); } smallestSoFar = std::min(smallestSoFar, largestForTheMatch); } return smallestSoFar; } }; Set::Set(const std::vector& rules, const std::vector& initialExpressions, const Matcher::OrderingSpec& orderingSpec, unsigned int randomSeed) : implementation_(std::make_shared(rules, initialExpressions, orderingSpec, randomSeed)) {} int64_t Set::replaceOnce(const std::function& shouldAbort) { return implementation_->replaceOnce(shouldAbort); } int64_t Set::replace(const StepSpecification& stepSpec, const std::function& shouldAbort) { return implementation_->replace(stepSpec, shouldAbort); } std::vector Set::expressions() const { return implementation_->expressions(); } Generation Set::maxCompleteGeneration(const std::function& shouldAbort) { return implementation_->maxCompleteGeneration(shouldAbort); } Set::TerminationReason Set::terminationReason() const { return implementation_->terminationReason(); } const std::vector& Set::eventRuleIDs() const { return implementation_->eventRuleIDs(); } } // namespace SetReplace 0 //===================== PRJ ===================== #include "player.h" //===================== SDK ===================== #include #include "mpp_mem.h" #include "system_opt.h" #include "ini_wrapper.h" #include "frame_queue.h" #include "endeCode_api.h" #include "disp.h" /* flip source image horizontally (around the vertical axis) */ #define HAL_TRANSFORM_FLIP_H 0x01 /* flip source image vertically (around the horizontal axis)*/ #define HAL_TRANSFORM_FLIP_V 0x02 /* rotate source image 0 degrees clockwise */ #define HAL_TRANSFORM_ROT_0 0x00 /* rotate source image 90 degrees clockwise */ #define HAL_TRANSFORM_ROT_90 0x04 /* rotate source image 180 degrees */ #define HAL_TRANSFORM_ROT_180 0x03 /* rotate source image 270 degrees clockwise */ #define HAL_TRANSFORM_ROT_270 0x07 /* decoder output width & height */ #define FRAME_WIDTH 1280 #define FRAME_HEIGHT 720 typedef struct{ Player *pSelf; }Player_para_t; void *cruiseCtrl_thread(void *para) { // 播放器对象 Player_para_t *pPlayerPara = (Player_para_t *)para; Player *pSelf = pPlayerPara->pSelf; // 本线程的控制参数 int cout = 1; uint32_t chnId = 0; while(1){ if(NULL == pSelf){ msleep(5); break; } /* 说明: * if(exeAtStart == (count%TimeInterval)) * exeAtStart: 是否在线程启动时执行。[0]-初次启动不执行,[n]-在第一个周期内的第n个单位时间执行 * TimeInterval: 一个周期包含的时间单位 */ if(1 == (cout%(5*100))){ //5s执行, 且启动时执行 pSelf->setPlayingChn(chnId); } if(0 == (cout%(5*100))){ //5s执行, 且启动时不执行 chnId++; chnId %= pSelf->maxChnNum(); } if(1 == (cout%4)){ //40ms执行, 且启动时执行 //pSelf->displayAllChn(); pSelf->displayCurChn(); } // 计时操作 cout++; cout %= 50000; // 时间单位:10ms usleep(10*1000); } if(pPlayerPara){ free(pPlayerPara); pPlayerPara = NULL; } pthread_exit(NULL); } static int32_t VideoPlayerHandle(void *pPlayer, VideoFrameData *pData) { static uint64_t preTime[MAX_CHN_NUM] = {0}; uint64_t curTime = 0; if(NULL == pPlayer){ return -1; } curTime = get_timeval_us(); if((0 != pData->err_info) || (0 != pData->discard)){ printf("[output] chn %02d ----- errinfo : %u discard : %u\n", pData->channel, pData->err_info, pData->discard); } #if 0 // 过滤 if(0/*[Chn 0]*/ == pData->channel){ //printf("chn[%02d] --- curTime = %llu us, preTime = %llu us, cha = %llu us\n", pData->channel, curTime, preTime, curTime - preTime); if(curTime - preTime[pData->channel] >= 1000000/* 每1s一张 */){ preTime[pData->channel] = curTime; }else{ return 0; } }else if(1/*[Chn 1]*/ == pData->channel){ if(curTime - preTime[pData->channel] >= 500000/* 每500ms一张 */){ preTime[pData->channel] = curTime; }else{ return 0; } }else if(2/*[Chn 2]*/ == pData->channel){ if(curTime - preTime[pData->channel] >= 150000/* 每1.5ms一张 */){ preTime[pData->channel] = curTime; }else{ return 0; } }else if(3/*[Chn 3]*/ == pData->channel){ if(curTime - preTime[pData->channel] >= 70000/* 每700ms一张 */){ preTime[pData->channel] = curTime; }else{ return 0; } } #endif #if 1 // 数帧 -- Debug用 static int frameCount[MAX_CHN_NUM] = {0}; if(curTime - preTime[pData->channel] >= 1000000){ preTime[pData->channel] = curTime; if(frameCount[pData->channel] < 20){ printf("[Chn][%02d] frame count = %d\n", pData->channel, frameCount[pData->channel]); } frameCount[pData->channel] = 0; }else{ frameCount[pData->channel]++; //printf("[Chn][%02d] --- timestamp = %llu.%03llu ms\n", pData->channel, curTime/1000, curTime%1000); } #endif Player *pSelf = (Player *)pPlayer; if(NULL == pSelf){ return -1; } if((0 == pData->err_info) && (0 == pData->discard)){ RgaSURF_FORMAT vFmt = RK_FORMAT_YCbCr_420_SP; pSelf->makeCamImg(pData->channel, pData->pBuf, vFmt, pData->width, pData->height, pData->hor_stride, pData->ver_stride); } return 0; } typedef struct { RgaSURF_FORMAT fmt; int width; int height; int hor_stride; int ver_stride; int rotation; void *pBuf; }Image; static int srcImg_ConvertTo_dstImg(Image *pDst, Image *pSrc) { rga_info_t src, dst; int ret = -1; if (!pSrc || !pDst) { printf("%s: NULL PTR!\n", __func__); return -1; } //图像参数转换 memset(&src, 0, sizeof(rga_info_t)); src.fd = -1; src.virAddr = pSrc->pBuf; src.mmuFlag = 1; src.rotation = pSrc->rotation; rga_set_rect(&src.rect, 0, 0, pSrc->width, pSrc->height, pSrc->hor_stride, pSrc->ver_stride, pSrc->fmt); memset(&dst, 0, sizeof(rga_info_t)); dst.fd = -1; dst.virAddr = pDst->pBuf; dst.mmuFlag = 1; dst.rotation = pDst->rotation; rga_set_rect(&dst.rect, 0, 0, pDst->width, pDst->height, pDst->hor_stride, pDst->ver_stride, pDst->fmt); if (c_RkRgaBlit(&src, &dst, NULL)) { printf("%s: rga fail\n", __func__); ret = -1; } else { ret = 0; } return ret; } #define SCREEN_WIDTH 720 #define SCREEN_HEIGHT 1280 Player::Player(int iChnNum) : mChnannelNumber(iChnNum), mPlayingChnId(0), bObjIsInited(0) { // ===================== 1.初始化显示资源 ===================== // 1.1-图像缓存初始化,以及结果数组初始化 for(int i = 0; i < mChnannelNumber; i++){ camImg[i] = Mat(FRAME_HEIGHT, FRAME_WIDTH, CV_8UC3); } // 1.2-读写锁初始化 for(int i = 0; i < mChnannelNumber; i++){ pthread_rwlock_init(&camImglock[i], NULL); } // ======================== 2.初始化显示屏 ======================== init(); // ======================== 3.初始化解码器 ======================== // 3.1-创建解码器 create_decoder(mChnannelNumber); // 3.2-初始化解码通道资源 for(int i = 0; i < mChnannelNumber; i++){ mChannelId[i] = 0; } // 3.3-向解码器申请解码通道 for(int i = 0; i < mChnannelNumber; i++){ if(0 == create_decMedia_channel(&mChannelId[i])){ //printf("============= [%d]time ==============\n", i); printf("create channel OK, chn = %u\n", mChannelId[i]); // 3.4-往成功申请的通道绑定解码输出处理函数 if(0 == mChannelId[i]){ set_decMedia_channel_callback(mChannelId[i], VideoPlayerHandle, this); }else if (1 == mChannelId[i]){ set_decMedia_channel_callback(mChannelId[i], VideoPlayerHandle, this); }else if (2 == mChannelId[i]){ set_decMedia_channel_callback(mChannelId[i], VideoPlayerHandle, this); }else if (3 == mChannelId[i]){ set_decMedia_channel_callback(mChannelId[i], VideoPlayerHandle, this); } } } // ======================= 4.初始化处理线程 ======================= Player_para_t *pPlayer = (Player_para_t *)malloc(sizeof(Player_para_t)); pPlayer->pSelf = this; // 4.1-初始化轮询线程 if(0 != CreateNormalThread(cruiseCtrl_thread, pPlayer, &mTid)){ free(pPlayer); } } Player::~Player() { int i; for(i = 0; mChnannelNumber < 1; i++){ close_decMedia_channel(mChannelId[i]); } deInit(); } void Player::init() { if(0 == disp_init(SCREEN_WIDTH, SCREEN_HEIGHT)){ bObjIsInited = 1; }else{ bObjIsInited = 0; } } void Player::deInit() { if(IsInited()){ disp_exit(); } } void Player::displayAllChn() { } void Player::displayCurChn() { Mat image; // 图像转换并输出 Image srcImage, dstImage; memset(&srcImage, 0, sizeof(srcImage)); memset(&dstImage, 0, sizeof(dstImage)); if(IsInited()){ image = camImg[mPlayingChnId]; srcImage.fmt = RK_FORMAT_RGB_888; srcImage.width = image.cols; srcImage.height = image.rows; srcImage.hor_stride = srcImage.width; srcImage.ver_stride = srcImage.height; srcImage.rotation = HAL_TRANSFORM_ROT_270; srcImage.pBuf = image.data; dstImage.fmt = RK_FORMAT_RGB_888; dstImage.width = SCREEN_WIDTH; dstImage.height = SCREEN_HEIGHT; dstImage.hor_stride = dstImage.width; dstImage.ver_stride = dstImage.height; dstImage.rotation = HAL_TRANSFORM_ROT_0; dstImage.pBuf = mpp_malloc(char, dstImage.width*dstImage.height*3); if(NULL == dstImage.pBuf){ return; } pthread_rwlock_rdlock(&camImglock[mPlayingChnId]); srcImg_ConvertTo_dstImg(&dstImage, &srcImage); pthread_rwlock_unlock(&camImglock[mPlayingChnId]); disp_commit(dstImage.pBuf, dstImage.width*dstImage.height*3); mpp_free(dstImage.pBuf); } } void Player::makeCamImg(int32_t chn, void *ptr, int vFmt, int w, int h, int hS, int vS) { Mat image; Image srcImage, dstImage; memset(&srcImage, 0, sizeof(srcImage)); memset(&dstImage, 0, sizeof(dstImage)); srcImage.fmt = (RgaSURF_FORMAT)vFmt; srcImage.width = w; srcImage.height = h; srcImage.hor_stride = hS; srcImage.ver_stride = vS; srcImage.rotation = HAL_TRANSFORM_ROT_0; srcImage.pBuf = ptr; dstImage.fmt = RK_FORMAT_RGB_888; dstImage.width = camImg[chn].cols; dstImage.height = camImg[chn].rows; dstImage.hor_stride = dstImage.width; dstImage.ver_stride = dstImage.height; dstImage.rotation = HAL_TRANSFORM_ROT_0; dstImage.pBuf = camImg[chn].data; pthread_rwlock_wrlock(&camImglock[chn]); srcImg_ConvertTo_dstImg(&dstImage, &srcImage); pthread_rwlock_unlock(&camImglock[chn]); return ; } int playerInit() { int ret = -1; int chnNum = 0; Player *pPlayer = NULL; if(0 == ini_read_int(RTSP_CLIENT_PATH, "configInfo", "enableChnNum", &chnNum)) { pPlayer = new Player(chnNum); if(NULL == pPlayer){ printf("Player Create faild !!!\n"); }else{ ret = 0; } } if(-1 == ret) return ret; while(1) { sleep(5); } } #include #include TEST(MathMatrix, log_deterimant_ldlt) { using stan::math::determinant; using std::log; using std::fabs; stan::math::matrix_d x(2,2); stan::math::LDLT_factor ldlt_x; x << 2, 1, 1, 3; ldlt_x.compute(x); ASSERT_TRUE(ldlt_x.success()); EXPECT_FLOAT_EQ(log(fabs(determinant(x))), stan::math::log_determinant_ldlt(ldlt_x)); x << 1, 0, 0, 3; ldlt_x.compute(x); ASSERT_TRUE(ldlt_x.success()); EXPECT_FLOAT_EQ(log(3.0), stan::math::log_determinant_ldlt(ldlt_x)); } services/proxy_resolver_win/winhttp_proxy_resolver_functions.cc // Copyright 2020 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 "services/proxy_resolver_win/winhttp_proxy_resolver_functions.h" namespace proxy_resolver_win { WinHttpProxyResolverFunctions::WinHttpProxyResolverFunctions() { HMODULE winhttp_module = LoadLibraryEx(L"winhttp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (winhttp_module) { create_proxy_resolver = reinterpret_cast( ::GetProcAddress(winhttp_module, "WinHttpCreateProxyResolver")); get_proxy_for_url_ex = reinterpret_cast( ::GetProcAddress(winhttp_module, "WinHttpGetProxyForUrlEx")); get_proxy_result = reinterpret_cast( ::GetProcAddress(winhttp_module, "WinHttpGetProxyResult")); free_proxy_result = reinterpret_cast( ::GetProcAddress(winhttp_module, "WinHttpFreeProxyResult")); } } // Never called due to base::NoDestructor. WinHttpProxyResolverFunctions::~WinHttpProxyResolverFunctions() = default; bool WinHttpProxyResolverFunctions::are_all_functions_loaded() const { return create_proxy_resolver && get_proxy_for_url_ex && get_proxy_result && free_proxy_result; } // static const WinHttpProxyResolverFunctions& WinHttpProxyResolverFunctions::GetInstance() { // This is a singleton for performance reasons. This avoids having to load // proxy resolver functions multiple times. static base::NoDestructor instance; return *instance; } } // namespace proxy_resolver_win /* * Copyright (C) 2018 Microchip Technology Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include "egt/detail/alignment.h" namespace egt { inline namespace v1 { namespace detail { Rect align_algorithm_force(const Rect& orig, const Rect& bounding, alignmask align, default_dim_type padding, default_dim_type horizontal_ratio, default_dim_type vertical_ratio, default_dim_type xratio, default_dim_type yratio) { auto p = orig.point(); auto s = orig.size(); if (p.x() < bounding.x()) p.set_x(bounding.x()); if (p.y() < bounding.y()) p.set_y(bounding.y()); if (xratio) { p.set_x(bounding.x() + padding + static_cast(bounding.width() - padding * 2) * (static_cast(xratio) / 100.)); } else if ((align & alignmask::left) == alignmask::left) p.set_x(bounding.x() + padding); else if ((align & alignmask::right) == alignmask::right) p.set_x(bounding.x() + bounding.width() - orig.size().width() - padding); else if ((align & alignmask::center_horizontal) == alignmask::center_horizontal) { p.set_x(bounding.x() + (bounding.width() / 2) - (orig.size().width() / 2)); } if (yratio) { p.set_y(bounding.y() + padding + static_cast(bounding.height() - padding * 2) * (static_cast(yratio) / 100.)); } else if ((align & alignmask::top) == alignmask::top) p.set_y(bounding.y() + padding); else if ((align & alignmask::bottom) == alignmask::bottom) p.set_y(bounding.y() + bounding.height() - orig.size().height() - padding); else if ((align & alignmask::center_vertical) == alignmask::center_vertical) { p.set_y(bounding.y() + (bounding.height() / 2) - (orig.size().height() / 2)); } if (horizontal_ratio) { s.set_width(static_cast(bounding.width() - padding * 2) * (static_cast(horizontal_ratio) / 100.)); } else if ((align & alignmask::expand_horizontal) == alignmask::expand_horizontal) { s.set_width(bounding.width() - padding * 2); p.set_x(bounding.x() + padding); } if (vertical_ratio) { s.set_height(static_cast(bounding.height() - padding * 2) * (static_cast(vertical_ratio) / 100.)); } else if ((align & alignmask::expand_vertical) == alignmask::expand_vertical) { s.set_height(bounding.height() - padding * 2); p.set_y(bounding.y() + padding); } return Rect(p, s); } Rect align_algorithm(const Rect& orig, const Rect& bounding, alignmask align, default_dim_type padding, default_dim_type horizontal_ratio, default_dim_type vertical_ratio, default_dim_type xratio, default_dim_type yratio) { /// this needs to be here, but grids don't work when we don't make /// sure the object is at least inside bounding //if (align == alignmask::none) // return orig; return align_algorithm_force(orig, bounding, align, padding, horizontal_ratio, vertical_ratio, xratio, yratio); } } } } B2G/gecko/dom/base/nsScriptNameSpaceManager.cpp1-10 /* -*- 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 "nsScriptNameSpaceManager.h" #include "nsCOMPtr.h" #include "nsIComponentManager.h" #include "nsIComponentRegistrar.h" #include "nsICategoryManager.h" #include "nsIMemoryReporter.h" #include "nsIServiceManager.h" #include "nsXPCOM.h" #include "nsISupportsPrimitives.h" #include "nsIScriptExternalNameSet.h" #include "nsIScriptNameSpaceManager.h" #include "nsIScriptContext.h" #include "nsIInterfaceInfoManager.h" #include "nsIInterfaceInfo.h" #include "xptinfo.h" #include "nsXPIDLString.h" #include "nsReadableUtils.h" #include "nsHashKeys.h" #include "nsDOMClassInfo.h" #include "nsCRT.h" #include "nsIObserverService.h" #include "mozilla/Services.h" #define NS_INTERFACE_PREFIX "nsI" #define NS_DOM_INTERFACE_PREFIX "nsIDOM" using namespace mozilla; // Our extended PLDHashEntryHdr class GlobalNameMapEntry : public PLDHashEntryHdr { public: // Our hash table ops don't care about the order of these members nsString mKey; nsGlobalNameStruct mGlobalName; size_t SizeOfExcludingThis(nsMallocSizeOfFun aMallocSizeOf) { // Measurement of the following members may be added later if DMD finds it // is worthwhile: // - mGlobalName return mKey.SizeOfExcludingThisMustBeUnshared(aMallocSizeOf); } }; static PLDHashNumber GlobalNameHashHashKey(PLDHashTable *table, const void *key) { const nsAString *str = static_cast(key); return HashString(*str); } static bool GlobalNameHashMatchEntry(PLDHashTable *table, const PLDHashEntryHdr *entry, const void *key) { const GlobalNameMapEntry *e = static_cast(entry); const nsAString *str = static_cast(key); return str->Equals(e->mKey); } static void GlobalNameHashClearEntry(PLDHashTable *table, PLDHashEntryHdr *entry) { GlobalNameMapEntry *e = static_cast(entry); // An entry is being cleared, let the key (nsString) do its own // cleanup. e->mKey.~nsString(); if (e->mGlobalName.mType == nsGlobalNameStruct::eTypeExternalClassInfo) { nsIClassInfo* ci = GET_CLEAN_CI_PTR(e->mGlobalName.mData->mCachedClassInfo); // If we constructed an internal helper, we'll let the helper delete // the nsDOMClassInfoData structure, if not we do it here. if (!ci || e->mGlobalName.mData->u.mExternalConstructorFptr) { delete e->mGlobalName.mData; } // Release our pointer to the helper. NS_IF_RELEASE(ci); } else if (e->mGlobalName.mType == nsGlobalNameStruct::eTypeExternalConstructorAlias) { delete e->mGlobalName.mAlias; } // This will set e->mGlobalName.mType to // nsGlobalNameStruct::eTypeNotInitialized memset(&e->mGlobalName, 0, sizeof(nsGlobalNameStruct)); } static bool GlobalNameHashInitEntry(PLDHashTable *table, PLDHashEntryHdr *entry, const void *key) { GlobalNameMapEntry *e = static_cast(entry); const nsAString *keyStr = static_cast(key); // Initialize the key in the entry with placement new new (&e->mKey) nsString(*keyStr); // This will set e->mGlobalName.mType to // nsGlobalNameStruct::eTypeNotInitialized memset(&e->mGlobalName, 0, sizeof(nsGlobalNameStruct)); return true; } NS_IMPL_ISUPPORTS2(nsScriptNameSpaceManager, nsIObserver, nsISupportsWeakReference) nsScriptNameSpaceManager::nsScriptNameSpaceManager() : mIsInitialized(false) { MOZ_COUNT_CTOR(nsScriptNameSpaceManager); } nsScriptNameSpaceManager::~nsScriptNameSpaceManager() { if (mIsInitialized) { // Destroy the hash PL_DHashTableFinish(&mGlobalNames); PL_DHashTableFinish(&mNavigatorNames); } MOZ_COUNT_DTOR(nsScriptNameSpaceManager); } nsGlobalNameStruct * nsScriptNameSpaceManager::AddToHash(PLDHashTable *aTable, const nsAString *aKey, const PRUnichar **aClassName) { GlobalNameMapEntry *entry = static_cast (PL_DHashTableOperate(aTable, aKey, PL_DHASH_ADD)); if (!entry) { return nullptr; } if (aClassName) { *aClassName = entry->mKey.get(); } return &entry->mGlobalName; } nsGlobalNameStruct* nsScriptNameSpaceManager::GetConstructorProto(const nsGlobalNameStruct* aStruct) { NS_ASSERTION(aStruct->mType == nsGlobalNameStruct::eTypeExternalConstructorAlias, "This function only works on constructor aliases!"); if (!aStruct->mAlias->mProto) { GlobalNameMapEntry *proto = static_cast (PL_DHashTableOperate(&mGlobalNames, &aStruct->mAlias->mProtoName, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(proto)) { aStruct->mAlias->mProto = &proto->mGlobalName; } } return aStruct->mAlias->mProto; } nsresult nsScriptNameSpaceManager::FillHash(nsICategoryManager *aCategoryManager, const char *aCategory) { nsCOMPtr e; nsresult rv = aCategoryManager->EnumerateCategory(aCategory, getter_AddRefs(e)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr entry; while (NS_SUCCEEDED(e->GetNext(getter_AddRefs(entry)))) { rv = AddCategoryEntryToHash(aCategoryManager, aCategory, entry); if (NS_FAILED(rv)) { return rv; } } return NS_OK; } // This method enumerates over all installed interfaces (in .xpt // files) and finds ones that start with "nsIDOM" and has constants // defined in the interface itself (inherited constants doesn't // count), once such an interface is found the "nsIDOM" prefix is cut // off the name and the rest of the name is added into the hash for // global names. This makes things like 'Node.ELEMENT_NODE' work in // JS. See nsCommonWindowSH::GlobalResolve() for detais on how this is used. nsresult nsScriptNameSpaceManager::FillHashWithDOMInterfaces() { nsCOMPtr iim(do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID)); NS_ENSURE_TRUE(iim, NS_ERROR_UNEXPECTED); // First look for all interfaces whose name starts with nsIDOM nsCOMPtr domInterfaces; nsresult rv = iim->EnumerateInterfacesWhoseNamesStartWith(NS_DOM_INTERFACE_PREFIX, getter_AddRefs(domInterfaces)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr entry; rv = domInterfaces->First(); if (NS_FAILED(rv)) { // Empty interface list? NS_WARNING("What, no nsIDOM interfaces installed?"); return NS_OK; } bool found_old; nsCOMPtr if_info; const char *if_name = nullptr; const nsIID *iid; for ( ; domInterfaces->IsDone() == static_cast(NS_ENUMERATOR_FALSE); domInterfaces->Next()) { rv = domInterfaces->CurrentItem(getter_AddRefs(entry)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr if_info(do_QueryInterface(entry)); if_info->GetNameShared(&if_name); if_info->GetIIDShared(&iid); rv = RegisterInterface(if_name + sizeof(NS_DOM_INTERFACE_PREFIX) - 1, iid, &found_old); #ifdef DEBUG NS_ASSERTION(!found_old, "Whaaa, interface name already in hash!"); #endif } // Next, look for externally registered DOM interfaces rv = RegisterExternalInterfaces(false); return rv; } nsresult nsScriptNameSpaceManager::RegisterExternalInterfaces(bool aAsProto) { nsresult rv; nsCOMPtr cm = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr iim(do_GetService(NS_INTERFACEINFOMANAGER_SERVICE_CONTRACTID)); NS_ENSURE_TRUE(iim, NS_ERROR_NOT_AVAILABLE); nsCOMPtr enumerator; rv = cm->EnumerateCategory(JAVASCRIPT_DOM_INTERFACE, getter_AddRefs(enumerator)); NS_ENSURE_SUCCESS(rv, rv); nsXPIDLCString IID_string; nsAutoCString category_entry; const char* if_name; nsCOMPtr entry; nsCOMPtr if_info; bool found_old, dom_prefix; while (NS_SUCCEEDED(enumerator->GetNext(getter_AddRefs(entry)))) { nsCOMPtr category(do_QueryInterface(entry)); if (!category) { NS_WARNING("Category entry not an nsISupportsCString!"); continue; } rv = category->GetData(category_entry); NS_ENSURE_SUCCESS(rv, rv); rv = cm->GetCategoryEntry(JAVASCRIPT_DOM_INTERFACE, category_entry.get(), getter_Copies(IID_string)); NS_ENSURE_SUCCESS(rv, rv); nsIID primary_IID; if (!primary_IID.Parse(IID_string) || primary_IID.Equals(NS_GET_IID(nsISupports))) { NS_ERROR("Invalid IID registered with the script namespace manager!"); continue; } iim->GetInfoForIID(&primary_IID, getter_AddRefs(if_info)); while (if_info) { const nsIID *iid; if_info->GetIIDShared(&iid); NS_ENSURE_TRUE(iid, NS_ERROR_UNEXPECTED); if (iid->Equals(NS_GET_IID(nsISupports))) { break; } if_info->GetNameShared(&if_name); dom_prefix = (strncmp(if_name, NS_DOM_INTERFACE_PREFIX, sizeof(NS_DOM_INTERFACE_PREFIX) - 1) == 0); const char* name; if (dom_prefix) { if (!aAsProto) { // nsIDOM* interfaces have already been registered. break; } name = if_name + sizeof(NS_DOM_INTERFACE_PREFIX) - 1; } else { name = if_name + sizeof(NS_INTERFACE_PREFIX) - 1; } if (aAsProto) { RegisterClassProto(name, iid, &found_old); } else { RegisterInterface(name, iid, &found_old); } if (found_old) { break; } nsCOMPtr tmp(if_info); tmp->GetParent(getter_AddRefs(if_info)); } } return NS_OK; } nsresult nsScriptNameSpaceManager::RegisterInterface(const char* aIfName, const nsIID *aIfIID, bool* aFoundOld) { *aFoundOld = false; nsGlobalNameStruct *s = AddToHash(&mGlobalNames, aIfName); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); if (s->mType != nsGlobalNameStruct::eTypeNotInitialized && s->mType != nsGlobalNameStruct::eTypeNewDOMBinding) { *aFoundOld = true; return NS_OK; } s->mType = nsGlobalNameStruct::eTypeInterface; s->mIID = *aIfIID; return NS_OK; } #define GLOBALNAME_HASHTABLE_INITIAL_SIZE 1024 nsresult nsScriptNameSpaceManager::Init() { static PLDHashTableOps hash_table_ops = { PL_DHashAllocTable, PL_DHashFreeTable, GlobalNameHashHashKey, GlobalNameHashMatchEntry, PL_DHashMoveEntryStub, GlobalNameHashClearEntry, PL_DHashFinalizeStub, GlobalNameHashInitEntry }; mIsInitialized = PL_DHashTableInit(&mGlobalNames, &hash_table_ops, nullptr, sizeof(GlobalNameMapEntry), GLOBALNAME_HASHTABLE_INITIAL_SIZE); NS_ENSURE_TRUE(mIsInitialized, NS_ERROR_OUT_OF_MEMORY); mIsInitialized = PL_DHashTableInit(&mNavigatorNames, &hash_table_ops, nullptr, sizeof(GlobalNameMapEntry), GLOBALNAME_HASHTABLE_INITIAL_SIZE); if (!mIsInitialized) { PL_DHashTableFinish(&mGlobalNames); return NS_ERROR_OUT_OF_MEMORY; } nsresult rv = NS_OK; rv = FillHashWithDOMInterfaces(); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr cm = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_GLOBAL_CONSTRUCTOR_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_GLOBAL_PROPERTY_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_GLOBAL_PRIVILEGED_PROPERTY_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_GLOBAL_STATIC_NAMESET_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_GLOBAL_DYNAMIC_NAMESET_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); rv = FillHash(cm, JAVASCRIPT_NAVIGATOR_PROPERTY_CATEGORY); NS_ENSURE_SUCCESS(rv, rv); // Initial filling of the has table has been done. // Now, listen for changes. nsCOMPtr serv = mozilla::services::GetObserverService(); if (serv) { serv->AddObserver(this, NS_XPCOM_CATEGORY_ENTRY_ADDED_OBSERVER_ID, true); } return NS_OK; } struct NameSetClosure { nsIScriptContext* ctx; nsresult rv; }; static PLDHashOperator NameSetInitCallback(PLDHashTable *table, PLDHashEntryHdr *hdr, uint32_t number, void *arg) { GlobalNameMapEntry *entry = static_cast(hdr); if (entry->mGlobalName.mType == nsGlobalNameStruct::eTypeStaticNameSet) { nsresult rv = NS_OK; nsCOMPtr ns = do_CreateInstance(entry->mGlobalName.mCID, &rv); NS_ENSURE_SUCCESS(rv, PL_DHASH_NEXT); NameSetClosure *closure = static_cast(arg); closure->rv = ns->InitializeNameSet(closure->ctx); if (NS_FAILED(closure->rv)) { NS_ERROR("Initing external script classes failed!"); return PL_DHASH_STOP; } } return PL_DHASH_NEXT; } nsresult nsScriptNameSpaceManager::InitForContext(nsIScriptContext *aContext) { NameSetClosure closure; closure.ctx = aContext; closure.rv = NS_OK; PL_DHashTableEnumerate(&mGlobalNames, NameSetInitCallback, &closure); return closure.rv; } nsGlobalNameStruct* nsScriptNameSpaceManager::LookupNameInternal(const nsAString& aName, const PRUnichar **aClassName) { GlobalNameMapEntry *entry = static_cast (PL_DHashTableOperate(&mGlobalNames, &aName, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(entry) && !((&entry->mGlobalName)->mDisabled)) { if (aClassName) { *aClassName = entry->mKey.get(); } return &entry->mGlobalName; } if (aClassName) { *aClassName = nullptr; } return nullptr; } nsresult nsScriptNameSpaceManager::LookupNavigatorName(const nsAString& aName, const nsGlobalNameStruct **aNameStruct) { GlobalNameMapEntry *entry = static_cast (PL_DHashTableOperate(&mNavigatorNames, &aName, PL_DHASH_LOOKUP)); if (PL_DHASH_ENTRY_IS_BUSY(entry) && !((&entry->mGlobalName)->mDisabled)) { *aNameStruct = &entry->mGlobalName; } else { *aNameStruct = nullptr; } return NS_OK; } nsresult nsScriptNameSpaceManager::RegisterClassName(const char *aClassName, int32_t aDOMClassInfoID, bool aPrivileged, bool aDisabled, const PRUnichar **aResult) { if (!nsCRT::IsAscii(aClassName)) { NS_ERROR("Trying to register a non-ASCII class name"); return NS_OK; } nsGlobalNameStruct *s = AddToHash(&mGlobalNames, aClassName, aResult); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); if (s->mType == nsGlobalNameStruct::eTypeClassConstructor) { return NS_OK; } // If a external constructor is already defined with aClassName we // won't overwrite it. if (s->mType == nsGlobalNameStruct::eTypeExternalConstructor) { return NS_OK; } NS_ASSERTION(s->mType == nsGlobalNameStruct::eTypeNotInitialized || s->mType == nsGlobalNameStruct::eTypeNewDOMBinding || s->mType == nsGlobalNameStruct::eTypeInterface, "Whaaa, JS environment name clash!"); s->mType = nsGlobalNameStruct::eTypeClassConstructor; s->mDOMClassInfoID = aDOMClassInfoID; s->mChromeOnly = aPrivileged; s->mDisabled = aDisabled; return NS_OK; } nsresult nsScriptNameSpaceManager::RegisterClassProto(const char *aClassName, const nsIID *aConstructorProtoIID, bool *aFoundOld) { NS_ENSURE_ARG_POINTER(aConstructorProtoIID); *aFoundOld = false; nsGlobalNameStruct *s = AddToHash(&mGlobalNames, aClassName); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); if (s->mType != nsGlobalNameStruct::eTypeNotInitialized && s->mType != nsGlobalNameStruct::eTypeNewDOMBinding && s->mType != nsGlobalNameStruct::eTypeInterface) { *aFoundOld = true; return NS_OK; } s->mType = nsGlobalNameStruct::eTypeClassProto; s->mIID = *aConstructorProtoIID; return NS_OK; } nsresult nsScriptNameSpaceManager::RegisterExternalClassName(const char *aClassName, nsCID& aCID) { nsGlobalNameStruct *s = AddToHash(&mGlobalNames, aClassName); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); // If an external constructor is already defined with aClassName we // won't overwrite it. if (s->mType == nsGlobalNameStruct::eTypeExternalConstructor) { return NS_OK; } NS_ASSERTION(s->mType == nsGlobalNameStruct::eTypeNotInitialized || s->mType == nsGlobalNameStruct::eTypeNewDOMBinding || s->mType == nsGlobalNameStruct::eTypeInterface, "Whaaa, JS environment name clash!"); s->mType = nsGlobalNameStruct::eTypeExternalClassInfoCreator; s->mCID = aCID; return NS_OK; } nsresult nsScriptNameSpaceManager::RegisterDOMCIData(const char *aName, nsDOMClassInfoExternalConstructorFnc aConstructorFptr, const nsIID *aProtoChainInterface, const nsIID **aInterfaces, uint32_t aScriptableFlags, bool aHasClassInterface, const nsCID *aConstructorCID) { const PRUnichar* className; nsGlobalNameStruct *s = AddToHash(&mGlobalNames, aName, &className); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); // If an external constructor is already defined with aClassName we // won't overwrite it. if (s->mType == nsGlobalNameStruct::eTypeClassConstructor || s->mType == nsGlobalNameStruct::eTypeExternalClassInfo) { return NS_OK; } // XXX Should we bail out here? NS_ASSERTION(s->mType == nsGlobalNameStruct::eTypeNotInitialized || s->mType == nsGlobalNameStruct::eTypeNewDOMBinding || s->mType == nsGlobalNameStruct::eTypeExternalClassInfoCreator, "Someone tries to register classinfo data for a class that isn't new or external!"); s->mData = new nsExternalDOMClassInfoData; NS_ENSURE_TRUE(s->mData, NS_ERROR_OUT_OF_MEMORY); s->mType = nsGlobalNameStruct::eTypeExternalClassInfo; s->mData->mName = aName; s->mData->mNameUTF16 = className; if (aConstructorFptr) s->mData->u.mExternalConstructorFptr = aConstructorFptr; else // null constructor will cause us to use nsDOMGenericSH::doCreate s->mData->u.mExternalConstructorFptr = nullptr; s->mData->mCachedClassInfo = nullptr; s->mData->mProtoChainInterface = aProtoChainInterface; s->mData->mInterfaces = aInterfaces; s->mData->mScriptableFlags = aScriptableFlags; s->mData->mHasClassInterface = aHasClassInterface; s->mData->mConstructorCID = aConstructorCID; return NS_OK; } nsresult nsScriptNameSpaceManager::AddCategoryEntryToHash(nsICategoryManager* aCategoryManager, const char* aCategory, nsISupports* aEntry) { // Get the type from the category name. // NOTE: we could have passed the type in FillHash() and guessed it in // Observe() but this way, we have only one place to update and this is // not performance sensitive. nsGlobalNameStruct::nametype type; if (strcmp(aCategory, JAVASCRIPT_GLOBAL_CONSTRUCTOR_CATEGORY) == 0) { type = nsGlobalNameStruct::eTypeExternalConstructor; } else if (strcmp(aCategory, JAVASCRIPT_GLOBAL_PROPERTY_CATEGORY) == 0 || strcmp(aCategory, JAVASCRIPT_GLOBAL_PRIVILEGED_PROPERTY_CATEGORY) == 0) { type = nsGlobalNameStruct::eTypeProperty; } else if (strcmp(aCategory, JAVASCRIPT_NAVIGATOR_PROPERTY_CATEGORY) == 0) { type = nsGlobalNameStruct::eTypeNavigatorProperty; } else if (strcmp(aCategory, JAVASCRIPT_GLOBAL_STATIC_NAMESET_CATEGORY) == 0) { type = nsGlobalNameStruct::eTypeStaticNameSet; } else if (strcmp(aCategory, JAVASCRIPT_GLOBAL_DYNAMIC_NAMESET_CATEGORY) == 0) { type = nsGlobalNameStruct::eTypeDynamicNameSet; } else { return NS_OK; } nsCOMPtr strWrapper = do_QueryInterface(aEntry); if (!strWrapper) { NS_WARNING("Category entry not an nsISupportsCString!"); return NS_OK; } nsAutoCString categoryEntry; nsresult rv = strWrapper->GetData(categoryEntry); NS_ENSURE_SUCCESS(rv, rv); nsXPIDLCString contractId; rv = aCategoryManager->GetCategoryEntry(aCategory, categoryEntry.get(), getter_Copies(contractId)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr registrar; rv = NS_GetComponentRegistrar(getter_AddRefs(registrar)); NS_ENSURE_SUCCESS(rv, rv); nsCID *cidPtr; rv = registrar->ContractIDToCID(contractId, &cidPtr); if (NS_FAILED(rv)) { NS_WARNING("Bad contract id registed with the script namespace manager"); return NS_OK; } // Copy CID onto the stack, so we can free it right away and avoid having // to add cleanup code at every exit point from this function. nsCID cid = *cidPtr; nsMemory::Free(cidPtr); if (type == nsGlobalNameStruct::eTypeExternalConstructor) { nsXPIDLCString constructorProto; rv = aCategoryManager->GetCategoryEntry(JAVASCRIPT_GLOBAL_CONSTRUCTOR_PROTO_ALIAS_CATEGORY, categoryEntry.get(), getter_Copies(constructorProto)); if (NS_SUCCEEDED(rv)) { nsGlobalNameStruct *s = AddToHash(&mGlobalNames, categoryEntry.get()); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); if (s->mType == nsGlobalNameStruct::eTypeNotInitialized || s->mType == nsGlobalNameStruct::eTypeNewDOMBinding) { s->mAlias = new nsGlobalNameStruct::ConstructorAlias; s->mType = nsGlobalNameStruct::eTypeExternalConstructorAlias; s->mChromeOnly = false; s->mAlias->mCID = cid; AppendASCIItoUTF16(constructorProto, s->mAlias->mProtoName); s->mAlias->mProto = nullptr; } else { NS_WARNING("Global script name not overwritten!"); } return NS_OK; } } PLDHashTable *table; if (type == nsGlobalNameStruct::eTypeNavigatorProperty) { table = &mNavigatorNames; } else { table = &mGlobalNames; } nsGlobalNameStruct *s = AddToHash(table, categoryEntry.get()); NS_ENSURE_TRUE(s, NS_ERROR_OUT_OF_MEMORY); if (s->mType == nsGlobalNameStruct::eTypeNotInitialized || s->mType == nsGlobalNameStruct::eTypeNewDOMBinding) { s->mType = type; s->mCID = cid; s->mChromeOnly = strcmp(aCategory, JAVASCRIPT_GLOBAL_PRIVILEGED_PROPERTY_CATEGORY) == 0; } else { NS_WARNING("Global script name not overwritten!"); } return NS_OK; } NS_IMETHODIMP nsScriptNameSpaceManager::Observe(nsISupports* aSubject, const char* aTopic, const PRUnichar* aData) { if (!aData) { return NS_OK; } if (strcmp(aTopic, NS_XPCOM_CATEGORY_ENTRY_ADDED_OBSERVER_ID) == 0) { nsCOMPtr cm = do_GetService(NS_CATEGORYMANAGER_CONTRACTID); if (!cm) { return NS_OK; } return AddCategoryEntryToHash(cm, NS_ConvertUTF16toUTF8(aData).get(), aSubject); } // TODO: we could observe NS_XPCOM_CATEGORY_ENTRY_REMOVED_OBSERVER_ID // and NS_XPCOM_CATEGORY_CLEARED_OBSERVER_ID but we are safe without it. // See bug 600460. return NS_OK; } void nsScriptNameSpaceManager::RegisterDefineDOMInterface(const nsAFlatString& aName, mozilla::dom::DefineInterface aDefineDOMInterface, mozilla::dom::PrefEnabled aPrefEnabled) { nsGlobalNameStruct *s = AddToHash(&mGlobalNames, &aName); if (s) { if (s->mType == nsGlobalNameStruct::eTypeNotInitialized) { s->mType = nsGlobalNameStruct::eTypeNewDOMBinding; } s->mDefineDOMInterface = aDefineDOMInterface; s->mPrefEnabled = aPrefEnabled; } } static size_t SizeOfEntryExcludingThis(PLDHashEntryHdr *aHdr, nsMallocSizeOfFun aMallocSizeOf, void *aArg) { GlobalNameMapEntry* entry = static_cast(aHdr); return entry->SizeOfExcludingThis(aMallocSizeOf); } size_t nsScriptNameSpaceManager::SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) { size_t n = 0; n += PL_DHashTableSizeOfExcludingThis(&mGlobalNames, SizeOfEntryExcludingThis, aMallocSizeOf); n += PL_DHashTableSizeOfExcludingThis(&mNavigatorNames, SizeOfEntryExcludingThis, aMallocSizeOf); return n; } #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace algorithms { struct dependency_correlation_matrix { private: std::vector> data; std::unordered_map task_id_to_index; public: dependency_correlation_matrix( workflow::workflow const & w, std::vector const & bag ) : data(bag.size()) { if (data.empty()) { return; } std::vector> successors{}; for (workflow::task_id const t_id : bag) { auto successor_view = w.get_task_outgoing_edges(t_id) | std::views::transform([] (auto const & edge) { auto const & [neighbor_id, weight] = edge; return neighbor_id; }); successors.emplace_back(successor_view.begin(), successor_view.end()); std::ranges::sort(successors.back()); } for (size_t i = 0; i < bag.size() - 1; ++i) { double const num_i_successors = successors.at(i).size(); for (size_t j = i + 1; j < bag.size(); ++j) { double const num_j_successors = successors.at(j).size(); std::vector i_j_intersection{}; std::ranges::set_intersection( successors.at(i), successors.at(j), std::back_inserter(i_j_intersection) ); double const num_i_j_successors = i_j_intersection.size(); double const i_j_cor = num_i_j_successors / std::sqrt(num_i_successors * num_j_successors); data.at(i).push_back(i_j_cor); } } for (size_t i = 0; i < bag.size(); ++i) { task_id_to_index.insert({bag.at(i), i}); } } double get(workflow::task_id const t0_id, workflow::task_id const t1_id) const { size_t const t0_index = task_id_to_index.at(t0_id); size_t const t1_index = task_id_to_index.at(t1_id); auto const [i, j] = std::minmax(t0_index, t1_index); return data.at(i).at(j - i - 1); } }; std::vector dependency_balanced_task_groups( workflow::workflow const & w, std::vector const & bag, size_t const num_cluster_nodes ) { size_t const num_groups = std::min(bag.size(), num_cluster_nodes); std::vector groups(num_groups); dependency_correlation_matrix const cor(w, bag); auto const required_group_sizes = split_most_evenly(bag.size(), num_groups); std::set remaining_task_ids(bag.begin(), bag.end()); for (size_t const i : std::ranges::iota_view{0ul, num_groups}) { size_t const required_group_size = required_group_sizes.at(i); task_group & group = groups.at(i); if (remaining_task_ids.empty()) { throw std::runtime_error("Internal bug: DBCA task list empty too early."); } // initialize the group with the just a single task // I removed the initialization from the paper with two tasks, // because I think the loop below does the exat same thing and // I don't have to implement the best task search twice workflow::task_id const t_id = *remaining_task_ids.begin(); group.add_task(w.get_task(t_id)); remaining_task_ids.erase(t_id); // I think in the paper pseudo code is a mistake and there is one loop too much // hence I don't implement the second for-loop here // keep adding tasks until the group has its required size while (group.cardinality < required_group_size) { if (remaining_task_ids.empty()) { throw std::runtime_error("Internal bug: DBCA task list empty too early."); } double max_added_correlation = std::numeric_limits::lowest(); double min_workfload_difference = std::numeric_limits::max(); workflow::task_id best_t_id = 0; double const average_group_workload = std::transform_reduce( group.begin(), group.end(), 0.0, std::plus<>(), [&w] (workflow::task_id const grouped_t_id) { return w.get_task(grouped_t_id).workload; } ) / group.cardinality; // find the task with most added similarity out of the remaining free tasks for (workflow::task_id const free_t_id : remaining_task_ids) { double const added_correlation = std::transform_reduce( group.begin(), group.end(), 0.0, std::plus<>(), [&cor, free_t_id] (workflow::task_id const grouped_t_id) { return cor.get(grouped_t_id, free_t_id); } ); double const workload_difference = average_group_workload - w.get_task(free_t_id).workload; if ( added_correlation > max_added_correlation || ( // tie-break correlation with workload similarity // the formula in the paper seems very weird or at least I don't understand it // so I implemented it in the way I assume it is meant from the textual description added_correlation == max_added_correlation && workload_difference < min_workfload_difference ) ) { max_added_correlation = added_correlation; min_workfload_difference = workload_difference; best_t_id = free_t_id; } } group.add_task(w.get_task(best_t_id)); remaining_task_ids.erase(best_t_id); } } if (!remaining_task_ids.empty()) { throw std::runtime_error("Internal bug: DBCA task list not empty in the end."); } return groups; } // Dependency balance clustering algorithm // Running time analysis: // TODO schedule::schedule dbca( cluster::cluster const & c, workflow::workflow const & w, io::command_line_arguments const & args ) { schedule::schedule s(c, args.use_memory_requirements); if (args.use_memory_requirements) { io::issue_warning(args, "Memory requirements not implemented/used for DBCA"); } // we use our bags instead of the levels as defined in the original paper // (makes sense, but is not always equal) auto const & task_ids_per_bag = w.get_task_ids_per_bag(); for (auto const & bag: task_ids_per_bag) { auto groups = dependency_balanced_task_groups(w, bag, c.size()); select_good_processors_for_expensive_groups( c, w, s, groups, args.use_memory_requirements ); } return s; } } // namespace algorithms // -*- coding:utf-8 -*- // Calc : 278*(ix-1)*(jx-1)*step #include #include #include #include #define MAT(i,j,ix) ((j)*(ix) + (i)) void DefaultValue(float* ro, float* pr, float* vx, float* vy, int ix, int jx); float cfl(const float* ro, const float* pr, const float* vx, const float* vy, float dx, float gamma, float safety, int ix, int jx); void lw2(float* ro, float* pr, float* vx, float* vy, float dt, float dx, float dy, float qav, float gamma, int ix, int jx); void output(const float* ro, const float* pr, const float* vx, const float* vy, float dx, float dy, int OutNum, int ix, int jx); void bnd(float* ro, float* pr, float* vx, float* vy, int ix, int jx); void chkdav(float* u, float* vx, float* vy, float floor, int ix, int jx); int main(){ const int ix = 1024; // Grid Size X const int jx = 1024; // Grid Size Y const float tMax = 0.2; // Time Step const float OutStep = 0.05; // Output per step const int OutNum = (int)(tMax/OutStep) + 1; const float dx = 0.004; const float dy = 0.004; const float gamma = 5.0/3.0; const float floor = 1.0e-9; // Threshold Density&Pressure const float safety = 0.4; // Courant Number Safety const float qv = 3.0; // Artificial Viscosity float* ro = new float[ix*jx]; // Density float* pr = new float[ix*jx]; // Pressure float* vx = new float[ix*jx]; // Velocity x float* vy = new float[ix*jx]; // Velocity y DefaultValue(ro, pr, vx, vy, ix, jx); // Main float t = 0.0; int step = 0; while(t2) { // choose verbosity switch (atoi(argcv[2])) { case(0): // shut up // ffmpeg_av_log_set_level(0); // fatal_log_all(); break; case(1): // normal break; case(2): // more verbose // ffmpeg_av_log_set_level(100); // debug_log_all(); break; case(3): // extremely verbose // ffmpeg_av_log_set_level(100); // crazy_log_all(); break; default: std::cout << "Unknown verbosity level "<< atoi(argcv[2]) <= 0) { iCH[indexCH++] = iCCW[tempIndex++]; } else { iCH[indexCH--] = iCCW[tempIndex]; } } generateDTri(); } void GLWidget::sortSetCCW() { // Point 0 iCCW[0] = findMinY(); indexCCW++; double previousAngle = 0.0; double lowestAngle = 360.0; int tempIndex = 0.0; // Point N for(int j = 1; j < SET; j++) { lowestAngle = 360.0; tempIndex = 0; for(int i = 0; i < SET; i++) { double tempAngle = atan2(PT[iCCW[0]].y - PT[i].y, PT[iCCW[0]].x - PT[i].x); if(j == 1 && tempAngle <= lowestAngle) { lowestAngle = tempAngle; tempIndex = i; } else if(tempAngle <= lowestAngle && tempAngle > previousAngle) { lowestAngle = tempAngle; tempIndex = i; } } previousAngle = lowestAngle; iCCW[j] = tempIndex; indexCCW++; } } int GLWidget::findMinY() { // Point 0 double tempY = 100.0; double tempX = -100.0; int index = 0; for(int i = 0; i < SET; i++) { if(PT[i].y <= tempY) { if(PT[i].y == tempY) { if(PT[i].x > tempX) { index = i; tempY = PT[i].y; tempX = PT[i].x; } } else { index = i; tempY = PT[i].y; tempX = PT[i].x; } } } return index; } void GLWidget::plotCCW() { bool color = true; double x = 0.0; for(int i = 1; i < SET; i++) { if(color) { x = 1.0; } else { x = 0.0; } color = !color; glColor3d(1.0, x, 0.0); glBegin(GL_LINES); glVertex2d(PT[iCCW[0]].x, PT[iCCW[0]].y); glVertex2d(PT[iCCW[i]].x, PT[iCCW[i]].y); glEnd(); } } void GLWidget::plotEdgeFlip() { glColor3d(1.0, 0.5, 0.0); for(int i = 0; i < indexEdge; i++) { glBegin(GL_LINES); glVertex2d(PT[DED[i].p1].x, PT[DED[i].p1].y); glVertex2d(PT[DED[i].p2].x, PT[DED[i].p2].y); glEnd(); } } void GLWidget::plotDTri() { glColor3d(1.0, 0.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_TRIANGLES); for(int i = 0; i < indexTri; i++) { glVertex2d(PT[DTRI[i].p1].x, PT[DTRI[i].p1].y); glVertex2d(PT[DTRI[i].p2].x, PT[DTRI[i].p2].y); glVertex2d(PT[DTRI[i].p3].x, PT[DTRI[i].p3].y); } glEnd(); } double GLWidget::isLeft(double xP1, double xP2, double xP3, double yP1, double yP2, double yP3) { return ((xP2 - xP1) * (yP3 - yP1)) - ((xP3 - xP1) * (yP2 - yP1)); } void GLWidget::plotCH() { glColor3d(0.0, 1.0, 0.0); glBegin(GL_LINE_LOOP); for(int i = 0; i < indexCH; i++) { glVertex2d(PT[iCH[i]].x, PT[iCH[i]].y); } glEnd(); } void GLWidget::generateDTri() { generateHOrder(); generateRandTri(); findIntEdges(); flipEdges(); generateCC(); } void GLWidget::printInfo() { qDebug("--\nPrinting All Information\n--\nPT\n--"); for(int i = 0; i < SET; i++) { qDebug("PT %d: %f, %f", i, PT[i].x, PT[i].y); } qDebug("--\nTRI\n--"); for(int i = 0; i < indexTri; i++) { qDebug("TRI %d: %d, %d, %d", i, TRI[i].p1, TRI[i].p2, TRI[i].p3); } qDebug("--\nED\n--"); for(int i = 0; i < indexTri; i++) { qDebug("ED %d: %d, %d", i, ED[i].p1, ED[i].p2); } } void GLWidget::flipEdges() { //printInfo(); for(int i = 0; i < indexEdge; i++) { int tri1, tri2, C, D; if(DED[i].isD == false) { getEdgeTriangles(DED[i], tri1, tri2, C, D); int A = DED[i].p1; int B = DED[i].p2; //qDebug("--\nDTRI 1: %d, %d, %d", DTRI[tri1].p1, DTRI[tri1].p2, DTRI[tri1].p3); //qDebug("DTRI 2: %d, %d, %d", DTRI[tri2].p1, DTRI[tri2].p2, DTRI[tri2].p3); //qDebug("DED %d: %d, %d", i, DED[i].p1, DED[i].p2); //qDebug("%d, %d, %d, %d", A, B, C, D); if(!isDelaunayEdge(PT[A].x, PT[A].y, PT[B].x, PT[B].y, PT[C].x, PT[C].y, PT[D].x, PT[D].y)) { //qDebug("Flipped!"); DED[i].p1 = C; DED[i].p2 = D; DTRI[tri1].p1 = A; DTRI[tri1].p2 = D; DTRI[tri1].p3 = C; DTRI[tri2].p1 = B; DTRI[tri2].p2 = C; DTRI[tri2].p3 = D; DED[i].isD = true; i = 0; //qDebug("New DTRI 1: %d, %d, %d", DTRI[tri1].p1, DTRI[tri1].p2, DTRI[tri1].p3); //qDebug("New DTRI 2: %d, %d, %d", DTRI[tri2].p1, DTRI[tri2].p2, DTRI[tri2].p3); //qDebug("New DED %d: %d, %d", i, DED[i].p1, DED[i].p2); } } } } void GLWidget::getEdgeTriangles(EDGE E, int &t1, int &t2, int &C, int &D) { int A = E.p1; int B = E.p2; int count = 0; for(int i = 0; i < indexTri; i++) { if((A == DTRI[i].p1 || A == DTRI[i].p2 || A == DTRI[i].p3) && (B == DTRI[i].p1 || B == DTRI[i].p2 || B == DTRI[i].p3)) { if(count++ == 0) { t1 = i; } else { t2 = i; } } } // Find C // TRI 1 if(A == DTRI[t1].p1 && B == DTRI[t1].p2) { C = DTRI[t1].p3; } else if(A == DTRI[t1].p2 && B == DTRI[t1].p3) { C = DTRI[t1].p1; } else if(A == DTRI[t1].p3 && B == DTRI[t1].p1) { C = DTRI[t1].p2; } // TRI 2 else if(A == DTRI[t2].p1 && B == DTRI[t2].p2) { C = DTRI[t2].p3; } else if(A == DTRI[t2].p2 && B == DTRI[t2].p3) { C = DTRI[t2].p1; } else if(A == DTRI[t2].p3 && B == DTRI[t2].p1) { C = DTRI[t2].p2; } // Find D // TRI 1 if(DTRI[t1].p1 != A && DTRI[t1].p1 != B && DTRI[t1].p1 != C) { D = DTRI[t1].p1; } else if(DTRI[t1].p2 != A && DTRI[t1].p2 != B && DTRI[t1].p2 != C) { D = DTRI[t1].p2; } else if(DTRI[t1].p3 != A && DTRI[t1].p3 != B && DTRI[t1].p3 != C) { D = DTRI[t1].p3; } // TRI 2 else if(DTRI[t2].p1 != A && DTRI[t2].p1 != B && DTRI[t2].p1 != C) { D = DTRI[t2].p1; } else if(DTRI[t2].p2 != A && DTRI[t2].p2 != B && DTRI[t2].p2 != C) { D = DTRI[t2].p2; } else if(DTRI[t2].p3 != A && DTRI[t2].p3 != B && DTRI[t2].p3 != C) { D = DTRI[t2].p3; } } void GLWidget::findIntEdges() { for(int i = 0; i < indexTri; i++) { if(onCH(TRI[i].p1) && onCH(TRI[i].p2)) { if(qAbs(getCHIndex(TRI[i].p1) - getCHIndex(TRI[i].p2)) < (indexCH - 1) && qAbs(getCHIndex(TRI[i].p1) - getCHIndex(TRI[i].p2)) > 1) { addEdge(TRI[i].p1, TRI[i].p2); } } else { addEdge(TRI[i].p1, TRI[i].p2); } if(onCH(TRI[i].p2) && onCH(TRI[i].p3)) { if(qAbs(getCHIndex(TRI[i].p2) - getCHIndex(TRI[i].p3)) < (indexCH - 1) && qAbs(getCHIndex(TRI[i].p2) - getCHIndex(TRI[i].p3)) > 1) { addEdge(TRI[i].p2, TRI[i].p3); } } else { addEdge(TRI[i].p2, TRI[i].p3); } if(onCH(TRI[i].p3) && onCH(TRI[i].p1)) { if(qAbs(getCHIndex(TRI[i].p3) - getCHIndex(TRI[i].p1)) < (indexCH - 1) && qAbs(getCHIndex(TRI[i].p3) - getCHIndex(TRI[i].p1)) > 1) { addEdge(TRI[i].p3, TRI[i].p1); } } else { addEdge(TRI[i].p3, TRI[i].p1); } } // Make Copy for(int i = 0; i < indexEdge; i++) { DED[i].p1 = ED[i].p1; DED[i].p2 = ED[i].p2; DED[i].isD = ED[i].isD; } } int GLWidget::getCHIndex(int v) { for(int i = 0; i < indexCH; i++) { if(v == iCH[i]) return i; } return 100; } void GLWidget::addEdge(int v1, int v2) { if(indexEdge == 0) { ED[indexEdge].p1 = v1; ED[indexEdge++].p2 = v2; return; } bool edgeExists = false; for(int i = 0; i < indexEdge; i ++) { if((v1 == ED[i].p1 && v2 == ED[i].p2) || (v2 == ED[i].p1 && v1 == ED[i].p2)) { edgeExists = true; } } if(!edgeExists) { ED[indexEdge].p1 = v1; ED[indexEdge++].p2 = v2; } } void GLWidget::plotIntEdges() { glColor3d(0.0, 0.5, 1.0); for(int i = 0; i < indexEdge; i++) { glBegin(GL_LINES); glVertex2d(PT[ED[i].p1].x, PT[ED[i].p1].y); glVertex2d(PT[ED[i].p2].x, PT[ED[i].p2].y); glEnd(); } } void GLWidget::generateRandTri() { for(int i = 0; i < indexCH - 2; i++) { TRI[indexTri].p1 = iCH[0]; TRI[indexTri].p2 = iCH[i + 1]; TRI[indexTri++].p3 = iCH[i + 2]; } for(int i = 0; i < SET; i++) { if(onCH(iHO[i])) { // Convex Hull Point } else { for(int j = 0; j < indexTri; j++) { if(inTriangle(PT[TRI[j].p1].x, PT[TRI[j].p1].y, PT[TRI[j].p2].x, PT[TRI[j].p2].y, PT[TRI[j].p3].x, PT[TRI[j].p3].y, PT[iHO[i]].x, PT[iHO[i]].y)) { int tempIndex = indexTri - 1; indexTri += 2; // Divide Outer Triangle int p1 = TRI[j].p1; int p2 = TRI[j].p2; int p3 = TRI[j].p3; int p = iHO[i]; while(tempIndex > j) { TRI[tempIndex + 2] = TRI[tempIndex--]; } TRI[j].p3 = p; TRI[j + 1].p1 = p2; TRI[j + 1].p2 = p3; TRI[j + 1].p3 = p; TRI[j + 2].p1 = p3; TRI[j + 2].p2 = p1; TRI[j + 2].p3 = p; // Exit For Loop break; } } } } // Make Copy for(int i = 0; i < indexTri; i++) { DTRI[i].p1 = TRI[i].p1; DTRI[i].p2 = TRI[i].p2; DTRI[i].p3 = TRI[i].p3; } } void GLWidget::generateHOrder() { double previousX = -100; int lowestIndex = 0; for(int j = 0; j < SET; j++) { double lowestNum = 100; for(int i = 0; i < SET; i++) { if(PT[i].x < lowestNum && PT[i].x > previousX) { lowestNum = PT[i].x; lowestIndex = i; } else if (PT[i].x < lowestNum && PT[i].x == previousX) { // Handle Same X Values int oldPoint = false; for(int k = 0; k < j; k++) { if(PT[i].x == PT[iHO[k]].x && PT[i].y == PT[iHO[k]].y) { oldPoint = true; } } if(!oldPoint) { lowestNum = PT[i].x; lowestIndex = i; } } } previousX = lowestNum; iHO[j] = lowestIndex; iHO[j] = lowestIndex; } } void GLWidget::plotHOrder() { glColor3d(0.0, 0.0, 1.0); glBegin(GL_LINE_STRIP); for(int i = 0; i < SET; i++) { glVertex2d(PT[iHO[i]].x, PT[iHO[i]].y); } glEnd(); } void GLWidget::plotTri() { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3d(0.5, 0.5, 0.5); glBegin(GL_TRIANGLES); for(int i = 0; i < indexTri; i++) { glVertex2d(PT[TRI[i].p1].x, PT[TRI[i].p1].y); glVertex2d(PT[TRI[i].p2].x, PT[TRI[i].p2].y); glVertex2d(PT[TRI[i].p3].x, PT[TRI[i].p3].y); } glEnd(); } bool GLWidget::onCH(int V) { for(int i = 0; i < indexCH; i++) { if(V == iCH[i]) return true; } return false; } bool GLWidget::inTriangle(double xP1, double yP1, double xP2, double yP2, double xP3, double yP3, double X, double Y) { // Barycentric Coordinates float alpha = ((yP2 - yP3)*(X - xP3) + (xP3 - xP2)*(Y - yP3)) / ((yP2 - yP3)*(xP1 - xP3) + (xP3 - xP2)*(yP1 - yP3)); float beta = ((yP3 - yP1)*(X - xP3) + (xP1 - xP3)*(Y - yP3)) / ((yP2 - yP3)*(xP1 - xP3) + (xP3 - xP2)*(yP1 - yP3)); float gamma = 1.0f - alpha - beta; if(alpha > 0 && beta > 0 && gamma > 0) { return true; } else { return false; } } bool GLWidget::isDelaunayEdge(double Ax, double Ay, double Bx, double By, double Cx, double Cy, double Dx, double Dy) { QMatrix4x4 tempMatrix ( Ax, Ay, (Ax*Ax) + (Ay*Ay), 1, Bx, By, (Bx*Bx) + (By*By), 1, Cx, Cy, (Cx*Cx) + (Cy*Cy), 1, Dx, Dy, (Dx*Dx) + (Dy*Dy), 1 ); if(tempMatrix.determinant() > 0) { return false; } else { return true; } } void GLWidget::generateCC() { for(int i = 0; i < indexTri; i++) { int A = DTRI[i].p1; int B = DTRI[i].p2; int C = DTRI[i].p3; // First Bisector double AxB = (PT[A].x + PT[B].x) / 2.0; double AyB = (PT[A].y + PT[B].y) / 2.0; double nAB = (PT[B].y - PT[A].y); double dAB = (PT[B].x - PT[A].x); double mAB = -(dAB / nAB); double bAB = AyB - (mAB * AxB); // Second Bisector double BxC = (PT[B].x + PT[C].x) / 2.0; double ByC = (PT[B].y + PT[C].y) / 2.0; double nBC = (PT[C].y - PT[B].y); double dBC = (PT[C].x - PT[B].x); double mBC = -(dBC / nBC); double bBC = ByC - (mBC * BxC); // X double x = (bBC - bAB) / (mAB - mBC); double y = (mAB * x) + bAB; CC[i].x = x; CC[i].y = y; CC[i].r = qSqrt(((CC[i].x - PT[DTRI[i].p1].x)*(CC[i].x - PT[DTRI[i].p1].x)) + ((CC[i].y - PT[DTRI[i].p1].y)*(CC[i].y - PT[DTRI[i].p1].y))); // qDebug("CC %d: %f, %f", i, x, y); } generateCand(); } void GLWidget::plotCircumcircles() { glColor3d(0.5, 0.5, 0.0); for(int i = 0; i < indexTri; i++) { glBegin(GL_POINTS); glVertex2d(CC[i].x, CC[i].y); glEnd(); drawCircle(CC[i].x, CC[i].y, CC[i].r, 100); } } void GLWidget::drawCircle(float cx, float cy, float r, int num_segments) { glBegin(GL_LINE_LOOP); for (int ii = 0; ii < num_segments; ii++) { float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments); float x = r * cosf(theta); float y = r * sinf(theta); glVertex2f(x + cx, y + cy); } glEnd(); } void GLWidget::generateCand() { // Check Circumcenters for(int i = 0; i < indexTri; i++) { bool isCandidate = false; for(int j = 0; j < indexTri; j++) { if(inTriangle(PT[DTRI[j].p1].x, PT[DTRI[j].p1].y, PT[DTRI[j].p2].x, PT[DTRI[j].p2].y, PT[DTRI[j].p3].x, PT[DTRI[j].p3].y, CC[i].x, CC[i].y)) { isCandidate = true; } } if(isCandidate) { CAND[indexCand].x = CC[i].x; CAND[indexCand].y = CC[i].y; CAND[indexCand++].r = CC[i].r; } } // Check CH + Voronoi Intersect for(int i = 0; i < indexCH; i++) { int A = iCH[i]; int B; if(i < indexCH - 1) { B = iCH[i + 1]; } else { B = iCH[0]; } double x = (PT[A].x + PT[B].x) / 2.0; double y = (PT[A].y + PT[B].y) / 2.0; CAND[indexCand].x = x; CAND[indexCand].y = y; CAND[indexCand++].r = qSqrt(((x - PT[A].x)*(x - PT[A].x)) + ((y - PT[A].y)*(y - PT[A].y))); } // Determine LEC determineLEC(); } void GLWidget::plotCandidate() { glColor3d(0.5, 0.1, 0.0); glBegin(GL_POINTS); for(int i = 0; i %f", i, LEC[indexLEC - 1].r, CAND[i].r); } } } bool GLWidget::isEmptyCircle(double x, double y, double radius) { int count = 0; for(int i = 0; i < SET; i++) { double tempRadius = qSqrt(((x - PT[i].x)*(x - PT[i].x)) + ((y - PT[i].y)*(y - PT[i].y))); if(tempRadius < radius) { count++; } } if(count > 0) { return false; } return true; } void GLWidget::plotLEC() { glColor3d(0.45, 0.85, 0.75); for(int i = 0; i < indexLEC; i++) { glBegin(GL_POINTS); glVertex2d(LEC[i].x, LEC[i].y); glEnd(); drawCircle(LEC[i].x, LEC[i].y, LEC[i].r, 100); } } // Copyright 2020 // // 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 "CFEContext.h" #include #include #include using llvm::cast; using llvm::cast_or_null; // Singleton context object that will be used by both the Clang plugin and // the LLVM pass. The only interface to this will be through the functions // defined here // static CFEContext* gCFEContext; CFEContext& CFEContext::getSingleton() { if(not gCFEContext) gCFEContext = new CFEContext; return *gCFEContext; } CFEContext::CFEContext() : papiContext(true), conf(papiContext) { ; } template static IDType constructID(std::string s) { const unsigned char* digest = reinterpret_cast(s.c_str()); unsigned char md5[MD5_DIGEST_LENGTH]; MD5(digest, s.length(), md5); // Read the 8 bytes of the 16 byte digest. Start somewhere in the middle for no // good reason IDType id = 0; for(unsigned start = 3, i = start; i < start + 8; i++) { id <<= 8; id |= md5[i]; } return id; } static RegionID constructRegionID(const std::string& file, unsigned startLine, unsigned endLine, const std::vector& counters) { // This is a ridiculous way of getting a hash // Concatenate everything including the counter ids. They are added to // minimize the small chances of a collision std::stringstream ss; ss << file << ":" << startLine << ":" << endLine; for(CounterID id : counters) ss << ":" << id; return constructID(ss.str()); } static FunctionID constructFunctionID(const std::string& mangled) { return constructID(mangled); } void CFEContext::addFunction(const std::string& mangled, const std::string& srcName, const std::string& qualName, const std::vector& counters) { funcs.emplace(std::pair( mangled, {constructFunctionID(mangled), counters, srcName, (srcName != qualName) ? qualName : ""})); } void CFEContext::addRegion(const std::string& file, unsigned startLine, unsigned endLine, const std::vector& counters) { regions.emplace_back(constructRegionID(file, startLine, endLine, counters), counters, file, startLine, endLine); } bool CFEContext::shouldInstrument(llvm::Function& f) const { return funcs.find(f.getName()) != funcs.end(); } const hwc::FEFuncMeta& CFEContext::getFuncMeta(llvm::Function& f) const { return funcs.at(f.getName()); } CFEContext::region_range CFEContext::getRegions() const { return region_range(regions.begin(), regions.end()); } const PAPIContext& CFEContext::getPAPIContext() const { return papiContext; } Conf& CFEContext::getConf() { return conf; } const Conf& CFEContext::getConf() const { return conf; } cspanier/shiftshift/render.vk/private/shift/render/vk/resource_streamer.hpp #ifndef SHIFT_RENDER_VK_RESOURCE_STREAMER_HPP #define SHIFT_RENDER_VK_RESOURCE_STREAMER_HPP #include #include #include #include #include #include #include #include #include "shift/render/vk/shared.hpp" #include "shift/render/vk/smart_ptr.hpp" #include "shift/render/vk/layer1/buffer.hpp" #include "shift/render/vk/layer1/image.hpp" namespace shift::resource_db { class image; } namespace shift::render::vk::layer1 { class device; class buffer; } namespace shift::render::vk::layer2 { class texture; } namespace shift::render::vk { /// This class manages asynchronous upload of buffer and image data using a /// separate device queue. /// @remarks /// We use a single large staging buffer of staging_buffer_size bytes. /// This buffer uses non-coherent shared memory that is permanently mapped /// into host address space. class resource_streamer { public: static constexpr std::size_t staging_buffer_size = 64 * 1024 * 1024; public: /// Constructor. resource_streamer(vk::layer1::device& device); /// Destructor. ~resource_streamer(); /// Creates device dependent resources. void create_resources(); /// Destroys all device dependent resources. void destroy_resources(); private: vk::layer1::device* _device = nullptr; vk::shared_ptr _staging_buffer; void* _staging_memory = nullptr; }; } #endif #include "dbusSensor.hpp" #include "exprtkTools.hpp" #include "thresholds.hpp" #include #include #include #include #include #include namespace phosphor { namespace virtualSensor { using Json = nlohmann::json; template using ServerObject = typename sdbusplus::server::object::object; using ValueIface = sdbusplus::xyz::openbmc_project::Sensor::server::Value; using ValueObject = ServerObject; class SensorParam { public: SensorParam() = delete; virtual ~SensorParam() = default; enum ParamType { constParam, dbusParam }; /** @brief Constructs SensorParam (type = constParam) * * @param[in] value - Value of constant parameter */ explicit SensorParam(double value) : value(value), paramType(constParam) {} /** @brief Constructs SensorParam (type = dbusParam) * * @param[in] bus - Handle to system dbus * @param[in] path - The Dbus path of sensor * @param[in] ctx - sensor context for update */ SensorParam(sdbusplus::bus::bus& bus, std::string path, void* ctx) : dbusSensor(std::make_unique(bus, path, ctx)), paramType(dbusParam) {} /** @brief Get sensor value property from D-bus interface */ double getParamValue(); private: std::unique_ptr dbusSensor = nullptr; double value = 0; ParamType paramType; }; class VirtualSensor : public ValueObject { public: VirtualSensor() = delete; virtual ~VirtualSensor() = default; /** @brief Constructs VirtualSensor * * @param[in] bus - Handle to system dbus * @param[in] objPath - The Dbus path of sensor * @param[in] sensorConfig - Json object for sensor config */ VirtualSensor(sdbusplus::bus::bus& bus, const char* objPath, const Json& sensorConfig, const std::string& name) : ValueObject(bus, objPath), bus(bus), name(name) { initVirtualSensor(sensorConfig, objPath); } /** @brief Set sensor value */ void setSensorValue(double value); /** @brief Update sensor at regular intrval */ void updateVirtualSensor(); /** @brief Map of list of parameters */ using ParamMap = std::unordered_map>; ParamMap paramMap; private: /** @brief sdbusplus bus client connection. */ sdbusplus::bus::bus& bus; /** @brief name of sensor */ std::string name; /** @brief Expression string for virtual sensor value calculations */ std::string exprStr; /** @brief symbol table from exprtk */ exprtk::symbol_table symbols{}; /** @brief expression from exprtk to calculate sensor value */ exprtk::expression expression{}; /** @brief The vecops package so the expression can use vectors */ exprtk::rtl::vecops::package vecopsPackage; /** @brief The critical threshold interface object */ std::unique_ptr> criticalIface; /** @brief The warning threshold interface object */ std::unique_ptr> warningIface; /** @brief The soft shutdown threshold interface object */ std::unique_ptr> softShutdownIface; /** @brief The hard shutdown threshold interface object */ std::unique_ptr> hardShutdownIface; /** @brief The performance loss threshold interface object */ std::unique_ptr> perfLossIface; /** @brief Read config from json object and initialize sensor data * for each virtual sensor */ void initVirtualSensor(const Json& sensorConfig, const std::string& objPath); /** @brief Check Sensor threshold and update alarm and log */ template void checkThresholds(V value, T& threshold) { if (!threshold) return; static constexpr auto tname = T::element_type::name; auto alarmHigh = threshold->alarmHigh(); if ((!alarmHigh && value >= threshold->high()) || (alarmHigh && value < threshold->high())) { if (!alarmHigh) { constexpr auto msg = "ASSERT: {} has exceeded the {} high threshold"; log(fmt::format(msg, name, tname).c_str()); threshold->alarmHighSignalAsserted(value); } else { constexpr auto msg = "DEASSERT: {} is under the {} high threshold"; log(fmt::format(msg, name, tname).c_str()); threshold->alarmHighSignalDeasserted(value); } threshold->alarmHigh(!alarmHigh); } auto alarmLow = threshold->alarmLow(); if ((!alarmLow && value <= threshold->low()) || (alarmLow && value > threshold->low())) { if (!alarmLow) { constexpr auto msg = "ASSERT: {} is under the {} low threshold"; log(fmt::format(msg, name, tname).c_str()); threshold->alarmLowSignalAsserted(value); } else { constexpr auto msg = "DEASSERT: {} is above the {} low threshold"; log(fmt::format(msg, name, tname).c_str()); threshold->alarmLowSignalDeasserted(value); } threshold->alarmLow(!alarmLow); } } }; class VirtualSensors { public: VirtualSensors() = delete; virtual ~VirtualSensors() = default; /** @brief Constructs VirtualSensors * * @param[in] bus - Handle to system dbus */ explicit VirtualSensors(sdbusplus::bus::bus& bus) : bus(bus) { createVirtualSensors(); } private: /** @brief sdbusplus bus client connection. */ sdbusplus::bus::bus& bus; /** @brief Parsing virtual sensor config JSON file */ Json parseConfigFile(const std::string configFile); /** @brief Map of the object VirtualSensor */ std::unordered_map> virtualSensorsMap; /** @brief Create list of virtual sensors */ void createVirtualSensors(); }; } // namespace virtualSensor } // namespace phosphor #include "PCH.h" #include "Humanoid.h" // Default constructor. Humanoid::Humanoid() { // Load textures. m_textureIDs[static_cast(ANIMATION_STATE::WALK_UP)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_walk_up.png"); m_textureIDs[static_cast(ANIMATION_STATE::WALK_DOWN)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_walk_down.png"); m_textureIDs[static_cast(ANIMATION_STATE::WALK_RIGHT)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_walk_right.png"); m_textureIDs[static_cast(ANIMATION_STATE::WALK_LEFT)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_walk_left.png"); m_textureIDs[static_cast(ANIMATION_STATE::IDLE_UP)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_idle_up.png"); m_textureIDs[static_cast(ANIMATION_STATE::IDLE_DOWN)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_idle_down.png"); m_textureIDs[static_cast(ANIMATION_STATE::IDLE_RIGHT)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_idle_right.png"); m_textureIDs[static_cast(ANIMATION_STATE::IDLE_LEFT)] = TextureManager::AddTexture("../resources/enemies/skeleton/spr_skeleton_idle_left.png"); // Set initial sprite. SetSprite(TextureManager::GetTexture(m_textureIDs[static_cast(ANIMATION_STATE::WALK_UP)]), false, 8, 12); }#include "Bitmap.h" #include "bitmaps.h" const static uint8_t bitmapData[] PROGMEM = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x18, 0x10, 0x30, 0x30, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf8, 0xf8, 0xf8, 0xf8, 0xf0, 0xf0, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0x78, 0x38, 0x18, 0x18, 0x8, 0x8, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, /* page 1 (lines 8-15) */ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xfe, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0x3, 0x7, 0x7, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3, 0x0, 0x0, 0x0, 0xe0, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x7c, 0x0, 0x0, 0x0, 0x0, 0x82, 0x86, 0x4, 0x8, 0x10, 0x0, 0x0, 0x0, 0x0, /* page 2 (lines 16-23) */ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0xff, 0xff, 0x80, 0x0, 0x0, 0x0, 0x3f, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x3f, 0x0, 0x0, 0x0, 0x80, 0xc1, 0xc1, 0xc1, 0xc1, 0x1, 0x1, 0x1, 0x0, 0x20, 0x60, 0xf0, 0xf8, 0xfc, 0xff, 0xff, 0xff, 0x7f, 0x3e, 0x0, 0x0, 0x0, 0x0, 0x0, /* page 3 (lines 24-31) */ 0x0, 0x0, 0x10, 0x10, 0x18, 0x1c, 0x1f, 0x1f, 0x1f, 0xf, 0xf, 0xf, 0xf, 0x7, 0x7, 0xc, 0x8, 0x0, 0x0, 0xb, 0xf, 0x1f, 0x1f, 0x1f, 0x1e, 0x1c, 0x8, 0x18, 0x10, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x8, 0x4, 0x6, 0x3, 0x3, 0x7, 0x7, 0xf, 0xf, 0xe, 0x1c, 0x18, 0x18, 0x10, 0x10, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }; const Bitmap nupoLogo(bitmapData, 63, 32); /*========================================================================= Program: Visualization Toolkit Module: vtkOpenXRRenderWindowInteractor.cxx Copyright (c) , , All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOpenXRRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkOpenGLState.h" #include "vtkOpenXRInteractorStyle.h" #include "vtkOpenXRRenderWindow.h" #include "vtkOpenXRUtilities.h" #include "vtk_jsoncpp.h" #include #include vtkStandardNewMacro(vtkOpenXRRenderWindowInteractor); //------------------------------------------------------------------------------ // Construct object so that light follows camera motion. vtkOpenXRRenderWindowInteractor::vtkOpenXRRenderWindowInteractor() { // This will create the actions name and store it in ActionMap vtkNew style; this->SetInteractorStyle(style); for (int i = 0; i < vtkEventDataNumberOfDevices; i++) { this->DeviceInputDownCount[i] = 0; } this->ActionManifestFileName = "./vtk_openxr_actions.json"; // OpenXR can't have slashes in the action set name (as well as action names) this->ActionSetName = "vtk-actions"; } //------------------------------------------------------------------------------ vtkOpenXRRenderWindowInteractor::~vtkOpenXRRenderWindowInteractor() { MapAction::iterator it; for (it = this->MapActionStruct_Name.begin(); it != this->MapActionStruct_Name.end(); ++it) { ActionData* actionData = it->second; delete actionData; } MapActionStruct_Name.clear(); } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::DoOneEvent( vtkVRRenderWindow* renWin, vtkRenderer* vtkNotUsed(ren)) { this->ProcessXrEvents(); if (this->Done || !vtkOpenXRManager::GetInstance().IsSessionRunning()) { return; } this->PollXrActions(); if (this->RecognizeGestures) { this->RecognizeComplexGesture(nullptr); } // Start a render this->InvokeEvent(vtkCommand::RenderEvent); renWin->Render(); } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::ProcessXrEvents() { vtkOpenXRManager& xrManager = vtkOpenXRManager::GetInstance(); XrEventDataBuffer eventData{}; while (xrManager.PollEvent(eventData)) { switch (eventData.type) { // We lost some data case XR_TYPE_EVENT_DATA_EVENTS_LOST: { const auto stateEvent = *reinterpret_cast(&eventData); vtkDebugMacro(<< "OpenXR event [XR_TYPE_EVENT_DATA_EVENTS_LOST] : " << stateEvent.lostEventCount << " events data lost!"); // do we care if the runtime loses events? break; } // case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: { vtkWarningMacro( << "OpenXR event [XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING] : exit render loop."); this->Done = true; return; } // case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { const auto stateEvent = *reinterpret_cast(&eventData); if (stateEvent.session != xrManager.GetSession()) { vtkErrorMacro(<< "OpenXR event [XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED] : session is " "different than this->Session. Aborting."); this->Done = true; return; } switch (stateEvent.state) { case XR_SESSION_STATE_READY: { vtkDebugMacro(<< "OpenXR event [XR_SESSION_STATE_READY] : Begin session"); xrManager.BeginSession(); break; } case XR_SESSION_STATE_STOPPING: vtkDebugMacro(<< "OpenXR event [XR_SESSION_STATE_STOPPING]"); case XR_SESSION_STATE_LOSS_PENDING: // Session was lost, so start over and poll for new systemId. vtkDebugMacro(<< "OpenXR event [XR_SESSION_STATE_LOSS_PENDING]"); case XR_SESSION_STATE_EXITING: { // Do not attempt to restart, because user closed this session. vtkDebugMacro(<< "OpenXR event [XR_SESSION_STATE_EXITING]"); vtkDebugMacro(<< "Exit render loop."); this->Done = true; break; } } break; } case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: { vtkDebugMacro(<< "OpenXR event [XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING]"); const auto stateEvent = *reinterpret_cast(&eventData); (void)stateEvent; break; } case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: { vtkDebugMacro(<< "OpenXR event [XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED]"); const auto stateEvent = *reinterpret_cast(&eventData); (void)stateEvent; XrInteractionProfileState state{ XR_TYPE_INTERACTION_PROFILE_STATE }; for (uint32_t hand : { vtkOpenXRManager::ControllerIndex::Left, vtkOpenXRManager::ControllerIndex::Right }) { if (!xrManager.XrCheckWarn(xrGetCurrentInteractionProfile(xrManager.GetSession(), xrManager.GetSubactionPaths()[hand], &state), "Failed to get interaction profile for hand " + hand)) { continue; } XrPath interactionProfile = state.interactionProfile; uint32_t strLength; char profileString[XR_MAX_PATH_LENGTH]; if (!xrManager.XrCheckWarn( xrPathToString(xrManager.GetXrRuntimeInstance(), interactionProfile, XR_MAX_PATH_LENGTH, &strLength, profileString), "Failed to get interaction profile path string for hand " + hand)) { continue; } vtkDebugMacro(<< "Interaction profile changed for " << hand << ": " << profileString); } break; } default: { vtkWarningMacro(<< "Unhandled event type " << vtkOpenXRUtilities::GetStructureTypeAsString(eventData.type)); break; } } } } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::ConvertOpenXRPoseToWorldCoordinates(const XrPosef& xrPose, double pos[3], // Output world position double wxyz[4], // Output world orientation quaternion double ppos[3], // Output physical position double wdir[3]) // Output world view direction (-Z) { vtkOpenXRUtilities::SetMatrixFromXrPose(this->PoseToWorldMatrix, xrPose); this->ConvertPoseToWorldCoordinates(this->PoseToWorldMatrix, pos, wxyz, ppos, wdir); } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::PollXrActions() { // Update the action states by syncing using the active action set vtkOpenXRManager::GetInstance().SyncActions(); // Iterate over all actions and update their data MapAction::iterator it; for (it = this->MapActionStruct_Name.begin(); it != this->MapActionStruct_Name.end(); ++it) { ActionData* actionData = it->second; // Update the state of the actions for left and right hands separately. for (uint32_t hand : { vtkOpenXRManager::ControllerIndex::Left, vtkOpenXRManager::ControllerIndex::Right }) { vtkOpenXRManager::GetInstance().UpdateActionData(actionData->ActionStruct, hand); } } // Construct the event data that contains position and orientation of each hand double pos[3] = { 0.0 }; double ppos[3] = { 0.0 }; double wxyz[4] = { 0.0 }; double wdir[3] = { 0.0 }; std::array, 2> eventDatas; for (const uint32_t hand : { vtkOpenXRManager::ControllerIndex::Left, vtkOpenXRManager::ControllerIndex::Right }) { XrPosef* handPose = this->GetHandPose(hand); if (handPose) { this->ConvertOpenXRPoseToWorldCoordinates(*handPose, pos, wxyz, ppos, wdir); auto edHand = vtkEventDataDevice3D::New(); edHand->SetDevice(hand == vtkOpenXRManager::ControllerIndex::Right ? vtkEventDataDevice::RightController : vtkEventDataDevice::LeftController); edHand->SetWorldPosition(pos); edHand->SetWorldOrientation(wxyz); edHand->SetWorldDirection(wdir); eventDatas[hand].TakeReference(edHand); // We should remove this and use event data directly int pointerIndex = static_cast(edHand->GetDevice()); this->SetPhysicalEventPosition(ppos[0], ppos[1], ppos[2], pointerIndex); this->SetWorldEventPosition(pos[0], pos[1], pos[2], pointerIndex); this->SetWorldEventOrientation(wxyz[0], wxyz[1], wxyz[2], wxyz[3], pointerIndex); } } // All actions are now updated, handle them now for (it = this->MapActionStruct_Name.begin(); it != this->MapActionStruct_Name.end(); ++it) { ActionData* actionData = it->second; for (uint32_t hand : { vtkOpenXRManager::ControllerIndex::Left, vtkOpenXRManager::ControllerIndex::Right }) { vtkEventDataDevice3D* eventData = eventDatas[hand]; if (eventData) { eventData->SetInput(actionData->DeviceInput); eventData->SetType(actionData->EventId); this->HandleAction(*actionData, hand, eventData); } } } } //------------------------------------------------------------------------------ XrPosef* vtkOpenXRRenderWindowInteractor::GetHandPose(const uint32_t hand) { if (this->MapActionStruct_Name.count("handpose") == 0) { return nullptr; } ActionData* adHandPose = this->MapActionStruct_Name["handpose"]; return &(adHandPose->ActionStruct.PoseLocations[hand].pose); } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::HandleAction( const ActionData& actionData, const int hand, vtkEventDataDevice3D* ed) { const Action_t& actionT = actionData.ActionStruct; switch (actionT.ActionType) { /*case XR_ACTION_TYPE_FLOAT_INPUT: actionT.States[hand]._float.type = XR_TYPE_ACTION_STATE_FLOAT; actionT.States[hand]._float.next = nullptr; if (!this->XrCheckError(xrGetActionStateFloat(Session, &info, &action_t.States[hand]._float), "Failed to get float value")) { return false; } break;*/ case XR_ACTION_TYPE_BOOLEAN_INPUT: this->HandleBooleanAction(actionData, hand, ed); break; case XR_ACTION_TYPE_VECTOR2F_INPUT: this->HandleVector2fAction(actionData, hand, ed); break; case XR_ACTION_TYPE_POSE_INPUT: this->HandlePoseAction(actionData, hand, ed); break; default: break; } } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::ApplyAction( const ActionData& actionData, vtkEventDataDevice3D* ed) { this->SetPointerIndex(static_cast(ed->GetDevice())); if (actionData.UseFunction) { actionData.Function(ed); } else { this->InvokeEvent(actionData.EventId, ed); } } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::HandleBooleanAction( const ActionData& actionData, const int hand, vtkEventDataDevice3D* ed) { XrActionStateBoolean value = actionData.ActionStruct.States[hand]._boolean; // Set the active state of the model vtkOpenXRRenderWindow::SafeDownCast(this->RenderWindow) ->SetModelActiveState(hand, value.isActive); // Do nothing if the controller is inactive if (!value.isActive) { return; } if (value.changedSinceLastSync) { vtkDebugMacro(<< "Boolean action \"" << actionData.Name << "\" is triggered with value " << value.currentState << " for hand " << hand); if (value.currentState == 1) { ed->SetAction(vtkEventDataAction::Press); } else { ed->SetAction(vtkEventDataAction::Release); } this->ApplyAction(actionData, ed); } } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::HandlePoseAction( const ActionData& actionData, const int hand, vtkEventDataDevice3D* ed) { XrActionStatePose pose = actionData.ActionStruct.States[hand]._pose; // Set the active state of the model vtkOpenXRRenderWindow::SafeDownCast(this->RenderWindow)->SetModelActiveState(hand, pose.isActive); // Do nothing if the controller is inactive if (!pose.isActive) { return; } this->ApplyAction(actionData, ed); } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::HandleVector2fAction( const ActionData& actionData, const int hand, vtkEventDataDevice3D* ed) { XrActionStateVector2f vec2f = actionData.ActionStruct.States[hand]._vec2f; // Set the active state of the model vtkOpenXRRenderWindow::SafeDownCast(this->RenderWindow) ->SetModelActiveState(hand, vec2f.isActive); // Do nothing if the controller is inactive if (!vec2f.isActive) { return; } if (vec2f.changedSinceLastSync) { vtkDebugMacro(<< "Vector2f : " << actionData.Name << ", x = " << vec2f.currentState.x << " / y = " << vec2f.currentState.y); if (vec2f.currentState.y == 0 || vec2f.currentState.x == 0) { return; } ed->SetTrackPadPosition(vec2f.currentState.x, vec2f.currentState.y); this->ApplyAction(actionData, ed); } } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::AddAction( const std::string& path, const vtkCommand::EventIds& eid) { if (this->MapActionStruct_Name.count(path) == 0) { ActionData* am = new ActionData(); this->MapActionStruct_Name[path] = am; } auto* am = this->MapActionStruct_Name[path]; am->EventId = eid; am->UseFunction = false; } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::AddAction( const std::string& path, const std::function& func) { if (this->MapActionStruct_Name.count(path) == 0) { ActionData* am = new ActionData(); this->MapActionStruct_Name[path] = am; } auto* am = this->MapActionStruct_Name[path]; am->UseFunction = true; am->Function = func; } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::Initialize() { if (this->Initialized) { return; } // Start with superclass initialization this->Superclass::Initialize(); vtkOpenXRRenderWindow* renWin = vtkOpenXRRenderWindow::SafeDownCast(this->RenderWindow); // Make sure the render window is initialized renWin->Initialize(); if (!renWin->GetInitialized()) { return; } // Grip actions are handled by the interactor directly (why?) this->AddAction("leftgripaction", [this](vtkEventData* ed) { this->HandleGripEvents(ed); }); this->AddAction("rightgripaction", [this](vtkEventData* ed) { this->HandleGripEvents(ed); }); // Create an entry for pose actions that are used to retrieve // Orientation and locations of trackers this->AddAction("handpose", vtkCommand::Move3DEvent); // this->AddAction("handposehandgrip", vtkCommand::Move3DEvent); std::string fullpath = vtksys::SystemTools::CollapseFullPath(this->ActionManifestFileName.c_str()); if (!this->LoadActions(fullpath)) { vtkErrorMacro(<< "Failed to load actions."); this->Initialized = false; return; } // All action sets have been created, so // We can now attach the action sets to the session if (!vtkOpenXRManager::GetInstance().AttachSessionActionSets()) { this->Initialized = false; return; } } //------------------------------------------------------------------------------ bool vtkOpenXRRenderWindowInteractor::LoadActions(const std::string& actionFilename) { vtkDebugMacro(<< "LoadActions from file : " << actionFilename); // As OpenXR does not yet have a way to pass a file to create actions // We need to create them programmatically, so we parse it with JsonCpp Json::Value root; // Open the file vtksys::ifstream file; file.open(actionFilename.c_str()); if (!file.is_open()) { vtkErrorMacro(<< "Unable to open openXR action file : " << actionFilename); return false; } Json::CharReaderBuilder builder; std::string formattedErrors; // parse the entire data into the Json::Value root if (!Json::parseFromStream(builder, file, &root, &formattedErrors)) { // Report failures and their locations in the document vtkErrorMacro(<< "Failed to parse action file with errors :" << endl << formattedErrors); return false; } // Create an action set std::string localizedActionSetName = "VTK actions"; vtkOpenXRManager::GetInstance().CreateActionSet(this->ActionSetName, localizedActionSetName); // We must select an action set to create actions // For instance only one action set so select it // Improvement: select each action set and create all actions // that belong to it vtkOpenXRManager::GetInstance().SelectActiveActionSet(0); // Create actions Json::Value actions = root["actions"]; if (actions.isNull()) { vtkErrorMacro(<< "Parse openxr_actions: Missing actions node"); return false; } Json::Value localization = root["localization"]; if (localization.isNull()) { vtkErrorMacro(<< "Parse openxr_actions: Missing localization node"); return false; } localization = localization[0]; for (Json::Value::ArrayIndex i = 0; i < actions.size(); ++i) { // Create one action per json value Json::Value action = actions[i]; std::string name = action["name"].asString(); std::string localizedName = localization[name].asString(); std::string type = action["type"].asString(); // If the action is an output, add it so that it will // connect to its binding without user having to specify. // Vibration is the only supported output if (type == "vibration") { if (this->MapActionStruct_Name.count(name) == 0) { ActionData* am = new ActionData(); this->MapActionStruct_Name[name] = am; } } // Check if the action is used by the interactor style // or ourself. If that's the case, create it // Else do nothing if (this->MapActionStruct_Name.count(name) == 0) { vtkWarningMacro( << "An action with name " << name << " is available but the interactor style or the interactor does not use it."); continue; } vtkDebugMacro(<< "Creating an action of type=" << type << ", with name=" << name << ", localizedName=" << localizedName); XrActionType xrActionType = this->GetActionTypeFromString(type); if (!xrActionType) { return false; } // Create the action using the selected action set Action_t actionStruct; actionStruct.ActionType = xrActionType; if (!vtkOpenXRManager::GetInstance().CreateOneAction(actionStruct, name, localizedName)) { return false; } // Store it to retrieve actions by their name this->MapActionStruct_Name[name]->ActionStruct = actionStruct; this->MapActionStruct_Name[name]->Name = name; } Json::Value defaultBindings = root["default_bindings"]; if (defaultBindings.isNull()) { vtkErrorMacro(<< "Parse openxr_actions: Missing default_bindings node"); return false; } // look in the same directory as the actionFilename std::string path = vtksys::SystemTools::GetFilenamePath(actionFilename); for (Json::Value::ArrayIndex i = 0; i < defaultBindings.size(); ++i) { Json::Value binding = defaultBindings[i]; std::string bindingUrl = binding["binding_url"].asString(); std::string bindingFilename = vtksys::SystemTools::CollapseFullPath(path + "/" + bindingUrl); if (!this->LoadDefaultBinding(bindingFilename)) { return false; } } return true; } //------------------------------------------------------------------------------ XrActionType vtkOpenXRRenderWindowInteractor::GetActionTypeFromString(const std::string& type) { if (type == "boolean") { return XR_ACTION_TYPE_BOOLEAN_INPUT; } else if (type == "float") { return XR_ACTION_TYPE_FLOAT_INPUT; } else if (type == "vector2") { return XR_ACTION_TYPE_VECTOR2F_INPUT; } else if (type == "pose") { return XR_ACTION_TYPE_POSE_INPUT; } else if (type == "vibration") { return XR_ACTION_TYPE_VIBRATION_OUTPUT; } else { vtkErrorMacro(<< "Unrecognized action type: " << type); return (XrActionType)0; } } //------------------------------------------------------------------------------ bool vtkOpenXRRenderWindowInteractor::LoadDefaultBinding(const std::string& bindingFilename) { Json::Value root; // Open the file vtksys::ifstream file; file.open(bindingFilename.c_str()); if (!file.is_open()) { vtkErrorMacro(<< "Unable to open openXR binding file : " << bindingFilename); return false; } Json::CharReaderBuilder builder; std::string formattedErrors; // parse the entire data into the Json::Value root if (!Json::parseFromStream(builder, file, &root, &formattedErrors)) { // Report failures and their locations in the document vtkErrorMacro(<< "Failed to parse binding file with errors :" << endl << formattedErrors); return false; } // Get the interaction profile name std::string interactionProfile = root["interaction_profile"].asString(); Json::Value bindings = root["bindings"]; Json::Value actionSet = bindings[this->ActionSetName]; if (actionSet.isNull()) { vtkErrorMacro(<< "Selected action set : " << this->ActionSetName << " is not in binding file : " << bindingFilename); return false; } // We need to fill this vector to suggest interaction profile bindings std::vector actionSuggestedBindings; // Get the XrPath from path string, // Get the XrAction from the string jsonValue["output"] // Store in the actionData the device input guessed from the path // And fill actionSuggestedBindings auto fillActionSuggestedBindings = [&](const std::string& path, const Json::Value& jsonValue) { // Get the action std::string action = jsonValue["output"].asString(); // Only suggest a binding for an action that is used by the interactor style // or ourself if (this->MapActionStruct_Name.count(action) == 0) { return; } vtkDebugMacro(<< "Add action : " << action << ", with path : " << path); ActionData* actionData = this->GetActionDataFromName(action); if (actionData != nullptr) { // Use the path to guess the device input if (path.find("trigger") != std::string::npos) { actionData->DeviceInput = vtkEventDataDeviceInput::Trigger; } else if (path.find("trackpad") != std::string::npos) { actionData->DeviceInput = vtkEventDataDeviceInput::TrackPad; } else if (path.find("grip") != std::string::npos) { actionData->DeviceInput = vtkEventDataDeviceInput::Grip; } else if (path.find("thumbstick") != std::string::npos) { actionData->DeviceInput = vtkEventDataDeviceInput::Joystick; } Action_t& actionT = actionData->ActionStruct; if (actionT.Action == XR_NULL_HANDLE) { vtkErrorMacro(<< "Action " << action << ", with path : " << path << " has a null handle !"); return; } XrPath xrPath = vtkOpenXRManager::GetInstance().GetXrPath(path); actionSuggestedBindings.push_back({ actionT.Action, xrPath }); } }; // First, look after all sources inputs, ie. boolean/float/vector2f actions Json::Value sources = actionSet["sources"]; for (Json::Value::ArrayIndex i = 0; i < sources.size(); ++i) { Json::Value source = sources[i]; // The path for this action std::string path = source["path"].asString(); // Iterate over all inputs and append to the path the selected input // For example, if the input is "click", then append click to the path // if the input is "position", add nothing as openxr binds the position as a vector2f // (for example if we want to retrieve the position of the trackpad as a vector2f directly) Json::Value inputs = source["inputs"]; for (auto const& inputStr : inputs.getMemberNames()) { Json::Value action = inputs[inputStr]; if (inputStr == "position") { fillActionSuggestedBindings(path, action); } else { fillActionSuggestedBindings(path + "/" + inputStr, action); } } } // Look under haptics for any outputs Json::Value haptics = actionSet["haptics"]; for (Json::Value::ArrayIndex i = 0; i < haptics.size(); i++) { Json::Value haptic = haptics[i]; // The path for this action std::string path = haptic["path"].asString(); // Iterate over all outputs fillActionSuggestedBindings(path, haptic); } // Submit all suggested bindings return vtkOpenXRManager::GetInstance().SuggestActions( interactionProfile, actionSuggestedBindings); } //------------------------------------------------------------------------------ vtkOpenXRRenderWindowInteractor::ActionData* vtkOpenXRRenderWindowInteractor::GetActionDataFromName( const std::string& actionName) { // Check if action data exists if (this->MapActionStruct_Name.count(actionName) == 0) { vtkWarningMacro(<< "vtkOpenXRRenderWindowInteractor: Attempt to get an action data with name " << actionName << " that does not exist in the map."); return nullptr; } return this->MapActionStruct_Name[actionName]; } //------------------------------------------------------------------------------ void vtkOpenXRRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) { os << indent << "vtkOpenXRRenderWindowInteractor" << "\n"; this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ bool vtkOpenXRRenderWindowInteractor::ApplyVibration(const std::string& actionName, const int hand, const float amplitude, const float duration, const float frequency) { ActionData* actionData = GetActionDataFromName(actionName); if (actionData == nullptr) { vtkWarningMacro( << "vtkOpenXRRenderWindowInteractor: Attempt to ApplyVibration using action data with name" << actionName << " that does not exist."); return false; } return vtkOpenXRManager::GetInstance().ApplyVibration( actionData->ActionStruct, hand, amplitude, duration, frequency); } /* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include "oauth2.h" #define BOOST_NETWORK_ENABLE_HTTPS #include #include #include #include #include #include #include #include #include #include "base64.h" #include "format.h" #include "http_common.h" #include "json.h" #include "logging.h" #include "time.h" namespace http = boost::network::http; namespace google { namespace { template struct Deleter { void operator()(T* p) { if (p) D(p); } }; class PKey { using PKCS8_Deleter = Deleter; using BIO_Deleter = Deleter; using EVP_PKEY_Deleter = Deleter; public: PKey() {} PKey(const std::string& private_key_pem) { std::unique_ptr buf( BIO_new_mem_buf((void*) private_key_pem.data(), -1)); if (buf == nullptr) { LOG(ERROR) << "BIO_new_mem_buf failed"; return; } std::unique_ptr p8inf( PEM_read_bio_PKCS8_PRIV_KEY_INFO(buf.get(), NULL, NULL, NULL)); if (p8inf == nullptr) { LOG(ERROR) << "PEM_read_bio_PKCS8_PRIV_KEY_INFO failed"; return; } private_key_.reset(EVP_PKCS82PKEY(p8inf.get())); if (private_key_ == nullptr) { LOG(ERROR) << "EVP_PKCS82PKEY failed"; } } std::string ToString() const { // TODO: Check for NULL and add exceptions. std::unique_ptr mem(BIO_new(BIO_s_mem())); EVP_PKEY_print_private(mem.get(), private_key_.get(), 0, NULL); char* pp; long len = BIO_get_mem_data(mem.get(), &pp); return std::string(pp, len); } EVP_PKEY* private_key() const { // A const_cast is fine because this is passed into functions that don't // modify pkey, but have silly signatures. return const_cast(private_key_.get()); } private: std::unique_ptr private_key_; }; class Finally { public: Finally(std::function cleanup) : cleanup_(cleanup) {} ~Finally() { cleanup_(); } private: std::function cleanup_; }; std::string Sign(const std::string& data, const PKey& pkey) { #if 0 LOG(ERROR) << "Signing '" << data << "' with '" << pkey.ToString() << "'"; #endif unsigned int capacity = EVP_PKEY_size(pkey.private_key()); std::unique_ptr result(new unsigned char[capacity]); char error[1024]; EVP_MD_CTX ctx; EVP_SignInit(&ctx, EVP_sha256()); Finally cleanup([&ctx, &error]() { if (EVP_MD_CTX_cleanup(&ctx) == 0) { ERR_error_string_n(ERR_get_error(), error, sizeof(error)); LOG(ERROR) << "EVP_MD_CTX_cleanup failed: " << error; } }); if (EVP_SignUpdate(&ctx, data.data(), data.size()) == 0) { ERR_error_string_n(ERR_get_error(), error, sizeof(error)); LOG(ERROR) << "EVP_SignUpdate failed: " << error; return ""; } unsigned int actual_result_size = 0; if (EVP_SignFinal(&ctx, result.get(), &actual_result_size, pkey.private_key()) == 0) { ERR_error_string_n(ERR_get_error(), error, sizeof(error)); LOG(ERROR) << "EVP_SignFinal failed: " << error; return ""; } #if 0 for (int i = 0; i < actual_result_size; ++i) { LOG(ERROR) << "Signature char '" << static_cast(result.get()[i]) << "'"; } #endif return std::string(reinterpret_cast(result.get()), actual_result_size); } } json::value OAuth2::ComputeTokenFromCredentials() const { const std::string service_account_email = environment_.CredentialsClientEmail(); const std::string private_key_pem = environment_.CredentialsPrivateKey(); if (private_key_pem.empty() || service_account_email.empty()) { return nullptr; } try { PKey private_key(private_key_pem); // Make a POST request to https://www.googleapis.com/oauth2/v3/token // with the body // grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$JWT_HEADER.$CLAIM_SET.$SIGNATURE // // The trailing part of that body has three variables that need to be // expanded. // Namely, $JWT_HEADER, $CLAIM_SET, and $SIGNATURE, separated by periods. // // $CLAIM_SET is a base64url encoding of a JSON object with five fields: // iss, scope, aud, exp, and iat. // iss: Service account email. We get this from user in the config file. // scope: Basically the requested scope (e.g. "permissions") for the token. // For our purposes, this is the constant string // "https://www.googleapis.com/auth/monitoring". // aud: Assertion target. Since we are asking for an access token, this is // the constant string "https://www.googleapis.com/oauth2/v3/token". This // is the same as the URL we are posting to. // iat: Time of the assertion (i.e. now) in units of "seconds from Unix // epoch". // exp: Expiration of assertion. For us this is 'iat' + 3600 seconds. // // $SIGNATURE is the base64url encoding of the signature of the string // $JWT_HEADER.$CLAIM_SET // where $JWT_HEADER and $CLAIM_SET are defined as above. Note that they are // separated by the period character. The signature algorithm used should be // SHA-256. The private key used to sign the data comes from the user. The // private key to use is the one associated with the service account email // address (i.e. the email address specified in the 'iss' field above). if (environment_.config().VerboseLogging()) { LOG(INFO) << "Getting an OAuth2 token"; } http::client client; http::client::request request(token_endpoint_); std::string grant_type = ::network::detail::encode_fragment( std::string("urn:ietf:params:oauth:grant-type:jwt-bearer")); //std::string jwt_header = ""; //std::string jwt_header = // base64::Encode("{\"alg\":\"RS256\",\"typ\":\"JWT\"}"); json::value jwt_object = json::object({ {"alg", json::string("RS256")}, {"typ", json::string("JWT")}, }); std::string jwt_header = base64::Encode(jwt_object->ToString()); auto now = std::chrono::system_clock::now(); auto exp = now + std::chrono::seconds(3600); json::value claim_set_object = json::object({ {"iss", json::string(service_account_email)}, {"scope", json::string("https://www.googleapis.com/auth/monitoring")}, {"aud", json::string(token_endpoint_)}, {"iat", json::number(time::SecondsSinceEpoch(now))}, {"exp", json::number(time::SecondsSinceEpoch(exp))}, }); if (environment_.config().VerboseLogging()) { LOG(INFO) << "claim_set = " << claim_set_object->ToString(); } std::string claim_set = base64::Encode(claim_set_object->ToString()); if (environment_.config().VerboseLogging()) { LOG(INFO) << "encoded claim_set = " << claim_set; } std::string signature = base64::Encode( Sign(jwt_header + "." + claim_set, private_key)); std::string request_body = "grant_type=" + grant_type + "&assertion=" + jwt_header + "." + claim_set + "." + signature; // TODO: Investigate whether we need this header. //request << boost::network::header("Connection", "close"); request << boost::network::header("Content-Length", std::to_string(request_body.size())); request << boost::network::header("Content-Type", "application/x-www-form-urlencoded"); request << boost::network::body(request_body); if (environment_.config().VerboseLogging()) { LOG(INFO) << "About to send request: " << request.uri().string() << " headers: " << request.headers() << " body: " << request.body(); } http::client::response response = client.post(request); if (status(response) >= 300) { throw boost::system::system_error( boost::system::errc::make_error_code(boost::system::errc::not_connected), format::Substitute("Server responded with '{{message}}' ({{code}})", {{"message", status_message(response)}, {"code", format::str(status(response))}})); } if (environment_.config().VerboseLogging()) { LOG(INFO) << "Token response: " << body(response); } json::value parsed_token = json::Parser::FromString(body(response)); if (environment_.config().VerboseLogging()) { LOG(INFO) << "Parsed token: " << *parsed_token; } return parsed_token; } catch (const json::Exception& e) { LOG(ERROR) << e.what(); return nullptr; } catch (const boost::system::system_error& e) { LOG(ERROR) << "HTTP error: " << e.what(); return nullptr; } } json::value OAuth2::GetMetadataToken() const { std::string token_response = environment_.GetMetadataString("instance/service-accounts/default/token"); if (token_response.empty()) { return nullptr; } if (environment_.config().VerboseLogging()) { LOG(INFO) << "Token response: " << token_response; } json::value parsed_token = json::Parser::FromString(token_response); if (environment_.config().VerboseLogging()) { LOG(INFO) << "Parsed token: " << *parsed_token; } return parsed_token; } std::string OAuth2::GetAuthHeaderValue() { if (auth_header_value_.empty() || token_expiration_->IsExpired()) { // Token expired; retrieve new value. json::value token_json = ComputeTokenFromCredentials(); if (token_json == nullptr) { LOG(INFO) << "Getting auth token from metadata server"; token_json = std::move(GetMetadataToken()); } if (token_json == nullptr) { LOG(ERROR) << "Unable to get auth token"; return ""; } try { // This object should be of the form: // { // "access_token" : $THE_ACCESS_TOKEN, // "token_type" : "Bearer", // "expires_in" : 3600 // } const json::Object* token = token_json->As(); const std::string access_token = token->Get("access_token"); const std::string token_type = token->Get("token_type"); const double expires_in = token->Get("expires_in"); if (token_type != "Bearer") { LOG(WARNING) << "Token type is not 'Bearer', but '" << token_type << "'"; } auth_header_value_ = token_type + " " + access_token; // Build in a 60 second slack to avoid timing problems (clock // skew, races). token_expiration_->Reset( std::chrono::seconds(static_cast(expires_in) - 60)); } catch (const json::Exception& e) { LOG(ERROR) << e.what(); return ""; } } return auth_header_value_; } } // google /** * Copyright (C) 2016 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/util/background_thread_clock_source.h" #include #include #include "mongo/stdx/memory.h" #include "mongo/stdx/thread.h" #include "mongo/util/time_support.h" namespace mongo { BackgroundThreadClockSource::BackgroundThreadClockSource(std::unique_ptr clockSource, Milliseconds granularity) : _clockSource(std::move(clockSource)), _granularity(granularity), _shutdownTimer(false) { _updateCurrent(); _startTimerThread(); } BackgroundThreadClockSource::~BackgroundThreadClockSource() { { stdx::unique_lock lock(_mutex); _shutdownTimer = true; _condition.notify_one(); } _timer.join(); } Milliseconds BackgroundThreadClockSource::getPrecision() { return _granularity; } Date_t BackgroundThreadClockSource::now() { return Date_t::fromMillisSinceEpoch(_current.load()); } void BackgroundThreadClockSource::_startTimerThread() { // Start the background thread that repeatedly sleeps for the specified duration of milliseconds // and wakes up to store the current time. _timer = stdx::thread([&]() { stdx::unique_lock lock(_mutex); while (!_shutdownTimer) { if (_condition.wait_for(lock, _granularity.toSystemDuration()) == stdx::cv_status::timeout) { _updateCurrent(); } } }); } void BackgroundThreadClockSource::_updateCurrent() { _current.store(_clockSource->now().toMillisSinceEpoch()); } } // namespace mongo // File: 4-5-5.cpp // Author: csh // Date: 2020/08/30 // =================== #include #include void reverseString(char *s1, int n = 1) { int len = strlen(s1); if(len > n) { char tmp = s1[len-n]; s1[len-n] = s1[0]; s1[0] = tmp; return reverseString(++s1, ++n); } } int main() { using namespace std; char s1[] = "abcde"; char s2[] = "abcdef"; reverseString(s1); reverseString(s2); cout << s1 << endl; cout << s2 << endl; return 0; } // Time: O(n) // Space: O(1) class Solution { public: bool verifyPreorder(vector& preorder) { int low = INT_MIN, i = -1; for (auto& p : preorder) { if (p < low) { return false; } while (i >= 0 && p > preorder[i]) { low = preorder[i--]; } preorder[++i] = p; } return true; } }; // Time: O(n) // Space: O(h) class Solution2 { public: bool verifyPreorder(vector& preorder) { int low = INT_MIN; stack path; for (auto& p : preorder) { if (p < low) { return false; } while (!path.empty() && p > path.top()) { // Traverse to its right subtree now. // Use the popped values as a lower bound because // we shouldn't come across a smaller number anymore. low = path.top(); path.pop(); } path.emplace(p); } return true; } }; /* -------------------------------------------------------------------------- * * OpenMM * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2010-2016 Stanford University and the Authors. * * Authors: * * Contributors: * * * * 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, CONTRIBUTORS 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 "openmm/serialization/CustomTorsionForceProxy.h" #include "openmm/serialization/SerializationNode.h" #include "openmm/Force.h" #include "openmm/CustomTorsionForce.h" #include using namespace OpenMM; using namespace std; CustomTorsionForceProxy::CustomTorsionForceProxy() : SerializationProxy("CustomTorsionForce") { } void CustomTorsionForceProxy::serialize(const void* object, SerializationNode& node) const { node.setIntProperty("version", 3); const CustomTorsionForce& force = *reinterpret_cast(object); node.setIntProperty("forceGroup", force.getForceGroup()); node.setBoolProperty("usesPeriodic", force.usesPeriodicBoundaryConditions()); node.setStringProperty("energy", force.getEnergyFunction()); SerializationNode& perTorsionParams = node.createChildNode("PerTorsionParameters"); for (int i = 0; i < force.getNumPerTorsionParameters(); i++) { perTorsionParams.createChildNode("Parameter").setStringProperty("name", force.getPerTorsionParameterName(i)); } SerializationNode& globalParams = node.createChildNode("GlobalParameters"); for (int i = 0; i < force.getNumGlobalParameters(); i++) { globalParams.createChildNode("Parameter").setStringProperty("name", force.getGlobalParameterName(i)).setDoubleProperty("default", force.getGlobalParameterDefaultValue(i)); } SerializationNode& energyDerivs = node.createChildNode("EnergyParameterDerivatives"); for (int i = 0; i < force.getNumEnergyParameterDerivatives(); i++) { energyDerivs.createChildNode("Parameter").setStringProperty("name", force.getEnergyParameterDerivativeName(i)); } SerializationNode& torsions = node.createChildNode("Torsions"); for (int i = 0; i < force.getNumTorsions(); i++) { int p1, p2, p3, p4; vector params; force.getTorsionParameters(i, p1, p2, p3, p4, params); SerializationNode& node = torsions.createChildNode("Torsion").setIntProperty("p1", p1).setIntProperty("p2", p2).setIntProperty("p3", p3).setIntProperty("p4", p4); for (int j = 0; j < (int) params.size(); j++) { stringstream key; key << "param"; key << j+1; node.setDoubleProperty(key.str(), params[j]); } } } void* CustomTorsionForceProxy::deserialize(const SerializationNode& node) const { int version = node.getIntProperty("version"); if (version < 1 || version > 3) throw OpenMMException("Unsupported version number"); CustomTorsionForce* force = NULL; try { CustomTorsionForce* force = new CustomTorsionForce(node.getStringProperty("energy")); force->setForceGroup(node.getIntProperty("forceGroup", 0)); if (version > 1) force->setUsesPeriodicBoundaryConditions(node.getBoolProperty("usesPeriodic")); const SerializationNode& perTorsionParams = node.getChildNode("PerTorsionParameters"); for (auto& parameter : perTorsionParams.getChildren()) force->addPerTorsionParameter(parameter.getStringProperty("name")); const SerializationNode& globalParams = node.getChildNode("GlobalParameters"); for (auto& parameter : globalParams.getChildren()) force->addGlobalParameter(parameter.getStringProperty("name"), parameter.getDoubleProperty("default")); if (version > 2) { const SerializationNode& energyDerivs = node.getChildNode("EnergyParameterDerivatives"); for (auto& parameter : energyDerivs.getChildren()) force->addEnergyParameterDerivative(parameter.getStringProperty("name")); } const SerializationNode& torsions = node.getChildNode("Torsions"); vector params(force->getNumPerTorsionParameters()); for (auto& torsion : torsions.getChildren()) { for (int j = 0; j < (int) params.size(); j++) { stringstream key; key << "param"; key << j+1; params[j] = torsion.getDoubleProperty(key.str()); } force->addTorsion(torsion.getIntProperty("p1"), torsion.getIntProperty("p2"), torsion.getIntProperty("p3"), torsion.getIntProperty("p4"), params); } return force; } catch (...) { if (force != NULL) delete force; throw; } } Engine/Plugins/Media/MfMedia/Source/MfMediaFactory/Private/MfMediaFactoryModule.cpp // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "MfMediaFactoryPrivate.h" #include "Containers/Array.h" #include "Containers/UnrealString.h" #include "IMediaModule.h" #include "IMediaOptions.h" #include "IMediaPlayerFactory.h" #include "Internationalization/Internationalization.h" #include "Misc/Paths.h" #include "Modules/ModuleInterface.h" #include "Modules/ModuleManager.h" #include "UObject/NameTypes.h" #include "../../MfMedia/Public/IMfMediaModule.h" DEFINE_LOG_CATEGORY(LogMfMediaFactory); #define LOCTEXT_NAMESPACE "FMfMediaFactoryModule" #define MFMEDIAFACTORY_USE_WINDOWS 0 // set this to one to enable MfMedia on Windows (experimental) /** * Implements the MfMediaFactory module. */ class FMfMediaFactoryModule : public IMediaPlayerFactory , public IModuleInterface { public: /** Default constructor. */ FMfMediaFactoryModule() { } public: //~ IMediaPlayerInfo interface virtual bool CanPlayUrl(const FString& Url, const IMediaOptions* Options, TArray* OutWarnings, TArray* OutErrors) const override { FString Scheme; FString Location; // check scheme if (!Url.Split(TEXT("://"), &Scheme, &Location, ESearchCase::CaseSensitive)) { if (OutErrors != nullptr) { OutErrors->Add(LOCTEXT("NoSchemeFound", "No URI scheme found")); } return false; } if (!SupportedUriSchemes.Contains(Scheme)) { if (OutErrors != nullptr) { OutErrors->Add(FText::Format(LOCTEXT("SchemeNotSupported", "The URI scheme '{0}' is not supported"), FText::FromString(Scheme))); } return false; } // check file extension if (Scheme == TEXT("file")) { const FString Extension = FPaths::GetExtension(Location, false); if (!SupportedFileExtensions.Contains(Extension)) { if (OutErrors != nullptr) { OutErrors->Add(FText::Format(LOCTEXT("ExtensionNotSupported", "The file extension '{0}' is not supported"), FText::FromString(Extension))); } return false; } } // check options if ((OutWarnings != nullptr) && (Options != nullptr)) { if (Options->GetMediaOption("PrecacheFile", false) && (Scheme != TEXT("file"))) { OutWarnings->Add(LOCTEXT("PrecachingNotSupported", "Precaching is supported for local files only")); } } return true; } virtual TSharedPtr CreatePlayer(IMediaEventSink& EventSink) override { auto MfMediaModule = FModuleManager::LoadModulePtr("MfMedia"); return (MfMediaModule != nullptr) ? MfMediaModule->CreatePlayer(EventSink) : nullptr; } virtual FText GetDisplayName() const override { return LOCTEXT("MediaPlayerDisplayName", "Microsoft Media Foundation"); } virtual FName GetPlayerName() const override { static FName PlayerName(TEXT("MfMedia")); return PlayerName; } virtual const TArray& GetSupportedPlatforms() const override { return SupportedPlatforms; } virtual bool SupportsFeature(EMediaFeature Feature) const override { return ((Feature == EMediaFeature::AudioSamples) || (Feature == EMediaFeature::AudioTracks) || (Feature == EMediaFeature::CaptionTracks) || (Feature == EMediaFeature::OverlaySamples) || (Feature == EMediaFeature::VideoSamples) || (Feature == EMediaFeature::VideoTracks)); } public: //~ IModuleInterface interface virtual void StartupModule() override { // supported file extensions SupportedFileExtensions.Add(TEXT("mp4")); #if MFMEDIAFACTORY_WINDOWS && MFMEDIAFACTORY_USE_WINDOWS SupportedFileExtensions.Add(TEXT("3g2")); SupportedFileExtensions.Add(TEXT("3gp")); SupportedFileExtensions.Add(TEXT("3gp2")); SupportedFileExtensions.Add(TEXT("3gpp")); SupportedFileExtensions.Add(TEXT("ac3")); SupportedFileExtensions.Add(TEXT("aif")); SupportedFileExtensions.Add(TEXT("aifc")); SupportedFileExtensions.Add(TEXT("aiff")); SupportedFileExtensions.Add(TEXT("amr")); SupportedFileExtensions.Add(TEXT("au")); SupportedFileExtensions.Add(TEXT("bwf")); SupportedFileExtensions.Add(TEXT("caf")); SupportedFileExtensions.Add(TEXT("cdda")); SupportedFileExtensions.Add(TEXT("m4a")); SupportedFileExtensions.Add(TEXT("m4v")); SupportedFileExtensions.Add(TEXT("mov")); SupportedFileExtensions.Add(TEXT("mp3")); SupportedFileExtensions.Add(TEXT("qt")); SupportedFileExtensions.Add(TEXT("sdv")); SupportedFileExtensions.Add(TEXT("snd")); SupportedFileExtensions.Add(TEXT("wav")); SupportedFileExtensions.Add(TEXT("wave")); #endif // supported platforms SupportedPlatforms.Add(TEXT("XboxOne")); #if MFMEDIAFACTORY_WINDOWS && MFMEDIAFACTORY_USE_WINDOWS SupportedPlatforms.Add(TEXT("Windows")); #endif // supported schemes SupportedUriSchemes.Add(TEXT("file")); #if MFMEDIAFACTORY_WINDOWS && MFMEDIAFACTORY_USE_WINDOWS SupportedUriSchemes.Add(TEXT("http")); SupportedUriSchemes.Add(TEXT("httpd")); SupportedUriSchemes.Add(TEXT("https")); SupportedUriSchemes.Add(TEXT("mms")); SupportedUriSchemes.Add(TEXT("rtsp")); SupportedUriSchemes.Add(TEXT("rtspt")); SupportedUriSchemes.Add(TEXT("rtspu")); #endif // register player factory auto MediaModule = FModuleManager::LoadModulePtr("Media"); if (MediaModule != nullptr) { MediaModule->RegisterPlayerFactory(*this); } } virtual void ShutdownModule() override { // unregister player factory auto MediaModule = FModuleManager::GetModulePtr("Media"); if (MediaModule != nullptr) { MediaModule->UnregisterPlayerFactory(*this); } } private: /** List of supported media file types. */ TArray SupportedFileExtensions; /** List of platforms that the media player support. */ TArray SupportedPlatforms; /** List of supported URI schemes. */ TArray SupportedUriSchemes; }; #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FMfMediaFactoryModule, MfMediaFactory); /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ using Heap = set>; class Solution { public: ListNode* mergeKLists(vector& lists) { Heap h; ListNode* temp, *res; temp = res = nullptr; const int &k = lists.size(); for (int i = 0; i < k; ++i) { if (lists[i] != nullptr) { h.insert(make_pair(lists[i] -> val, lists[i])); } } while (h.empty() == false) { ListNode* x = (*h.begin()).second; if (res == nullptr) { res = temp = x; } else { temp -> next = x; temp = temp -> next; } h.erase(h.begin()); if (x -> next != nullptr) { x = x -> next; h.insert(make_pair(x -> val, x)); } } return res; } }; RomanGaraev/diplomacy_searchbot /* Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ #include "encoding.h" #include #include #include #include #include #include "checks.h" #include "game.h" #include "game_state.h" #include "loc.h" #include "power.h" #define S_ARMY 0 #define S_FLEET 1 #define S_UNIT_NONE 2 #define S_AUS 3 #define S_ENG 4 #define S_FRA 5 #define S_ITA 6 #define S_GER 7 #define S_RUS 8 #define S_TUR 9 #define S_POW_NONE 10 #define S_BUILDABLE 11 #define S_REMOVABLE 12 #define S_DIS_ARMY 13 #define S_DIS_FLEET 14 #define S_DIS_UNIT_NONE 15 #define S_DIS_AUS 16 #define S_DIS_ENG 17 #define S_DIS_FRA 18 #define S_DIS_ITA 19 #define S_DIS_GER 20 #define S_DIS_RUS 21 #define S_DIS_TUR 22 #define S_DIS_POW_NONE 23 #define S_LAND 24 #define S_WATER 25 #define S_COAST 26 #define S_SC_AUS 27 #define S_SC_ENG 28 #define S_SC_FRA 29 #define S_SC_ITA 30 #define S_SC_GER 31 #define S_SC_RUS 32 #define S_SC_TUR 33 #define S_SC_POW_NONE 34 #define O_ARMY 0 #define O_FLEET 1 #define O_UNIT_NONE 2 #define O_AUS 3 #define O_ENG 4 #define O_FRA 5 #define O_ITA 6 #define O_GER 7 #define O_RUS 8 #define O_TUR 9 #define O_POW_NONE 10 #define O_HOLD 11 #define O_MOVE 12 #define O_SUPPORT 13 #define O_CONVOY 14 #define O_ORDER_NONE 15 #define O_SRC_AUS 16 #define O_SRC_ENG 17 #define O_SRC_FRA 18 #define O_SRC_ITA 19 #define O_SRC_GER 20 #define O_SRC_RUS 21 #define O_SRC_TUR 22 #define O_SRC_NONE 23 #define O_DEST_AUS 24 #define O_DEST_ENG 25 #define O_DEST_FRA 26 #define O_DEST_ITA 27 #define O_DEST_GER 28 #define O_DEST_RUS 29 #define O_DEST_TUR 30 #define O_DEST_NONE 31 #define O_SC_AUS 32 #define O_SC_ENG 33 #define O_SC_FRA 34 #define O_SC_ITA 35 #define O_SC_GER 36 #define O_SC_RUS 37 #define O_SC_TUR 38 #define O_SC_NONE 39 #define P_BOARD_STATE(r, i, j) (*((r) + ((i)*BOARD_STATE_ENC_WIDTH) + (j))) #define P_PREV_ORDERS(r, i, j) (*((r) + ((i)*PREV_ORDERS_ENC_WIDTH) + (j))) namespace py = pybind11; namespace dipcc { void encode_board_state(GameState &state, float *r) { memset(r, 0, 81 * BOARD_STATE_ENC_WIDTH * sizeof(float)); ////////////////////////////////////// // unit type, unit power, removable // ////////////////////////////////////// std::vector filled(81, false); for (auto p : state.get_units()) { OwnedUnit unit = p.second; JCHECK(unit.type != UnitType::NONE, "UnitType::NONE"); JCHECK(unit.loc != Loc::NONE, "Loc::NONE"); JCHECK(unit.power != Power::NONE, "Power::NONE"); bool removable = state.get_phase().season == 'W' && state.get_n_builds(unit.power) < 0; size_t loc_i = static_cast(unit.loc) - 1; P_BOARD_STATE(r, loc_i, unit.type == UnitType::ARMY ? S_ARMY : S_FLEET) = 1; P_BOARD_STATE(r, loc_i, S_AUS + static_cast(unit.power) - 1) = 1; P_BOARD_STATE(r, loc_i, S_REMOVABLE) = static_cast(removable); filled[loc_i] = true; // Mark parent if it's a coast Loc rloc = root_loc(unit.loc); if (unit.loc != rloc) { size_t rloc_i = static_cast(rloc) - 1; P_BOARD_STATE(r, rloc_i, unit.type == UnitType::ARMY ? S_ARMY : S_FLEET) = 1; P_BOARD_STATE(r, rloc_i, S_AUS + static_cast(unit.power) - 1) = 1; P_BOARD_STATE(r, rloc_i, S_REMOVABLE) = static_cast(removable); filled[rloc_i] = true; } } // Set locs with no units for (int i = 0; i < 81; ++i) { if (!filled[i]) { P_BOARD_STATE(r, i, S_UNIT_NONE) = 1; P_BOARD_STATE(r, i, S_POW_NONE) = 1; } } /////////////// // buildable // /////////////// if (state.get_phase().phase_type == 'A') { for (auto &p : state.get_all_possible_orders()) { auto order = p.second.begin(); if (order->get_type() == OrderType::B) { Loc loc = order->get_unit().loc; size_t loc_i = static_cast(loc) - 1; P_BOARD_STATE(r, loc_i, S_BUILDABLE) = 1; } } } ///////////////////// // dislodged units // ///////////////////// std::fill(filled.begin(), filled.end(), false); for (OwnedUnit unit : state.get_dislodged_units()) { size_t loc_i = static_cast(unit.loc) - 1; P_BOARD_STATE(r, loc_i, unit.type == UnitType::ARMY ? S_DIS_ARMY : S_DIS_FLEET) = 1; P_BOARD_STATE(r, loc_i, S_DIS_AUS + static_cast(unit.power) - 1) = 1; filled[loc_i] = true; // Mark parent if it's a coast Loc rloc = root_loc(unit.loc); if (unit.loc != rloc) { size_t rloc_i = static_cast(rloc) - 1; P_BOARD_STATE(r, rloc_i, unit.type == UnitType::ARMY ? S_DIS_ARMY : S_DIS_FLEET) = 1; P_BOARD_STATE(r, rloc_i, S_DIS_AUS + static_cast(unit.power) - 1) = 1; filled[rloc_i] = true; } } // Set locs with no dislodged units for (int i = 0; i < 81; ++i) { if (!filled[i]) { P_BOARD_STATE(r, i, S_DIS_UNIT_NONE) = 1; P_BOARD_STATE(r, i, S_DIS_POW_NONE) = 1; } } /////////////// // Area type // /////////////// for (int i = 0; i < 81; ++i) { Loc loc = LOCS[i]; if (is_water(loc)) { P_BOARD_STATE(r, i, S_WATER) = 1; } else if (is_coast(loc)) { P_BOARD_STATE(r, i, S_COAST) = 1; } else { P_BOARD_STATE(r, i, S_LAND) = 1; } } /////////////////// // supply center // /////////////////// auto centers = state.get_centers(); for (int i = 0; i < 81; ++i) { Loc loc = LOCS[i]; if (!is_center(loc) || loc != root_loc(loc)) { continue; } auto it = centers.find(loc); Power power = it == centers.end() ? Power::NONE : it->second; int off = power == Power::NONE ? 7 : static_cast(power) - 1; for (Loc cloc : expand_coasts(loc)) { int cloc_i = static_cast(cloc) - 1; P_BOARD_STATE(r, cloc_i, S_SC_AUS + off) = 1; } } } // encode_board_state void encode_prev_orders(PhaseData &phase_data, float *r) { JCHECK(phase_data.get_state().get_phase().phase_type == 'M', "encode_prev_orders called on non-movement phase"); memset(r, 0, 81 * PREV_ORDERS_ENC_WIDTH * sizeof(float)); // Store owner of each loc: unit owner if there is a unit, otherwise SC // owner, otherwise none (7) std::vector loc_owner(81, 7); //////////////////// // supply centers // //////////////////// std::vector filled(81, false); for (auto &p : phase_data.get_state().get_centers()) { Loc loc = p.first; Power power = p.second; int power_i = static_cast(power) - 1; for (Loc cloc : expand_coasts(loc)) { int cloc_i = static_cast(cloc) - 1; loc_owner[cloc_i] = power_i; P_PREV_ORDERS(r, cloc_i, O_SC_AUS + power_i) = 1; filled[cloc_i] = true; } } // Set unowned SC for (int i = 0; i < 81; ++i) { Loc loc = LOCS[i]; if (!filled[i] && is_center(root_loc(loc))) { P_PREV_ORDERS(r, i, O_SC_NONE) = 1; } } // set owner: units for (auto &p : phase_data.get_state().get_units()) { OwnedUnit unit = p.second; JCHECK(unit.type != UnitType::NONE, "UnitType::NONE"); JCHECK(unit.loc != Loc::NONE, "Loc::NONE"); JCHECK(unit.power != Power::NONE, "Power::NONE"); int power_i = static_cast(unit.power) - 1; for (Loc cloc : expand_coasts(unit.loc)) { int cloc_i = static_cast(cloc) - 1; loc_owner[cloc_i] = power_i; } } //////////// // orders // //////////// std::fill(filled.begin(), filled.end(), false); for (auto &it : phase_data.get_orders()) { Power power = it.first; for (auto &order : it.second) { Unit unit = order.get_unit(); int loc_i = static_cast(unit.loc) - 1; int rloc_i = static_cast(root_loc(unit.loc)) - 1; if (phase_data.get_state().get_unit(unit.loc) != unit.owned_by(power)) { // ignore bad order continue; } // Unit type, power P_PREV_ORDERS(r, loc_i, unit.type == UnitType::ARMY ? O_ARMY : O_FLEET) = 1; P_PREV_ORDERS(r, rloc_i, unit.type == UnitType::ARMY ? O_ARMY : O_FLEET) = 1; P_PREV_ORDERS(r, loc_i, O_AUS + static_cast(power) - 1) = 1; P_PREV_ORDERS(r, rloc_i, O_AUS + static_cast(power) - 1) = 1; // Order Type OrderType order_type = order.get_type(); int order_type_idx; if (order_type == OrderType::H) { order_type_idx = O_HOLD; } else if (order_type == OrderType::M) { order_type_idx = O_MOVE; } else if (order_type == OrderType::C) { order_type_idx = O_CONVOY; } else if (order_type == OrderType::SM || order_type == OrderType::SH) { order_type_idx = O_SUPPORT; } else { JFAIL("Unexpected order type"); } P_PREV_ORDERS(r, loc_i, order_type_idx) = 1; P_PREV_ORDERS(r, rloc_i, order_type_idx) = 1; // Src power if (order_type == OrderType::SH || order_type == OrderType::SM || order_type == OrderType::C) { int src_idx = O_SRC_AUS + loc_owner[static_cast(order.get_target().loc) - 1]; P_PREV_ORDERS(r, loc_i, src_idx) = 1; P_PREV_ORDERS(r, rloc_i, src_idx) = 1; } else { P_PREV_ORDERS(r, loc_i, O_SRC_NONE) = 1; P_PREV_ORDERS(r, rloc_i, O_SRC_NONE) = 1; } // Dest power if (order_type == OrderType::M || order_type == OrderType::SM || order_type == OrderType::C) { int dest_idx = O_DEST_AUS + loc_owner[static_cast(order.get_dest()) - 1]; P_PREV_ORDERS(r, loc_i, dest_idx) = 1; P_PREV_ORDERS(r, rloc_i, dest_idx) = 1; } else { P_PREV_ORDERS(r, loc_i, O_DEST_NONE) = 1; P_PREV_ORDERS(r, rloc_i, O_DEST_NONE) = 1; } filled[loc_i] = true; filled[rloc_i] = true; } // for (order : orders) } // for (power : powers) // Fill locations with no orders for (int i = 0; i < 81; ++i) { if (filled[i]) { continue; } P_PREV_ORDERS(r, i, O_UNIT_NONE) = 1; P_PREV_ORDERS(r, i, O_POW_NONE) = 1; P_PREV_ORDERS(r, i, O_ORDER_NONE) = 1; P_PREV_ORDERS(r, i, O_SRC_NONE) = 1; P_PREV_ORDERS(r, i, O_DEST_NONE) = 1; } } // encode_prev_orders } // namespace dipcc #include #include main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); setfillstyle( WIDE_DOT_FILL, RED); circle(100, 100, 50); floodfill(100, 100, WHITE); getch(); closegraph(); return 0; } Pcornat/BenLib0 /* ** BENSUPERPC PROJECT, 2020 ** Math ** File description: ** getSchwarzschild.cpp */ #ifndef GETSCHWARZCHILD_HPP_ #define GETSCHWARZCHILD_HPP_ #include #include "constant.hpp" namespace my { namespace math { namespace schwarzschild { template T getSchwarzschild(const T &masse); } // namespace schwarzschild } // namespace math } // namespace my #include "getSchwarzschild_imp.hpp" #endif 100-1000 /* * Copyright (c) 2013-2014 - Adjacent Link LLC, Bridgewater, New Jersey * Copyright (c) 2008 - DRS CenGen, LLC, Columbia, Maryland * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of DRS CenGen, LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "nemstatefullayer.h" #include "nemlayerstate.h" #include "nemlayerstateuninitialized.h" EMANE::NEMStatefulLayer::NEMStatefulLayer(NEMId id, NEMLayer * pLayer, EMANE::PlatformServiceProvider *pPlatformService): NEMLayer(id, pPlatformService), pLayer_(pLayer), pState_(NEMLayerStateUninitializedSingleton::instance()){} EMANE::NEMStatefulLayer::~NEMStatefulLayer(){} void EMANE::NEMStatefulLayer::initialize(Registrar & registrar) { pState_->handleInitialize(this,pLayer_.get(),registrar); } void EMANE::NEMStatefulLayer::configure(const ConfigurationUpdate & update) { pState_->handleConfigure(this,pLayer_.get(),update); } void EMANE::NEMStatefulLayer::start() { pState_->handleStart(this,pLayer_.get()); } void EMANE::NEMStatefulLayer::postStart() { pState_->handlePostStart(this,pLayer_.get()); } void EMANE::NEMStatefulLayer::stop() { pState_->handleStop(this,pLayer_.get()); } void EMANE::NEMStatefulLayer::destroy() throw() { pState_->handleDestroy(this,pLayer_.get()); } void EMANE::NEMStatefulLayer::processConfiguration(const ConfigurationUpdate & update) { pState_->processConfiguration(this,pLayer_.get(),update); } void EMANE::NEMStatefulLayer::processDownstreamControl(const ControlMessages & msgs) { pState_->processDownstreamControl(this,pLayer_.get(),msgs); } void EMANE::NEMStatefulLayer::processDownstreamPacket(DownstreamPacket & pkt, const ControlMessages & msgs) { pState_->processDownstreamPacket(this,pLayer_.get(),pkt,msgs); } void EMANE::NEMStatefulLayer::processUpstreamPacket(UpstreamPacket & pkt, const ControlMessages & msgs) { pState_->processUpstreamPacket(this,pLayer_.get(),pkt,msgs); } void EMANE::NEMStatefulLayer::processUpstreamControl(const ControlMessages & msgs) { pState_->processUpstreamControl(this,pLayer_.get(),msgs); } void EMANE::NEMStatefulLayer::processEvent(const EventId & id, const Serialization & serialization) { pState_->processEvent(this,pLayer_.get(),id,serialization); } void EMANE::NEMStatefulLayer::setUpstreamTransport(UpstreamTransport * pUpstreamTransport) { pLayer_->setUpstreamTransport(pUpstreamTransport); } void EMANE::NEMStatefulLayer::setDownstreamTransport(DownstreamTransport * pDownstreamTransport) { pLayer_->setDownstreamTransport(pDownstreamTransport); } void EMANE::NEMStatefulLayer::changeState(NEMLayerState * pState) { pState_ = pState; } void EMANE::NEMStatefulLayer::processTimedEvent(TimerEventId eventId, const TimePoint & expireTime, const TimePoint & scheduleTime, const TimePoint & fireTime, const void * arg) { pState_->processTimedEvent(this, pLayer_.get(),eventId,expireTime,scheduleTime,fireTime,arg); } rovedit/Fort-Candleextern/typed-geometry/src/typed-geometry/feature/quadric.hh0 #pragma once #include #include "Image.h" #include namespace sol { struct Image::ImageImpl { ImageImpl(unsigned int width, unsigned int height) : image(width, height) { } png::image image; }; Image::Image(unsigned int width, unsigned int height) : pimpl(std::make_unique(width, height)) { } Image::~Image() { } unsigned int Image::getWidth() const { return pimpl->image.get_width(); } unsigned int Image::getHeight() const { return pimpl->image.get_height(); } void Image::write(const char * const filename) { pimpl->image.write(filename); } void Image::setPixel(unsigned int x, unsigned int y, unsigned char r, unsigned char g, unsigned char b) { png::rgb_pixel pixel(r, g, b); pimpl->image.set_pixel(x, y, pixel); } }/* * Machine Generated source file for message "Death Message". * NOTE: The functions here must be completed by hand. * Generated on 05-February-1997 at 18:30:20 * Generated from file EVENTS.XLS by */ #include "MsgInc/DeathMessage.h" #include "mesg.h" #include "Squadron.h" #include "uicomms.h" #include "msginc/radiochattermsg.h" #include "falclib.h" #include "falcmesg.h" #include "falcgame.h" #include "falcsess.h" #include "team.h" #include "MissEval.h" //sfr: added here for checks #include "InvalidBufferException.h" extern bool g_bLogEvents; extern uchar GetOwner(uchar* map_data, GridIndex x, GridIndex y); void EvaluateKill(FalconDeathMessage *dtm, SimBaseClass *simShooter, CampBaseClass *campShooter, SimBaseClass *simTarget, CampBaseClass *campTarget); FalconDeathMessage::FalconDeathMessage(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback) : FalconEvent(DeathMessage, FalconEvent::SimThread, entityId, target, loopback) { dataBlock.dEntityID = FalconNullId; dataBlock.fEntityID = FalconNullId; } FalconDeathMessage::FalconDeathMessage(VU_MSG_TYPE type, VU_ID senderid, VU_ID target) : FalconEvent(DeathMessage, FalconEvent::SimThread, senderid, target) { type; } FalconDeathMessage::~FalconDeathMessage(void) { // Your Code Goes Here } int FalconDeathMessage::Process(uchar autodisp) { SimBaseClass* target = (SimBaseClass*) vuDatabase->Find(dataBlock.dEntityID); SimBaseClass* shooter = (SimBaseClass*) vuDatabase->Find(dataBlock.fEntityID); CampEntity campTarget = (CampEntity) GetEntityByCampID(dataBlock.dCampID); CampEntity campShooter = (CampEntity) GetEntityByCampID(dataBlock.fCampID); if (autodisp) return 0; // send the death message to the base obj if (target) target->ApplyDeathMessage(this); // KCK: Chalk off a vehicle in the unit if the target is a Campaign Unit if (campTarget and campTarget->IsUnit()) { if ( not campTarget->IsAggregate() and target and not target->IsSetFalcFlag(FEC_REGENERATING)) campTarget->GetComponents()->Remove(target); if (campTarget->IsLocal()) campTarget->RecordCurrentState(NULL, FALSE); // Check for radar being killed // KCK NOTE: This will shut down radar for unit if ANY of our possibly multiple radar vehicles are killed if (target and campTarget->IsBattalion() and target->GetSlot() == ((Unit)campTarget)->GetUnitClassData()->RadarVehicle and campTarget->IsEmitting()) campTarget->SetEmitting(0); } // KCK: update kill records for mission evaluator. EvaluateKill(this, shooter, campShooter, target, campTarget); if (target and (target->IsAirplane() or not (rand() % 3))) { if (shooter and shooter->IsAirplane() and (GetTTRelations(shooter->GetTeam(), target->GetTeam()) >= Hostile) and rand() % 2 and not shooter->IsPlayer()) { FalconRadioChatterMessage *radioMessage = new FalconRadioChatterMessage(shooter->Id(), FalconLocalSession); radioMessage->dataBlock.from = shooter->Id(); radioMessage->dataBlock.to = MESSAGE_FOR_TEAM; if (((CampBaseClass*)shooter->GetCampaignObject())->IsFlight()) { radioMessage->dataBlock.voice_id = (uchar)((Flight)shooter->GetCampaignObject())->GetPilotVoiceID(((AircraftClass*)shooter)->vehicleInUnit); radioMessage->dataBlock.edata[0] = (short)shooter->GetCallsignIdx(); radioMessage->dataBlock.edata[1] = (short)((Flight)shooter->GetCampaignObject())->GetPilotCallNumber(((AircraftClass*)shooter)->vehicleInUnit); } else { radioMessage->dataBlock.voice_id = (uchar)(((int)shooter) % 12); // JPO VOICEFIX radioMessage->dataBlock.edata[0] = -1; radioMessage->dataBlock.edata[1] = -1; } if (target->IsAirplane()) { radioMessage->dataBlock.message = rcAIRBDA; //M.N. changed to 32767 which flexibly uses randomized values of available eval indexes radioMessage->dataBlock.edata[2] = 32767; /* if(rand()%2) radioMessage->dataBlock.edata[2] = 1; else radioMessage->dataBlock.edata[2] = 9;*/ } else if (target->IsUnit()) { radioMessage->dataBlock.message = rcMOVERBDA; radioMessage->dataBlock.edata[0] = 32767; } else { radioMessage->dataBlock.message = rcSTATICBDA; radioMessage->dataBlock.edata[2] = 32767; } FalconSendMessage(radioMessage, FALSE); } } return 0; } // ============================================= // Support Functions // ============================================= // Anytime something is killed, we need to credit the kill to the appropriate sources. void EvaluateKill(FalconDeathMessage *dtm, SimBaseClass *simShooter, CampBaseClass *campShooter, SimBaseClass *simTarget, CampBaseClass *campTarget) { int kill_type = -1, tid, ps = PILOT_KIA; Squadron sq; if ( not campShooter or not campTarget) return; // Determine type of kill // KCK: This check for being a player will probably not work if (simTarget and simTarget->IsSetFalcFlag(FEC_HASPLAYERS)) kill_type = ASTAT_PKILL; else if (campTarget->IsObjective()) kill_type = ASTAT_ASKILL; else if (campTarget->IsFlight()) kill_type = ASTAT_AAKILL; else if (campTarget->IsBattalion()) kill_type = ASTAT_AGKILL; else if (campTarget->IsTaskForce()) kill_type = ASTAT_ANKILL; // Credit kill if shooter was a flight and target was not on our team (not nessisarily ok for RoE) if (campShooter->IsFlight() and campShooter->GetTeam() not_eq campTarget->GetTeam()) { int pilot, squadron_pilot; // Find the pilot who did the killing (or pick one) sq = (Squadron)((Flight)campShooter)->GetUnitSquadron(); // JB 010107 //if (simShooter) if (simShooter and (void*) simShooter not_eq (void*) campShooter) // JB 010107 CTD Sanity check // JB 010107 pilot = ((SimMoverClass*)simShooter)->pilotSlot; else pilot = ((Flight)campShooter)->PickRandomPilot(campTarget->Id().num_); if (pilot < PILOTS_PER_FLIGHT) squadron_pilot = ((Flight)campShooter)->pilots[pilot]; else squadron_pilot = 255; // Player kill, probably // Update squadron records if (sq and squadron_pilot >= 0 and squadron_pilot < PILOTS_PER_SQUADRON and kill_type > -1) sq->ScoreKill(squadron_pilot, kill_type); } // Determine pilot status and chalk up a loss if (campTarget->IsFlight()) { GridIndex x, y; PilotClass *pc; int pilot, squadron_pilot; sq = (Squadron)((Flight)campTarget)->GetUnitSquadron(); // Find the target pilot if (simTarget) pilot = ((SimMoverClass*)simTarget)->pilotSlot; else if (dtm) pilot = dtm->dataBlock.dPilotID; else pilot = ((Flight)campTarget)->PickRandomPilot(campTarget->GetCampID()); if (pilot < PILOTS_PER_FLIGHT) squadron_pilot = ((Flight)campTarget)->pilots[pilot]; else squadron_pilot = 255; // Player kill, probably if (sq and squadron_pilot >= 0 and squadron_pilot < PILOTS_PER_SQUADRON) { pc = sq->GetPilotData(squadron_pilot); if (pc and pc->pilot_status not_eq PILOT_RESCUED) { pc->pilot_status = PILOT_KIA; // For campaign spawned deaths, we use the aircraft status, and assume rescued if over friendly // territory. // For sim spawned deaths, we assume KIA. Choose between MIA and rescued if and when we get an // eject message if ( not dtm or dtm->dataBlock.dEntityID not_eq FalconNullId) { if (((Flight)campTarget)->plane_stats[pilot] == AIRCRAFT_MISSING) { campTarget->GetLocation(&x, &y); if (GetRoE(GetOwner(TheCampaign.CampMapData, x, y), campTarget->GetTeam(), ROE_AIR_USE_BASES) == ROE_ALLOWED) ps = pc->pilot_status = PILOT_RESCUED; else ps = pc->pilot_status = PILOT_MIA; } } if (pc->pilot_id == 1) pc->pilot_status = PILOT_AVAILABLE; } } } // Update mission evaluation records if either target or shooter is in our package if (dtm and ((campTarget and (campTarget->InPackage() or g_bLogEvents)) or (campShooter and (campShooter->InPackage() or g_bLogEvents)))) TheCampaign.MissionEvaluator->RegisterKill(dtm, kill_type, ps); // Update some status flags as well for all hits if (simTarget) tid = simTarget->GetSlot(); else tid = 255; TheCampaign.MissionEvaluator->RegisterKill(campShooter, campTarget, tid); } 1-10 // Copyright 2016 The Goma 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 "local_output_cache.h" #include #include #include #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "content.h" #include "path.h" #include "unittest_util.h" #ifdef _WIN32 # include "posix_helper_win.h" #endif namespace devtools_goma { // // /cache -- LocalOutputCache // build -- build directory // class LocalOutputCacheTest : public ::testing::Test { protected: void SetUp() override { tmpdir_ = absl::make_unique("localoutputcache-test"); tmpdir_->MkdirForPath("build", true); tmpdir_->MkdirForPath("cache", true); } void TearDown() override { LocalOutputCache::Quit(); } void InitLocalOutputCache() { const std::int64_t max_cache_amount = 1000000; const std::int64_t threshold_cache_amount = 10000000; const size_t max_items = 1000; const size_t threshold_items = 1000; InitLocalOutputCacheWithParams(max_cache_amount, threshold_cache_amount, max_items, threshold_items); } void InitLocalOutputCacheWithParams(std::int64_t max_cache_amount, std::int64_t threshold_cache_amount, size_t max_items, size_t threshold_items) { LocalOutputCache::Init(tmpdir_->FullPath("cache"), nullptr, max_cache_amount, threshold_cache_amount, max_items, threshold_items); } ExecReq MakeFakeExecReq() { ExecReq req; req.mutable_command_spec()->set_name("clang"); req.mutable_command_spec()->set_version("4.2.1"); req.mutable_command_spec()->set_target("x86_64-unknown-linux-gnu"); req.set_cwd(tmpdir_->FullPath("build")); return req; } ExecReq MakeFakeExecReqWithArgs(const std::vector& args) { ExecReq req = MakeFakeExecReq(); for (const auto& arg : args) { req.add_arg(arg); } return req; } ExecResp MakeFakeExecResp() { ExecResp resp; resp.mutable_result()->set_exit_status(0); ExecResult_Output* output = resp.mutable_result()->add_output(); output->set_filename("output.o"); return resp; } std::string CacheFilePath(absl::string_view key) { return LocalOutputCache::instance()->CacheFilePath(key); } bool ShouldInvokeGarbageCollection() { return LocalOutputCache::instance()->ShouldInvokeGarbageCollection(); } void RunGarbageCollection(LocalOutputCache::GarbageCollectionStat* stat) { LocalOutputCache::instance()->RunGarbageCollection(stat); } std::unique_ptr tmpdir_; }; TEST_F(LocalOutputCacheTest, Match) { InitLocalOutputCache(); const std::string trace_id = "(test-match)"; // 1. Make ExecReq and ExecResp for fake compile ExecReq req = MakeFakeExecReq(); ExecResp resp = MakeFakeExecResp(); // 2. Try to Save output. tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::MakeCacheKey(req); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); // 3. Clean build directory tmpdir_->RemoveTmpFile("build/output.o"); // 4. Lookup ExecResp looked_up_resp; EXPECT_TRUE(LocalOutputCache::instance()->Lookup(key, &looked_up_resp, trace_id)); // 5. Check ExecResp content EXPECT_EQ(1, looked_up_resp.result().output_size()); EXPECT_EQ("output.o", looked_up_resp.result().output(0).filename()); } TEST_F(LocalOutputCacheTest, NoMatch) { InitLocalOutputCache(); const std::string trace_id = "(test-nomatch)"; // 1. Make ExecReq and ExecResp for fake compile ExecReq req = MakeFakeExecReq(); ExecResp resp = MakeFakeExecResp(); // 2. Try to Save output. tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::MakeCacheKey(req); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); // 3. Clean build directory tmpdir_->RemoveTmpFile("build/output.o"); // 4. Lookup (should fail here) ExecResp looked_up_resp; std::string fake_key = ""; EXPECT_FALSE(LocalOutputCache::instance()->Lookup(fake_key, &looked_up_resp, trace_id)); } TEST_F(LocalOutputCacheTest, CollectGarbage) { InitLocalOutputCacheWithParams(0, 0, 100, 100); const std::string trace_id = "(garbage)"; // Make Item. ExecReq req = MakeFakeExecReq(); ExecResp resp = MakeFakeExecResp(); tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::instance()->MakeCacheKey(req); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); // Check key exists. std::string path = CacheFilePath(key); EXPECT_EQ(0, access(path.c_str(), F_OK)); // The item should be removed here, since max cache amount is small enough. { LocalOutputCache::GarbageCollectionStat stat; RunGarbageCollection(&stat); EXPECT_NE(0, access(path.c_str(), F_OK)); EXPECT_EQ(1U, stat.num_removed); EXPECT_EQ(0U, stat.num_failed); } } TEST_F(LocalOutputCacheTest, WontCollectGarbage) { InitLocalOutputCacheWithParams(1000000, 1000000, 100, 100); const std::string trace_id = "(garbage)"; // Make Item. ExecReq req = MakeFakeExecReq(); ExecResp resp = MakeFakeExecResp(); tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::instance()->MakeCacheKey(req); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); // Check key exists. std::string path = CacheFilePath(key); EXPECT_EQ(0, access(path.c_str(), F_OK)); // Run garbage collection. Here, anything won't be removed, since // max cache amount is large enough. { LocalOutputCache::GarbageCollectionStat stat; RunGarbageCollection(&stat); EXPECT_EQ(0, access(path.c_str(), F_OK)); EXPECT_EQ(0U, stat.num_removed); EXPECT_EQ(0U, stat.num_failed); } } TEST_F(LocalOutputCacheTest, CollectGarbageByNumItems) { // Allow max 99 items. InitLocalOutputCacheWithParams(10000000, 10000000, 99, 60); const std::string trace_id = "(garbage)"; std::vector keys; absl::flat_hash_set key_set; // Make 99 items. for (int i = 0; i < 99; ++i) { ExecReq req = MakeFakeExecReqWithArgs(std::vector { "clang", "-DFOO=" + std::to_string(i), }); ExecResp resp = MakeFakeExecResp(); tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::instance()->MakeCacheKey(req); keys.push_back(key); key_set.insert(key); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); } // All keys must be different. EXPECT_EQ(99UL, key_set.size()); // Check key exists. for (const auto& key : keys) { std::string path = CacheFilePath(key); EXPECT_EQ(0, access(path.c_str(), F_OK)); } // GC won't run yet. EXPECT_FALSE(ShouldInvokeGarbageCollection()); // Add last one. { ExecReq req = MakeFakeExecReqWithArgs(std::vector { "clang", "-DFOO=" + std::to_string(99), }); ExecResp resp = MakeFakeExecResp(); tmpdir_->CreateTmpFile("build/output.o", "(output)"); std::string key = LocalOutputCache::instance()->MakeCacheKey(req); keys.push_back(key); key_set.insert(key); EXPECT_TRUE(LocalOutputCache::instance()->SaveOutput( key, &req, &resp, trace_id)); } // All keys must be different. EXPECT_EQ(100UL, key_set.size()); // GC should run now. EXPECT_TRUE(ShouldInvokeGarbageCollection()); // Run garbage collection. // Since threshold is 60, 40 items must be removed. { LocalOutputCache::GarbageCollectionStat stat; RunGarbageCollection(&stat); EXPECT_EQ(40U, stat.num_removed); EXPECT_EQ(0U, stat.num_failed); } } } // namespace devtools_goma Graphs/DFS.cpp https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/tutorial/ DFS (Depth First Search) Is a recursive algorithm that uses the idea of backtracking. Time complexity : O(V+E) --------------------------- Applications: 1- How to find connected components using DFS? In an undirected graph : a connected component is a set of vertices in a graph that are linked to each other by paths. # Code: --------------------------- /*Author : */ /**************************/ /* Dear online judge: * I've read the problem, and tried to solve it. * Even if you don't accept my solution, you should respect my effort. * I hope my code compiles and gets accepted. * ___ __ * |\ \|\ \ * \ \ \_\ \ * \ \ ___ \emdan * \ \ \\ \ \ * \ \__\\ \_\ * \|__| \|__| */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define mp make_pair #define pb push_back #define endl '\n' #define sz ((int)(size())) #define len length() #define IO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define X first #define Y second #define all(v) ((v).begin()), ((v).end()) #define lop(i,init,n) for(int i=init;i #define vll vector #define si set #define sll set typedef long long int ll; typedef long double ld; const double EPS = 1e-9; const int MOD = 1e9 + 7; //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); //ll GCD(ll a, ll b) { // if (b == 0) return a; // return GCD(b, a%b); //} //ll LCM(ll a, ll b) { // return a / (GCD(a, b))* b; //} const int dx[] = { 1,-1,0,0,0,0 }; const int dy[] = { 0,0,1,-1,0,0 }; const int dz[] = { 0,0,0,0,1,-1 }; using namespace std; vector Adj[10]; bool Visited[15]; void DFS(int s) { Visited[s] = true; lop(i, 0, Adj[s].size()) { if (!Visited[Adj[s][i]]) { DFS(Adj[s][i]); } } } int main() { IO; int Nodes, Edges; int x, y; cin >> Nodes >> Edges; lop(i, 0, Edges) { cin >> x >> y; Adj[x].push_back(y); Adj[y].push_back(x); } mms(Visited, false); int CntCompo = 0; lop(i, 1, Nodes + 1) { // Means that this node is the beginning of a new Component.. if (!Visited[i]) { DFS(i); CntCompo++; } } cout << CntCompo << endl; } #ifdef PEGASUS_OS_STUB #ifndef __UNIX_DIAGNOSTICSETTINGDATA_PRIVATE_H #define __UNIX_DIAGNOSTICSETTINGDATA_PRIVATE_H #endif #endif #pragma once #include #include #define MAIN_MENU_ID 0x11000011 #define INFORMATION_MENU_ID 0x22000022 #define LOBBY_MENU_ID 0x33000033 #define GAME_MENU_ID 0x44000044 #define QUEST_MENU_ID 0x55000055 #define QUEST_FILTER_MENU_ID 0x66000066 #define PROXY_DESTINATIONS_MENU_ID 0x77000077 #define MAIN_MENU_GO_TO_LOBBY 0x11AAAA11 #define MAIN_MENU_INFORMATION 0x11BBBB11 #define MAIN_MENU_DOWNLOAD_QUESTS 0x11CCCC11 #define MAIN_MENU_PROXY_DESTINATIONS 0x11DDDD11 #define MAIN_MENU_DISCONNECT 0x11EEEE11 #define INFORMATION_MENU_GO_BACK 0x22FFFF22 #define PROXY_DESTINATIONS_MENU_GO_BACK 0x77FFFF77 struct MenuItem { enum Flag { INVISIBLE_ON_DC = 0x01, INVISIBLE_ON_PC = 0x02, INVISIBLE_ON_GC = 0x04, INVISIBLE_ON_BB = 0x08, DC_ONLY = INVISIBLE_ON_PC | INVISIBLE_ON_GC | INVISIBLE_ON_BB, PC_ONLY = INVISIBLE_ON_DC | INVISIBLE_ON_GC | INVISIBLE_ON_BB, GC_ONLY = INVISIBLE_ON_DC | INVISIBLE_ON_PC | INVISIBLE_ON_BB, BB_ONLY = INVISIBLE_ON_DC | INVISIBLE_ON_PC | INVISIBLE_ON_GC, REQUIRES_MESSAGE_BOXES = 0x10, }; uint32_t item_id; std::u16string name; std::u16string description; uint32_t flags; MenuItem(uint32_t item_id, const std::u16string& name, const std::u16string& description, uint32_t flags); }; 1-10 #include #include using namespace std; struct contatto { string nome; string numero; int preferenza; }; void ricerca(contatto rubrica[], string nome, int n) { for (int i = 0; i < n; i++) { if (rubrica[i].nome == nome) { cout << rubrica[i].nome << " " << rubrica[i].numero << endl; break; } } } void inserisci(contatto rubrica[]) { int n; cin >> n; if (n > 100) return 1; for (int i = 0; i < n; i++) { cout << "Inserire nome numero e preferenza: " string nome; cin >> nome; rubrica[i].nome = nome; // cin >> rubrica[i].nome; cin >> rubrica[i].numero; // ... } } int main() { // software gestione rubrica telefonica // contatto -> nome, numero contatto rubrica[100]; contatto pippo = {"Pippo", "1234567", 1}; contatto pluto = {"Pluto", "557789", 2}; rubrica[0] = pippo; rubrica[1] = pluto; string nome = "Pluto"; ricerca(rubrica, nome, 2); return 0; } 1-10 /* -------------------------------------------------------------------------------- # # 4DPlugin-vision.cpp # source generated by 4D Plugin Wizard # Project : vision # author : miyako # 2020/12/31 # # --------------------------------------------------------------------------------*/ #include "4DPlugin-vision.h" #pragma mark - void PluginMain(PA_long32 selector, PA_PluginParameters params) { try { switch(selector) { // --- vision case 1 : vision_process_data(params); break; case 2 : vision_get_version(params); break; } } catch(...) { } } #pragma mark utilities static void collection_push(PA_CollectionRef c, CFStringRef str) { if(str){ CFIndex len = CFStringGetLength(str); std::vector buf((len+1) * sizeof(PA_Unichar)); CFStringGetCharacters(str, CFRangeMake(0, len), (UniChar *)&buf[0]); PA_Unistring _value = PA_CreateUnistring((PA_Unichar *)&buf[0]); PA_Variable v = PA_CreateVariable(eVK_Unistring); PA_SetStringVariable(&v, &_value); PA_SetCollectionElement(c, PA_GetCollectionLength(c), v); // the unistring belongs to the collection // PA_DisposeUnistring(&_value); PA_ClearVariable(&v); } } static void collection_push(PA_CollectionRef c, PA_ObjectRef value) { if (value) { PA_Variable v = PA_CreateVariable(eVK_Object); PA_SetObjectVariable(&v, value); PA_SetCollectionElement(c, PA_GetCollectionLength(c), v); PA_ClearVariable(&v); } } static void collection_push(PA_CollectionRef c, const char *value) { if (value) { CFStringRef str = CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8 *)value, strlen(value), kCFStringEncodingUTF8, true); if(str){ collection_push(c, str); CFRelease(str); } } } static void collection_push(PA_CollectionRef c, NSString *str) { collection_push(c, (CFStringRef)str); } #pragma mark params static NSUInteger getMaxCandidateCount(PA_ObjectRef param) { NSUInteger maxCandidateCount = 1; if(param) { if(ob_is_defined(param, L"maxCandidateCount")) { NSUInteger value = ob_get_n(param, L"maxCandidateCount"); if((value < 11) && (value > 0)) maxCandidateCount = value; } } return maxCandidateCount; } static CGImagePropertyOrientation getOrientation(PA_ObjectRef param) { CGImagePropertyOrientation orientation = kCGImagePropertyOrientationUp; if(param) { if(ob_is_defined(param, L"orientation")) { CUTF8String _orientation; if(ob_get_s(param, L"orientation", &_orientation)) { if(_orientation == (const uint8_t *)"mirrored") { orientation = kCGImagePropertyOrientationUpMirrored; goto exit; } if(_orientation == (const uint8_t *)"down") { orientation = kCGImagePropertyOrientationDown; goto exit; } if(_orientation == (const uint8_t *)"downMirrored") { orientation = kCGImagePropertyOrientationDownMirrored; goto exit; } if(_orientation == (const uint8_t *)"leftMirrored") { orientation = kCGImagePropertyOrientationLeftMirrored; goto exit; } if(_orientation == (const uint8_t *)"right") { orientation = kCGImagePropertyOrientationRight; goto exit; } if(_orientation == (const uint8_t *)"rightMirrored") { orientation = kCGImagePropertyOrientationRightMirrored; goto exit; } if(_orientation == (const uint8_t *)"left") { orientation = kCGImagePropertyOrientationLeft; goto exit; } } } } exit: return orientation; } #pragma mark configure request static void getParamsForRequest(PA_ObjectRef detect, VNRequest *request) { if(ob_is_defined(detect, L"preferBackgroundProcessing")) { request.preferBackgroundProcessing = ob_get_b(detect, L"preferBackgroundProcessing"); } if(ob_is_defined(detect, L"usesCPUOnly")) { request.usesCPUOnly = ob_get_b(detect, L"usesCPUOnly"); } } static void getParamsForImageRequest(PA_ObjectRef detect, VNImageBasedRequest *request) { PA_ObjectRef regionOfInterest = ob_get_o(detect, L"regionOfInterest"); if(regionOfInterest) { CGRect rect; rect.origin.x = ob_get_n(regionOfInterest, L"x"); rect.origin.y = ob_get_n(regionOfInterest, L"y"); rect.size.width = ob_get_n(regionOfInterest, L"width"); rect.size.height = ob_get_n(regionOfInterest, L"height"); request.regionOfInterest = rect; } } static NSArray *createStringArrayForParam(PA_CollectionRef col) { NSMutableArray *arr = [[NSMutableArray alloc]init]; PA_long32 len = PA_GetCollectionLength(col); for(PA_long32 i = 0; i < len; ++i) { PA_Variable v = PA_GetCollectionElement(col, i); if(PA_GetVariableKind(v) == eVK_Unistring) { PA_Unistring ustr = PA_GetStringVariable(v); if(ustr.fLength) { NSString *str = [[NSString alloc]initWithCharacters:(const unichar *)ustr.fString length:ustr.fLength]; [arr addObject:str]; [str release]; } } } return arr; } API_AVAILABLE(macos(10.15)) static void getParamsForTextRequest(PA_ObjectRef detect, VNRecognizeTextRequest *request) { if(ob_is_defined(detect, L"minimumTextHeight")) { request.minimumTextHeight = ob_get_n(detect, L"minimumTextHeight"); } if(ob_is_defined(detect, L"usesLanguageCorrection")) { request.usesLanguageCorrection = ob_get_b(detect, L"usesLanguageCorrection"); } if(ob_is_defined(detect, L"recognitionLevel")) { request.recognitionLevel = (VNRequestTextRecognitionLevel)ob_get_n(detect, L"recognitionLevel"); } PA_CollectionRef recognitionLanguages = ob_get_c(detect, L"recognitionLanguages"); if(recognitionLanguages) { NSArray *arr = createStringArrayForParam(recognitionLanguages); request.customWords = arr; [arr release]; } PA_CollectionRef customWords = ob_get_c(detect, L"customWords"); if(customWords) { NSArray *arr = createStringArrayForParam(customWords); request.customWords = arr; [arr release]; } } static void getParamsForTextRequest(PA_ObjectRef detect, VNDetectTextRectanglesRequest *request) { if(ob_is_defined(detect, L"reportCharacterBoxes")) { request.reportCharacterBoxes = ob_get_b(detect, L"reportCharacterBoxes"); } } static void getParamsForLandmarkRequest(PA_ObjectRef detect, VNDetectFaceLandmarksRequest *request) { if(ob_is_defined(detect, L"constellation")) { if (@available(macOS 10.15, *)) { request.constellation = (VNRequestFaceLandmarksConstellation)ob_get_n(detect, L"constellation"); } else { // Fallback on earlier versions } } } #pragma mark get result for observation static bool targetContains(PA_ObjectRef param, NSString *target) { bool contains = false; if(param) { PA_CollectionRef targets = ob_get_c(param, L"targets"); if(targets) { NSArray *arr = createStringArrayForParam(targets); NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE %@", target]; contains = [[arr filteredArrayUsingPredicate:predicate]count]; [arr release]; } } return contains; } static VNDetectBarcodesRequest *getBarcodesRequest(PA_ObjectRef param) { //VNDetectBarcodesRequest < VNImageBasedRequest < VNRequest VNDetectBarcodesRequest *request = nil; if(targetContains(param, @"barcode")) { request = [[VNDetectBarcodesRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } static VNDetectFaceRectanglesRequest *getFaceRectanglesRequest(PA_ObjectRef param) { //VNDetectFaceRectanglesRequest < VNImageBasedRequest < VNRequest VNDetectFaceRectanglesRequest *request = nil; if(targetContains(param, @"face")) { request = [[VNDetectFaceRectanglesRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } static VNDetectFaceLandmarksRequest *getFaceLandmarksRequest(PA_ObjectRef param) { //VNDetectFaceLandmarksRequest < VNImageBasedRequest < VNRequest VNDetectFaceLandmarksRequest *request = nil; if(targetContains(param, @"part")) { request = [[VNDetectFaceLandmarksRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); getParamsForLandmarkRequest(param, request); } return request; } static VNDetectRectanglesRequest *getRectanglesRequest(PA_ObjectRef param) { //VNDetectRectanglesRequest < VNImageBasedRequest < VNRequest VNDetectRectanglesRequest *request = nil; if(targetContains(param, @"rect")) { request = [[VNDetectRectanglesRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } static VNDetectHorizonRequest *getHorizonRequest(PA_ObjectRef param) { //VNDetectHorizonRequest < VNImageBasedRequest < VNRequest VNDetectHorizonRequest *request = nil; if(targetContains(param, @"horizon")) { request = [[VNDetectHorizonRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } API_AVAILABLE(macos(10.15)) static VNDetectHumanRectanglesRequest *getHumanRectanglesRequest(PA_ObjectRef param) { //VNDetectHumanRectanglesRequest < VNImageBasedRequest < VNRequest VNDetectHumanRectanglesRequest *request = nil; if(targetContains(param, @"human")) { request = [[VNDetectHumanRectanglesRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } API_AVAILABLE(macos(10.15)) static VNRecognizeAnimalsRequest *getAnimalRequest(PA_ObjectRef param) { //VNRecognizeAnimalsRequest < VNImageBasedRequest < VNRequest VNRecognizeAnimalsRequest *request = nil; if(targetContains(param, @"animal")) { request = [[VNRecognizeAnimalsRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); } return request; } static VNDetectTextRectanglesRequest *getTextRectanglesRequest(PA_ObjectRef param) { //VNDetectTextRectanglesRequest < VNImageBasedRequest < VNRequest VNDetectTextRectanglesRequest *request = nil; if(targetContains(param, @"string")) { request = [[VNDetectTextRectanglesRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); getParamsForTextRequest(param, request); } return request; } API_AVAILABLE(macos(10.15)) static VNRecognizeTextRequest *getTextRequest(PA_ObjectRef param) { //VNRecognizeTextRequest < VNImageBasedRequest < VNRequest VNRecognizeTextRequest *request = nil; if(targetContains(param, @"text")) { request = [[VNRecognizeTextRequest alloc]initWithCompletionHandler:^void(VNRequest *request, NSError *error){ }]; getParamsForRequest(param, request); getParamsForImageRequest(param, request); getParamsForTextRequest(param, request); } return request; } #pragma mark - static void getResultsForObject(PA_ObjectRef result, VNDetectedObjectObservation *observation) { if(observation) { CGRect rect = observation.boundingBox; ob_set_n(result, L"x", rect.origin.x); ob_set_n(result, L"y", 1-rect.size.height-rect.origin.y); ob_set_n(result, L"width", rect.size.width); ob_set_n(result, L"height", rect.size.height); ob_set_n(result, L"confidence", observation.confidence); } } static void getResultsForHorizon(PA_ObjectRef result, VNHorizonObservation *observation) { if(observation) { ob_set_n(result, L"angle", observation.angle); CGAffineTransform transform = observation.transform; ob_set_n(result, L"a", transform.a); ob_set_n(result, L"b", transform.b); ob_set_n(result, L"c", transform.c); ob_set_n(result, L"d", transform.d); ob_set_n(result, L"tx", transform.tx); ob_set_n(result, L"ty", transform.ty); } } API_AVAILABLE(macos(10.15)) static void getResultsForText(PA_ObjectRef result, VNRecognizedTextObservation *observation, NSUInteger maxCandidateCount) { if(observation) { getResultsForObject(result, observation); NSArray *topCandidates = [observation topCandidates:maxCandidateCount]; for(VNRecognizedText *candidate in topCandidates) { ob_set_s(result, L"string", (const char *)[candidate.string UTF8String]); ob_set_n(result, L"confidence", candidate.confidence); } } } static void getResultsForText(PA_ObjectRef result, VNTextObservation *observation) { if(observation) { getResultsForObject(result, observation); NSArray *characterBoxes = [observation characterBoxes]; if(characterBoxes) { PA_CollectionRef characters = PA_CreateCollection(); for(VNRectangleObservation *characterBox in characterBoxes) { PA_ObjectRef character = PA_CreateObject(); getResultsForObject(character, characterBox); collection_push(characters, character); } ob_set_c(result, L"characters", characters); } } } static void getResultsForBarcode(PA_ObjectRef result, VNBarcodeObservation *observation) { if(observation) { getResultsForObject(result, observation); VNBarcodeSymbology symbology = observation.symbology; NSString *payloadStringValue = observation.payloadStringValue; ob_set_s(result, L"symbology", (const char *)[symbology UTF8String]); ob_set_s(result, L"payloadStringValue", (const char *)[payloadStringValue UTF8String]); } } static void getResultsForFace(PA_ObjectRef result, VNFaceObservation *observation) { if (@available(macOS 10.14, *)) { if(observation) { getResultsForObject(result, observation); VNFaceLandmarks2D *landmarks = observation.landmarks; if(landmarks) { NSArray *parts = @[ @"leftPupil", @"rightPupil", @"leftEyebrow", @"rightEyebrow", @"leftEye", @"rightEye", @"innerLips", @"outerLips", @"nose", @"noseCrest", @"medianLine", @"faceContour", @"allPoints" ]; PA_CollectionRef col = PA_CreateCollection(); CGFloat height = observation.boundingBox.size.height; for(NSString *part in parts) { PA_ObjectRef o = PA_CreateObject(); VNFaceLandmarkRegion2D *region = [landmarks valueForKey:part]; const CGPoint *pts = region.normalizedPoints; NSUInteger len = region.pointCount; PA_CollectionRef points = PA_CreateCollection(); for(NSUInteger i = 0; i < len; ++i) { CGPoint p = *pts; NSString *xy = [NSString stringWithFormat:@"%lf,%lf", p.x, 1-p.y]; collection_push(points, xy); pts++; } ob_set_c(o, L"points", points); ob_set_s(o, L"type", (const char *)[part UTF8String]); collection_push(col, o); } ob_set_c(result, L"parts", col); } ob_set_n(result, L"roll", [observation.roll doubleValue]); ob_set_n(result, L"yaw", [observation.yaw doubleValue]); if (@available(macOS 10.15, *)) { ob_set_n(result, L"faceCaptureQuality", [observation.faceCaptureQuality doubleValue]); } } } } #pragma mark get result for request static void getResultsForRects(PA_ObjectRef returnValue, VNDetectRectanglesRequest *request) { PA_CollectionRef barcodes = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNRectangleObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForObject(result, observation); collection_push(barcodes, result); } } ob_set_c(returnValue, L"barcodes", barcodes); } static void getResultsForBarcodes(PA_ObjectRef returnValue, VNDetectBarcodesRequest *request) { PA_CollectionRef barcodes = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNBarcodeObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForBarcode(result, observation); collection_push(barcodes, result); } } ob_set_c(returnValue, L"barcodes", barcodes); } static void getResultsForHorizon(PA_ObjectRef returnValue, VNDetectHorizonRequest *request) { PA_CollectionRef barcodes = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNHorizonObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForHorizon(result, observation); collection_push(barcodes, result); } } ob_set_c(returnValue, L"barcodes", barcodes); } static void getResultsForTexts(PA_ObjectRef returnValue, VNDetectTextRectanglesRequest *request) { PA_CollectionRef texts = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNTextObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForText(result, observation); collection_push(texts, result); } } ob_set_c(returnValue, L"texts", texts); } static void getResultsForFaces(PA_ObjectRef returnValue, VNDetectFaceRectanglesRequest *request) { PA_CollectionRef faces = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNFaceObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForFace(result, observation); collection_push(faces, result); } } ob_set_c(returnValue, L"faces", faces); } static void getResultsForFaceLandmarks(PA_ObjectRef returnValue, VNDetectFaceLandmarksRequest *request) { PA_CollectionRef parts = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNFaceObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForFace(result, observation); collection_push(parts, result); } } ob_set_c(returnValue, L"faceLandmarks", parts); } API_AVAILABLE(macos(10.15)) static void getResultsForTexts(PA_ObjectRef returnValue, VNRecognizeTextRequest *request, NSUInteger maxCandidateCount) { PA_CollectionRef texts = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNRecognizedTextObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForText(result, observation, maxCandidateCount); collection_push(texts, result); } } ob_set_c(returnValue, L"recognizedTexts", texts); } API_AVAILABLE(macos(10.15)) static void getResultsForHumans(PA_ObjectRef returnValue, VNDetectHumanRectanglesRequest *request) { PA_CollectionRef humans = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNDetectedObjectObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForObject(result, observation); collection_push(humans, result); } } ob_set_c(returnValue, L"humans", humans); } API_AVAILABLE(macos(10.15)) static void getResultsForAnimals(PA_ObjectRef returnValue, VNRecognizeAnimalsRequest *request) { PA_CollectionRef animals = PA_CreateCollection(); if(request) { NSArray *results = [request results]; for(VNRecognizedObjectObservation *observation in results) { PA_ObjectRef result = PA_CreateObject(); getResultsForObject(result, observation); collection_push(animals, result); } } ob_set_c(returnValue, L"animals", animals); } #pragma mark API void vision_get_version(PA_PluginParameters params) { //animal,barcode,text PA_ObjectRef returnValue = PA_CreateObject(); ob_set_b(returnValue, L"success", false); BOOL success = false; NSError *error = nil; NSUInteger revision = 1; NSArray *supportedLanguages = nil; if (@available(macOS 10.15, *)) { PA_ObjectRef animal = PA_CreateObject(); revision = [VNRecognizeAnimalsRequest currentRevision]; NSArray *knownAnimalIdentifiersForRevision = [VNRecognizeAnimalsRequest knownAnimalIdentifiersForRevision:revision error:&error]; if(!error) { success = true; PA_CollectionRef knownAnimalIdentifiers = PA_CreateCollection(); for(VNAnimalIdentifier animalIdentifier in knownAnimalIdentifiersForRevision) { collection_push(knownAnimalIdentifiers, animalIdentifier); } ob_set_c(animal, L"knownAnimalIdentifiers", knownAnimalIdentifiers); ob_set_o(returnValue, L"animal", animal); } } PA_ObjectRef barcode = PA_CreateObject(); PA_CollectionRef symbologies = PA_CreateCollection(); NSArray *supportedSymbologies = [VNDetectBarcodesRequest supportedSymbologies]; for(VNBarcodeSymbology symbology in supportedSymbologies) { collection_push(symbologies, symbology); } ob_set_c(barcode, L"symbologies", symbologies); ob_set_o(returnValue, L"barcode", barcode); if (@available(macOS 10.15, *)) { PA_ObjectRef text = PA_CreateObject(); PA_ObjectRef languages = PA_CreateObject(); revision = [VNRecognizeTextRequest currentRevision]; supportedLanguages = [VNRecognizeTextRequest supportedRecognitionLanguagesForTextRecognitionLevel:VNRequestTextRecognitionLevelAccurate revision:revision error:&error]; if(!error) { PA_CollectionRef _languages = PA_CreateCollection(); for(NSString *language in supportedLanguages) { collection_push(_languages, language); } ob_set_c(languages, L"accurate", _languages); } supportedLanguages = [VNRecognizeTextRequest supportedRecognitionLanguagesForTextRecognitionLevel:VNRequestTextRecognitionLevelFast revision:revision error:&error]; if(!error) { PA_CollectionRef _languages = PA_CreateCollection(); for(NSString *language in supportedLanguages) { collection_push(_languages, language); } ob_set_c(languages, L"fast", _languages); } ob_set_o(text, L"languages", languages); ob_set_o(returnValue, L"text", text); } ob_set_b(returnValue, L"success", success); PA_ReturnObject(params, returnValue); } static NSData *createDataParameter(PA_PluginParameters params, short index) { NSData *data = nil; void *bytes = NULL; PA_long32 len = PA_GetBlobParameter(params, 1, bytes); if(len) { std::vectorbuf(len); bytes = &buf[0]; PA_GetBlobParameter(params, 1, bytes); data = [[NSData alloc]initWithBytes:(const void *)bytes length:(NSUInteger)len]; } return data; } void vision_process_data(PA_PluginParameters params) { PA_ObjectRef returnValue = PA_CreateObject(); ob_set_b(returnValue, L"success", false); NSData *imageData = createDataParameter(params, 1); PA_ObjectRef param = PA_GetObjectParameter(params, 2); if(imageData) { CGImagePropertyOrientation orientation = getOrientation(param); NSUInteger maxCandidateCount = getMaxCandidateCount(param); VNImageRequestHandler *requestHandler = [[VNImageRequestHandler alloc] initWithData:imageData orientation:orientation options:[NSDictionary dictionary]]; NSMutableArray *requests = [[NSMutableArray alloc]init]; VNDetectFaceRectanglesRequest *faceRequest = getFaceRectanglesRequest(param); VNDetectTextRectanglesRequest *textRequest = getTextRectanglesRequest(param); VNDetectHorizonRequest *horizonRequest = getHorizonRequest(param); VNDetectBarcodesRequest *barcodeRequest = getBarcodesRequest(param); VNDetectRectanglesRequest *rectRequest = getRectanglesRequest(param); VNDetectFaceLandmarksRequest *partRequest = getFaceLandmarksRequest(param); id recognizeTextRequest = nil; if (@available(macOS 10.15, *)) { recognizeTextRequest = getTextRequest(param); } id humanRequest = nil; if (@available(macOS 10.15, *)) { humanRequest = getHumanRectanglesRequest(param); } id animalRequest = nil; if (@available(macOS 10.15, *)) { animalRequest = getAnimalRequest(param); } if(faceRequest) { [requests addObject:faceRequest]; } if(partRequest) { [requests addObject:partRequest]; } if(textRequest) { [requests addObject:textRequest]; } if(horizonRequest) { [requests addObject:horizonRequest]; } if(barcodeRequest) { [requests addObject:barcodeRequest]; } if(rectRequest) { [requests addObject:rectRequest]; } if(recognizeTextRequest) { [requests addObject:recognizeTextRequest]; } if(humanRequest) { [requests addObject:humanRequest]; } if(animalRequest) { [requests addObject:animalRequest]; } NSError *error; BOOL success = [requestHandler performRequests:requests error:&error]; if(!success) { ob_set_n(returnValue, L"code", [error code]); ob_set_s(returnValue, L"description", [[error localizedDescription]UTF8String]); }else { if(partRequest) getResultsForFaceLandmarks(returnValue, partRequest); if(faceRequest) getResultsForFaces(returnValue, faceRequest); if(textRequest) getResultsForTexts(returnValue, textRequest); if(horizonRequest) getResultsForHorizon(returnValue, horizonRequest); if(barcodeRequest) getResultsForBarcodes(returnValue, barcodeRequest); if(rectRequest) getResultsForRects(returnValue, rectRequest); if (@available(macOS 10.15, *)) { if(humanRequest) getResultsForHumans(returnValue,humanRequest); } if (@available(macOS 10.15, *)) { if(animalRequest) getResultsForAnimals(returnValue,animalRequest); } if (@available(macOS 10.15, *)) { if(recognizeTextRequest) getResultsForTexts(returnValue,recognizeTextRequest, maxCandidateCount); } } ob_set_b(returnValue, L"success", success); if(partRequest) [partRequest release]; if(faceRequest) [faceRequest release]; if(textRequest) [textRequest release]; if(horizonRequest) [horizonRequest release]; if(barcodeRequest) [barcodeRequest release]; if(rectRequest) [rectRequest release]; if(recognizeTextRequest) [recognizeTextRequest release]; if(humanRequest) [humanRequest release]; if(animalRequest) [animalRequest release]; [requests release]; [requestHandler release]; [imageData release]; } PA_ReturnObject(params, returnValue); } include/alibabacloud/rpc.hpp1-10 // This file is auto-generated, don't edit it. Thanks. #ifndef ALIBABACLOUD_RPC_H_ #define ALIBABACLOUD_RPC_H_ #include #include #include #include #include #include #include using namespace std; namespace Alibabacloud_RPC { class Config : public Darabonba::Model { public: Config() {} explicit Config(const std::map &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { Darabonba::Model::validatePattern("regionId", regionId, "^[a-zA-Z0-9_-]+$"); Darabonba::Model::validatePattern("network", network, "^[a-zA-Z0-9_-]+$"); Darabonba::Model::validatePattern("suffix", suffix, "^[a-zA-Z0-9_-]+$"); } map toMap() override { map res; if (accessKeyId) { res["accessKeyId"] = boost::any(*accessKeyId); } if (accessKeySecret) { res["accessKeySecret"] = boost::any(*accessKeySecret); } if (securityToken) { res["securityToken"] = boost::any(*securityToken); } if (protocol) { res["protocol"] = boost::any(*protocol); } if (regionId) { res["regionId"] = boost::any(*regionId); } if (readTimeout) { res["readTimeout"] = boost::any(*readTimeout); } if (connectTimeout) { res["connectTimeout"] = boost::any(*connectTimeout); } if (httpProxy) { res["httpProxy"] = boost::any(*httpProxy); } if (httpsProxy) { res["httpsProxy"] = boost::any(*httpsProxy); } if (endpoint) { res["endpoint"] = boost::any(*endpoint); } if (noProxy) { res["noProxy"] = boost::any(*noProxy); } if (maxIdleConns) { res["maxIdleConns"] = boost::any(*maxIdleConns); } if (network) { res["network"] = boost::any(*network); } if (userAgent) { res["userAgent"] = boost::any(*userAgent); } if (suffix) { res["suffix"] = boost::any(*suffix); } if (socks5Proxy) { res["socks5Proxy"] = boost::any(*socks5Proxy); } if (socks5NetWork) { res["socks5NetWork"] = boost::any(*socks5NetWork); } if (endpointType) { res["endpointType"] = boost::any(*endpointType); } if (openPlatformEndpoint) { res["openPlatformEndpoint"] = boost::any(*openPlatformEndpoint); } if (type) { res["type"] = boost::any(*type); } return res; } void fromMap(map m) override { if (m.find("accessKeyId") != m.end() && !m["accessKeyId"].empty()) { accessKeyId = make_shared(boost::any_cast(m["accessKeyId"])); } if (m.find("accessKeySecret") != m.end() && !m["accessKeySecret"].empty()) { accessKeySecret = make_shared(boost::any_cast(m["accessKeySecret"])); } if (m.find("securityToken") != m.end() && !m["securityToken"].empty()) { securityToken = make_shared(boost::any_cast(m["securityToken"])); } if (m.find("protocol") != m.end() && !m["protocol"].empty()) { protocol = make_shared(boost::any_cast(m["protocol"])); } if (m.find("regionId") != m.end() && !m["regionId"].empty()) { regionId = make_shared(boost::any_cast(m["regionId"])); } if (m.find("readTimeout") != m.end() && !m["readTimeout"].empty()) { readTimeout = make_shared(boost::any_cast(m["readTimeout"])); } if (m.find("connectTimeout") != m.end() && !m["connectTimeout"].empty()) { connectTimeout = make_shared(boost::any_cast(m["connectTimeout"])); } if (m.find("httpProxy") != m.end() && !m["httpProxy"].empty()) { httpProxy = make_shared(boost::any_cast(m["httpProxy"])); } if (m.find("httpsProxy") != m.end() && !m["httpsProxy"].empty()) { httpsProxy = make_shared(boost::any_cast(m["httpsProxy"])); } if (m.find("endpoint") != m.end() && !m["endpoint"].empty()) { endpoint = make_shared(boost::any_cast(m["endpoint"])); } if (m.find("noProxy") != m.end() && !m["noProxy"].empty()) { noProxy = make_shared(boost::any_cast(m["noProxy"])); } if (m.find("maxIdleConns") != m.end() && !m["maxIdleConns"].empty()) { maxIdleConns = make_shared(boost::any_cast(m["maxIdleConns"])); } if (m.find("network") != m.end() && !m["network"].empty()) { network = make_shared(boost::any_cast(m["network"])); } if (m.find("userAgent") != m.end() && !m["userAgent"].empty()) { userAgent = make_shared(boost::any_cast(m["userAgent"])); } if (m.find("suffix") != m.end() && !m["suffix"].empty()) { suffix = make_shared(boost::any_cast(m["suffix"])); } if (m.find("socks5Proxy") != m.end() && !m["socks5Proxy"].empty()) { socks5Proxy = make_shared(boost::any_cast(m["socks5Proxy"])); } if (m.find("socks5NetWork") != m.end() && !m["socks5NetWork"].empty()) { socks5NetWork = make_shared(boost::any_cast(m["socks5NetWork"])); } if (m.find("endpointType") != m.end() && !m["endpointType"].empty()) { endpointType = make_shared(boost::any_cast(m["endpointType"])); } if (m.find("openPlatformEndpoint") != m.end() && !m["openPlatformEndpoint"].empty()) { openPlatformEndpoint = make_shared( boost::any_cast(m["openPlatformEndpoint"])); } if (m.find("type") != m.end() && !m["type"].empty()) { type = make_shared(boost::any_cast(m["type"])); } } shared_ptr accessKeyId{}; shared_ptr accessKeySecret{}; shared_ptr securityToken{}; shared_ptr protocol{}; shared_ptr regionId{}; shared_ptr readTimeout{}; shared_ptr connectTimeout{}; shared_ptr httpProxy{}; shared_ptr httpsProxy{}; shared_ptr credential{}; shared_ptr endpoint{}; shared_ptr noProxy{}; shared_ptr maxIdleConns{}; shared_ptr network{}; shared_ptr userAgent{}; shared_ptr suffix{}; shared_ptr socks5Proxy{}; shared_ptr socks5NetWork{}; shared_ptr endpointType{}; shared_ptr openPlatformEndpoint{}; shared_ptr type{}; ~Config() = default; }; class Client { public: shared_ptr _endpoint{}; shared_ptr _regionId{}; shared_ptr _protocol{}; shared_ptr _userAgent{}; shared_ptr _endpointRule{}; shared_ptr> _endpointMap{}; shared_ptr _suffix{}; shared_ptr _readTimeout{}; shared_ptr _connectTimeout{}; shared_ptr _httpProxy{}; shared_ptr _httpsProxy{}; shared_ptr _socks5Proxy{}; shared_ptr _socks5NetWork{}; shared_ptr _noProxy{}; shared_ptr _network{}; shared_ptr _productId{}; shared_ptr _maxIdleConns{}; shared_ptr _endpointType{}; shared_ptr _openPlatformEndpoint{}; shared_ptr _credential{}; explicit Client(const shared_ptr &config); map doRequest(shared_ptr action, shared_ptr protocol, shared_ptr method, shared_ptr version, shared_ptr authType, shared_ptr> query, shared_ptr> body, shared_ptr runtime); string getUserAgent(); string getAccessKeyId(); string getAccessKeySecret(); string getSecurityToken(); void checkConfig(shared_ptr config); static boost::any defaultAny(const boost::any &inputValue, const boost::any &defaultValue); ~Client() = default; }; } // namespace Alibabacloud_RPC #endif #include "ocr_engine/ocr_result.h" #include #include "ocr_engine/ocr_result_text.h" namespace dpso { OcrResult::OcrResult(Status status, const char* text) : status{status} , text{OcrResultText::create(text)} { } OcrResult::OcrResult( Status status, std::unique_ptr text) : status{status} , text{std::move(text)} { } OcrResult::~OcrResult() = default; OcrResult::OcrResult(OcrResult&&) noexcept = default; OcrResult& OcrResult::operator=(OcrResult&&) noexcept = default; OcrResult::Status OcrResult::getStatus() const { return status; } const char* OcrResult::getText() const { return text ? text->getData() : ""; } std::size_t OcrResult::getTextLen() const { return text ? text->getLen() : 0; } } 0 // /////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013 - // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. // /////////////////////////////////////////////////////////////////////////// #include #include #include #include #include namespace Bit { // Construcotrs Quad::Quad( ) { } Quad::Quad( Vector2_f32 p_Size ) : Size( p_Size ), Positsion( 0.0f, 0.0f ) { } Quad::Quad( Vector2_f32 p_Size, Vector2_f32 p_Positsion ) : Size( p_Size ), Positsion( p_Positsion ) { } // Public functions BIT_FLOAT32 Quad::GetArea( ) const { return Size.x * Size.y; } BIT_FLOAT32 Quad::GetDiagonal( ) const { return sqrt( ( Size.x * Size.x ) + ( Size.y * Size.y ) ); } Vector2_f32 Quad::GetLowCoords( ) const { return Vector2_f32( Positsion.x - ( Size.x / 2.0f ), Positsion.y - ( Size.y / 2.0f ) ); } Vector2_f32 Quad::GetHighCoords( ) const { return Vector2_f32( Positsion.x + ( Size.x / 2.0f ), Positsion.y + ( Size.y / 2.0f ) ); } // Intersection functions BIT_BOOL Quad::Intersection( Vector2_f32 p_Point ) { return IntersectionPoint2Quad( p_Point, *this ); } BIT_BOOL Quad::Intersection( Line2 p_Line ) { return IntersectionLine2Quad( p_Line, *this ); } BIT_BOOL Quad::Intersection( Circle p_Circle ) { return IntersectionCircleQuad( p_Circle, *this ); } BIT_BOOL Quad::Intersection( Quad p_Quad ) { return IntersectionQuadQuad( *this, p_Quad); } } joydit/solidframe // consensus/src/consensusregistrar.cpp // // Copyright (c) 2013 () // // This file is part of SolidFrame framework. // // 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. // #include "frame/common.hpp" #include "consensus/consensusregistrar.hpp" #include "system/mutex.hpp" #include namespace solid{ namespace consensus{ struct Registrar::Data{ struct Stub{ Stub():objuid(frame::invalid_uid()){} frame::ObjectUidT objuid; }; typedef std::vector ObjectUidVectorT; Data():insertidx(0){} Mutex mtx; ObjectUidVectorT objuidvec; size_t insertidx; }; /*static*/ Registrar& Registrar::the(){ static Registrar r; return r; } frame::IndexT Registrar::registerObject(const frame::ObjectUidT &_robjuid, const frame::IndexT &_ridx){ Locker lock(d.mtx); if(frame::is_valid_index(_ridx)){ if(_ridx >= d.objuidvec.size()){ d.objuidvec.resize(_ridx + 1); } if(frame::is_invalid_uid(d.objuidvec[_ridx].objuid)){ d.objuidvec[_ridx].objuid = _robjuid; return _ridx; }else{ return INVALID_INDEX; } } while(d.insertidx < d.objuidvec.size() && frame::is_valid_uid(d.objuidvec[d.insertidx].objuid)){ ++d.insertidx; } if(d.insertidx == d.objuidvec.size()){ d.objuidvec.push_back(Data::Stub()); } d.objuidvec[d.insertidx].objuid = _robjuid; ++d.insertidx; return d.insertidx - 1; } void Registrar::unregisterObject(frame::IndexT &_ridx){ Locker lock(d.mtx); if(_ridx < d.objuidvec.size() && frame::is_valid_uid(d.objuidvec[_ridx].objuid)){ d.objuidvec[_ridx].objuid = frame::invalid_uid(); } _ridx = INVALID_INDEX; } frame::ObjectUidT Registrar::objectUid(const frame::IndexT &_ridx)const{ Locker lock(d.mtx); if(_ridx < d.objuidvec.size() && !frame::is_invalid_uid(d.objuidvec[_ridx].objuid)){ return d.objuidvec[_ridx].objuid; }else{ return frame::invalid_uid(); } } Registrar::Registrar():d(*(new Data)){} Registrar::~Registrar(){ delete &d; } }//namespace consensus }//namespace solid Dataset/Leetcode/train/101/401.cpp0 class Solution { public: string dfs(TreeNode* root){ string res{}; if(root){ res+='0'+root->val; res+=dfs(root->left); res+=dfs(root->right); return res; }else return "n"; } string dfs2(TreeNode* root){ string res{}; if(root){ res+='0'+root->val; res+=dfs2(root->right); res+=dfs2(root->left); return res; }else return "n"; } bool XXX(TreeNode* root) { if(!root) return true; string left=dfs(root->left); string right=dfs2(root->right); if(left==right) return true; else return false; } }; #include "m_widget.h" #include "ui_m_widget.h" #include "map.h" #include extern Map m; int m_widget::currentBarrier=3; m_widget::m_widget(QWidget *parent) : QWidget(parent), ui(new Ui::m_widget) { ui->setupUi(this); //之前进入这个界面时,停止了父界面的音乐播放,所以返回时应该再重新播放 //关卡的页面跳转 connect(ui->guan1,SIGNAL(clicked()),this,SLOT(onGuan1Button())); connect(ui->guan2,SIGNAL(clicked()),this,SLOT(onGuan2Button())); connect(ui->guan3,SIGNAL(clicked()),this,SLOT(onGuan3Button())); connect(ui->guan4,SIGNAL(clicked()),this,SLOT(onGuan4Button())); } m_widget::~m_widget() { delete ui; } void m_widget::on_returnButton_clicked() { //关闭当前窗口,返回到父窗口界面 this->close(); } //进入第一关 void m_widget::onGuan1Button() { qDebug()<<"进入第一关的按钮按下"; //新建第一关页面 Guanqia_1 = new guanqia_1(this); //覆盖原ui Guanqia_1->show(); } void m_widget::onGuan2Button() { qDebug()<<"进入第二关的按钮按下"; //建立第二关页面 Guanqia_2 = new guanqia_1(this,2); //覆盖原ui Guanqia_2->show(); } void m_widget::onGuan3Button() { qDebug()<<"进入第三关的按钮按下"; //建立第三关页面 Guanqia_3 = new guanqia_1(this,3); //覆盖原ui Guanqia_3->show(); } void m_widget::onGuan4Button() { QMessageBox::information(this,"提示","功能正在维护中",QMessageBox::Ok); } void m_widget::paintEvent(QPaintEvent *) { //监视开启关卡 switch(currentBarrier) { case 2: ui->guan2->setEnabled(true); break; case 3: ui->guan3->setEnabled(true); break; case 4: ui->guan4->setEnabled(true); break; case 5: ui->guan5->setEnabled(true); break; case 6: ui->guan6->setEnabled(true); break; case 7: ui->guan7->setEnabled(true); break; case 8: ui->guan8->setEnabled(true); break; case 9: ui->guan9->setEnabled(true); break; } } #include #include #include void CreateListF(CSLList * &L, ElemType a[], int n) { CSLList *s; L = (CSLList *)malloc(sizeof(CSLList)); L->next = L; for(int i = 0; i < n; i++) { s = (CSLList *)malloc(sizeof(CSLList)); s->data = a[i]; s->next = L->next; L->next = s; } } void CreateListR(CSLList * &L, ElemType a[], int n) { CSLList *s, *r; L = (CSLList *)malloc(sizeof(CSLList)); L->next = L; r = L; for(int i = 0; i < n; i++) { s = (CSLList *)malloc(sizeof(CSLList)); s->data = a[i]; r->next = s; r = s; } r->next = L; } void InitList(CSLList * &L) { L = (CSLList *)malloc(sizeof(CSLList)); L->next = L; //create head_node and set L to its next } bool ListInsert(CSLList * &L, int i, ElemType e) { if(i < 1) return false; CSLList *p = L; int k = 0; while(k < i - 1 && p->next != L) { p = p->next; k++; } if(p->next == L) return false; else { CSLList *s = (CSLList *)malloc(sizeof(CSLList)); s->data = e; s->next = p->next; p->next = s; return true; } } bool ListDelete(CSLList * &L, int i, ElemType &e) { int j = 0; CSLList *p = L, *q; if(i <= 0) return false; while(j < i - 1 && p->next != L) { j++; p = p->next; } if(p->next == L) return false; else { q = p->next; if(q->next == L) return false; e = q->data; p->next = q->next; free(q); return true; } } jvirico/kalman-tracker1-10 #include #include #include #include #include #include "ShowManyImages.hpp" #include "blobs.hpp" #include "fgseg.hpp" #include "kalman.hpp" #include "vsrc.hpp" using namespace cv; using namespace std; int main(int argc, char ** argv) { //********************************************************** // Debug detailed mode -> acctiaves all the 'cout' code lines. bool bFullDebugOn = false; //********************************************************** //********************************************************** //PARAMETRIZATION: DATASET // // We initialize the Video source (0, 1, 2, 3 or 4) // 0 -> takes videos from the arguments of main (main url1) // 1-4 -> videos from 4 datasets defined in 'vsrc.hpp' //********************************************************** int iVideoMode = 0; vidsrc::vsrc oSRC(iVideoMode); int iNumCategories; int iNumSequences; string sVideoPath; if (iVideoMode > 0){ iNumCategories = oSRC.GetNumCategs(); iNumSequences = oSRC.GetNumSeqs(); }else { iNumCategories = argc-1; iNumSequences = 1; sVideoPath = argv[1];} //********************************************************** //********************************************************** // PARAMETRIZATION: FOREGROUND SEGM. AND BLOB ANALYSIS // // We initialize the Foreground Segementation object // to use MOG2 and morphological operation OPENING. // Arg1 = 0 -> MOG2 // Arg2 = 1 -> OPENING // = 2 -> OPENING + CLOSING // = 3 -> OPENING x 4 // // learningrate: between 0-1, for MOG2 // structuringElement_CCA: for Connected Component Analysis // min_width and min_height for Blob extraction //********************************************************** fgseg::bgs oBGS(0, 3); double learningrate = 0.001;//Test 3.1 //double learningrate = 0.001;//Test 3.2 //double learningrate = 0.0001;//Test 3.3 int structuringElement_CCA = 4; // 4 or 8 int min_width = 15;//Test 3.1 int min_height = 15;//Test 3.1 //int min_width = 55;//Test 3.2 //int min_height = 55;//Test 3.2 int max_width = 150;//Test 3.2 int max_height = 150;//Test 3.2 //int min_width = 15; //Test 3.3_1 //int min_height = 29; //Test 3.3_1 //int min_width = 30; //Test 3.3_2 //int min_height = 65; //Test 3.3_2 //int min_width = 25; //Test 3.3_3 //int min_height = 55; //Test 3.3_3 //int min_width = 30; //Test 3.3_4 //int min_height = 30; //Test 3.3_4 //********************************************************** //********************************************************** // PARAMETRIZATION: KALMAN INIT //********************************************************** // First parameter sets the predefenied values for: // 1 -> Constant Velocity Model // 2 -> Accelaration Model //********************************************************** int iKalmanMode = 2; //********************************************************** Mat frame; // current Frame Mat fgmask; // foreground mask std::vector bloblist; // list for blobs std::vector bloblistFiltered; // list for blobs cv::Rect rectBall; cv::Rect rectKBall; Point ball; Point kalmanBall; Scalar K_corr_Color(0, 0, 255); Scalar K_pred_Color(0, 255, 0); Scalar GT_Color(255, 0, 0); int iTextOffsetCorrection_1 = 15; //PutText function has a small offset in y axis depending on the simbol you print (* or _) int iTextOffsetCorrection_2 = 7; //Loop for all categories for (int c = 0; c < iNumCategories; c++) { //Loop for all sequence of each category for (int s = 0; s < iNumSequences; s++) { //********************************************************** // KALMAN TUNING //********************************************************** kalmantracking::kalman oKF(iKalmanMode, bFullDebugOn); //Mat R; //R = Mat::zeros(Size(2, 2), CV_32F); //cv::setIdentity(R); //R.at(0) = 100.0f; //R.at(3) = 100.0f; //if (bFullDebugOn) cout << "R = " << endl << " " << R << endl << endl; //oKF.SetUncertaintyMatrix(R); //********************************************************** VideoCapture cap; if (iVideoMode > 0) { //From object to manage video sources sVideoPath = oSRC.GetVideoPath(c, s); }else { //From command line argument sVideoPath = argv[c + 1]; } cap.open(sVideoPath); cout << "Accessing video " << sVideoPath << endl; if (!cap.isOpened()) { cout << "Could not open video file " << sVideoPath << endl; return -1; } Mat img; // current Frame int it = 1; int iFrameNum = 0; for (;;) { cap >> frame; iFrameNum += 1; //check if we achieved the end of the file if (!frame.data) break; //********************************************************** // FOREGROUND DETECTION // 0 bkg, 255 fg, 127 (gray) shadows ... //********************************************************** fgmask = oBGS.getFGmask(frame, learningrate); fgmask = oBGS.removeShadows_127(fgmask); //********************************************************** // BLOB EXTRACTION //********************************************************** // Extract the blobs in fgmask extractBlobs(fgmask, bloblist, structuringElement_CCA); // cout << "Num blobs extracted=" << bloblist.size() << endl; removeSmallBlobs(bloblist, bloblistFiltered, min_width, min_height); //removeBigBlobs(bloblistFiltered, bloblistFiltered, max_width, max_height); // cout << "Num small blobs removed=" << bloblist.size()-bloblistFiltered.size() << endl; ball = GetBallCoordinates(bloblistFiltered); //********************************************************** // KALMAN TRACKING //********************************************************** // //ball is the center of the object, parameter for Kalman kalmanBall = oKF.Predict(ball); //********************************************************** // RESULTS VISUALIZATION //********************************************************** // int iTextSize1 = 1;//Test 3.1 and 3.3 int iTextSize2 = 1.5;//Test 3.1 and 3.3 int iTextThickness = 1;//Test 3.1 and 3.3 int iTestsOffset = 20;//Test 3.1 and 3.3 //int iTextSize1 = 1.8;//Test 3.2 //int iTextSize2 = 2.5;//Test 3.2 //int iTextThickness = 3;//Test 3.2 //int iTestsOffset = 400;//Test 3.2 //putText(frame,"Ground Truth (ball)", Point(10,15+ iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, Scalar(255, 255, 255), 1);//Test 3.1 and 3.3 putText(frame, "Ground Truth (ball)", Point(10, 15 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, GT_Color, iTextThickness);//Test 3.1 and 3.3 putText(frame, "Kalman Prediction", Point(10, 40 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, K_pred_Color, iTextThickness);//Test 3.1 and 3.3 putText(frame, "Kalman Corrected", Point(10, 65 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, K_corr_Color, iTextThickness);//Test 3.1 and 3.3 //putText(frame, "Ground Truth (ball)", Point(10, 50 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, GT_Color, iTextThickness);//Test 3.2 //putText(frame, "Kalman Prediction", Point(10, 100 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, K_pred_Color, iTextThickness);//Test 3.2 //putText(frame, "Kalman Corrected", Point(10, 150 + iTestsOffset), FONT_HERSHEY_SIMPLEX, iTextSize1, K_corr_Color, iTextThickness);//Test 3.2 //putText(frame, "Frame " + to_string(iFrameNum), Point(10, 200 + iTestsOffset), FONT_HERSHEY_COMPLEX, iTextSize1, Scalar(255,255,255), iTextThickness);//Test 3.2 putText(frame, "Frame " + to_string(iFrameNum), Point(10, 90 + iTestsOffset), FONT_HERSHEY_COMPLEX, iTextSize1, Scalar(255, 255, 255), iTextThickness);//Test 3.2 and 3.3 //Point p1 = Point(kalmanBall.x-10, kalmanBall.y-10); //Test 3.3 //Point p2 = Point(kalmanBall.x + 10, kalmanBall.y + 10); //Test 3.3 Point p1 = Point(kalmanBall.x - 10, kalmanBall.y - 10); //Test 3.3 Point p2 = Point(kalmanBall.x + 10, kalmanBall.y + 10); //Test 3.3 if (oKF.getStatus() == "Predicted") {rectangle(frame, p1, p2, K_pred_Color, 1, 8, 0);} else {rectangle(frame, p1, p2, K_corr_Color, 1, 8, 0);} for (int i = 0; i < oKF.getGroundTruthList().size(); i++) { putText(frame, "o", Point(oKF.getGroundTruthList()[i].x, oKF.getGroundTruthList()[i].y + iTextOffsetCorrection_2), FONT_HERSHEY_COMPLEX, iTextSize2, GT_Color, iTextThickness); } for (int i = 0; i < oKF.getPredictedList().size(); i++) { putText(frame, "*", Point(oKF.getPredictedList()[i].x, oKF.getPredictedList()[i].y + iTextOffsetCorrection_1), FONT_HERSHEY_COMPLEX, iTextSize2, K_pred_Color, iTextThickness); } for (int i = 0; i < oKF.getCorrectedList().size(); i++) { putText(frame, "*", Point(oKF.getCorrectedList()[i].x, oKF.getCorrectedList()[i].y + iTextOffsetCorrection_1), FONT_HERSHEY_COMPLEX, iTextSize2, K_corr_Color, iTextThickness); } if (bFullDebugOn) cout << "Ball.x = " << ball.x << endl << "Ball.y = " << ball.y << endl; if (bFullDebugOn) cout << "KBall.x = " << kalmanBall.x << endl << "KBall.y = " << kalmanBall.y << endl; //ShowManyImages("AVSA Lab 3", 6, frame, fgmask, fgmask, // paintBlobImage(frame, bloblistFiltered, false), paintBlobImage(frame, bloblistFiltered, true), paintBlobImage(frame, bloblistFiltered, true)); ShowManyImages("AVSA Lab 3", 2, paintBlobImage(frame, bloblistFiltered, false), fgmask); //exit if ESC key is pressed if (waitKey(30) == 27) break; it++; } cap.release(); destroyAllWindows(); waitKey(0); } } return 0; } /* * Wavefront Alignments Algorithms * Copyright (c) 2019 by <> * * This file is part of Wavefront Alignments Algorithms. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * PROJECT: Wavefront Alignments Algorithms * AUTHOR(S): <> */ #include #include #include #include #include #include namespace edlign { /* * Translate k and offset to coordinates h,v */ #define EWAVEFRONT_V(k,offset) ((offset)-(k)) #define EWAVEFRONT_H(k,offset) (offset) #define EWAVEFRONT_DIAGONAL(h,v) ((h)-(v)) #define EWAVEFRONT_OFFSET(h,v) (h) #define MAX(a,b) (((a)>=(b))?(a):(b)) #define ABS(a) (((a)>=0)?(a):-(a)) /* * Wavefront */ typedef int ewf_offset_t; // Edit Wavefront Offset typedef struct { int lo; // Effective lowest diagonal (inclusive) int hi; // Effective highest diagonal (inclusive) ewf_offset_t* offsets; // Offsets ewf_offset_t* offsets_mem; // Offsets memory } edit_wavefront_t; /* * Edit Wavefronts */ typedef struct { // Dimensions int pattern_length; int text_length; int max_distance; // Waves Offsets edit_wavefront_t* wavefronts; int wavefronts_allocated; // CIGAR char* edit_cigar; int edit_cigar_length; } edit_wavefronts_t; void edit_wavefronts_init( edit_wavefronts_t* const wavefronts, const int pattern_length, const int text_length); void edit_wavefronts_clean( edit_wavefronts_t* const wavefronts); edit_wavefront_t* edit_wavefronts_allocate_wavefront( edit_wavefronts_t* const edit_wavefronts, const int distance, const int lo_base, const int hi_base); int edit_wavefronts_backtrace( edit_wavefronts_t* const wavefronts, const int target_k, const int target_distance); void edit_wavefronts_extend_wavefront( edit_wavefronts_t* const wavefronts, const std::function& extend_match, const int pattern_length, const int text_length, const int distance); void edit_wavefronts_compute_wavefront( edit_wavefronts_t* const wavefronts, const int pattern_length, const int text_length, const int distance); void edit_wavefronts_align( edit_wavefronts_t* const wavefronts, const std::function& extend_match, const int pattern_length, const int text_length); } #include "../../include/entities/visuals/Fragment.h" #include "../../include/math/transform.h" // Constructor / Destructor Fragment::Fragment() { } Fragment::~Fragment() { } // Data Functions (For additional texture data) // Transform Function (Specific to Fragment) void Fragment::updateTransformByAnchors() { int size = (int)fragData.anchors.size(); if (size == 0) { return; } // Exit early on bad call int i = 0; int minX = 0, maxX = 0, minY = 0, maxY = 0; float qX, qY; for (i; i < size; i++) { qX = fragData.anchors[i].pos.x; qY = fragData.anchors[i].pos.y; if (minX == 0 && maxX == 0) { minX = (int)qX; maxX = (int)qX; } else { if (qX < minX) { minX = (int)qX; } if (qX > maxX) { maxX = (int)qX; } } if (minY == 0 && maxY == 0) { minY = (int)qY; maxY = (int)qY; } else { if (qY < minY) { minY = (int)qY; } if (qY > maxY) { maxY = (int)qY; } } } // Set the transform data this->transform = EntityTransform( glm::vec3(float(minX), float(minY), 0.0f), Bounds(0, 0, maxX * 2, maxY * 2), 0.0f); }1-10 #include "FWCore/PluginManager/interface/PluginManager.h" #include "FWCore/PluginManager/interface/standard.h" #include "FWCore/PluginManager/interface/SharedLibrary.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/ServiceRegistry.h" // #include "CondCore/CondDB/interface/ConnectionPool.h" // #include #include #include #include using namespace cond::persistency; int run( const std::string& connectionString ){ try{ //************* std::cout <<"> Connecting with db in "<0 /*2473*/ /*Cheating*/ #include #include #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; int arr[5005]; for(int i = 0; i < n; i++) cin >> arr[i]; sort(arr, arr + n); if(arr[0] >= 0) cout << arr[0] << " " << arr[1] << " " << arr[2]; else if(arr[n - 1] <= 0) cout << arr[n - 3] << " " << arr[n - 2] << " " << arr[n - 1]; else{ int idx = -1, a, b; long long ans = 9999987654321; for(int i = 0; i < n - 2; i++){ int left = i + 1, right = n - 1; while(left < right){ long long tmp = arr[left] + arr[right] + arr[i]; if(abs(ans) >= abs(tmp)){ a = arr[left]; b = arr[right]; idx = i; ans = tmp; } if(tmp > 0) right--; else left++; } } cout << arr[idx] << " " << a << " " << b; } return 0; } #ifndef SSDB_PLATFORM_WINDOWS #define SSDB_PLATFORM_WINDOWS 1 #endif #define SSDB_RECONNECT 1 #include "../src/util/bytes.cpp" #include "../src/net/link.cpp" #include "../api/cpp/SSDB_impl.cpp" /* Global Include Path: /ssdb/api/cpp ssdb_client.cpp File include Path: /ssdb/src */1-10 /** * @file Timer.hpp * @author * @date 10 Jun 2017 * @brief Thread safe version of Timer class * It is based on boost::asio::deadline_timer * @copyright , MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_TIMER_HPP #define ICC_TIMER_HPP #include #include #include #include #include #include #include "ITimerListener.hpp" namespace icc { class Timer : public icc::ITimer , public icc::os::ITimerListener { public: enum : int32_t { /** * Should be used for setting continuous mode */ Infinite = -1, /** * Should be used for setting one time mode */ OneTime = 0, }; public: Timer() : timer_ptr_(icc::os::EventLoop::getDefaultInstance().createTimer()) { timer_ptr_->addListener(this); } Timer(icc::os::EventLoop * eventLoop) : timer_ptr_(eventLoop->createTimer()) { timer_ptr_->addListener(this); } Timer(std::shared_ptr eventLoop) : timer_ptr_(eventLoop->createTimer()) { timer_ptr_->addListener(this); } ~Timer() { timer_ptr_->removeListener(this); timer_ptr_->stop(); } public: Event timer_event_; /** * Enable continuous mode */ void enableContinuous() override { timer_ptr_->enableContinuous(); } /** * Disable continuous mode */ void disableContinuous() override { timer_ptr_->disableContinuous(); } /** * Setting number of repetitions * @param number Number of repetition */ void setNumberOfRepetition(const int32_t &number) override { timer_ptr_->setNumberOfRepetition(number); } /** * Setting interval mode for the timer * @param _duration Timeout duration in std::chrono::nanoseconds */ void setInterval(const std::chrono::nanoseconds _duration) override { timer_ptr_->setInterval(_duration); } /** * Method is used to start async waiting timer */ bool start() override { const bool kResult = timer_ptr_->start(); timer_event_(TimerEvents::STARTED); return kResult; } /** * Method is used to stop waiting timer */ bool stop() override { const bool kResult = timer_ptr_->stop(); timer_event_(TimerEvents::STOPPED); return kResult; } /** * Method is used to add the listener * @param _listener Listener that is being adding */ template void addListener(_Listener *_listener) { static_assert(std::is_base_of::value, "_listener is not derived from Component"); static_assert(std::is_base_of::value, "_listener is not derived from icc::ITimerLisener"); if (_listener) { timer_event_.connect(&_Listener::processEvent, _listener); } } /** * Method is used to add the listener * @param _listener Listener that is being adding */ template void addListener(std::shared_ptr<_Listener> _listener) { static_assert(std::is_base_of::value, "_listener is not derived from Component"); static_assert(std::is_base_of::value, "_listener is not derived from icc::ITimerLisener"); if (_listener) { timer_event_.connect(&_Listener::processEvent, _listener); } } /** * Method is used to remove the listener * @param _listener Listener that is being removing */ template void removeListener(_Listener *_listener) { static_assert(std::is_base_of::value, "_listener is not derived from IComponent"); static_assert(std::is_base_of::value, "_listener is not derived from icc::ITimerLisener"); if (_listener) { timer_event_.disconnect(&_Listener::processEvent, _listener); } } /** * Method is used to remove the listener * @param _listener Listener that is being removing */ template void removeListener(std::shared_ptr<_Listener> _listener) { static_assert(std::is_base_of::value, "_listener is not derived from IComponent"); static_assert(std::is_base_of::value, "_listener is not derived from icc::ITimerLisener"); if (_listener) { timer_event_.disconnect(&_Listener::processEvent, _listener); } } protected: /** * Method that handle Timer expire event * @param _error */ void onTimerExpired() override { timer_event_(TimerEvents::EXPIRED); } protected: std::shared_ptr timer_ptr_; }; } #endif //ICC_TIMER_HPP // Runs in O(n log n) time. Could work a bit harder to make it linear. #include using namespace std; int main() { int n; cin >> n; vector v(n); vector alive(n, true); list q; vector::iterator> q_it; set lookat; for (int i = 0; i < n; ++i) { cin >> v[i]; lookat.insert(i); q.push_back(i); q_it.push_back(prev(q.end())); } vector> rounds; /* INVARIANTS: alive[i] == true IFF i is in the linked list q i in lookat IFF alive[i] == true and either this is the first round or a neighbour of i was deleted last round. */ while (lookat.size()) { set nlookat; vector round; for (int i : lookat) { assert(alive[i]); auto it = q_it[i]; // check adjacent entries to see if candidate i should leave the queue if (it != q.begin() && v[*it] < v[*prev(it)]) alive[i] = false; if (next(it) != q.end() && v[*it] < v[*next(it)]) alive[i] = false; // if they will leave the queue, record this and flag its neighbours // for "lookat" next round if (!alive[i]) { round.push_back(i); if (it != q.begin()) nlookat.insert(*prev(it)); if (next(it) != q.end()) nlookat.insert(*next(it)); } } // if i was killed, we now actually remove it from the queue for (int i : lookat) if (!alive[i]) q.erase(q_it[i]); sort(round.begin(), round.end()); if (round.size()) rounds.push_back(round); // now only keep the "tagged" entries that did not die lookat.clear(); for (int i : nlookat) if (alive[i]) lookat.insert(i); } cout << rounds.size() << endl; rounds.push_back(vector(q.begin(), q.end())); for (const auto& round : rounds) for (int i = 0; i < round.size(); ++i) cout << v[round[i]] << (i+1 == round.size() ? '\n' : ' '); return 0; } petergerasimov/oop-project-breakout1-10 #ifndef __GAME_OBJECT_HPP #define __GAME_OBJECT_HPP #include "gameUtils.hpp" /** * Клас за игрови обекти. Той е предназначен да бъде наследяван. * Грижи се за позициите на обектите и за тяхното рисуване. */ class GameObject { private: /** * Позиция на обекта. */ sf::Vector2f pos = {0, 0}; /** * Посоката в която обекта се движи. */ sf::Vector2f dir = {0, 0}; /** * Текстура на обекта. */ sf::Texture shapeTexture; /** * Скорост на обекта. */ float vel = 1; /** * Указател към прозорецът върху който обекта ще бъде нарисуван. */ sf::RenderWindow* window = nullptr; /** * Ограничения извън които обекта не може да излиза. */ Rect boundingBox = {0, 0, 0, 0}; public: GameObject(); /** * Конструктор който задава прозореца върху който обекта да бъде нарисуван. */ GameObject(sf::RenderWindow* window); ~GameObject(); //Setters /** * Задава стойност на x. * @param x абсциса - реално число */ void setX(float x); /** * Задава стойност на y. * @param y ордината - реално число */ void setY(float y); /** * Задава позицията. * @param p позиция представена чрез sf::Vector2f */ void setPos(sf::Vector2f p); /** * Задава посоката. * @param dir посока представена чрез sf::Vector2f */ void setDir(sf::Vector2f dir); /** * Задава посоката. * @param angle посока представена чрез ъгъл */ void setDir(float angle); /** * Задава скоростта. * @param vel скорост - реално число */ void setVelocity(float vel); /** * Задава прозорец. * @param window указател към прозорец */ void setWindow(sf::RenderWindow* window); /** * Задава ограничения. * @param boundingBox правоъгълник */ void setBoundingBox(Rect boundingBox); /** * Задава текстура. * @param filename път на файл */ void setTexture(std::string filename); //Getters /** * Връща стойността на абсцисата * @return реално число */ float getX() const; /** * Връща стойността на ординатата * @return реално число */ float getY() const; /** * Връща позицията. * @return вектор (sf::Vector2f) */ sf::Vector2f getPos() const; /** * Връща скоростта. * @return реално число */ float getVelocity() const; /** * Връща указател към прозореца. * @return указател (sf::RenderWindow*) */ sf::RenderWindow* getWindow() const; /** * Връща ограниченията. * @return правоъгълник (Rect) */ Rect getBoundingBox() const; /** * Връща посоката. * @return вектор (sf::Vector2f) */ sf::Vector2f getDir() const; /** * Връща указател към текстурата. * @return указател (sf::Texture*) */ sf::Texture* getTexture(); /** * Виртуален метод, който рисува обекта. */ virtual void draw(); /** * Виртуален метод, който обновява позицията на обекта. */ virtual void updatePos(); /** * Виртуален метод, който проверява дали обекта е в ограниченията си. */ virtual void checkBounds(); /** * Обновява обекта. Вика виртуалните методи за рисуване, обновяване на позицията и проверка за ограниченията. */ void update(); }; #endif //__GAME_OBJECT_HPPmatlab_code/Tools/supportingfiles/standard_templates.cpp #ifndef STANDARD_TEMPLATES_CPP #define STANDARD_TEMPLATES_CPP /* This file provides a set of standard templates : * IF< condition, then, else> :: RET * AND< A, B >:: RET * OR< A, B>::RET * XOR< A, B> ::RET * * empty_type * which is used in ISEMPTY< type >::RET * * IS_vec< type >::TF * * Created by , */ template struct IF { typedef Then RET; }; template struct IF { typedef Else RET; }; template struct AND { enum {RET = false}; }; template <> struct AND< true, true > { enum {RET = true}; }; template struct OR { enum {RET = true}; }; template <> struct OR< false, false > { enum {RET = false}; }; template struct XOR { enum {RET = true}; }; template <> struct XOR< false, false > { enum {RET = false}; }; template <> struct XOR< true, true > { enum {RET = false}; }; // Make a dummy/signaling type that should not be actually used. Allow casting of any type to BAD_TYPE. struct BAD_TYPE { template < typename anyType> BAD_TYPE( anyType dummy) { mexErrMsgTxt("Don't create any objects of 'BAD_TYPE'."); }; }; class empty_type { ; }; template< typename T > struct ISEMPTY { enum {RET=false};}; template<> class ISEMPTY { enum {RET=true};}; template< typename T> struct STDTYPES { typedef typename T::value_type value_type; }; template <> struct STDTYPES { typedef double value_type; }; // Test template template < typename T> struct IS_vec { enum { TF = false }; }; template < typename T, int vlen > struct IS_vec< vec > { enum { TF = vec_support::supported }; }; #endif/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include #include #include using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Connect { namespace Model { Queue::Queue() : m_nameHasBeenSet(false), m_queueArnHasBeenSet(false), m_queueIdHasBeenSet(false), m_descriptionHasBeenSet(false), m_outboundCallerConfigHasBeenSet(false), m_hoursOfOperationIdHasBeenSet(false), m_maxContacts(0), m_maxContactsHasBeenSet(false), m_status(QueueStatus::NOT_SET), m_statusHasBeenSet(false), m_tagsHasBeenSet(false) { } Queue::Queue(JsonView jsonValue) : m_nameHasBeenSet(false), m_queueArnHasBeenSet(false), m_queueIdHasBeenSet(false), m_descriptionHasBeenSet(false), m_outboundCallerConfigHasBeenSet(false), m_hoursOfOperationIdHasBeenSet(false), m_maxContacts(0), m_maxContactsHasBeenSet(false), m_status(QueueStatus::NOT_SET), m_statusHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } Queue& Queue::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("QueueArn")) { m_queueArn = jsonValue.GetString("QueueArn"); m_queueArnHasBeenSet = true; } if(jsonValue.ValueExists("QueueId")) { m_queueId = jsonValue.GetString("QueueId"); m_queueIdHasBeenSet = true; } if(jsonValue.ValueExists("Description")) { m_description = jsonValue.GetString("Description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("OutboundCallerConfig")) { m_outboundCallerConfig = jsonValue.GetObject("OutboundCallerConfig"); m_outboundCallerConfigHasBeenSet = true; } if(jsonValue.ValueExists("HoursOfOperationId")) { m_hoursOfOperationId = jsonValue.GetString("HoursOfOperationId"); m_hoursOfOperationIdHasBeenSet = true; } if(jsonValue.ValueExists("MaxContacts")) { m_maxContacts = jsonValue.GetInteger("MaxContacts"); m_maxContactsHasBeenSet = true; } if(jsonValue.ValueExists("Status")) { m_status = QueueStatusMapper::GetQueueStatusForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("Tags")) { Aws::Map tagsJsonMap = jsonValue.GetObject("Tags").GetAllObjects(); for(auto& tagsItem : tagsJsonMap) { m_tags[tagsItem.first] = tagsItem.second.AsString(); } m_tagsHasBeenSet = true; } return *this; } JsonValue Queue::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_queueArnHasBeenSet) { payload.WithString("QueueArn", m_queueArn); } if(m_queueIdHasBeenSet) { payload.WithString("QueueId", m_queueId); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_outboundCallerConfigHasBeenSet) { payload.WithObject("OutboundCallerConfig", m_outboundCallerConfig.Jsonize()); } if(m_hoursOfOperationIdHasBeenSet) { payload.WithString("HoursOfOperationId", m_hoursOfOperationId); } if(m_maxContactsHasBeenSet) { payload.WithInteger("MaxContacts", m_maxContacts); } if(m_statusHasBeenSet) { payload.WithString("Status", QueueStatusMapper::GetNameForQueueStatus(m_status)); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("Tags", std::move(tagsJsonMap)); } return payload; } } // namespace Model } // namespace Connect } // namespace Aws /* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include #include "../torch/TensorHostObject.h" #include "../torch/utils/helpers.h" #include "AbstractScriptModule.h" #include "CenterCropModule.h" #include "GrayscaleModule.h" #include "NormalizeModule.h" #include "ResizeModule.h" #include "VisionTransformHostObject.h" // Namespace alias for torch to avoid namespace conflicts with torchlive::torch namespace torch_ = torch; namespace torchlive { namespace torchvision { namespace transforms { using namespace facebook; // TransformsHostObject Method Name static const std::string CENTER_CROP = "centerCrop"; static const std::string GRAYSCALE = "grayscale"; static const std::string NORMALIZE = "normalize"; static const std::string RESIZE = "resize"; // TransformsHostObject Property Names // empty // TransformsHostObject Properties static const std::vector PROPERTIES = {}; // TransformsHostObject Methods const std::vector METHODS = { CENTER_CROP, GRAYSCALE, NORMALIZE, RESIZE}; /* * This function returns a lambda factory function (i.e. transformFactoryFunc). * When the factory function is called, it loads the target operator's script * module, parses the parameters, and returns a exec function(i.e. * transformExecFunc). When the exec function is called, it parses the input * (tensor), and returns a transformed tensor. */ template static jsi::Function createJITScriptModuleFactory(jsi::Runtime& runtime) { auto transformFactoryFunc = [](jsi::Runtime& runtimeFactory, const jsi::Value& thisValueFactory, const jsi::Value* argumentsFactory, size_t countFactory) -> jsi::Value { // ScriptModule would be loaded when transformFactoryFunc is called AbstractScriptModule* scriptModule = T::getInstance(); auto params = scriptModule->parseParameters( runtimeFactory, thisValueFactory, argumentsFactory, countFactory); auto transformExecFunc = [params, scriptModule]( jsi::Runtime& runtimeExec, const jsi::Value& thisValueExec, const jsi::Value* argumentsExec, size_t countExec) -> jsi::Value { auto inputs = scriptModule->parseInput( runtimeExec, thisValueExec, argumentsExec, countExec); inputs.insert(inputs.end(), params.begin(), params.end()); auto transformed = scriptModule->forward(inputs).toTensor(); auto transformedTensorHostObject = std::make_shared( runtimeExec, transformed); return jsi::Object::createFromHostObject( runtimeExec, transformedTensorHostObject); }; auto transform = jsi::Function::createFromHostFunction( runtimeFactory, jsi::PropNameID::forUtf8(runtimeFactory, T::moduleName), T::inputCount, transformExecFunc); // operator can be called with "op.forward(tensor)" or "op(tensor)" transform.setProperty(runtimeFactory, "forward", transform); return transform; }; return jsi::Function::createFromHostFunction( runtime, jsi::PropNameID::forUtf8(runtime, T::moduleName), T::parameterCount, transformFactoryFunc); } VisionTransformHostObject::VisionTransformHostObject(jsi::Runtime& runtime) : centerCrop_(createJITScriptModuleFactory(runtime)), grayscale_(createJITScriptModuleFactory(runtime)), normalize_(createJITScriptModuleFactory(runtime)), resize_(createJITScriptModuleFactory(runtime)) {} std::vector VisionTransformHostObject::getPropertyNames( jsi::Runtime& rt) { std::vector result; for (std::string property : PROPERTIES) { result.push_back(jsi::PropNameID::forUtf8(rt, property)); } for (std::string method : METHODS) { result.push_back(jsi::PropNameID::forUtf8(rt, method)); } return result; } jsi::Value VisionTransformHostObject::get( jsi::Runtime& runtime, const jsi::PropNameID& propName) { auto name = propName.utf8(runtime); if (name == CENTER_CROP) { return jsi::Value(runtime, centerCrop_); } else if (name == GRAYSCALE) { return jsi::Value(runtime, grayscale_); } else if (name == NORMALIZE) { return jsi::Value(runtime, normalize_); } else if (name == RESIZE) { return jsi::Value(runtime, resize_); } return jsi::Value::undefined(); } } // namespace transforms } // namespace torchvision } // namespace torchlive 100-1000 /* Copyright 2015 Samsung Electronics Co., LTD * * 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. */ /*************************************************************************** * JNI ***************************************************************************/ #include "light.h" #include "util/gvr_jni.h" #include "glm/gtc/type_ptr.hpp" #include "scene.h" #include "lightlist.h" namespace gvr { extern "C" { JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeLight_ctor(JNIEnv * env, jobject obj, jstring juniformDesc); JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeLight_getComponentType(JNIEnv * env, jobject obj); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_enable(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getLightName(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_disable(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_getCastShadow(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setTexture(JNIEnv* env, jobject obj, jlong jlight, jstring key, jlong jtexture); JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeLight_getFloat(JNIEnv* env, jobject obj, jlong jlight, jstring key); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setFloat(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat value); JNIEXPORT jint JNICALL Java_org_gearvrf_NativeLight_getInt(JNIEnv* env, jobject obj, jlong jlight, jstring key); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setInt(JNIEnv* env, jobject obj, jlong jlight, jstring key, jint value); JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeLight_getFloatVec(JNIEnv* env, jobject obj, jlong jlight, jstring key); JNIEXPORT jintArray JNICALL Java_org_gearvrf_NativeLight_getIntVec(JNIEnv* env, jobject obj, jlong jlight, jstring key); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setFloatVec(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloatArray jvec, jint size); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setIntVec(JNIEnv* env, jobject obj, jlong jlight, jstring key, jintArray jvec, jint size); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec2(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec3(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y, jfloat z); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec4(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y, jfloat z, jfloat w); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setMat4(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x1, jfloat y1, jfloat z1, jfloat w1, jfloat x2, jfloat y2, jfloat z2, jfloat w2, jfloat x3, jfloat y3, jfloat z3, jfloat w3, jfloat x4, jfloat y4, jfloat z4, jfloat w4); JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeLight_getMat4(JNIEnv* env, jobject obj, jlong jlight, jstring key); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_hasUniform(JNIEnv*, jobject, jlong, jstring); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_hasTexture(JNIEnv*, jobject, jlong, jstring); JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getLightClass(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setLightClass(JNIEnv * env, jobject obj, jlong jlight, jstring lightclass); JNIEXPORT jint JNICALL Java_org_gearvrf_NativeLight_getLightIndex(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setLightIndex(JNIEnv * env, jobject obj, jlong jlight, jint index); JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getShaderType(JNIEnv* env, jobject, jlong jlight, jstring jtype); JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_makeShaderLayout(JNIEnv * env, jobject obj, jlong jlight); JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_makeShaderBlock(JNIEnv * env, jobject obj, jlong jscene); } JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeLight_ctor(JNIEnv * env, jobject obj, jstring juniformDesc) { const char* uniform_desc = env->GetStringUTFChars(juniformDesc, 0); const char* texture_desc = ""; Renderer* renderer = Renderer::getInstance(); Light* light = renderer->createLight(uniform_desc, texture_desc); jlong ptr = reinterpret_cast(light); env->ReleaseStringUTFChars(juniformDesc, uniform_desc); return ptr; } JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeLight_getComponentType(JNIEnv * env, jobject obj) { return Light::getComponentType(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_enable(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); light->set_enable(true); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_disable(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); light->set_enable(false); } JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getLightClass(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); std::string clz = light->getLightClass(); return env->NewStringUTF(clz.c_str()); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setLightClass(JNIEnv * env, jobject obj, jlong jlight, jstring jlightClass) { Light* light = reinterpret_cast(jlight); const char* char_id = env->GetStringUTFChars(jlightClass, 0); light->setLightClass(char_id); } JNIEXPORT jint JNICALL Java_org_gearvrf_NativeLight_getLightIndex(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); return light->getLightIndex(); } JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getLightName(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); std::string clz = light->getLightName(); return env->NewStringUTF(clz.c_str()); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setLightIndex(JNIEnv * env, jobject obj, jlong jlight, jint index) { Light* light = reinterpret_cast(jlight); light->setLightIndex(index); } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_getCastShadow(JNIEnv * env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); unsigned char rc = (unsigned char) light->castShadow(); return reinterpret_cast(rc); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setTexture(JNIEnv* env, jobject obj, jlong jlight, jstring key, jlong jtexture) { Light* light = reinterpret_cast(jlight); Texture* texture = reinterpret_cast(jtexture); const char* char_key = env->GetStringUTFChars(key, 0); light->setTexture(char_key, texture); env->ReleaseStringUTFChars(key, char_key); } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setIntVec(JNIEnv* env, jobject obj, jlong jlight, jstring key, jintArray jvec, jint size) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); int* elems = env->GetIntArrayElements(jvec, 0); bool rc = light->setIntVec(char_key, elems, size); env->ReleaseStringUTFChars(key, char_key); env->ReleaseIntArrayElements(jvec, elems, 0); return rc; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setFloatVec(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloatArray jvec, jint size) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); float* elems = env->GetFloatArrayElements(jvec, 0); bool rc = light->setFloatVec(char_key, elems, size); env->ReleaseStringUTFChars(key, char_key); env->ReleaseFloatArrayElements(jvec, elems, 0); return rc; } JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeLight_getFloatVec(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); int size = light->getByteSize(char_key) / sizeof(float); if (size > 0) { jfloatArray jvec = env->NewFloatArray(size); float* elems = env->GetFloatArrayElements(jvec, 0); light->getFloatVec(char_key, elems, size); env->ReleaseFloatArrayElements(jvec, elems, 0); env->ReleaseStringUTFChars(key, char_key); return jvec; } env->ReleaseStringUTFChars(key, char_key); return NULL; } JNIEXPORT jintArray JNICALL Java_org_gearvrf_NativeLight_getIntVec(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); int size = light->getByteSize(char_key) / sizeof(int); if (size > 0) { jintArray jvec = env->NewIntArray(size); int* elems = env->GetIntArrayElements(jvec, 0); light->getIntVec(char_key, elems, size); env->ReleaseStringUTFChars(key, char_key); env->ReleaseIntArrayElements(jvec, elems, 0); return jvec; } env->ReleaseStringUTFChars(key, char_key); return NULL; } JNIEXPORT jfloat JNICALL Java_org_gearvrf_NativeLight_getFloat(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); jfloat f = 0.0f; light->getFloat(char_key, f); env->ReleaseStringUTFChars(key, char_key); return f; } JNIEXPORT void JNICALL Java_org_gearvrf_NativeLight_setFloat(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat value) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); light->setFloat(char_key, value); env->ReleaseStringUTFChars(key, char_key); } JNIEXPORT jint JNICALL Java_org_gearvrf_NativeLight_getInt(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); int i = 0; light->getInt(char_key, i); env->ReleaseStringUTFChars(key, char_key); return static_cast(i); } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setInt(JNIEnv* env, jobject obj, jlong jlight, jstring key, jint value) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool rc = light->setInt(char_key, value); env->ReleaseStringUTFChars(key, char_key); return rc; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec2(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool rc = light->setVec2(char_key, glm::vec2(x, y)); env->ReleaseStringUTFChars(key, char_key); return rc; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec3(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y, jfloat z) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool rc = light->setVec3(char_key, glm::vec3(x, y, z)); env->ReleaseStringUTFChars(key, char_key); return rc; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setVec4(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x, jfloat y, jfloat z, jfloat w) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool rc = light->setVec4(char_key, glm::vec4(x, y, z, w)); env->ReleaseStringUTFChars(key, char_key); return rc; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_setMat4(JNIEnv* env, jobject obj, jlong jlight, jstring key, jfloat x1, jfloat y1, jfloat z1, jfloat w1, jfloat x2, jfloat y2, jfloat z2, jfloat w2, jfloat x3, jfloat y3, jfloat z3, jfloat w3, jfloat x4, jfloat y4, jfloat z4, jfloat w4) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); float m[16] = {x1, y1, z1, w1, x2, y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4}; bool rc = light->setFloatVec(char_key, m, 16); env->ReleaseStringUTFChars(key, char_key); return rc; } JNIEXPORT jfloatArray JNICALL Java_org_gearvrf_NativeLight_getMat4(JNIEnv* env, jobject obj, jlong jlight, jstring key) { return Java_org_gearvrf_NativeLight_getFloatVec(env, obj, jlight, key); } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_hasTexture(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool hasKey = (light->getTexture(char_key) != NULL); env->ReleaseStringUTFChars(key, char_key); return (jboolean) hasKey; } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeLight_hasUniform(JNIEnv* env, jobject obj, jlong jlight, jstring key) { Light* light = reinterpret_cast(jlight); const char* char_key = env->GetStringUTFChars(key, 0); bool hasUniform = light->hasUniform(char_key); env->ReleaseStringUTFChars(key, char_key); return (jboolean) hasUniform; } JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_getShaderType(JNIEnv* env, jobject, jlong jlight, jstring jtype) { Light* light = reinterpret_cast(jlight); const char* char_type = env->GetStringUTFChars(jtype, 0); const std::string& type = light->getShaderType(char_type); env->ReleaseStringUTFChars(jtype, char_type); return env->NewStringUTF(type.c_str()); } JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_makeShaderLayout(JNIEnv* env, jobject obj, jlong jlight) { Light* light = reinterpret_cast(jlight); std::string layout; light->makeShaderLayout(layout); return env->NewStringUTF(layout.c_str()); } JNIEXPORT jstring JNICALL Java_org_gearvrf_NativeLight_makeShaderBlock(JNIEnv* env, jobject obj, jlong jscene) { Scene* scene = reinterpret_cast(jscene); const LightList& lights = scene->getLights(); std::string layout; lights.makeShaderBlock(layout); return env->NewStringUTF(layout.c_str()); } } #include "udp_channel.hpp" #include udp_channel::udp_channel(std::string p) : port(p), socket(context, udp::endpoint(asio::ip::address::from_string("127.0.0.1"), std::stoi(p))), state(init_state) { } void udp_channel::receive_data() { this->data.len = this->socket.receive_from( asio::buffer(this->data.raw, MAX_LEN), this->endpoint); /* Format raw data into string of correct length */ this->data.formatted = std::string(this->data.raw, this->data.len); this->data.formatted.erase(std::remove(this->data.formatted.begin(), this->data.formatted.end(), '\n'), this->data.formatted.end()); /* For debug */ //std::cout << "msg is: " << this->data.formatted; } void udp_channel::send_data(std::string msg) { std::strcpy(this->data.raw, msg.c_str()); this->socket.send_to(asio::buffer(this->data.raw, msg.length()), this->endpoint); } visanplot/vtkColorTable.cxx // // Copyright (C) 2002-2021 S[&]T, The Netherlands. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include #include #include #include #include "vtkColorTable.h" #include "vtkLookupTable.h" vtkStandardNewMacro(vtkColorTable); vtkColorTable::vtkColorTable() { this->gradientEdge = nullptr; this->numberOfGradientEdges = 0; this->colorTableName = vtkStdString(""); this->interpolationMode = GRADIENT_INTERPOLATION_MODE_LINEAR; this->lut = vtkSmartPointer::New(); this->lut->SetNumberOfTableValues(256); this->lut->SetTableRange(0, 1); this->SetColorTableByName(vtkStdString("Default")); } vtkColorTable::~vtkColorTable() { if (gradientEdge != nullptr) { free(gradientEdge); gradientEdge = nullptr; } } void vtkColorTable::SetColorRange(double minValue, double maxValue) { this->lut->SetTableRange(minValue, maxValue); this->InvokeEvent("ColorTableChanged"); } double *vtkColorTable::GetColorRange() { return this->lut->GetTableRange(); } void vtkColorTable::GetColorRange(double *minValue, double *maxValue) { double range[2]; this->lut->GetTableRange(range); *minValue = range[0]; *maxValue = range[1]; } int vtkColorTable::GetNumTableColors() { return this->lut->GetNumberOfTableValues(); } void vtkColorTable::SetNumTableColors(int num_colors) { this->lut->SetNumberOfTableValues(num_colors); this->UpdateColorTable(); } double *vtkColorTable::GetTableColor(int index) { return this->lut->GetTableValue(index); } void vtkColorTable::GetTableColor(int index, double *r, double *g, double *b, double *a) { double *rgba; rgba = this->lut->GetTableValue(index); *r = rgba[0]; *g = rgba[1]; *b = rgba[2]; *a = rgba[3]; } double *vtkColorTable::GetGradientEdgeValue(int index) { if (index < 0 || index >= this->numberOfGradientEdges) { vtkErrorMacro("Invalid gradient edge index for color table"); return nullptr; } static_assert(sizeof(GradientEdge)==sizeof(double[5]), "GradientEdge layout must be compatible with double[5]"); return &gradientEdge[index].x; } void vtkColorTable::GetGradientEdgeValue(int index, double *x, double *r, double *g, double *b, double *a) { if (index < 0 || index >= this->numberOfGradientEdges) { vtkErrorMacro("Invalid gradient edge index for color table"); return; } *x = gradientEdge[index].x; *r = gradientEdge[index].r; *g = gradientEdge[index].g; *b = gradientEdge[index].b; *a = gradientEdge[index].a; } int vtkColorTable::InsertGradientEdgeValue(double x, double r, double g, double b, double a) { GradientEdge *newGradientEdge; int index; int i; if (x < 0 || x > 1 || r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1 || a < 0 || a > 1) { vtkErrorMacro("Gradient edge values are out of range (should be between 0 and 1)"); return -1; } newGradientEdge = (GradientEdge *)realloc(gradientEdge, (numberOfGradientEdges + 1) * sizeof(GradientEdge)); assert(newGradientEdge); gradientEdge = newGradientEdge; index = 1; while (index < numberOfGradientEdges && x > gradientEdge[index].x) { index++; } for (i = this->numberOfGradientEdges; i > index; i--) { gradientEdge[i] = gradientEdge[i - 1]; } gradientEdge[index].x = x; gradientEdge[index].r = r; gradientEdge[index].g = g; gradientEdge[index].b = b; gradientEdge[index].a = a; numberOfGradientEdges++; // We now have a custom color table, so clear the color table name this->colorTableName = vtkStdString(""); this->UpdateColorTable(); return index; } void vtkColorTable::SetGradientEdgeValue(int index, double x, double r, double g, double b, double a) { if (index < 0 || index >= this->numberOfGradientEdges) { vtkErrorMacro("Invalid gradient edge index for color table"); return; } if (r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1 || a < 0 || a > 1) { vtkErrorMacro("Gradient edge color values are out of range (should be between 0 and 1)"); return; } if ((index == 0 && x != 0.0) || (index > 0 && x < gradientEdge[index - 1].x) || (index == numberOfGradientEdges - 1 && x != 1.0) || (index < numberOfGradientEdges - 1 && x > gradientEdge[index + 1].x)) { vtkErrorMacro("Gradient edge position is not valid"); return; } gradientEdge[index].x = x; gradientEdge[index].r = r; gradientEdge[index].g = g; gradientEdge[index].b = b; gradientEdge[index].a = a; // We now have a custom color table, so clear the color table name this->colorTableName = vtkStdString(""); this->UpdateColorTable(); } void vtkColorTable::RemoveGradientEdgeValue(int index) { int i; if (index < 0 || index >= this->numberOfGradientEdges) { vtkErrorMacro("Invalid gradient edge index for color table"); return; } for (i = index; i < this->numberOfGradientEdges - 1; i++) { gradientEdge[i] = gradientEdge[i + 1]; } this->numberOfGradientEdges--; // We now have a custom color table, so clear the color table name this->colorTableName = vtkStdString(""); this->UpdateColorTable(); } void vtkColorTable::SetColorTableByName(const char *name) { SetColorTableByName(vtkStdString(name)); } void vtkColorTable::SetColorTableByName(const vtkStdString &name) { if (name == "Default") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 0.0; this->gradientEdge[1].g = 0.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; } else if (name == "BlackToWhite") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 1.0; this->gradientEdge[1].g = 1.0; this->gradientEdge[1].b = 1.0; this->gradientEdge[1].a = 1.0; } else if (name == "WhiteToBlack") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 1.0; this->gradientEdge[0].g = 1.0; this->gradientEdge[0].b = 1.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 0.0; this->gradientEdge[1].g = 0.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; } else if (name == "GreenToRed") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 1.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 1.0; this->gradientEdge[1].g = 0.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; } else if (name == "RedToGreen") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 1.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 0.0; this->gradientEdge[1].g = 1.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; } else if (name == "Cloud") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 2; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 1.0; this->gradientEdge[0].g = 1.0; this->gradientEdge[0].b = 1.0; this->gradientEdge[0].a = 0.0; this->gradientEdge[1].x = 1.0; this->gradientEdge[1].r = 0.5; this->gradientEdge[1].g = 0.5; this->gradientEdge[1].b = 0.5; this->gradientEdge[1].a = 0.5; } else if (name == "Rainbow") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 5; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 1.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0/3; this->gradientEdge[1].r = 1.0; this->gradientEdge[1].g = 1.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; this->gradientEdge[2].x = 0.5; this->gradientEdge[2].r = 0.0; this->gradientEdge[2].g = 1.0; this->gradientEdge[2].b = 0.0; this->gradientEdge[2].a = 1.0; this->gradientEdge[3].x = 2.0/3; this->gradientEdge[3].r = 0.0; this->gradientEdge[3].g = 0.0; this->gradientEdge[3].b = 1.0; this->gradientEdge[3].a = 1.0; this->gradientEdge[4].x = 1.0; this->gradientEdge[4].r = 1.0; this->gradientEdge[4].g = 0.0; this->gradientEdge[4].b = 1.0; this->gradientEdge[4].a = 1.0; } else if (name == "Ozone") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 8; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0/7; this->gradientEdge[1].r = 0.0; this->gradientEdge[1].g = 0.0; this->gradientEdge[1].b = 1.0; this->gradientEdge[1].a = 1.0; this->gradientEdge[2].x = 2.0/7; this->gradientEdge[2].r = 0.0; this->gradientEdge[2].g = 1.0; this->gradientEdge[2].b = 1.0; this->gradientEdge[2].a = 1.0; this->gradientEdge[3].x = 3.0/7; this->gradientEdge[3].r = 0.0; this->gradientEdge[3].g = 1.0; this->gradientEdge[3].b = 0.0; this->gradientEdge[3].a = 1.0; this->gradientEdge[4].x = 4.0/7; this->gradientEdge[4].r = 1.0; this->gradientEdge[4].g = 1.0; this->gradientEdge[4].b = 0.0; this->gradientEdge[4].a = 1.0; this->gradientEdge[5].x = 5.0/7; this->gradientEdge[5].r = 1.0; this->gradientEdge[5].g = 0.0; this->gradientEdge[5].b = 0.0; this->gradientEdge[5].a = 1.0; this->gradientEdge[6].x = 6.0/7; this->gradientEdge[6].r = 1.0; this->gradientEdge[6].g = 0.0; this->gradientEdge[6].b = 1.0; this->gradientEdge[6].a = 1.0; this->gradientEdge[7].x = 1.0; this->gradientEdge[7].r = 1.0; this->gradientEdge[7].g = 1.0; this->gradientEdge[7].b = 1.0; this->gradientEdge[7].a = 1.0; } else if (name == "Blackbody") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 4; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 1.0/3; this->gradientEdge[1].r = 1.0; this->gradientEdge[1].g = 0.0; this->gradientEdge[1].b = 0.0; this->gradientEdge[1].a = 1.0; this->gradientEdge[2].x = 2.0/3; this->gradientEdge[2].r = 1.0; this->gradientEdge[2].g = 1.0; this->gradientEdge[2].b = 0.0; this->gradientEdge[2].a = 1.0; this->gradientEdge[3].x = 1.0; this->gradientEdge[3].r = 1.0; this->gradientEdge[3].g = 1.0; this->gradientEdge[3].b = 1.0; this->gradientEdge[3].a = 1.0; } else if (name == "Aerosol") { if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = 5; this->gradientEdge = (GradientEdge *)malloc(this->numberOfGradientEdges * sizeof(GradientEdge)); assert(this->gradientEdge); this->gradientEdge[0].x = 0.0; this->gradientEdge[0].r = 0.0; this->gradientEdge[0].g = 0.0; this->gradientEdge[0].b = 0.0; this->gradientEdge[0].a = 1.0; this->gradientEdge[1].x = 0.25; this->gradientEdge[1].r = 0.0; this->gradientEdge[1].g = 0.5; this->gradientEdge[1].b = 1.0; this->gradientEdge[1].a = 1.0; this->gradientEdge[2].x = 0.5; this->gradientEdge[2].r = 0.0; this->gradientEdge[2].g = 1.0; this->gradientEdge[2].b = 1.0; this->gradientEdge[2].a = 1.0; this->gradientEdge[3].x = 0.75; this->gradientEdge[3].r = 1.0; this->gradientEdge[3].g = 1.0; this->gradientEdge[3].b = 0.0; this->gradientEdge[3].a = 1.0; this->gradientEdge[4].x = 1.0; this->gradientEdge[4].r = 1.0; this->gradientEdge[4].g = 0.0; this->gradientEdge[4].b = 0.0; this->gradientEdge[4].a = 1.0; } else { vtkErrorMacro("Unknown color table name"); return; } this->colorTableName = name; this->UpdateColorTable(); } void vtkColorTable::SetGradientInterpolationMode(int interpolationMode) { if (interpolationMode < 0 || interpolationMode > 2) { vtkErrorMacro("Invalid color table interpolation mode"); return; } this->interpolationMode = interpolationMode; this->UpdateColorTable(); } void vtkColorTable::Import(const vtkStdString &filename) { FILE *f; char name[51]; int numValues; int n; int i; f = fopen(filename.c_str(), "r"); if (f == nullptr) { vtkErrorMacro("could not open ColorTable file for import"); return; } n = 0; fscanf(f, "ColorTable 1.0\n%n", &n); if (n != 15) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid header"); return; } n = fscanf(f, "TableSize=%d\n", &numValues); if (n != 1) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid format (TableSize)"); return; } this->lut->SetNumberOfTableValues(numValues); n = 0; fscanf(f, "Name=%50[^\n]\n%n", name, &n); if (n == 0) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid format (Name)"); return; } name[n - 6] = '\0'; if (strcmp(name, "Custom") == 0) { int mode; this->colorTableName = vtkStdString(""); n = fscanf(f, "NumberOfGradientEdges=%d\n", &numValues); if (n != 1) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid format (NumberOfGradientEdges)"); return; } if (this->gradientEdge) { free(this->gradientEdge); } this->numberOfGradientEdges = numValues; this->gradientEdge = (GradientEdge *)malloc(numValues * sizeof(GradientEdge)); assert(this->gradientEdge); n = fscanf(f, "InterPolationMode=%d\n", &mode); if (n != 1 || mode < 0 || mode > 2) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid format (InterPolationMode)"); return; } this->interpolationMode = mode; for (i = 0; i < numValues; i++) { double x; double rgba[4]; n = fscanf(f, "%lf %lf %lf %lf %lf\n", &x, &rgba[0], &rgba[1], &rgba[2], &rgba[3]); if (n != 5) { fclose(f); vtkErrorMacro("could not import ColorTable file: invalid format (xrgba value)"); return; } this->gradientEdge[i].x = x; this->gradientEdge[i].r = rgba[0]; this->gradientEdge[i].g = rgba[1]; this->gradientEdge[i].b = rgba[2]; this->gradientEdge[i].a = rgba[3]; } } else { this->SetColorTableByName(name); } this->UpdateColorTable(); fclose(f); } void vtkColorTable::Export(const vtkStdString &filename) { FILE *f; int numValues; f = fopen(filename.c_str(), "w"); if (f == nullptr) { vtkErrorMacro("could not open ColorTable file for export"); return; } numValues = this->lut->GetNumberOfTableValues(); fprintf(f, "ColorTable 1.0\n"); fprintf(f, "TableSize=%d\n", numValues); if (this->colorTableName != "") { const char *str = this->colorTableName; fprintf(f, "Name=%s\n", str); } else { int i; fprintf(f, "Name=Custom\n"); fprintf(f, "NumberOfGradientEdges=%d\n", this->numberOfGradientEdges); fprintf(f, "InterPolationMode=%d\n", this->interpolationMode); for (i = 0; i < this->numberOfGradientEdges; i++) { fprintf(f, "%lf %lf %lf %lf %lf\n", this->gradientEdge[i].x, this->gradientEdge[i].r, this->gradientEdge[i].g, this->gradientEdge[i].b, this->gradientEdge[i].a); } } fclose(f); } void vtkColorTable::UpdateColorTable() { int numValues; int index; int i; numValues = this->lut->GetNumberOfTableValues(); index = 0; for (i = 0; i < numValues; i++) { const double pi = 3.141592653589793; double x, r, g, b, a; double d; // interpolation distance between x and lower gradient edge x = (numValues > 1) ? ((double)i) / (numValues - 1) : 0; while (x > gradientEdge[index + 1].x) { index++; } d = (x - gradientEdge[index].x) / (gradientEdge[index + 1].x - gradientEdge[index].x); switch (this->interpolationMode) { case GRADIENT_INTERPOLATION_MODE_LINEAR: // use d as-is break; case GRADIENT_INTERPOLATION_MODE_SQRT: d = sqrt(d); break; case GRADIENT_INTERPOLATION_MODE_SCURVE: d = (1 + cos(1 - d * pi)) / 2; break; } r = gradientEdge[index].r * (1 - d) + gradientEdge[index + 1].r * d; g = gradientEdge[index].g * (1 - d) + gradientEdge[index + 1].g * d; b = gradientEdge[index].b * (1 - d) + gradientEdge[index + 1].b * d; a = gradientEdge[index].a * (1 - d) + gradientEdge[index + 1].a * d; this->lut->SetTableValue(i, r, g, b, a); } this->InvokeEvent("ColorTableChanged"); } fishermans/CloverBootloaderrEFIt_UEFI/Platform/hda.cpp /* * HDA injector, part of the Chameleon Boot Loader Project * * Ported and adapted by Fabio (ErmaC), October 2016. * * HDA injector is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HDA injector is distributed in the hope that it will be useful, but * WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Platform.h" #include "FixBiosDsdt.h" #include "../include/Devices.h" #include "../include/Pci.h" #include "device_inject.h" #ifndef DEBUG_HDA #ifndef DEBUG_ALL #define DEBUG_HDA 1 #else #define DEBUG_HDA DEBUG_ALL #endif #endif #if DEBUG_HDA == 0 #define DBG(...) #else #define DBG(...) DebugLog(DEBUG_HDA, __VA_ARGS__) #endif // HDA layout-id device injection by dmazar /* CODECs */ /* * ErmaC: There's definitely a lot of different versions of the same audio codec variant out there... * in the next struct you will find a "generic" but IMHO detailed list of * possible codec... anyway to specific a new one or find difference beetween revision * check it under linux enviroment with: * $cat /proc/asound/Intel/codec#0 * -------------------------------- * Codec: Analog Devices AD1989B * Address: 0 * AFG Function Id: 0x1 (unsol 0) * Vendor Id: 0x11d4989b * Subsystem Id: 0x10438372 * Revision Id: 0x100300 * -------------------------------- * or * $cat /proc/asound/NVidia/codec#0 * -------------------------------- * Codec: Nvidia GPU 14 HDMI/DP * Address: 0 * AFG Function Id: 0x1 (unsol 0) * Vendor Id: 0x10de0014 * Subsystem Id: 0x10de0101 * Revision Id: 0x100100 * -------------------------------- */ /***************** * Device Methods *****************/ #if 0 // executing HDA verb command using Immediate Command Input and Output Registers UINT32 HDA_IC_sendVerb(EFI_PCI_IO_PROTOCOL *PciIo, UINT32 codecAdr, UINT32 nodeId, UINT32 verb) { EFI_STATUS Status; UINT16 ics = 0; UINT32 data32 = 0; UINT64 data64 = 0; // about that polling below ... // spec says that delay is in 100ns units. value 1.000.000.0 // should then be 1 second, but users of newer Aptio boards were reporting // delays of 10-20 secs when this value was used. maybe this polling timeout // value does not mean the same on all implementations? // anyway, delay is lowered now to 10.000.0 (10 millis). // poll ICS[0] to become 0 Status = PciIo->PollMem(PciIo, EfiPciIoWidthUint16, 0/*bar*/, HDA_ICS/*offset*/, 0x1/*mask*/, 0/*value*/, 100000/*delay in 100ns*/, &data64); ics = (UINT16)(data64 & 0xFFFF); //DBG("poll ICS[0] == 0: Status=%s, ICS=%X, ICS[0]=%d\n", strerror(Status), ics, (ics & 0x0001)); if (EFI_ERROR(Status)) return 0; // prepare and write verb to ICO data32 = codecAdr << 28 | ((nodeId & 0xFF)<<20) | (verb & 0xFFFFF); Status = PciIo->Mem.Write(PciIo, EfiPciIoWidthUint32, 0, HDA_ICO, 1, &data32); //DBG("ICO write verb Codec=%X, Node=%X, verb=%X, command verb=%X: Status=%s\n", codecAdr, nodeId, verb, data32, strerror(Status)); if (EFI_ERROR(Status)) return 0; // write 11b to ICS[1:0] to send command ics |= 0x3; Status = PciIo->Mem.Write(PciIo, EfiPciIoWidthUint16, 0, HDA_ICS, 1, &ics); //DBG("ICS[1:0] = 11b: Status=%s\n", strerror(Status)); if (EFI_ERROR(Status)) return 0; // poll ICS[1:0] to become 10b Status = PciIo->PollMem(PciIo, EfiPciIoWidthUint16, 0/*bar*/, HDA_ICS/*offset*/, 0x3/*mask*/, 0x2/*value*/, 100000/*delay in 100ns*/, &data64); //DBG("poll ICS[0] == 0: Status=%s\n", strerror(Status)); if (EFI_ERROR(Status)) return 0; // read IRI for VendorId/DeviceId Status = PciIo->Mem.Read(PciIo, EfiPciIoWidthUint32, 0, HDA_IRI, 1, &data32); if (EFI_ERROR(Status)) return 0; return data32; } #endif BOOLEAN EFIAPI IsHDMIAudio(EFI_HANDLE PciDevHandle) { EFI_STATUS Status; EFI_PCI_IO_PROTOCOL *PciIo; UINTN Segment; UINTN Bus; UINTN Device; UINTN Function; UINTN Index; // get device PciIo protocol Status = gBS->OpenProtocol(PciDevHandle, &gEfiPciIoProtocolGuid, (VOID **)&PciIo, gImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { return FALSE; } // get device location Status = PciIo->GetLocation (PciIo, &Segment, &Bus, &Device, &Function); if (EFI_ERROR(Status)) { return FALSE; } // iterate over all GFX devices and check for sibling for (Index = 0; Index < NGFX; Index++) { if (gGraphics[Index].Segment == Segment && gGraphics[Index].Bus == Bus && gGraphics[Index].Device == Device) { return TRUE; } } return FALSE; } BOOLEAN setup_hda_devprop(EFI_PCI_IO_PROTOCOL *PciIo, pci_dt_t *hda_dev, CHAR8 *OSVersion) { DevPropDevice *device = NULL; UINT32 layoutId = 0; UINT32 codecId = 0; BOOLEAN Injected = FALSE; UINTN i; if (!device_inject_string) { device_inject_string = devprop_create_string(); } if (IsHDMIAudio(hda_dev->DeviceHandle)) { if (!gSettings.HDMIInjection) { return FALSE; } if (hda_dev && !hda_dev->used) { device = devprop_add_device_pci(device_inject_string, hda_dev, NULL); hda_dev->used = TRUE; } if (!device) { return FALSE; } if (gSettings.NrAddProperties != 0xFFFE) { for (i = 0; i < gSettings.NrAddProperties; i++) { if (gSettings.AddProperties[i].Device != DEV_HDMI) { continue; } Injected = TRUE; if (!gSettings.AddProperties[i].MenuItem.BValue) { //DBG(" disabled property Key: %s, len: %d\n", gSettings.AddProperties[i].Key, gSettings.AddProperties[i].ValueLen); } else { devprop_add_value(device, gSettings.AddProperties[i].Key, (UINT8*)gSettings.AddProperties[i].Value, gSettings.AddProperties[i].ValueLen); //DBG(" added property Key: %s, len: %d\n", gSettings.AddProperties[i].Key, gSettings.AddProperties[i].ValueLen); } } } if (Injected) { DBG("Additional HDMI properties injected, continue\n"); //return TRUE; } else { if (gSettings.UseIntelHDMI) { DBG(" HDMI Audio, used with HDA setting hda-gfx=onboard-2\n"); devprop_add_value(device, "hda-gfx", (UINT8*)"onboard-2", 10); } else { DBG(" HDMI Audio, used without HDA setting hda-gfx=onboard-1\n"); devprop_add_value(device, "hda-gfx", (UINT8*)"onboard-1", 10); } } } else { if (!gSettings.HDAInjection) { return FALSE; } if (hda_dev && !hda_dev->used) { device = devprop_add_device_pci(device_inject_string, hda_dev, NULL); hda_dev->used = TRUE; } if (!device) { return FALSE; } // HDA - determine layout-id if (gSettings.HDALayoutId > 0) { // layoutId is specified - use it layoutId = (UINT32)gSettings.HDALayoutId; DBG(" setting specified layout-id=%d (0x%X)\n", layoutId, layoutId); } else { layoutId = 12; } if (gSettings.NrAddProperties != 0xFFFE) { for (i = 0; i < gSettings.NrAddProperties; i++) { if (gSettings.AddProperties[i].Device != DEV_HDA) { continue; } Injected = TRUE; if (!gSettings.AddProperties[i].MenuItem.BValue) { //DBG(" disabled property Key: %s, len: %d\n", gSettings.AddProperties[i].Key, gSettings.AddProperties[i].ValueLen); } else { devprop_add_value(device, gSettings.AddProperties[i].Key, (UINT8*)gSettings.AddProperties[i].Value, gSettings.AddProperties[i].ValueLen); //DBG(" added property Key: %s, len: %d\n", gSettings.AddProperties[i].Key, gSettings.AddProperties[i].ValueLen); } } } if (!Injected) { if ((OSVersion != NULL && AsciiOSVersionToUint64(OSVersion) < AsciiOSVersionToUint64("10.8")) || (gSettings.HDALayoutId > 0)) { devprop_add_value(device, "layout-id", (UINT8 *)&layoutId, 4); } layoutId = 0; // reuse variable if (gSettings.UseIntelHDMI) { devprop_add_value(device, "hda-gfx", (UINT8 *)"onboard-1", 10); } codecId = 1; // reuse variable again if (gSettings.AFGLowPowerState) { devprop_add_value(device, "AFGLowPowerState", (UINT8 *)&codecId, 4); } devprop_add_value(device, "MaximumBootBeepVolume", (UINT8 *)&layoutId, 1); devprop_add_value(device, "PinConfigurations", (UINT8 *)&layoutId, 1); } } return TRUE; } src/Providers/UNIXProviders/OpaqueManagementDataCapabilities/UNIX_OpaqueManagementDataCapabilities_ZOS.hxx1-10 #ifdef PEGASUS_OS_ZOS #ifndef __UNIX_OPAQUEMANAGEMENTDATACAPABILITIES_PRIVATE_H #define __UNIX_OPAQUEMANAGEMENTDATACAPABILITIES_PRIVATE_H #endif #endif ////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// // Automatically generated cpp file for the UE4 PlayFab plugin. // // API: Client ////////////////////////////////////////////////////////////////////////////////////////////// #include "PlayFabClientAPI.h" #include "PlayFabClientModels.h" #include "PlayFabClientModelDecoder.h" #include "PlayFabPrivate.h" #include "PlayFabEnums.h" #include "PlayFabCommon/Public/PlayFabAuthenticationContext.h" #include "PlayFabCommon/Public/PlayFabCommonUtils.h" UPlayFabClientAPI::UPlayFabClientAPI(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , CallAuthenticationContext(nullptr) { } void UPlayFabClientAPI::SetCallAuthenticationContext(UPlayFabAuthenticationContext* InAuthenticationContext) { CallAuthenticationContext = InAuthenticationContext; } void UPlayFabClientAPI::SetRequestObject(UPlayFabJsonObject* JsonObject) { RequestJsonObj = JsonObject; } UPlayFabJsonObject* UPlayFabClientAPI::GetResponseObject() { return ResponseJsonObj; } FString UPlayFabClientAPI::PercentEncode(const FString& Text) { FString OutText = Text; OutText = OutText.Replace(TEXT("!"), TEXT("%21")); OutText = OutText.Replace(TEXT("\""), TEXT("%22")); OutText = OutText.Replace(TEXT("#"), TEXT("%23")); OutText = OutText.Replace(TEXT("$"), TEXT("%24")); //OutText = OutText.Replace(TEXT("&"), TEXT("%26")); OutText = OutText.Replace(TEXT("'"), TEXT("%27")); OutText = OutText.Replace(TEXT("("), TEXT("%28")); OutText = OutText.Replace(TEXT(")"), TEXT("%29")); OutText = OutText.Replace(TEXT("*"), TEXT("%2A")); OutText = OutText.Replace(TEXT("+"), TEXT("%2B")); OutText = OutText.Replace(TEXT(","), TEXT("%2C")); //OutText = OutText.Replace(TEXT("/"), TEXT("%2F")); OutText = OutText.Replace(TEXT(":"), TEXT("%3A")); OutText = OutText.Replace(TEXT(";"), TEXT("%3B")); OutText = OutText.Replace(TEXT("="), TEXT("%3D")); //OutText = OutText.Replace(TEXT("?"), TEXT("%3F")); OutText = OutText.Replace(TEXT("@"), TEXT("%40")); OutText = OutText.Replace(TEXT("["), TEXT("%5B")); OutText = OutText.Replace(TEXT("]"), TEXT("%5D")); OutText = OutText.Replace(TEXT("{"), TEXT("%7B")); OutText = OutText.Replace(TEXT("}"), TEXT("%7D")); return OutText; } ////////////////////////////////////////////////////////////////////////// // Generated PlayFab Client API Functions ////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // Account Management ////////////////////////////////////////////////////// /** Adds the specified generic service identifier to the player's PlayFab account. This is designed to allow for a PlayFab ID lookup of any arbitrary service identifier a title wants to add. This identifier should never be used as authentication credentials, as the intent is that it is easily accessible by other players. */ UPlayFabClientAPI* UPlayFabClientAPI::AddGenericID(FClientAddGenericIDRequest request, FDelegateOnSuccessAddGenericID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddGenericID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddGenericID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddGenericID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.GenericId != nullptr) OutRestJsonObj->SetObjectField(TEXT("GenericId"), request.GenericId); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddGenericID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddGenericID.IsBound()) { FClientAddGenericIDResult ResultStruct = UPlayFabClientModelDecoder::decodeAddGenericIDResultResponse(response.responseData); OnSuccessAddGenericID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Adds or updates a contact email to the player's profile. */ UPlayFabClientAPI* UPlayFabClientAPI::AddOrUpdateContactEmail(FClientAddOrUpdateContactEmailRequest request, FDelegateOnSuccessAddOrUpdateContactEmail onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddOrUpdateContactEmail = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddOrUpdateContactEmail); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddOrUpdateContactEmail"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.EmailAddress.IsEmpty() || request.EmailAddress == "") { OutRestJsonObj->SetFieldNull(TEXT("EmailAddress")); } else { OutRestJsonObj->SetStringField(TEXT("EmailAddress"), request.EmailAddress); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddOrUpdateContactEmail(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddOrUpdateContactEmail.IsBound()) { FClientAddOrUpdateContactEmailResult ResultStruct = UPlayFabClientModelDecoder::decodeAddOrUpdateContactEmailResultResponse(response.responseData); OnSuccessAddOrUpdateContactEmail.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Adds playfab username/password auth to an existing account created via an anonymous auth method, e.g. automatic device ID login. */ UPlayFabClientAPI* UPlayFabClientAPI::AddUsernamePassword(FClientAddUsernamePasswordRequest request, FDelegateOnSuccessAddUsernamePassword onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddUsernamePassword = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddUsernamePassword); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddUsernamePassword"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Email.IsEmpty() || request.Email == "") { OutRestJsonObj->SetFieldNull(TEXT("Email")); } else { OutRestJsonObj->SetStringField(TEXT("Email"), request.Email); } if (request.Password.IsEmpty() || request.Password == "") { OutRestJsonObj->SetFieldNull(TEXT("Password")); } else { OutRestJsonObj->SetStringField(TEXT("Password"), request.Password); } if (request.Username.IsEmpty() || request.Username == "") { OutRestJsonObj->SetFieldNull(TEXT("Username")); } else { OutRestJsonObj->SetStringField(TEXT("Username"), request.Username); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddUsernamePassword(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddUsernamePassword.IsBound()) { FClientAddUsernamePasswordResult ResultStruct = UPlayFabClientModelDecoder::decodeAddUsernamePasswordResultResponse(response.responseData); OnSuccessAddUsernamePassword.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the user's PlayFab account details */ UPlayFabClientAPI* UPlayFabClientAPI::GetAccountInfo(FClientGetAccountInfoRequest request, FDelegateOnSuccessGetAccountInfo onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetAccountInfo = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetAccountInfo); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetAccountInfo"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Email.IsEmpty() || request.Email == "") { OutRestJsonObj->SetFieldNull(TEXT("Email")); } else { OutRestJsonObj->SetStringField(TEXT("Email"), request.Email); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } if (request.TitleDisplayName.IsEmpty() || request.TitleDisplayName == "") { OutRestJsonObj->SetFieldNull(TEXT("TitleDisplayName")); } else { OutRestJsonObj->SetStringField(TEXT("TitleDisplayName"), request.TitleDisplayName); } if (request.Username.IsEmpty() || request.Username == "") { OutRestJsonObj->SetFieldNull(TEXT("Username")); } else { OutRestJsonObj->SetStringField(TEXT("Username"), request.Username); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetAccountInfo(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetAccountInfo.IsBound()) { FClientGetAccountInfoResult ResultStruct = UPlayFabClientModelDecoder::decodeGetAccountInfoResultResponse(response.responseData); OnSuccessGetAccountInfo.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves all of the user's different kinds of info. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerCombinedInfo(FClientGetPlayerCombinedInfoRequest request, FDelegateOnSuccessGetPlayerCombinedInfo onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerCombinedInfo = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerCombinedInfo); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerCombinedInfo"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerCombinedInfo(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerCombinedInfo.IsBound()) { FClientGetPlayerCombinedInfoResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerCombinedInfoResultResponse(response.responseData); OnSuccessGetPlayerCombinedInfo.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the player's profile */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerProfile(FClientGetPlayerProfileRequest request, FDelegateOnSuccessGetPlayerProfile onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerProfile = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerProfile); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerProfile"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerProfile(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerProfile.IsBound()) { FClientGetPlayerProfileResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerProfileResultResponse(response.responseData); OnSuccessGetPlayerProfile.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Facebook identifiers. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromFacebookIDs(FClientGetPlayFabIDsFromFacebookIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromFacebookIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromFacebookIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromFacebookIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromFacebookIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.FacebookIDs.IsEmpty() || request.FacebookIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("FacebookIDs")); } else { TArray FacebookIDsArray; FString(request.FacebookIDs).ParseIntoArray(FacebookIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("FacebookIDs"), FacebookIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromFacebookIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromFacebookIDs.IsBound()) { FClientGetPlayFabIDsFromFacebookIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromFacebookIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromFacebookIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Facebook Instant Game identifiers. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromFacebookInstantGamesIds(FClientGetPlayFabIDsFromFacebookInstantGamesIdsRequest request, FDelegateOnSuccessGetPlayFabIDsFromFacebookInstantGamesIds onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromFacebookInstantGamesIds = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromFacebookInstantGamesIds); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromFacebookInstantGamesIds"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.FacebookInstantGamesIds.IsEmpty() || request.FacebookInstantGamesIds == "") { OutRestJsonObj->SetFieldNull(TEXT("FacebookInstantGamesIds")); } else { TArray FacebookInstantGamesIdsArray; FString(request.FacebookInstantGamesIds).ParseIntoArray(FacebookInstantGamesIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("FacebookInstantGamesIds"), FacebookInstantGamesIdsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromFacebookInstantGamesIds(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromFacebookInstantGamesIds.IsBound()) { FClientGetPlayFabIDsFromFacebookInstantGamesIdsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromFacebookInstantGamesIdsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromFacebookInstantGamesIds.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Game Center identifiers (referenced in the Game Center Programming Guide as the Player Identifier). */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromGameCenterIDs(FClientGetPlayFabIDsFromGameCenterIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromGameCenterIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromGameCenterIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromGameCenterIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromGameCenterIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.GameCenterIDs.IsEmpty() || request.GameCenterIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("GameCenterIDs")); } else { TArray GameCenterIDsArray; FString(request.GameCenterIDs).ParseIntoArray(GameCenterIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("GameCenterIDs"), GameCenterIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromGameCenterIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromGameCenterIDs.IsBound()) { FClientGetPlayFabIDsFromGameCenterIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromGameCenterIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromGameCenterIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of generic service identifiers. A generic identifier is the service name plus the service-specific ID for the player, as specified by the title when the generic identifier was added to the player account. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromGenericIDs(FClientGetPlayFabIDsFromGenericIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromGenericIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromGenericIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromGenericIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromGenericIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.GenericIDs.Num() == 0) { OutRestJsonObj->SetFieldNull(TEXT("GenericIDs")); } else { OutRestJsonObj->SetObjectArrayField(TEXT("GenericIDs"), request.GenericIDs); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromGenericIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromGenericIDs.IsBound()) { FClientGetPlayFabIDsFromGenericIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromGenericIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromGenericIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Google identifiers. The Google identifiers are the IDs for the user accounts, available as "id" in the Google+ People API calls. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromGoogleIDs(FClientGetPlayFabIDsFromGoogleIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromGoogleIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromGoogleIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromGoogleIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromGoogleIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.GoogleIDs.IsEmpty() || request.GoogleIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("GoogleIDs")); } else { TArray GoogleIDsArray; FString(request.GoogleIDs).ParseIntoArray(GoogleIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("GoogleIDs"), GoogleIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromGoogleIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromGoogleIDs.IsBound()) { FClientGetPlayFabIDsFromGoogleIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromGoogleIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromGoogleIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Kongregate identifiers. The Kongregate identifiers are the IDs for the user accounts, available as "user_id" from the Kongregate API methods(ex: http://developers.kongregate.com/docs/client/getUserId). */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromKongregateIDs(FClientGetPlayFabIDsFromKongregateIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromKongregateIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromKongregateIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromKongregateIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromKongregateIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.KongregateIDs.IsEmpty() || request.KongregateIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("KongregateIDs")); } else { TArray KongregateIDsArray; FString(request.KongregateIDs).ParseIntoArray(KongregateIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("KongregateIDs"), KongregateIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromKongregateIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromKongregateIDs.IsBound()) { FClientGetPlayFabIDsFromKongregateIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromKongregateIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromKongregateIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Nintendo Switch identifiers. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromNintendoSwitchDeviceIds(FClientGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest request, FDelegateOnSuccessGetPlayFabIDsFromNintendoSwitchDeviceIds onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromNintendoSwitchDeviceIds = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromNintendoSwitchDeviceIds); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromNintendoSwitchDeviceIds"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.NintendoSwitchDeviceIds.IsEmpty() || request.NintendoSwitchDeviceIds == "") { OutRestJsonObj->SetFieldNull(TEXT("NintendoSwitchDeviceIds")); } else { TArray NintendoSwitchDeviceIdsArray; FString(request.NintendoSwitchDeviceIds).ParseIntoArray(NintendoSwitchDeviceIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("NintendoSwitchDeviceIds"), NintendoSwitchDeviceIdsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromNintendoSwitchDeviceIds(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromNintendoSwitchDeviceIds.IsBound()) { FClientGetPlayFabIDsFromNintendoSwitchDeviceIdsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromNintendoSwitchDeviceIdsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromNintendoSwitchDeviceIds.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of PlayStation Network identifiers. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromPSNAccountIDs(FClientGetPlayFabIDsFromPSNAccountIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromPSNAccountIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromPSNAccountIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromPSNAccountIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromPSNAccountIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("IssuerId"), request.IssuerId); // Check to see if string is empty if (request.PSNAccountIDs.IsEmpty() || request.PSNAccountIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("PSNAccountIDs")); } else { TArray PSNAccountIDsArray; FString(request.PSNAccountIDs).ParseIntoArray(PSNAccountIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("PSNAccountIDs"), PSNAccountIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromPSNAccountIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromPSNAccountIDs.IsBound()) { FClientGetPlayFabIDsFromPSNAccountIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromPSNAccountIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromPSNAccountIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Steam identifiers. The Steam identifiers are the profile IDs for the user accounts, available as SteamId in the Steamworks Community API calls. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromSteamIDs(FClientGetPlayFabIDsFromSteamIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromSteamIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromSteamIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromSteamIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromSteamIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.SteamStringIDs.IsEmpty() || request.SteamStringIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("SteamStringIDs")); } else { TArray SteamStringIDsArray; FString(request.SteamStringIDs).ParseIntoArray(SteamStringIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("SteamStringIDs"), SteamStringIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromSteamIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromSteamIDs.IsBound()) { FClientGetPlayFabIDsFromSteamIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromSteamIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromSteamIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of Twitch identifiers. The Twitch identifiers are the IDs for the user accounts, available as "_id" from the Twitch API methods (ex: https://github.com/justintv/Twitch-API/blob/master/v3_resources/users.md#get-usersuser). */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromTwitchIDs(FClientGetPlayFabIDsFromTwitchIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromTwitchIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromTwitchIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromTwitchIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromTwitchIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.TwitchIds.IsEmpty() || request.TwitchIds == "") { OutRestJsonObj->SetFieldNull(TEXT("TwitchIds")); } else { TArray TwitchIdsArray; FString(request.TwitchIds).ParseIntoArray(TwitchIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("TwitchIds"), TwitchIdsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromTwitchIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromTwitchIDs.IsBound()) { FClientGetPlayFabIDsFromTwitchIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromTwitchIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromTwitchIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the unique PlayFab identifiers for the given set of XboxLive identifiers. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayFabIDsFromXboxLiveIDs(FClientGetPlayFabIDsFromXboxLiveIDsRequest request, FDelegateOnSuccessGetPlayFabIDsFromXboxLiveIDs onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayFabIDsFromXboxLiveIDs = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayFabIDsFromXboxLiveIDs); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayFabIDsFromXboxLiveIDs"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Sandbox.IsEmpty() || request.Sandbox == "") { OutRestJsonObj->SetFieldNull(TEXT("Sandbox")); } else { OutRestJsonObj->SetStringField(TEXT("Sandbox"), request.Sandbox); } // Check to see if string is empty if (request.XboxLiveAccountIDs.IsEmpty() || request.XboxLiveAccountIDs == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxLiveAccountIDs")); } else { TArray XboxLiveAccountIDsArray; FString(request.XboxLiveAccountIDs).ParseIntoArray(XboxLiveAccountIDsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("XboxLiveAccountIDs"), XboxLiveAccountIDsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayFabIDsFromXboxLiveIDs(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayFabIDsFromXboxLiveIDs.IsBound()) { FClientGetPlayFabIDsFromXboxLiveIDsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayFabIDsFromXboxLiveIDsResultResponse(response.responseData); OnSuccessGetPlayFabIDsFromXboxLiveIDs.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Android device identifier to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkAndroidDeviceID(FClientLinkAndroidDeviceIDRequest request, FDelegateOnSuccessLinkAndroidDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkAndroidDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkAndroidDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkAndroidDeviceID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AndroidDevice.IsEmpty() || request.AndroidDevice == "") { OutRestJsonObj->SetFieldNull(TEXT("AndroidDevice")); } else { OutRestJsonObj->SetStringField(TEXT("AndroidDevice"), request.AndroidDevice); } if (request.AndroidDeviceId.IsEmpty() || request.AndroidDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("AndroidDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("AndroidDeviceId"), request.AndroidDeviceId); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.OS.IsEmpty() || request.OS == "") { OutRestJsonObj->SetFieldNull(TEXT("OS")); } else { OutRestJsonObj->SetStringField(TEXT("OS"), request.OS); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkAndroidDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkAndroidDeviceID.IsBound()) { FClientLinkAndroidDeviceIDResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkAndroidDeviceIDResultResponse(response.responseData); OnSuccessLinkAndroidDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the custom identifier, generated by the title, to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkCustomID(FClientLinkCustomIDRequest request, FDelegateOnSuccessLinkCustomID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkCustomID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkCustomID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkCustomID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CustomId.IsEmpty() || request.CustomId == "") { OutRestJsonObj->SetFieldNull(TEXT("CustomId")); } else { OutRestJsonObj->SetStringField(TEXT("CustomId"), request.CustomId); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkCustomID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkCustomID.IsBound()) { FClientLinkCustomIDResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkCustomIDResultResponse(response.responseData); OnSuccessLinkCustomID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Facebook account associated with the provided Facebook access token to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkFacebookAccount(FClientLinkFacebookAccountRequest request, FDelegateOnSuccessLinkFacebookAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkFacebookAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkFacebookAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkFacebookAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AccessToken.IsEmpty() || request.AccessToken == "") { OutRestJsonObj->SetFieldNull(TEXT("AccessToken")); } else { OutRestJsonObj->SetStringField(TEXT("AccessToken"), request.AccessToken); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkFacebookAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkFacebookAccount.IsBound()) { FClientLinkFacebookAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkFacebookAccountResultResponse(response.responseData); OnSuccessLinkFacebookAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Facebook Instant Games Id to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkFacebookInstantGamesId(FClientLinkFacebookInstantGamesIdRequest request, FDelegateOnSuccessLinkFacebookInstantGamesId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkFacebookInstantGamesId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkFacebookInstantGamesId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkFacebookInstantGamesId"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FacebookInstantGamesSignature.IsEmpty() || request.FacebookInstantGamesSignature == "") { OutRestJsonObj->SetFieldNull(TEXT("FacebookInstantGamesSignature")); } else { OutRestJsonObj->SetStringField(TEXT("FacebookInstantGamesSignature"), request.FacebookInstantGamesSignature); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkFacebookInstantGamesId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkFacebookInstantGamesId.IsBound()) { FClientLinkFacebookInstantGamesIdResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkFacebookInstantGamesIdResultResponse(response.responseData); OnSuccessLinkFacebookInstantGamesId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Game Center account associated with the provided Game Center ID to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkGameCenterAccount(FClientLinkGameCenterAccountRequest request, FDelegateOnSuccessLinkGameCenterAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkGameCenterAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkGameCenterAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkGameCenterAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.GameCenterId.IsEmpty() || request.GameCenterId == "") { OutRestJsonObj->SetFieldNull(TEXT("GameCenterId")); } else { OutRestJsonObj->SetStringField(TEXT("GameCenterId"), request.GameCenterId); } if (request.PublicKeyUrl.IsEmpty() || request.PublicKeyUrl == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKeyUrl")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKeyUrl"), request.PublicKeyUrl); } if (request.Salt.IsEmpty() || request.Salt == "") { OutRestJsonObj->SetFieldNull(TEXT("Salt")); } else { OutRestJsonObj->SetStringField(TEXT("Salt"), request.Salt); } if (request.Signature.IsEmpty() || request.Signature == "") { OutRestJsonObj->SetFieldNull(TEXT("Signature")); } else { OutRestJsonObj->SetStringField(TEXT("Signature"), request.Signature); } if (request.Timestamp.IsEmpty() || request.Timestamp == "") { OutRestJsonObj->SetFieldNull(TEXT("Timestamp")); } else { OutRestJsonObj->SetStringField(TEXT("Timestamp"), request.Timestamp); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkGameCenterAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkGameCenterAccount.IsBound()) { FClientLinkGameCenterAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkGameCenterAccountResultResponse(response.responseData); OnSuccessLinkGameCenterAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the currently signed-in user account to their Google account, using their Google account credentials */ UPlayFabClientAPI* UPlayFabClientAPI::LinkGoogleAccount(FClientLinkGoogleAccountRequest request, FDelegateOnSuccessLinkGoogleAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkGoogleAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkGoogleAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkGoogleAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.ServerAuthCode.IsEmpty() || request.ServerAuthCode == "") { OutRestJsonObj->SetFieldNull(TEXT("ServerAuthCode")); } else { OutRestJsonObj->SetStringField(TEXT("ServerAuthCode"), request.ServerAuthCode); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkGoogleAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkGoogleAccount.IsBound()) { FClientLinkGoogleAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkGoogleAccountResultResponse(response.responseData); OnSuccessLinkGoogleAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the vendor-specific iOS device identifier to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkIOSDeviceID(FClientLinkIOSDeviceIDRequest request, FDelegateOnSuccessLinkIOSDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkIOSDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkIOSDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkIOSDeviceID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.DeviceId.IsEmpty() || request.DeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceId"), request.DeviceId); } if (request.DeviceModel.IsEmpty() || request.DeviceModel == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceModel")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceModel"), request.DeviceModel); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.OS.IsEmpty() || request.OS == "") { OutRestJsonObj->SetFieldNull(TEXT("OS")); } else { OutRestJsonObj->SetStringField(TEXT("OS"), request.OS); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkIOSDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkIOSDeviceID.IsBound()) { FClientLinkIOSDeviceIDResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkIOSDeviceIDResultResponse(response.responseData); OnSuccessLinkIOSDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Kongregate identifier to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkKongregate(FClientLinkKongregateAccountRequest request, FDelegateOnSuccessLinkKongregate onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkKongregate = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkKongregate); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkKongregate"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AuthTicket.IsEmpty() || request.AuthTicket == "") { OutRestJsonObj->SetFieldNull(TEXT("AuthTicket")); } else { OutRestJsonObj->SetStringField(TEXT("AuthTicket"), request.AuthTicket); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.KongregateId.IsEmpty() || request.KongregateId == "") { OutRestJsonObj->SetFieldNull(TEXT("KongregateId")); } else { OutRestJsonObj->SetStringField(TEXT("KongregateId"), request.KongregateId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkKongregate(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkKongregate.IsBound()) { FClientLinkKongregateAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkKongregateAccountResultResponse(response.responseData); OnSuccessLinkKongregate.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the NintendoSwitchDeviceId to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkNintendoSwitchDeviceId(FClientLinkNintendoSwitchDeviceIdRequest request, FDelegateOnSuccessLinkNintendoSwitchDeviceId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkNintendoSwitchDeviceId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkNintendoSwitchDeviceId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkNintendoSwitchDeviceId"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.NintendoSwitchDeviceId.IsEmpty() || request.NintendoSwitchDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("NintendoSwitchDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("NintendoSwitchDeviceId"), request.NintendoSwitchDeviceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkNintendoSwitchDeviceId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkNintendoSwitchDeviceId.IsBound()) { FClientLinkNintendoSwitchDeviceIdResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkNintendoSwitchDeviceIdResultResponse(response.responseData); OnSuccessLinkNintendoSwitchDeviceId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links an OpenID Connect account to a user's PlayFab account, based on an existing relationship between a title and an Open ID Connect provider and the OpenId Connect JWT from that provider. */ UPlayFabClientAPI* UPlayFabClientAPI::LinkOpenIdConnect(FClientLinkOpenIdConnectRequest request, FDelegateOnSuccessLinkOpenIdConnect onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkOpenIdConnect = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkOpenIdConnect); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkOpenIdConnect"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.ConnectionId.IsEmpty() || request.ConnectionId == "") { OutRestJsonObj->SetFieldNull(TEXT("ConnectionId")); } else { OutRestJsonObj->SetStringField(TEXT("ConnectionId"), request.ConnectionId); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.IdToken.IsEmpty() || request.IdToken == "") { OutRestJsonObj->SetFieldNull(TEXT("IdToken")); } else { OutRestJsonObj->SetStringField(TEXT("IdToken"), request.IdToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkOpenIdConnect(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkOpenIdConnect.IsBound()) { FClientEmptyResult ResultStruct = UPlayFabClientModelDecoder::decodeEmptyResultResponse(response.responseData); OnSuccessLinkOpenIdConnect.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the PlayStation Network account associated with the provided access code to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkPSNAccount(FClientLinkPSNAccountRequest request, FDelegateOnSuccessLinkPSNAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkPSNAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkPSNAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkPSNAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AuthCode.IsEmpty() || request.AuthCode == "") { OutRestJsonObj->SetFieldNull(TEXT("AuthCode")); } else { OutRestJsonObj->SetStringField(TEXT("AuthCode"), request.AuthCode); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); OutRestJsonObj->SetNumberField(TEXT("IssuerId"), request.IssuerId); if (request.RedirectUri.IsEmpty() || request.RedirectUri == "") { OutRestJsonObj->SetFieldNull(TEXT("RedirectUri")); } else { OutRestJsonObj->SetStringField(TEXT("RedirectUri"), request.RedirectUri); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkPSNAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkPSNAccount.IsBound()) { FClientLinkPSNAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkPSNAccountResultResponse(response.responseData); OnSuccessLinkPSNAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Steam account associated with the provided Steam authentication ticket to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkSteamAccount(FClientLinkSteamAccountRequest request, FDelegateOnSuccessLinkSteamAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkSteamAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkSteamAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkSteamAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.SteamTicket.IsEmpty() || request.SteamTicket == "") { OutRestJsonObj->SetFieldNull(TEXT("SteamTicket")); } else { OutRestJsonObj->SetStringField(TEXT("SteamTicket"), request.SteamTicket); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkSteamAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkSteamAccount.IsBound()) { FClientLinkSteamAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkSteamAccountResultResponse(response.responseData); OnSuccessLinkSteamAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Twitch account associated with the token to the user's PlayFab account. */ UPlayFabClientAPI* UPlayFabClientAPI::LinkTwitch(FClientLinkTwitchAccountRequest request, FDelegateOnSuccessLinkTwitch onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkTwitch = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkTwitch); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkTwitch"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AccessToken.IsEmpty() || request.AccessToken == "") { OutRestJsonObj->SetFieldNull(TEXT("AccessToken")); } else { OutRestJsonObj->SetStringField(TEXT("AccessToken"), request.AccessToken); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkTwitch(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkTwitch.IsBound()) { FClientLinkTwitchAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkTwitchAccountResultResponse(response.responseData); OnSuccessLinkTwitch.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Link Windows Hello authentication to the current PlayFab Account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkWindowsHello(FClientLinkWindowsHelloAccountRequest request, FDelegateOnSuccessLinkWindowsHello onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkWindowsHello = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkWindowsHello); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkWindowsHello"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.DeviceName.IsEmpty() || request.DeviceName == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceName")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceName"), request.DeviceName); } OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.PublicKey.IsEmpty() || request.PublicKey == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKey")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKey"), request.PublicKey); } if (request.UserName.IsEmpty() || request.UserName == "") { OutRestJsonObj->SetFieldNull(TEXT("UserName")); } else { OutRestJsonObj->SetStringField(TEXT("UserName"), request.UserName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkWindowsHello(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkWindowsHello.IsBound()) { FClientLinkWindowsHelloAccountResponse ResultStruct = UPlayFabClientModelDecoder::decodeLinkWindowsHelloAccountResponseResponse(response.responseData); OnSuccessLinkWindowsHello.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Links the Xbox Live account associated with the provided access code to the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::LinkXboxAccount(FClientLinkXboxAccountRequest request, FDelegateOnSuccessLinkXboxAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLinkXboxAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLinkXboxAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LinkXboxAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("ForceLink"), request.ForceLink); if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLinkXboxAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLinkXboxAccount.IsBound()) { FClientLinkXboxAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeLinkXboxAccountResultResponse(response.responseData); OnSuccessLinkXboxAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Removes a contact email from the player's profile. */ UPlayFabClientAPI* UPlayFabClientAPI::RemoveContactEmail(FClientRemoveContactEmailRequest request, FDelegateOnSuccessRemoveContactEmail onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRemoveContactEmail = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRemoveContactEmail); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RemoveContactEmail"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRemoveContactEmail(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRemoveContactEmail.IsBound()) { FClientRemoveContactEmailResult ResultStruct = UPlayFabClientModelDecoder::decodeRemoveContactEmailResultResponse(response.responseData); OnSuccessRemoveContactEmail.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Removes the specified generic service identifier from the player's PlayFab account. */ UPlayFabClientAPI* UPlayFabClientAPI::RemoveGenericID(FClientRemoveGenericIDRequest request, FDelegateOnSuccessRemoveGenericID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRemoveGenericID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRemoveGenericID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RemoveGenericID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.GenericId != nullptr) OutRestJsonObj->SetObjectField(TEXT("GenericId"), request.GenericId); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRemoveGenericID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRemoveGenericID.IsBound()) { FClientRemoveGenericIDResult ResultStruct = UPlayFabClientModelDecoder::decodeRemoveGenericIDResultResponse(response.responseData); OnSuccessRemoveGenericID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Submit a report for another player (due to bad bahavior, etc.), so that customer service representatives for the title can take action concerning potentially toxic players. */ UPlayFabClientAPI* UPlayFabClientAPI::ReportPlayer(FClientReportPlayerClientRequest request, FDelegateOnSuccessReportPlayer onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessReportPlayer = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperReportPlayer); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ReportPlayer"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Comment.IsEmpty() || request.Comment == "") { OutRestJsonObj->SetFieldNull(TEXT("Comment")); } else { OutRestJsonObj->SetStringField(TEXT("Comment"), request.Comment); } if (request.ReporteeId.IsEmpty() || request.ReporteeId == "") { OutRestJsonObj->SetFieldNull(TEXT("ReporteeId")); } else { OutRestJsonObj->SetStringField(TEXT("ReporteeId"), request.ReporteeId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperReportPlayer(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessReportPlayer.IsBound()) { FClientReportPlayerClientResult ResultStruct = UPlayFabClientModelDecoder::decodeReportPlayerClientResultResponse(response.responseData); OnSuccessReportPlayer.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Forces an email to be sent to the registered email address for the user's account, with a link allowing the user to change the password.If an account recovery email template ID is provided, an email using the custom email template will be used. */ UPlayFabClientAPI* UPlayFabClientAPI::SendAccountRecoveryEmail(FClientSendAccountRecoveryEmailRequest request, FDelegateOnSuccessSendAccountRecoveryEmail onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessSendAccountRecoveryEmail = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperSendAccountRecoveryEmail); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/SendAccountRecoveryEmail"; // Serialize all the request properties to json if (request.Email.IsEmpty() || request.Email == "") { OutRestJsonObj->SetFieldNull(TEXT("Email")); } else { OutRestJsonObj->SetStringField(TEXT("Email"), request.Email); } if (request.EmailTemplateId.IsEmpty() || request.EmailTemplateId == "") { OutRestJsonObj->SetFieldNull(TEXT("EmailTemplateId")); } else { OutRestJsonObj->SetStringField(TEXT("EmailTemplateId"), request.EmailTemplateId); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperSendAccountRecoveryEmail(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessSendAccountRecoveryEmail.IsBound()) { FClientSendAccountRecoveryEmailResult ResultStruct = UPlayFabClientModelDecoder::decodeSendAccountRecoveryEmailResultResponse(response.responseData); OnSuccessSendAccountRecoveryEmail.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Android device identifier from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkAndroidDeviceID(FClientUnlinkAndroidDeviceIDRequest request, FDelegateOnSuccessUnlinkAndroidDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkAndroidDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkAndroidDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkAndroidDeviceID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AndroidDeviceId.IsEmpty() || request.AndroidDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("AndroidDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("AndroidDeviceId"), request.AndroidDeviceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkAndroidDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkAndroidDeviceID.IsBound()) { FClientUnlinkAndroidDeviceIDResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkAndroidDeviceIDResultResponse(response.responseData); OnSuccessUnlinkAndroidDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related custom identifier from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkCustomID(FClientUnlinkCustomIDRequest request, FDelegateOnSuccessUnlinkCustomID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkCustomID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkCustomID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkCustomID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CustomId.IsEmpty() || request.CustomId == "") { OutRestJsonObj->SetFieldNull(TEXT("CustomId")); } else { OutRestJsonObj->SetStringField(TEXT("CustomId"), request.CustomId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkCustomID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkCustomID.IsBound()) { FClientUnlinkCustomIDResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkCustomIDResultResponse(response.responseData); OnSuccessUnlinkCustomID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Facebook account from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkFacebookAccount(FClientUnlinkFacebookAccountRequest request, FDelegateOnSuccessUnlinkFacebookAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkFacebookAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkFacebookAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkFacebookAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkFacebookAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkFacebookAccount.IsBound()) { FClientUnlinkFacebookAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkFacebookAccountResultResponse(response.responseData); OnSuccessUnlinkFacebookAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Facebook Instant Game Ids from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkFacebookInstantGamesId(FClientUnlinkFacebookInstantGamesIdRequest request, FDelegateOnSuccessUnlinkFacebookInstantGamesId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkFacebookInstantGamesId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkFacebookInstantGamesId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkFacebookInstantGamesId"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FacebookInstantGamesId.IsEmpty() || request.FacebookInstantGamesId == "") { OutRestJsonObj->SetFieldNull(TEXT("FacebookInstantGamesId")); } else { OutRestJsonObj->SetStringField(TEXT("FacebookInstantGamesId"), request.FacebookInstantGamesId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkFacebookInstantGamesId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkFacebookInstantGamesId.IsBound()) { FClientUnlinkFacebookInstantGamesIdResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkFacebookInstantGamesIdResultResponse(response.responseData); OnSuccessUnlinkFacebookInstantGamesId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Game Center account from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkGameCenterAccount(FClientUnlinkGameCenterAccountRequest request, FDelegateOnSuccessUnlinkGameCenterAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkGameCenterAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkGameCenterAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkGameCenterAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkGameCenterAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkGameCenterAccount.IsBound()) { FClientUnlinkGameCenterAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkGameCenterAccountResultResponse(response.responseData); OnSuccessUnlinkGameCenterAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Google account from the user's PlayFab account (https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil#public-methods). */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkGoogleAccount(FClientUnlinkGoogleAccountRequest request, FDelegateOnSuccessUnlinkGoogleAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkGoogleAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkGoogleAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkGoogleAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkGoogleAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkGoogleAccount.IsBound()) { FClientUnlinkGoogleAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkGoogleAccountResultResponse(response.responseData); OnSuccessUnlinkGoogleAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related iOS device identifier from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkIOSDeviceID(FClientUnlinkIOSDeviceIDRequest request, FDelegateOnSuccessUnlinkIOSDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkIOSDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkIOSDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkIOSDeviceID"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.DeviceId.IsEmpty() || request.DeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceId"), request.DeviceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkIOSDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkIOSDeviceID.IsBound()) { FClientUnlinkIOSDeviceIDResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkIOSDeviceIDResultResponse(response.responseData); OnSuccessUnlinkIOSDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Kongregate identifier from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkKongregate(FClientUnlinkKongregateAccountRequest request, FDelegateOnSuccessUnlinkKongregate onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkKongregate = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkKongregate); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkKongregate"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkKongregate(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkKongregate.IsBound()) { FClientUnlinkKongregateAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkKongregateAccountResultResponse(response.responseData); OnSuccessUnlinkKongregate.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related NintendoSwitchDeviceId from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkNintendoSwitchDeviceId(FClientUnlinkNintendoSwitchDeviceIdRequest request, FDelegateOnSuccessUnlinkNintendoSwitchDeviceId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkNintendoSwitchDeviceId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkNintendoSwitchDeviceId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkNintendoSwitchDeviceId"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.NintendoSwitchDeviceId.IsEmpty() || request.NintendoSwitchDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("NintendoSwitchDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("NintendoSwitchDeviceId"), request.NintendoSwitchDeviceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkNintendoSwitchDeviceId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkNintendoSwitchDeviceId.IsBound()) { FClientUnlinkNintendoSwitchDeviceIdResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkNintendoSwitchDeviceIdResultResponse(response.responseData); OnSuccessUnlinkNintendoSwitchDeviceId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks an OpenID Connect account from a user's PlayFab account, based on the connection ID of an existing relationship between a title and an Open ID Connect provider. */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkOpenIdConnect(FClientUninkOpenIdConnectRequest request, FDelegateOnSuccessUnlinkOpenIdConnect onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkOpenIdConnect = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkOpenIdConnect); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkOpenIdConnect"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.ConnectionId.IsEmpty() || request.ConnectionId == "") { OutRestJsonObj->SetFieldNull(TEXT("ConnectionId")); } else { OutRestJsonObj->SetStringField(TEXT("ConnectionId"), request.ConnectionId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkOpenIdConnect(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkOpenIdConnect.IsBound()) { FClientEmptyResponse ResultStruct = UPlayFabClientModelDecoder::decodeEmptyResponseResponse(response.responseData); OnSuccessUnlinkOpenIdConnect.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related PSN account from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkPSNAccount(FClientUnlinkPSNAccountRequest request, FDelegateOnSuccessUnlinkPSNAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkPSNAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkPSNAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkPSNAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkPSNAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkPSNAccount.IsBound()) { FClientUnlinkPSNAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkPSNAccountResultResponse(response.responseData); OnSuccessUnlinkPSNAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Steam account from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkSteamAccount(FClientUnlinkSteamAccountRequest request, FDelegateOnSuccessUnlinkSteamAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkSteamAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkSteamAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkSteamAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkSteamAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkSteamAccount.IsBound()) { FClientUnlinkSteamAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkSteamAccountResultResponse(response.responseData); OnSuccessUnlinkSteamAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Twitch account from the user's PlayFab account. */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkTwitch(FClientUnlinkTwitchAccountRequest request, FDelegateOnSuccessUnlinkTwitch onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkTwitch = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkTwitch); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkTwitch"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkTwitch(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkTwitch.IsBound()) { FClientUnlinkTwitchAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkTwitchAccountResultResponse(response.responseData); OnSuccessUnlinkTwitch.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlink Windows Hello authentication from the current PlayFab Account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkWindowsHello(FClientUnlinkWindowsHelloAccountRequest request, FDelegateOnSuccessUnlinkWindowsHello onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkWindowsHello = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkWindowsHello); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkWindowsHello"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.PublicKeyHint.IsEmpty() || request.PublicKeyHint == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKeyHint")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKeyHint"), request.PublicKeyHint); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkWindowsHello(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkWindowsHello.IsBound()) { FClientUnlinkWindowsHelloAccountResponse ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkWindowsHelloAccountResponseResponse(response.responseData); OnSuccessUnlinkWindowsHello.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Unlinks the related Xbox Live account from the user's PlayFab account */ UPlayFabClientAPI* UPlayFabClientAPI::UnlinkXboxAccount(FClientUnlinkXboxAccountRequest request, FDelegateOnSuccessUnlinkXboxAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlinkXboxAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlinkXboxAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlinkXboxAccount"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlinkXboxAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlinkXboxAccount.IsBound()) { FClientUnlinkXboxAccountResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlinkXboxAccountResultResponse(response.responseData); OnSuccessUnlinkXboxAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Update the avatar URL of the player */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateAvatarUrl(FClientUpdateAvatarUrlRequest request, FDelegateOnSuccessUpdateAvatarUrl onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateAvatarUrl = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateAvatarUrl); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateAvatarUrl"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.ImageUrl.IsEmpty() || request.ImageUrl == "") { OutRestJsonObj->SetFieldNull(TEXT("ImageUrl")); } else { OutRestJsonObj->SetStringField(TEXT("ImageUrl"), request.ImageUrl); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateAvatarUrl(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateAvatarUrl.IsBound()) { FClientEmptyResponse ResultStruct = UPlayFabClientModelDecoder::decodeEmptyResponseResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessUpdateAvatarUrl.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Updates the title specific display name for the user */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateUserTitleDisplayName(FClientUpdateUserTitleDisplayNameRequest request, FDelegateOnSuccessUpdateUserTitleDisplayName onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateUserTitleDisplayName = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateUserTitleDisplayName); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateUserTitleDisplayName"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.DisplayName.IsEmpty() || request.DisplayName == "") { OutRestJsonObj->SetFieldNull(TEXT("DisplayName")); } else { OutRestJsonObj->SetStringField(TEXT("DisplayName"), request.DisplayName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateUserTitleDisplayName(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateUserTitleDisplayName.IsBound()) { FClientUpdateUserTitleDisplayNameResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateUserTitleDisplayNameResultResponse(response.responseData); OnSuccessUpdateUserTitleDisplayName.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Advertising ////////////////////////////////////////////////////// /** Attributes an install for advertisment. */ UPlayFabClientAPI* UPlayFabClientAPI::AttributeInstall(FClientAttributeInstallRequest request, FDelegateOnSuccessAttributeInstall onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAttributeInstall = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAttributeInstall); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AttributeInstall"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Adid.IsEmpty() || request.Adid == "") { OutRestJsonObj->SetFieldNull(TEXT("Adid")); } else { OutRestJsonObj->SetStringField(TEXT("Adid"), request.Adid); } if (request.Idfa.IsEmpty() || request.Idfa == "") { OutRestJsonObj->SetFieldNull(TEXT("Idfa")); } else { OutRestJsonObj->SetStringField(TEXT("Idfa"), request.Idfa); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAttributeInstall(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAttributeInstall.IsBound()) { FClientAttributeInstallResult ResultStruct = UPlayFabClientModelDecoder::decodeAttributeInstallResultResponse(response.responseData); OnSuccessAttributeInstall.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Analytics ////////////////////////////////////////////////////// /** Write a PlayStream event to describe the provided player device information. This API method is not designed to be called directly by developers. Each PlayFab client SDK will eventually report this information automatically. */ UPlayFabClientAPI* UPlayFabClientAPI::ReportDeviceInfo(FClientDeviceInfoRequest request, FDelegateOnSuccessReportDeviceInfo onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessReportDeviceInfo = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperReportDeviceInfo); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ReportDeviceInfo"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Info != nullptr) OutRestJsonObj->SetObjectField(TEXT("Info"), request.Info); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperReportDeviceInfo(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessReportDeviceInfo.IsBound()) { FClientEmptyResponse ResultStruct = UPlayFabClientModelDecoder::decodeEmptyResponseResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessReportDeviceInfo.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Writes a character-based event into PlayStream. */ UPlayFabClientAPI* UPlayFabClientAPI::WriteCharacterEvent(FClientWriteClientCharacterEventRequest request, FDelegateOnSuccessWriteCharacterEvent onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessWriteCharacterEvent = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperWriteCharacterEvent); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/WriteCharacterEvent"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Body != nullptr) OutRestJsonObj->SetObjectField(TEXT("Body"), request.Body); if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.EventName.IsEmpty() || request.EventName == "") { OutRestJsonObj->SetFieldNull(TEXT("EventName")); } else { OutRestJsonObj->SetStringField(TEXT("EventName"), request.EventName); } if (request.Timestamp.IsEmpty() || request.Timestamp == "") { OutRestJsonObj->SetFieldNull(TEXT("Timestamp")); } else { OutRestJsonObj->SetStringField(TEXT("Timestamp"), request.Timestamp); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperWriteCharacterEvent(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessWriteCharacterEvent.IsBound()) { FClientWriteEventResponse ResultStruct = UPlayFabClientModelDecoder::decodeWriteEventResponseResponse(response.responseData); OnSuccessWriteCharacterEvent.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Writes a player-based event into PlayStream. */ UPlayFabClientAPI* UPlayFabClientAPI::WritePlayerEvent(FClientWriteClientPlayerEventRequest request, FDelegateOnSuccessWritePlayerEvent onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessWritePlayerEvent = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperWritePlayerEvent); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/WritePlayerEvent"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Body != nullptr) OutRestJsonObj->SetObjectField(TEXT("Body"), request.Body); if (request.EventName.IsEmpty() || request.EventName == "") { OutRestJsonObj->SetFieldNull(TEXT("EventName")); } else { OutRestJsonObj->SetStringField(TEXT("EventName"), request.EventName); } if (request.Timestamp.IsEmpty() || request.Timestamp == "") { OutRestJsonObj->SetFieldNull(TEXT("Timestamp")); } else { OutRestJsonObj->SetStringField(TEXT("Timestamp"), request.Timestamp); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperWritePlayerEvent(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessWritePlayerEvent.IsBound()) { FClientWriteEventResponse ResultStruct = UPlayFabClientModelDecoder::decodeWriteEventResponseResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessWritePlayerEvent.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Writes a title-based event into PlayStream. */ UPlayFabClientAPI* UPlayFabClientAPI::WriteTitleEvent(FClientWriteTitleEventRequest request, FDelegateOnSuccessWriteTitleEvent onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessWriteTitleEvent = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperWriteTitleEvent); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/WriteTitleEvent"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Body != nullptr) OutRestJsonObj->SetObjectField(TEXT("Body"), request.Body); if (request.EventName.IsEmpty() || request.EventName == "") { OutRestJsonObj->SetFieldNull(TEXT("EventName")); } else { OutRestJsonObj->SetStringField(TEXT("EventName"), request.EventName); } if (request.Timestamp.IsEmpty() || request.Timestamp == "") { OutRestJsonObj->SetFieldNull(TEXT("Timestamp")); } else { OutRestJsonObj->SetStringField(TEXT("Timestamp"), request.Timestamp); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperWriteTitleEvent(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessWriteTitleEvent.IsBound()) { FClientWriteEventResponse ResultStruct = UPlayFabClientModelDecoder::decodeWriteEventResponseResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessWriteTitleEvent.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Authentication ////////////////////////////////////////////////////// /** Gets a Photon custom authentication token that can be used to securely join the player into a Photon room. See https://docs.microsoft.com/en-us/gaming/playfab/features/multiplayer/photon/quickstart for more details. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPhotonAuthenticationToken(FClientGetPhotonAuthenticationTokenRequest request, FDelegateOnSuccessGetPhotonAuthenticationToken onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPhotonAuthenticationToken = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPhotonAuthenticationToken); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPhotonAuthenticationToken"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.PhotonApplicationId.IsEmpty() || request.PhotonApplicationId == "") { OutRestJsonObj->SetFieldNull(TEXT("PhotonApplicationId")); } else { OutRestJsonObj->SetStringField(TEXT("PhotonApplicationId"), request.PhotonApplicationId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPhotonAuthenticationToken(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPhotonAuthenticationToken.IsBound()) { FClientGetPhotonAuthenticationTokenResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPhotonAuthenticationTokenResultResponse(response.responseData); OnSuccessGetPhotonAuthenticationToken.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Returns the title's base 64 encoded RSA CSP blob. */ UPlayFabClientAPI* UPlayFabClientAPI::GetTitlePublicKey(FClientGetTitlePublicKeyRequest request, FDelegateOnSuccessGetTitlePublicKey onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetTitlePublicKey = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetTitlePublicKey); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetTitlePublicKey"; // Serialize all the request properties to json OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); if (request.TitleSharedSecret.IsEmpty() || request.TitleSharedSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("TitleSharedSecret")); } else { OutRestJsonObj->SetStringField(TEXT("TitleSharedSecret"), request.TitleSharedSecret); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetTitlePublicKey(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetTitlePublicKey.IsBound()) { FClientGetTitlePublicKeyResult ResultStruct = UPlayFabClientModelDecoder::decodeGetTitlePublicKeyResultResponse(response.responseData); OnSuccessGetTitlePublicKey.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Requests a challenge from the server to be signed by Windows Hello Passport service to authenticate. */ UPlayFabClientAPI* UPlayFabClientAPI::GetWindowsHelloChallenge(FClientGetWindowsHelloChallengeRequest request, FDelegateOnSuccessGetWindowsHelloChallenge onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetWindowsHelloChallenge = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetWindowsHelloChallenge); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetWindowsHelloChallenge"; // Serialize all the request properties to json if (request.PublicKeyHint.IsEmpty() || request.PublicKeyHint == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKeyHint")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKeyHint"), request.PublicKeyHint); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetWindowsHelloChallenge(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetWindowsHelloChallenge.IsBound()) { FClientGetWindowsHelloChallengeResponse ResultStruct = UPlayFabClientModelDecoder::decodeGetWindowsHelloChallengeResponseResponse(response.responseData); OnSuccessGetWindowsHelloChallenge.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using the Android device identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithAndroidDeviceID(FClientLoginWithAndroidDeviceIDRequest request, FDelegateOnSuccessLoginWithAndroidDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithAndroidDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithAndroidDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithAndroidDeviceID"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.AndroidDevice.IsEmpty() || request.AndroidDevice == "") { OutRestJsonObj->SetFieldNull(TEXT("AndroidDevice")); } else { OutRestJsonObj->SetStringField(TEXT("AndroidDevice"), request.AndroidDevice); } if (request.AndroidDeviceId.IsEmpty() || request.AndroidDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("AndroidDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("AndroidDeviceId"), request.AndroidDeviceId); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.OS.IsEmpty() || request.OS == "") { OutRestJsonObj->SetFieldNull(TEXT("OS")); } else { OutRestJsonObj->SetStringField(TEXT("OS"), request.OS); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithAndroidDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithAndroidDeviceID.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); OnSuccessLoginWithAndroidDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a custom unique identifier generated by the title, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithCustomID(FClientLoginWithCustomIDRequest request, FDelegateOnSuccessLoginWithCustomID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithCustomID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithCustomID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithCustomID"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.CustomId.IsEmpty() || request.CustomId == "") { OutRestJsonObj->SetFieldNull(TEXT("CustomId")); } else { OutRestJsonObj->SetStringField(TEXT("CustomId"), request.CustomId); } if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithCustomID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithCustomID.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithCustomID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user into the PlayFab account, returning a session identifier that can subsequently be used for API calls which require an authenticated user. Unlike most other login API calls, LoginWithEmailAddress does not permit the creation of new accounts via the CreateAccountFlag. Email addresses may be used to create accounts via RegisterPlayFabUser. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithEmailAddress(FClientLoginWithEmailAddressRequest request, FDelegateOnSuccessLoginWithEmailAddress onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithEmailAddress = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithEmailAddress); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithEmailAddress"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.Email.IsEmpty() || request.Email == "") { OutRestJsonObj->SetFieldNull(TEXT("Email")); } else { OutRestJsonObj->SetStringField(TEXT("Email"), request.Email); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.Password.IsEmpty() || request.Password == "") { OutRestJsonObj->SetFieldNull(TEXT("Password")); } else { OutRestJsonObj->SetStringField(TEXT("Password"), request.Password); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithEmailAddress(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithEmailAddress.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithEmailAddress.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Facebook access token, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithFacebook(FClientLoginWithFacebookRequest request, FDelegateOnSuccessLoginWithFacebook onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithFacebook = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithFacebook); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithFacebook"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.AccessToken.IsEmpty() || request.AccessToken == "") { OutRestJsonObj->SetFieldNull(TEXT("AccessToken")); } else { OutRestJsonObj->SetStringField(TEXT("AccessToken"), request.AccessToken); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithFacebook(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithFacebook.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithFacebook.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Facebook Instant Games ID, returning a session identifier that can subsequently be used for API calls which require an authenticated user. Requires Facebook Instant Games to be configured. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithFacebookInstantGamesId(FClientLoginWithFacebookInstantGamesIdRequest request, FDelegateOnSuccessLoginWithFacebookInstantGamesId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithFacebookInstantGamesId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithFacebookInstantGamesId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithFacebookInstantGamesId"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.FacebookInstantGamesSignature.IsEmpty() || request.FacebookInstantGamesSignature == "") { OutRestJsonObj->SetFieldNull(TEXT("FacebookInstantGamesSignature")); } else { OutRestJsonObj->SetStringField(TEXT("FacebookInstantGamesSignature"), request.FacebookInstantGamesSignature); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithFacebookInstantGamesId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithFacebookInstantGamesId.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithFacebookInstantGamesId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using an iOS Game Center player identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithGameCenter(FClientLoginWithGameCenterRequest request, FDelegateOnSuccessLoginWithGameCenter onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithGameCenter = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithGameCenter); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithGameCenter"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerId.IsEmpty() || request.PlayerId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerId"), request.PlayerId); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } if (request.PublicKeyUrl.IsEmpty() || request.PublicKeyUrl == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKeyUrl")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKeyUrl"), request.PublicKeyUrl); } if (request.Salt.IsEmpty() || request.Salt == "") { OutRestJsonObj->SetFieldNull(TEXT("Salt")); } else { OutRestJsonObj->SetStringField(TEXT("Salt"), request.Salt); } if (request.Signature.IsEmpty() || request.Signature == "") { OutRestJsonObj->SetFieldNull(TEXT("Signature")); } else { OutRestJsonObj->SetStringField(TEXT("Signature"), request.Signature); } if (request.Timestamp.IsEmpty() || request.Timestamp == "") { OutRestJsonObj->SetFieldNull(TEXT("Timestamp")); } else { OutRestJsonObj->SetStringField(TEXT("Timestamp"), request.Timestamp); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithGameCenter(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithGameCenter.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithGameCenter.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using their Google account credentials */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithGoogleAccount(FClientLoginWithGoogleAccountRequest request, FDelegateOnSuccessLoginWithGoogleAccount onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithGoogleAccount = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithGoogleAccount); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithGoogleAccount"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } if (request.ServerAuthCode.IsEmpty() || request.ServerAuthCode == "") { OutRestJsonObj->SetFieldNull(TEXT("ServerAuthCode")); } else { OutRestJsonObj->SetStringField(TEXT("ServerAuthCode"), request.ServerAuthCode); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithGoogleAccount(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithGoogleAccount.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithGoogleAccount.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using the vendor-specific iOS device identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithIOSDeviceID(FClientLoginWithIOSDeviceIDRequest request, FDelegateOnSuccessLoginWithIOSDeviceID onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithIOSDeviceID = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithIOSDeviceID); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithIOSDeviceID"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.DeviceId.IsEmpty() || request.DeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceId"), request.DeviceId); } if (request.DeviceModel.IsEmpty() || request.DeviceModel == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceModel")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceModel"), request.DeviceModel); } if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.OS.IsEmpty() || request.OS == "") { OutRestJsonObj->SetFieldNull(TEXT("OS")); } else { OutRestJsonObj->SetStringField(TEXT("OS"), request.OS); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithIOSDeviceID(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithIOSDeviceID.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithIOSDeviceID.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Kongregate player account. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithKongregate(FClientLoginWithKongregateRequest request, FDelegateOnSuccessLoginWithKongregate onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithKongregate = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithKongregate); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithKongregate"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.AuthTicket.IsEmpty() || request.AuthTicket == "") { OutRestJsonObj->SetFieldNull(TEXT("AuthTicket")); } else { OutRestJsonObj->SetStringField(TEXT("AuthTicket"), request.AuthTicket); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.KongregateId.IsEmpty() || request.KongregateId == "") { OutRestJsonObj->SetFieldNull(TEXT("KongregateId")); } else { OutRestJsonObj->SetStringField(TEXT("KongregateId"), request.KongregateId); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithKongregate(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithKongregate.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithKongregate.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Nintendo Switch Device ID, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithNintendoSwitchDeviceId(FClientLoginWithNintendoSwitchDeviceIdRequest request, FDelegateOnSuccessLoginWithNintendoSwitchDeviceId onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithNintendoSwitchDeviceId = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithNintendoSwitchDeviceId); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithNintendoSwitchDeviceId"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.NintendoSwitchDeviceId.IsEmpty() || request.NintendoSwitchDeviceId == "") { OutRestJsonObj->SetFieldNull(TEXT("NintendoSwitchDeviceId")); } else { OutRestJsonObj->SetStringField(TEXT("NintendoSwitchDeviceId"), request.NintendoSwitchDeviceId); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithNintendoSwitchDeviceId(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithNintendoSwitchDeviceId.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithNintendoSwitchDeviceId.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Logs in a user with an Open ID Connect JWT created by an existing relationship between a title and an Open ID Connect provider. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithOpenIdConnect(FClientLoginWithOpenIdConnectRequest request, FDelegateOnSuccessLoginWithOpenIdConnect onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithOpenIdConnect = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithOpenIdConnect); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithOpenIdConnect"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.ConnectionId.IsEmpty() || request.ConnectionId == "") { OutRestJsonObj->SetFieldNull(TEXT("ConnectionId")); } else { OutRestJsonObj->SetStringField(TEXT("ConnectionId"), request.ConnectionId); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.IdToken.IsEmpty() || request.IdToken == "") { OutRestJsonObj->SetFieldNull(TEXT("IdToken")); } else { OutRestJsonObj->SetStringField(TEXT("IdToken"), request.IdToken); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithOpenIdConnect(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithOpenIdConnect.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithOpenIdConnect.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user into the PlayFab account, returning a session identifier that can subsequently be used for API calls which require an authenticated user. Unlike most other login API calls, LoginWithPlayFab does not permit the creation of new accounts via the CreateAccountFlag. Username/Password credentials may be used to create accounts via RegisterPlayFabUser, or added to existing accounts using AddUsernamePassword. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithPlayFab(FClientLoginWithPlayFabRequest request, FDelegateOnSuccessLoginWithPlayFab onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithPlayFab = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithPlayFab); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithPlayFab"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.Password.IsEmpty() || request.Password == "") { OutRestJsonObj->SetFieldNull(TEXT("Password")); } else { OutRestJsonObj->SetStringField(TEXT("Password"), request.Password); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); if (request.Username.IsEmpty() || request.Username == "") { OutRestJsonObj->SetFieldNull(TEXT("Username")); } else { OutRestJsonObj->SetStringField(TEXT("Username"), request.Username); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithPlayFab(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithPlayFab.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithPlayFab.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a PlayStation Network authentication code, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithPSN(FClientLoginWithPSNRequest request, FDelegateOnSuccessLoginWithPSN onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithPSN = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithPSN); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithPSN"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.AuthCode.IsEmpty() || request.AuthCode == "") { OutRestJsonObj->SetFieldNull(TEXT("AuthCode")); } else { OutRestJsonObj->SetStringField(TEXT("AuthCode"), request.AuthCode); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); OutRestJsonObj->SetNumberField(TEXT("IssuerId"), request.IssuerId); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } if (request.RedirectUri.IsEmpty() || request.RedirectUri == "") { OutRestJsonObj->SetFieldNull(TEXT("RedirectUri")); } else { OutRestJsonObj->SetStringField(TEXT("RedirectUri"), request.RedirectUri); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithPSN(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithPSN.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithPSN.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Steam authentication ticket, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithSteam(FClientLoginWithSteamRequest request, FDelegateOnSuccessLoginWithSteam onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithSteam = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithSteam); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithSteam"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } if (request.SteamTicket.IsEmpty() || request.SteamTicket == "") { OutRestJsonObj->SetFieldNull(TEXT("SteamTicket")); } else { OutRestJsonObj->SetStringField(TEXT("SteamTicket"), request.SteamTicket); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithSteam(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithSteam.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithSteam.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Twitch access token. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithTwitch(FClientLoginWithTwitchRequest request, FDelegateOnSuccessLoginWithTwitch onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithTwitch = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithTwitch); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithTwitch"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.AccessToken.IsEmpty() || request.AccessToken == "") { OutRestJsonObj->SetFieldNull(TEXT("AccessToken")); } else { OutRestJsonObj->SetStringField(TEXT("AccessToken"), request.AccessToken); } OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithTwitch(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithTwitch.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithTwitch.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Completes the Windows Hello login flow by returning the signed value of the challange from GetWindowsHelloChallenge. Windows Hello has a 2 step client to server authentication scheme. Step one is to request from the server a challenge string. Step two is to request the user sign the string via Windows Hello and then send the signed value back to the server. */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithWindowsHello(FClientLoginWithWindowsHelloRequest request, FDelegateOnSuccessLoginWithWindowsHello onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithWindowsHello = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithWindowsHello); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithWindowsHello"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.ChallengeSignature.IsEmpty() || request.ChallengeSignature == "") { OutRestJsonObj->SetFieldNull(TEXT("ChallengeSignature")); } else { OutRestJsonObj->SetStringField(TEXT("ChallengeSignature"), request.ChallengeSignature); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PublicKeyHint.IsEmpty() || request.PublicKeyHint == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKeyHint")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKeyHint"), request.PublicKeyHint); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithWindowsHello(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithWindowsHello.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithWindowsHello.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Signs the user in using a Xbox Live Token, returning a session identifier that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::LoginWithXbox(FClientLoginWithXboxRequest request, FDelegateOnSuccessLoginWithXbox onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessLoginWithXbox = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperLoginWithXbox); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/LoginWithXbox"; manager->returnsSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("CreateAccount"), request.CreateAccount); if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperLoginWithXbox(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessLoginWithXbox.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessLoginWithXbox.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Registers a new Playfab user account, returning a session identifier that can subsequently be used for API calls which require an authenticated user. You must supply either a username or an email address. */ UPlayFabClientAPI* UPlayFabClientAPI::RegisterPlayFabUser(FClientRegisterPlayFabUserRequest request, FDelegateOnSuccessRegisterPlayFabUser onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRegisterPlayFabUser = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRegisterPlayFabUser); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RegisterPlayFabUser"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.DisplayName.IsEmpty() || request.DisplayName == "") { OutRestJsonObj->SetFieldNull(TEXT("DisplayName")); } else { OutRestJsonObj->SetStringField(TEXT("DisplayName"), request.DisplayName); } if (request.Email.IsEmpty() || request.Email == "") { OutRestJsonObj->SetFieldNull(TEXT("Email")); } else { OutRestJsonObj->SetStringField(TEXT("Email"), request.Email); } if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.Password.IsEmpty() || request.Password == "") { OutRestJsonObj->SetFieldNull(TEXT("Password")); } else { OutRestJsonObj->SetStringField(TEXT("Password"), request.Password); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } OutRestJsonObj->SetBoolField(TEXT("RequireBothUsernameAndEmail"), request.RequireBothUsernameAndEmail); OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); if (request.Username.IsEmpty() || request.Username == "") { OutRestJsonObj->SetFieldNull(TEXT("Username")); } else { OutRestJsonObj->SetStringField(TEXT("Username"), request.Username); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRegisterPlayFabUser(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRegisterPlayFabUser.IsBound()) { FClientRegisterPlayFabUserResult ResultStruct = UPlayFabClientModelDecoder::decodeRegisterPlayFabUserResultResponse(response.responseData); OnSuccessRegisterPlayFabUser.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Registers a new PlayFab user account using Windows Hello authentication, returning a session ticket that can subsequently be used for API calls which require an authenticated user */ UPlayFabClientAPI* UPlayFabClientAPI::RegisterWithWindowsHello(FClientRegisterWithWindowsHelloRequest request, FDelegateOnSuccessRegisterWithWindowsHello onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRegisterWithWindowsHello = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRegisterWithWindowsHello); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RegisterWithWindowsHello"; manager->returnsSessionTicket = true; // Serialize all the request properties to json if (request.DeviceName.IsEmpty() || request.DeviceName == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceName")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceName"), request.DeviceName); } if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.InfoRequestParameters != nullptr) OutRestJsonObj->SetObjectField(TEXT("InfoRequestParameters"), request.InfoRequestParameters); if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } if (request.PublicKey.IsEmpty() || request.PublicKey == "") { OutRestJsonObj->SetFieldNull(TEXT("PublicKey")); } else { OutRestJsonObj->SetStringField(TEXT("PublicKey"), request.PublicKey); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); if (request.UserName.IsEmpty() || request.UserName == "") { OutRestJsonObj->SetFieldNull(TEXT("UserName")); } else { OutRestJsonObj->SetStringField(TEXT("UserName"), request.UserName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRegisterWithWindowsHello(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRegisterWithWindowsHello.IsBound()) { FClientLoginResult ResultStruct = UPlayFabClientModelDecoder::decodeLoginResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; // CallAuthenticationContext was set in OnProcessRequestComplete ResultStruct.AuthenticationContext = CallAuthenticationContext; OnSuccessRegisterWithWindowsHello.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Sets the player's secret if it is not already set. Player secrets are used to sign API requests. To reset a player's secret use the Admin or Server API method SetPlayerSecret. */ UPlayFabClientAPI* UPlayFabClientAPI::SetPlayerSecret(FClientSetPlayerSecretRequest request, FDelegateOnSuccessSetPlayerSecret onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessSetPlayerSecret = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperSetPlayerSecret); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/SetPlayerSecret"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.EncryptedRequest.IsEmpty() || request.EncryptedRequest == "") { OutRestJsonObj->SetFieldNull(TEXT("EncryptedRequest")); } else { OutRestJsonObj->SetStringField(TEXT("EncryptedRequest"), request.EncryptedRequest); } if (request.PlayerSecret.IsEmpty() || request.PlayerSecret == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayerSecret")); } else { OutRestJsonObj->SetStringField(TEXT("PlayerSecret"), request.PlayerSecret); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperSetPlayerSecret(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessSetPlayerSecret.IsBound()) { FClientSetPlayerSecretResult ResultStruct = UPlayFabClientModelDecoder::decodeSetPlayerSecretResultResponse(response.responseData); OnSuccessSetPlayerSecret.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Character Data ////////////////////////////////////////////////////// /** Retrieves the title-specific custom data for the character which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetCharacterData(FClientGetCharacterDataRequest request, FDelegateOnSuccessGetCharacterData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCharacterData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCharacterData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCharacterData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCharacterData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCharacterData.IsBound()) { FClientGetCharacterDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCharacterDataResultResponse(response.responseData); OnSuccessGetCharacterData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the title-specific custom data for the character which can only be read by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetCharacterReadOnlyData(FClientGetCharacterDataRequest request, FDelegateOnSuccessGetCharacterReadOnlyData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCharacterReadOnlyData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCharacterReadOnlyData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCharacterReadOnlyData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCharacterReadOnlyData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCharacterReadOnlyData.IsBound()) { FClientGetCharacterDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCharacterDataResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessGetCharacterReadOnlyData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Creates and updates the title-specific custom data for the user's character which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateCharacterData(FClientUpdateCharacterDataRequest request, FDelegateOnSuccessUpdateCharacterData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateCharacterData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateCharacterData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateCharacterData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.Data != nullptr) OutRestJsonObj->SetObjectField(TEXT("Data"), request.Data); // Check to see if string is empty if (request.KeysToRemove.IsEmpty() || request.KeysToRemove == "") { OutRestJsonObj->SetFieldNull(TEXT("KeysToRemove")); } else { TArray KeysToRemoveArray; FString(request.KeysToRemove).ParseIntoArray(KeysToRemoveArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("KeysToRemove"), KeysToRemoveArray); } FString temp_Permission; if (GetEnumValueToString(TEXT("EUserDataPermission"), request.Permission, temp_Permission)) OutRestJsonObj->SetStringField(TEXT("Permission"), temp_Permission); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateCharacterData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateCharacterData.IsBound()) { FClientUpdateCharacterDataResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateCharacterDataResultResponse(response.responseData); OnSuccessUpdateCharacterData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Characters ////////////////////////////////////////////////////// /** Lists all of the characters that belong to a specific user. CharacterIds are not globally unique; characterId must be evaluated with the parent PlayFabId to guarantee uniqueness. */ UPlayFabClientAPI* UPlayFabClientAPI::GetAllUsersCharacters(FClientListUsersCharactersRequest request, FDelegateOnSuccessGetAllUsersCharacters onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetAllUsersCharacters = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetAllUsersCharacters); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetAllUsersCharacters"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetAllUsersCharacters(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetAllUsersCharacters.IsBound()) { FClientListUsersCharactersResult ResultStruct = UPlayFabClientModelDecoder::decodeListUsersCharactersResultResponse(response.responseData); OnSuccessGetAllUsersCharacters.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of ranked characters for the given statistic, starting from the indicated point in the leaderboard */ UPlayFabClientAPI* UPlayFabClientAPI::GetCharacterLeaderboard(FClientGetCharacterLeaderboardRequest request, FDelegateOnSuccessGetCharacterLeaderboard onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCharacterLeaderboard = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCharacterLeaderboard); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCharacterLeaderboard"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterType.IsEmpty() || request.CharacterType == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterType")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterType"), request.CharacterType); } OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); OutRestJsonObj->SetNumberField(TEXT("StartPosition"), request.StartPosition); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCharacterLeaderboard(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCharacterLeaderboard.IsBound()) { FClientGetCharacterLeaderboardResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCharacterLeaderboardResultResponse(response.responseData); OnSuccessGetCharacterLeaderboard.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the details of all title-specific statistics for the user */ UPlayFabClientAPI* UPlayFabClientAPI::GetCharacterStatistics(FClientGetCharacterStatisticsRequest request, FDelegateOnSuccessGetCharacterStatistics onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCharacterStatistics = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCharacterStatistics); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCharacterStatistics"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCharacterStatistics(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCharacterStatistics.IsBound()) { FClientGetCharacterStatisticsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCharacterStatisticsResultResponse(response.responseData); OnSuccessGetCharacterStatistics.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of ranked characters for the given statistic, centered on the requested Character ID */ UPlayFabClientAPI* UPlayFabClientAPI::GetLeaderboardAroundCharacter(FClientGetLeaderboardAroundCharacterRequest request, FDelegateOnSuccessGetLeaderboardAroundCharacter onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetLeaderboardAroundCharacter = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetLeaderboardAroundCharacter); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetLeaderboardAroundCharacter"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.CharacterType.IsEmpty() || request.CharacterType == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterType")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterType"), request.CharacterType); } OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetLeaderboardAroundCharacter(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetLeaderboardAroundCharacter.IsBound()) { FClientGetLeaderboardAroundCharacterResult ResultStruct = UPlayFabClientModelDecoder::decodeGetLeaderboardAroundCharacterResultResponse(response.responseData); OnSuccessGetLeaderboardAroundCharacter.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of all of the user's characters for the given statistic. */ UPlayFabClientAPI* UPlayFabClientAPI::GetLeaderboardForUserCharacters(FClientGetLeaderboardForUsersCharactersRequest request, FDelegateOnSuccessGetLeaderboardForUserCharacters onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetLeaderboardForUserCharacters = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetLeaderboardForUserCharacters); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetLeaderboardForUserCharacters"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetLeaderboardForUserCharacters(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetLeaderboardForUserCharacters.IsBound()) { FClientGetLeaderboardForUsersCharactersResult ResultStruct = UPlayFabClientModelDecoder::decodeGetLeaderboardForUsersCharactersResultResponse(response.responseData); OnSuccessGetLeaderboardForUserCharacters.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Grants the specified character type to the user. CharacterIds are not globally unique; characterId must be evaluated with the parent PlayFabId to guarantee uniqueness. */ UPlayFabClientAPI* UPlayFabClientAPI::GrantCharacterToUser(FClientGrantCharacterToUserRequest request, FDelegateOnSuccessGrantCharacterToUser onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGrantCharacterToUser = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGrantCharacterToUser); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GrantCharacterToUser"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterName.IsEmpty() || request.CharacterName == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterName")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterName"), request.CharacterName); } if (request.ItemId.IsEmpty() || request.ItemId == "") { OutRestJsonObj->SetFieldNull(TEXT("ItemId")); } else { OutRestJsonObj->SetStringField(TEXT("ItemId"), request.ItemId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGrantCharacterToUser(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGrantCharacterToUser.IsBound()) { FClientGrantCharacterToUserResult ResultStruct = UPlayFabClientModelDecoder::decodeGrantCharacterToUserResultResponse(response.responseData); OnSuccessGrantCharacterToUser.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Updates the values of the specified title-specific statistics for the specific character. By default, clients are not permitted to update statistics. Developers may override this setting in the Game Manager > Settings > API Features. */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateCharacterStatistics(FClientUpdateCharacterStatisticsRequest request, FDelegateOnSuccessUpdateCharacterStatistics onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateCharacterStatistics = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateCharacterStatistics); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateCharacterStatistics"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.CharacterStatistics != nullptr) OutRestJsonObj->SetObjectField(TEXT("CharacterStatistics"), request.CharacterStatistics); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateCharacterStatistics(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateCharacterStatistics.IsBound()) { FClientUpdateCharacterStatisticsResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateCharacterStatisticsResultResponse(response.responseData); OnSuccessUpdateCharacterStatistics.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Content ////////////////////////////////////////////////////// /** This API retrieves a pre-signed URL for accessing a content file for the title. A subsequent HTTP GET to the returned URL will attempt to download the content. A HEAD query to the returned URL will attempt to retrieve the metadata of the content. Note that a successful result does not guarantee the existence of this content - if it has not been uploaded, the query to retrieve the data will fail. See this post for more information: https://community.playfab.com/hc/en-us/community/posts/205469488-How-to-upload-files-to-PlayFab-s-Content-Service. Also, please be aware that the Content service is specifically PlayFab's CDN offering, for which standard CDN rates apply. */ UPlayFabClientAPI* UPlayFabClientAPI::GetContentDownloadUrl(FClientGetContentDownloadUrlRequest request, FDelegateOnSuccessGetContentDownloadUrl onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetContentDownloadUrl = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetContentDownloadUrl); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetContentDownloadUrl"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.HttpMethod.IsEmpty() || request.HttpMethod == "") { OutRestJsonObj->SetFieldNull(TEXT("HttpMethod")); } else { OutRestJsonObj->SetStringField(TEXT("HttpMethod"), request.HttpMethod); } if (request.Key.IsEmpty() || request.Key == "") { OutRestJsonObj->SetFieldNull(TEXT("Key")); } else { OutRestJsonObj->SetStringField(TEXT("Key"), request.Key); } OutRestJsonObj->SetBoolField(TEXT("ThruCDN"), request.ThruCDN); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetContentDownloadUrl(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetContentDownloadUrl.IsBound()) { FClientGetContentDownloadUrlResult ResultStruct = UPlayFabClientModelDecoder::decodeGetContentDownloadUrlResultResponse(response.responseData); OnSuccessGetContentDownloadUrl.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Friend List Management ////////////////////////////////////////////////////// /** Adds the PlayFab user, based upon a match against a supplied unique identifier, to the friend list of the local user. At least one of FriendPlayFabId,FriendUsername,FriendEmail, or FriendTitleDisplayName should be initialized. */ UPlayFabClientAPI* UPlayFabClientAPI::AddFriend(FClientAddFriendRequest request, FDelegateOnSuccessAddFriend onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddFriend = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddFriend); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddFriend"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FriendEmail.IsEmpty() || request.FriendEmail == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendEmail")); } else { OutRestJsonObj->SetStringField(TEXT("FriendEmail"), request.FriendEmail); } if (request.FriendPlayFabId.IsEmpty() || request.FriendPlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendPlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("FriendPlayFabId"), request.FriendPlayFabId); } if (request.FriendTitleDisplayName.IsEmpty() || request.FriendTitleDisplayName == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendTitleDisplayName")); } else { OutRestJsonObj->SetStringField(TEXT("FriendTitleDisplayName"), request.FriendTitleDisplayName); } if (request.FriendUsername.IsEmpty() || request.FriendUsername == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendUsername")); } else { OutRestJsonObj->SetStringField(TEXT("FriendUsername"), request.FriendUsername); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddFriend(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddFriend.IsBound()) { FClientAddFriendResult ResultStruct = UPlayFabClientModelDecoder::decodeAddFriendResultResponse(response.responseData); OnSuccessAddFriend.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the current friend list for the local user, constrained to users who have PlayFab accounts. Friends from linked accounts (Facebook, Steam) are also included. You may optionally exclude some linked services' friends. */ UPlayFabClientAPI* UPlayFabClientAPI::GetFriendsList(FClientGetFriendsListRequest request, FDelegateOnSuccessGetFriendsList onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetFriendsList = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetFriendsList); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetFriendsList"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("IncludeFacebookFriends"), request.IncludeFacebookFriends); OutRestJsonObj->SetBoolField(TEXT("IncludeSteamFriends"), request.IncludeSteamFriends); if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetFriendsList(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetFriendsList.IsBound()) { FClientGetFriendsListResult ResultStruct = UPlayFabClientModelDecoder::decodeGetFriendsListResultResponse(response.responseData); OnSuccessGetFriendsList.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Removes a specified user from the friend list of the local user */ UPlayFabClientAPI* UPlayFabClientAPI::RemoveFriend(FClientRemoveFriendRequest request, FDelegateOnSuccessRemoveFriend onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRemoveFriend = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRemoveFriend); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RemoveFriend"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FriendPlayFabId.IsEmpty() || request.FriendPlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendPlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("FriendPlayFabId"), request.FriendPlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRemoveFriend(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRemoveFriend.IsBound()) { FClientRemoveFriendResult ResultStruct = UPlayFabClientModelDecoder::decodeRemoveFriendResultResponse(response.responseData); OnSuccessRemoveFriend.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Updates the tag list for a specified user in the friend list of the local user */ UPlayFabClientAPI* UPlayFabClientAPI::SetFriendTags(FClientSetFriendTagsRequest request, FDelegateOnSuccessSetFriendTags onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessSetFriendTags = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperSetFriendTags); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/SetFriendTags"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FriendPlayFabId.IsEmpty() || request.FriendPlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("FriendPlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("FriendPlayFabId"), request.FriendPlayFabId); } // Check to see if string is empty if (request.Tags.IsEmpty() || request.Tags == "") { OutRestJsonObj->SetFieldNull(TEXT("Tags")); } else { TArray TagsArray; FString(request.Tags).ParseIntoArray(TagsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Tags"), TagsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperSetFriendTags(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessSetFriendTags.IsBound()) { FClientSetFriendTagsResult ResultStruct = UPlayFabClientModelDecoder::decodeSetFriendTagsResultResponse(response.responseData); OnSuccessSetFriendTags.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Matchmaking ////////////////////////////////////////////////////// /** Get details about all current running game servers matching the given parameters. */ UPlayFabClientAPI* UPlayFabClientAPI::GetCurrentGames(FClientCurrentGamesRequest request, FDelegateOnSuccessGetCurrentGames onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCurrentGames = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCurrentGames); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCurrentGames"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.BuildVersion.IsEmpty() || request.BuildVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("BuildVersion")); } else { OutRestJsonObj->SetStringField(TEXT("BuildVersion"), request.BuildVersion); } if (request.GameMode.IsEmpty() || request.GameMode == "") { OutRestJsonObj->SetFieldNull(TEXT("GameMode")); } else { OutRestJsonObj->SetStringField(TEXT("GameMode"), request.GameMode); } FString temp_Region; if (GetEnumValueToString(TEXT("ERegion"), request.Region, temp_Region)) OutRestJsonObj->SetStringField(TEXT("Region"), temp_Region); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } if (request.TagFilter != nullptr) OutRestJsonObj->SetObjectField(TEXT("TagFilter"), request.TagFilter); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCurrentGames(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCurrentGames.IsBound()) { FClientCurrentGamesResult ResultStruct = UPlayFabClientModelDecoder::decodeCurrentGamesResultResponse(response.responseData); OnSuccessGetCurrentGames.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Get details about the regions hosting game servers matching the given parameters. */ UPlayFabClientAPI* UPlayFabClientAPI::GetGameServerRegions(FClientGameServerRegionsRequest request, FDelegateOnSuccessGetGameServerRegions onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetGameServerRegions = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetGameServerRegions); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetGameServerRegions"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.BuildVersion.IsEmpty() || request.BuildVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("BuildVersion")); } else { OutRestJsonObj->SetStringField(TEXT("BuildVersion"), request.BuildVersion); } OutRestJsonObj->SetStringField(TEXT("TitleId"), IPlayFab::Get().getGameTitleId()); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetGameServerRegions(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetGameServerRegions.IsBound()) { FClientGameServerRegionsResult ResultStruct = UPlayFabClientModelDecoder::decodeGameServerRegionsResultResponse(response.responseData); OnSuccessGetGameServerRegions.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Attempts to locate a game session matching the given parameters. If the goal is to match the player into a specific active session, only the LobbyId is required. Otherwise, the BuildVersion, GameMode, and Region are all required parameters. Note that parameters specified in the search are required (they are not weighting factors). If a slot is found in a server instance matching the parameters, the slot will be assigned to that player, removing it from the availabe set. In that case, the information on the game session will be returned, otherwise the Status returned will be GameNotFound. */ UPlayFabClientAPI* UPlayFabClientAPI::Matchmake(FClientMatchmakeRequest request, FDelegateOnSuccessMatchmake onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessMatchmake = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperMatchmake); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/Matchmake"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.BuildVersion.IsEmpty() || request.BuildVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("BuildVersion")); } else { OutRestJsonObj->SetStringField(TEXT("BuildVersion"), request.BuildVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.GameMode.IsEmpty() || request.GameMode == "") { OutRestJsonObj->SetFieldNull(TEXT("GameMode")); } else { OutRestJsonObj->SetStringField(TEXT("GameMode"), request.GameMode); } if (request.LobbyId.IsEmpty() || request.LobbyId == "") { OutRestJsonObj->SetFieldNull(TEXT("LobbyId")); } else { OutRestJsonObj->SetStringField(TEXT("LobbyId"), request.LobbyId); } FString temp_Region; if (GetEnumValueToString(TEXT("ERegion"), request.Region, temp_Region)) OutRestJsonObj->SetStringField(TEXT("Region"), temp_Region); OutRestJsonObj->SetBoolField(TEXT("StartNewIfNoneFound"), request.StartNewIfNoneFound); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } if (request.TagFilter != nullptr) OutRestJsonObj->SetObjectField(TEXT("TagFilter"), request.TagFilter); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperMatchmake(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessMatchmake.IsBound()) { FClientMatchmakeResult ResultStruct = UPlayFabClientModelDecoder::decodeMatchmakeResultResponse(response.responseData); OnSuccessMatchmake.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Start a new game server with a given configuration, add the current player and return the connection information. */ UPlayFabClientAPI* UPlayFabClientAPI::StartGame(FClientStartGameRequest request, FDelegateOnSuccessStartGame onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessStartGame = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperStartGame); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/StartGame"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.BuildVersion.IsEmpty() || request.BuildVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("BuildVersion")); } else { OutRestJsonObj->SetStringField(TEXT("BuildVersion"), request.BuildVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.CustomCommandLineData.IsEmpty() || request.CustomCommandLineData == "") { OutRestJsonObj->SetFieldNull(TEXT("CustomCommandLineData")); } else { OutRestJsonObj->SetStringField(TEXT("CustomCommandLineData"), request.CustomCommandLineData); } if (request.GameMode.IsEmpty() || request.GameMode == "") { OutRestJsonObj->SetFieldNull(TEXT("GameMode")); } else { OutRestJsonObj->SetStringField(TEXT("GameMode"), request.GameMode); } FString temp_Region; if (GetEnumValueToString(TEXT("ERegion"), request.Region, temp_Region)) OutRestJsonObj->SetStringField(TEXT("Region"), temp_Region); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperStartGame(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessStartGame.IsBound()) { FClientStartGameResult ResultStruct = UPlayFabClientModelDecoder::decodeStartGameResultResponse(response.responseData); OnSuccessStartGame.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Platform Specific Methods ////////////////////////////////////////////////////// /** Registers the Android device to receive push notifications */ UPlayFabClientAPI* UPlayFabClientAPI::AndroidDevicePushNotificationRegistration(FClientAndroidDevicePushNotificationRegistrationRequest request, FDelegateOnSuccessAndroidDevicePushNotificationRegistration onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAndroidDevicePushNotificationRegistration = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAndroidDevicePushNotificationRegistration); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AndroidDevicePushNotificationRegistration"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.ConfirmationMessage.IsEmpty() || request.ConfirmationMessage == "") { OutRestJsonObj->SetFieldNull(TEXT("ConfirmationMessage")); } else { OutRestJsonObj->SetStringField(TEXT("ConfirmationMessage"), request.ConfirmationMessage); } if (request.DeviceToken.IsEmpty() || request.DeviceToken == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceToken")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceToken"), request.DeviceToken); } OutRestJsonObj->SetBoolField(TEXT("SendPushNotificationConfirmation"), request.SendPushNotificationConfirmation); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAndroidDevicePushNotificationRegistration(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAndroidDevicePushNotificationRegistration.IsBound()) { FClientAndroidDevicePushNotificationRegistrationResult ResultStruct = UPlayFabClientModelDecoder::decodeAndroidDevicePushNotificationRegistrationResultResponse(response.responseData); OnSuccessAndroidDevicePushNotificationRegistration.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Checks for any new consumable entitlements. If any are found, they are consumed and added as PlayFab items */ UPlayFabClientAPI* UPlayFabClientAPI::ConsumePSNEntitlements(FClientConsumePSNEntitlementsRequest request, FDelegateOnSuccessConsumePSNEntitlements onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessConsumePSNEntitlements = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperConsumePSNEntitlements); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ConsumePSNEntitlements"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } OutRestJsonObj->SetNumberField(TEXT("ServiceLabel"), request.ServiceLabel); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperConsumePSNEntitlements(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessConsumePSNEntitlements.IsBound()) { FClientConsumePSNEntitlementsResult ResultStruct = UPlayFabClientModelDecoder::decodeConsumePSNEntitlementsResultResponse(response.responseData); OnSuccessConsumePSNEntitlements.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Grants the player's current entitlements from Xbox Live, consuming all availble items in Xbox and granting them to the player's PlayFab inventory. This call is idempotent and will not grant previously granted items to the player. */ UPlayFabClientAPI* UPlayFabClientAPI::ConsumeXboxEntitlements(FClientConsumeXboxEntitlementsRequest request, FDelegateOnSuccessConsumeXboxEntitlements onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessConsumeXboxEntitlements = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperConsumeXboxEntitlements); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ConsumeXboxEntitlements"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperConsumeXboxEntitlements(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessConsumeXboxEntitlements.IsBound()) { FClientConsumeXboxEntitlementsResult ResultStruct = UPlayFabClientModelDecoder::decodeConsumeXboxEntitlementsResultResponse(response.responseData); OnSuccessConsumeXboxEntitlements.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Uses the supplied OAuth code to refresh the internally cached player PSN auth token */ UPlayFabClientAPI* UPlayFabClientAPI::RefreshPSNAuthToken(FClientRefreshPSNAuthTokenRequest request, FDelegateOnSuccessRefreshPSNAuthToken onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRefreshPSNAuthToken = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRefreshPSNAuthToken); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RefreshPSNAuthToken"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.AuthCode.IsEmpty() || request.AuthCode == "") { OutRestJsonObj->SetFieldNull(TEXT("AuthCode")); } else { OutRestJsonObj->SetStringField(TEXT("AuthCode"), request.AuthCode); } OutRestJsonObj->SetNumberField(TEXT("IssuerId"), request.IssuerId); if (request.RedirectUri.IsEmpty() || request.RedirectUri == "") { OutRestJsonObj->SetFieldNull(TEXT("RedirectUri")); } else { OutRestJsonObj->SetStringField(TEXT("RedirectUri"), request.RedirectUri); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRefreshPSNAuthToken(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRefreshPSNAuthToken.IsBound()) { FClientEmptyResponse ResultStruct = UPlayFabClientModelDecoder::decodeEmptyResponseResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessRefreshPSNAuthToken.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Registers the iOS device to receive push notifications */ UPlayFabClientAPI* UPlayFabClientAPI::RegisterForIOSPushNotification(FClientRegisterForIOSPushNotificationRequest request, FDelegateOnSuccessRegisterForIOSPushNotification onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRegisterForIOSPushNotification = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRegisterForIOSPushNotification); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RegisterForIOSPushNotification"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.ConfirmationMessage.IsEmpty() || request.ConfirmationMessage == "") { OutRestJsonObj->SetFieldNull(TEXT("ConfirmationMessage")); } else { OutRestJsonObj->SetStringField(TEXT("ConfirmationMessage"), request.ConfirmationMessage); } if (request.DeviceToken.IsEmpty() || request.DeviceToken == "") { OutRestJsonObj->SetFieldNull(TEXT("DeviceToken")); } else { OutRestJsonObj->SetStringField(TEXT("DeviceToken"), request.DeviceToken); } OutRestJsonObj->SetBoolField(TEXT("SendPushNotificationConfirmation"), request.SendPushNotificationConfirmation); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRegisterForIOSPushNotification(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRegisterForIOSPushNotification.IsBound()) { FClientRegisterForIOSPushNotificationResult ResultStruct = UPlayFabClientModelDecoder::decodeRegisterForIOSPushNotificationResultResponse(response.responseData); OnSuccessRegisterForIOSPushNotification.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Restores all in-app purchases based on the given restore receipt */ UPlayFabClientAPI* UPlayFabClientAPI::RestoreIOSPurchases(FClientRestoreIOSPurchasesRequest request, FDelegateOnSuccessRestoreIOSPurchases onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRestoreIOSPurchases = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRestoreIOSPurchases); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RestoreIOSPurchases"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.ReceiptData.IsEmpty() || request.ReceiptData == "") { OutRestJsonObj->SetFieldNull(TEXT("ReceiptData")); } else { OutRestJsonObj->SetStringField(TEXT("ReceiptData"), request.ReceiptData); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRestoreIOSPurchases(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRestoreIOSPurchases.IsBound()) { FClientRestoreIOSPurchasesResult ResultStruct = UPlayFabClientModelDecoder::decodeRestoreIOSPurchasesResultResponse(response.responseData); OnSuccessRestoreIOSPurchases.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Validates with Amazon that the receipt for an Amazon App Store in-app purchase is valid and that it matches the purchased catalog item */ UPlayFabClientAPI* UPlayFabClientAPI::ValidateAmazonIAPReceipt(FClientValidateAmazonReceiptRequest request, FDelegateOnSuccessValidateAmazonIAPReceipt onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessValidateAmazonIAPReceipt = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperValidateAmazonIAPReceipt); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ValidateAmazonIAPReceipt"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CurrencyCode.IsEmpty() || request.CurrencyCode == "") { OutRestJsonObj->SetFieldNull(TEXT("CurrencyCode")); } else { OutRestJsonObj->SetStringField(TEXT("CurrencyCode"), request.CurrencyCode); } OutRestJsonObj->SetNumberField(TEXT("PurchasePrice"), request.PurchasePrice); if (request.ReceiptId.IsEmpty() || request.ReceiptId == "") { OutRestJsonObj->SetFieldNull(TEXT("ReceiptId")); } else { OutRestJsonObj->SetStringField(TEXT("ReceiptId"), request.ReceiptId); } if (request.UserId.IsEmpty() || request.UserId == "") { OutRestJsonObj->SetFieldNull(TEXT("UserId")); } else { OutRestJsonObj->SetStringField(TEXT("UserId"), request.UserId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperValidateAmazonIAPReceipt(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessValidateAmazonIAPReceipt.IsBound()) { FClientValidateAmazonReceiptResult ResultStruct = UPlayFabClientModelDecoder::decodeValidateAmazonReceiptResultResponse(response.responseData); OnSuccessValidateAmazonIAPReceipt.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Validates a Google Play purchase and gives the corresponding item to the player. */ UPlayFabClientAPI* UPlayFabClientAPI::ValidateGooglePlayPurchase(FClientValidateGooglePlayPurchaseRequest request, FDelegateOnSuccessValidateGooglePlayPurchase onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessValidateGooglePlayPurchase = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperValidateGooglePlayPurchase); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ValidateGooglePlayPurchase"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CurrencyCode.IsEmpty() || request.CurrencyCode == "") { OutRestJsonObj->SetFieldNull(TEXT("CurrencyCode")); } else { OutRestJsonObj->SetStringField(TEXT("CurrencyCode"), request.CurrencyCode); } OutRestJsonObj->SetNumberField(TEXT("PurchasePrice"), request.PurchasePrice); if (request.ReceiptJson.IsEmpty() || request.ReceiptJson == "") { OutRestJsonObj->SetFieldNull(TEXT("ReceiptJson")); } else { OutRestJsonObj->SetStringField(TEXT("ReceiptJson"), request.ReceiptJson); } if (request.Signature.IsEmpty() || request.Signature == "") { OutRestJsonObj->SetFieldNull(TEXT("Signature")); } else { OutRestJsonObj->SetStringField(TEXT("Signature"), request.Signature); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperValidateGooglePlayPurchase(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessValidateGooglePlayPurchase.IsBound()) { FClientValidateGooglePlayPurchaseResult ResultStruct = UPlayFabClientModelDecoder::decodeValidateGooglePlayPurchaseResultResponse(response.responseData); OnSuccessValidateGooglePlayPurchase.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Validates with the Apple store that the receipt for an iOS in-app purchase is valid and that it matches the purchased catalog item */ UPlayFabClientAPI* UPlayFabClientAPI::ValidateIOSReceipt(FClientValidateIOSReceiptRequest request, FDelegateOnSuccessValidateIOSReceipt onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessValidateIOSReceipt = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperValidateIOSReceipt); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ValidateIOSReceipt"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CurrencyCode.IsEmpty() || request.CurrencyCode == "") { OutRestJsonObj->SetFieldNull(TEXT("CurrencyCode")); } else { OutRestJsonObj->SetStringField(TEXT("CurrencyCode"), request.CurrencyCode); } OutRestJsonObj->SetNumberField(TEXT("PurchasePrice"), request.PurchasePrice); if (request.ReceiptData.IsEmpty() || request.ReceiptData == "") { OutRestJsonObj->SetFieldNull(TEXT("ReceiptData")); } else { OutRestJsonObj->SetStringField(TEXT("ReceiptData"), request.ReceiptData); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperValidateIOSReceipt(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessValidateIOSReceipt.IsBound()) { FClientValidateIOSReceiptResult ResultStruct = UPlayFabClientModelDecoder::decodeValidateIOSReceiptResultResponse(response.responseData); OnSuccessValidateIOSReceipt.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Validates with Windows that the receipt for an Windows App Store in-app purchase is valid and that it matches the purchased catalog item */ UPlayFabClientAPI* UPlayFabClientAPI::ValidateWindowsStoreReceipt(FClientValidateWindowsReceiptRequest request, FDelegateOnSuccessValidateWindowsStoreReceipt onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessValidateWindowsStoreReceipt = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperValidateWindowsStoreReceipt); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ValidateWindowsStoreReceipt"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CurrencyCode.IsEmpty() || request.CurrencyCode == "") { OutRestJsonObj->SetFieldNull(TEXT("CurrencyCode")); } else { OutRestJsonObj->SetStringField(TEXT("CurrencyCode"), request.CurrencyCode); } OutRestJsonObj->SetNumberField(TEXT("PurchasePrice"), request.PurchasePrice); if (request.Receipt.IsEmpty() || request.Receipt == "") { OutRestJsonObj->SetFieldNull(TEXT("Receipt")); } else { OutRestJsonObj->SetStringField(TEXT("Receipt"), request.Receipt); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperValidateWindowsStoreReceipt(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessValidateWindowsStoreReceipt.IsBound()) { FClientValidateWindowsReceiptResult ResultStruct = UPlayFabClientModelDecoder::decodeValidateWindowsReceiptResultResponse(response.responseData); OnSuccessValidateWindowsStoreReceipt.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Player Data Management ////////////////////////////////////////////////////// /** Retrieves a list of ranked friends of the current player for the given statistic, starting from the indicated point in the leaderboard */ UPlayFabClientAPI* UPlayFabClientAPI::GetFriendLeaderboard(FClientGetFriendLeaderboardRequest request, FDelegateOnSuccessGetFriendLeaderboard onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetFriendLeaderboard = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetFriendLeaderboard); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetFriendLeaderboard"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("IncludeFacebookFriends"), request.IncludeFacebookFriends); OutRestJsonObj->SetBoolField(TEXT("IncludeSteamFriends"), request.IncludeSteamFriends); OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); OutRestJsonObj->SetNumberField(TEXT("StartPosition"), request.StartPosition); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } OutRestJsonObj->SetBoolField(TEXT("UseSpecificVersion"), request.UseSpecificVersion); OutRestJsonObj->SetNumberField(TEXT("Version"), request.Version); if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetFriendLeaderboard(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetFriendLeaderboard.IsBound()) { FClientGetLeaderboardResult ResultStruct = UPlayFabClientModelDecoder::decodeGetLeaderboardResultResponse(response.responseData); OnSuccessGetFriendLeaderboard.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of ranked friends of the current player for the given statistic, centered on the requested PlayFab user. If PlayFabId is empty or null will return currently logged in user. */ UPlayFabClientAPI* UPlayFabClientAPI::GetFriendLeaderboardAroundPlayer(FClientGetFriendLeaderboardAroundPlayerRequest request, FDelegateOnSuccessGetFriendLeaderboardAroundPlayer onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetFriendLeaderboardAroundPlayer = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetFriendLeaderboardAroundPlayer); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetFriendLeaderboardAroundPlayer"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("IncludeFacebookFriends"), request.IncludeFacebookFriends); OutRestJsonObj->SetBoolField(TEXT("IncludeSteamFriends"), request.IncludeSteamFriends); OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } OutRestJsonObj->SetBoolField(TEXT("UseSpecificVersion"), request.UseSpecificVersion); OutRestJsonObj->SetNumberField(TEXT("Version"), request.Version); if (request.XboxToken.IsEmpty() || request.XboxToken == "") { OutRestJsonObj->SetFieldNull(TEXT("XboxToken")); } else { OutRestJsonObj->SetStringField(TEXT("XboxToken"), request.XboxToken); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetFriendLeaderboardAroundPlayer(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetFriendLeaderboardAroundPlayer.IsBound()) { FClientGetFriendLeaderboardAroundPlayerResult ResultStruct = UPlayFabClientModelDecoder::decodeGetFriendLeaderboardAroundPlayerResultResponse(response.responseData); OnSuccessGetFriendLeaderboardAroundPlayer.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of ranked users for the given statistic, starting from the indicated point in the leaderboard */ UPlayFabClientAPI* UPlayFabClientAPI::GetLeaderboard(FClientGetLeaderboardRequest request, FDelegateOnSuccessGetLeaderboard onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetLeaderboard = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetLeaderboard); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetLeaderboard"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); OutRestJsonObj->SetNumberField(TEXT("StartPosition"), request.StartPosition); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } OutRestJsonObj->SetBoolField(TEXT("UseSpecificVersion"), request.UseSpecificVersion); OutRestJsonObj->SetNumberField(TEXT("Version"), request.Version); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetLeaderboard(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetLeaderboard.IsBound()) { FClientGetLeaderboardResult ResultStruct = UPlayFabClientModelDecoder::decodeGetLeaderboardResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessGetLeaderboard.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a list of ranked users for the given statistic, centered on the requested player. If PlayFabId is empty or null will return currently logged in user. */ UPlayFabClientAPI* UPlayFabClientAPI::GetLeaderboardAroundPlayer(FClientGetLeaderboardAroundPlayerRequest request, FDelegateOnSuccessGetLeaderboardAroundPlayer onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetLeaderboardAroundPlayer = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetLeaderboardAroundPlayer); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetLeaderboardAroundPlayer"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("MaxResultsCount"), request.MaxResultsCount); if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } if (request.ProfileConstraints != nullptr) OutRestJsonObj->SetObjectField(TEXT("ProfileConstraints"), request.ProfileConstraints); if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } OutRestJsonObj->SetBoolField(TEXT("UseSpecificVersion"), request.UseSpecificVersion); OutRestJsonObj->SetNumberField(TEXT("Version"), request.Version); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetLeaderboardAroundPlayer(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetLeaderboardAroundPlayer.IsBound()) { FClientGetLeaderboardAroundPlayerResult ResultStruct = UPlayFabClientModelDecoder::decodeGetLeaderboardAroundPlayerResultResponse(response.responseData); OnSuccessGetLeaderboardAroundPlayer.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the indicated statistics (current version and values for all statistics, if none are specified), for the local player. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerStatistics(FClientGetPlayerStatisticsRequest request, FDelegateOnSuccessGetPlayerStatistics onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerStatistics = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerStatistics); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerStatistics"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.StatisticNames.IsEmpty() || request.StatisticNames == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticNames")); } else { TArray StatisticNamesArray; FString(request.StatisticNames).ParseIntoArray(StatisticNamesArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("StatisticNames"), StatisticNamesArray); } if (request.StatisticNameVersions.Num() == 0) { OutRestJsonObj->SetFieldNull(TEXT("StatisticNameVersions")); } else { OutRestJsonObj->SetObjectArrayField(TEXT("StatisticNameVersions"), request.StatisticNameVersions); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerStatistics(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerStatistics.IsBound()) { FClientGetPlayerStatisticsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerStatisticsResultResponse(response.responseData); OnSuccessGetPlayerStatistics.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the information on the available versions of the specified statistic. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerStatisticVersions(FClientGetPlayerStatisticVersionsRequest request, FDelegateOnSuccessGetPlayerStatisticVersions onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerStatisticVersions = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerStatisticVersions); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerStatisticVersions"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.StatisticName.IsEmpty() || request.StatisticName == "") { OutRestJsonObj->SetFieldNull(TEXT("StatisticName")); } else { OutRestJsonObj->SetStringField(TEXT("StatisticName"), request.StatisticName); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerStatisticVersions(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerStatisticVersions.IsBound()) { FClientGetPlayerStatisticVersionsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerStatisticVersionsResultResponse(response.responseData); OnSuccessGetPlayerStatisticVersions.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the title-specific custom data for the user which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetUserData(FClientGetUserDataRequest request, FDelegateOnSuccessGetUserData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetUserData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetUserData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetUserData"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetUserData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetUserData.IsBound()) { FClientGetUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetUserDataResultResponse(response.responseData); OnSuccessGetUserData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the publisher-specific custom data for the user which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetUserPublisherData(FClientGetUserDataRequest request, FDelegateOnSuccessGetUserPublisherData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetUserPublisherData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetUserPublisherData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetUserPublisherData"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetUserPublisherData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetUserPublisherData.IsBound()) { FClientGetUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetUserDataResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessGetUserPublisherData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the publisher-specific custom data for the user which can only be read by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetUserPublisherReadOnlyData(FClientGetUserDataRequest request, FDelegateOnSuccessGetUserPublisherReadOnlyData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetUserPublisherReadOnlyData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetUserPublisherReadOnlyData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetUserPublisherReadOnlyData"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetUserPublisherReadOnlyData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetUserPublisherReadOnlyData.IsBound()) { FClientGetUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetUserDataResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessGetUserPublisherReadOnlyData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the title-specific custom data for the user which can only be read by the client */ UPlayFabClientAPI* UPlayFabClientAPI::GetUserReadOnlyData(FClientGetUserDataRequest request, FDelegateOnSuccessGetUserReadOnlyData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetUserReadOnlyData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetUserReadOnlyData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetUserReadOnlyData"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("IfChangedFromDataVersion"), request.IfChangedFromDataVersion); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetUserReadOnlyData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetUserReadOnlyData.IsBound()) { FClientGetUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetUserDataResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessGetUserReadOnlyData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Updates the values of the specified title-specific statistics for the user. By default, clients are not permitted to update statistics. Developers may override this setting in the Game Manager > Settings > API Features. */ UPlayFabClientAPI* UPlayFabClientAPI::UpdatePlayerStatistics(FClientUpdatePlayerStatisticsRequest request, FDelegateOnSuccessUpdatePlayerStatistics onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdatePlayerStatistics = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdatePlayerStatistics); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdatePlayerStatistics"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Statistics.Num() == 0) { OutRestJsonObj->SetFieldNull(TEXT("Statistics")); } else { OutRestJsonObj->SetObjectArrayField(TEXT("Statistics"), request.Statistics); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdatePlayerStatistics(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdatePlayerStatistics.IsBound()) { FClientUpdatePlayerStatisticsResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdatePlayerStatisticsResultResponse(response.responseData); OnSuccessUpdatePlayerStatistics.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Creates and updates the title-specific custom data for the user which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateUserData(FClientUpdateUserDataRequest request, FDelegateOnSuccessUpdateUserData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateUserData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateUserData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateUserData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Data != nullptr) OutRestJsonObj->SetObjectField(TEXT("Data"), request.Data); // Check to see if string is empty if (request.KeysToRemove.IsEmpty() || request.KeysToRemove == "") { OutRestJsonObj->SetFieldNull(TEXT("KeysToRemove")); } else { TArray KeysToRemoveArray; FString(request.KeysToRemove).ParseIntoArray(KeysToRemoveArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("KeysToRemove"), KeysToRemoveArray); } FString temp_Permission; if (GetEnumValueToString(TEXT("EUserDataPermission"), request.Permission, temp_Permission)) OutRestJsonObj->SetStringField(TEXT("Permission"), temp_Permission); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateUserData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateUserData.IsBound()) { FClientUpdateUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateUserDataResultResponse(response.responseData); OnSuccessUpdateUserData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Creates and updates the publisher-specific custom data for the user which is readable and writable by the client */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateUserPublisherData(FClientUpdateUserDataRequest request, FDelegateOnSuccessUpdateUserPublisherData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateUserPublisherData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateUserPublisherData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateUserPublisherData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Data != nullptr) OutRestJsonObj->SetObjectField(TEXT("Data"), request.Data); // Check to see if string is empty if (request.KeysToRemove.IsEmpty() || request.KeysToRemove == "") { OutRestJsonObj->SetFieldNull(TEXT("KeysToRemove")); } else { TArray KeysToRemoveArray; FString(request.KeysToRemove).ParseIntoArray(KeysToRemoveArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("KeysToRemove"), KeysToRemoveArray); } FString temp_Permission; if (GetEnumValueToString(TEXT("EUserDataPermission"), request.Permission, temp_Permission)) OutRestJsonObj->SetStringField(TEXT("Permission"), temp_Permission); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateUserPublisherData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateUserPublisherData.IsBound()) { FClientUpdateUserDataResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateUserDataResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessUpdateUserPublisherData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Player Item Management ////////////////////////////////////////////////////// /** Increments the user's balance of the specified virtual currency by the stated amount */ UPlayFabClientAPI* UPlayFabClientAPI::AddUserVirtualCurrency(FClientAddUserVirtualCurrencyRequest request, FDelegateOnSuccessAddUserVirtualCurrency onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddUserVirtualCurrency = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddUserVirtualCurrency); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddUserVirtualCurrency"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("Amount"), request.Amount); if (request.VirtualCurrency.IsEmpty() || request.VirtualCurrency == "") { OutRestJsonObj->SetFieldNull(TEXT("VirtualCurrency")); } else { OutRestJsonObj->SetStringField(TEXT("VirtualCurrency"), request.VirtualCurrency); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddUserVirtualCurrency(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddUserVirtualCurrency.IsBound()) { FClientModifyUserVirtualCurrencyResult ResultStruct = UPlayFabClientModelDecoder::decodeModifyUserVirtualCurrencyResultResponse(response.responseData); OnSuccessAddUserVirtualCurrency.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Confirms with the payment provider that the purchase was approved (if applicable) and adjusts inventory and virtual currency balances as appropriate */ UPlayFabClientAPI* UPlayFabClientAPI::ConfirmPurchase(FClientConfirmPurchaseRequest request, FDelegateOnSuccessConfirmPurchase onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessConfirmPurchase = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperConfirmPurchase); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ConfirmPurchase"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.OrderId.IsEmpty() || request.OrderId == "") { OutRestJsonObj->SetFieldNull(TEXT("OrderId")); } else { OutRestJsonObj->SetStringField(TEXT("OrderId"), request.OrderId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperConfirmPurchase(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessConfirmPurchase.IsBound()) { FClientConfirmPurchaseResult ResultStruct = UPlayFabClientModelDecoder::decodeConfirmPurchaseResultResponse(response.responseData); OnSuccessConfirmPurchase.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Consume uses of a consumable item. When all uses are consumed, it will be removed from the player's inventory. */ UPlayFabClientAPI* UPlayFabClientAPI::ConsumeItem(FClientConsumeItemRequest request, FDelegateOnSuccessConsumeItem onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessConsumeItem = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperConsumeItem); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ConsumeItem"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } OutRestJsonObj->SetNumberField(TEXT("ConsumeCount"), request.ConsumeCount); if (request.ItemInstanceId.IsEmpty() || request.ItemInstanceId == "") { OutRestJsonObj->SetFieldNull(TEXT("ItemInstanceId")); } else { OutRestJsonObj->SetStringField(TEXT("ItemInstanceId"), request.ItemInstanceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperConsumeItem(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessConsumeItem.IsBound()) { FClientConsumeItemResult ResultStruct = UPlayFabClientModelDecoder::decodeConsumeItemResultResponse(response.responseData); OnSuccessConsumeItem.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the specified character's current inventory of virtual goods */ UPlayFabClientAPI* UPlayFabClientAPI::GetCharacterInventory(FClientGetCharacterInventoryRequest request, FDelegateOnSuccessGetCharacterInventory onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCharacterInventory = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCharacterInventory); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCharacterInventory"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCharacterInventory(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCharacterInventory.IsBound()) { FClientGetCharacterInventoryResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCharacterInventoryResultResponse(response.responseData); OnSuccessGetCharacterInventory.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** For payments flows where the provider requires playfab (the fulfiller) to initiate the transaction, but the client completes the rest of the flow. In the Xsolla case, the token returned here will be passed to Xsolla by the client to create a cart. Poll GetPurchase using the returned OrderId once you've completed the payment. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPaymentToken(FClientGetPaymentTokenRequest request, FDelegateOnSuccessGetPaymentToken onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPaymentToken = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPaymentToken); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPaymentToken"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.TokenProvider.IsEmpty() || request.TokenProvider == "") { OutRestJsonObj->SetFieldNull(TEXT("TokenProvider")); } else { OutRestJsonObj->SetStringField(TEXT("TokenProvider"), request.TokenProvider); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPaymentToken(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPaymentToken.IsBound()) { FClientGetPaymentTokenResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPaymentTokenResultResponse(response.responseData); OnSuccessGetPaymentToken.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves a purchase along with its current PlayFab status. Returns inventory items from the purchase that are still active. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPurchase(FClientGetPurchaseRequest request, FDelegateOnSuccessGetPurchase onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPurchase = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPurchase); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPurchase"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.OrderId.IsEmpty() || request.OrderId == "") { OutRestJsonObj->SetFieldNull(TEXT("OrderId")); } else { OutRestJsonObj->SetStringField(TEXT("OrderId"), request.OrderId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPurchase(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPurchase.IsBound()) { FClientGetPurchaseResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPurchaseResultResponse(response.responseData); OnSuccessGetPurchase.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the user's current inventory of virtual goods */ UPlayFabClientAPI* UPlayFabClientAPI::GetUserInventory(FClientGetUserInventoryRequest request, FDelegateOnSuccessGetUserInventory onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetUserInventory = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetUserInventory); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetUserInventory"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetUserInventory(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetUserInventory.IsBound()) { FClientGetUserInventoryResult ResultStruct = UPlayFabClientModelDecoder::decodeGetUserInventoryResultResponse(response.responseData); OnSuccessGetUserInventory.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Selects a payment option for purchase order created via StartPurchase */ UPlayFabClientAPI* UPlayFabClientAPI::PayForPurchase(FClientPayForPurchaseRequest request, FDelegateOnSuccessPayForPurchase onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessPayForPurchase = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperPayForPurchase); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/PayForPurchase"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Currency.IsEmpty() || request.Currency == "") { OutRestJsonObj->SetFieldNull(TEXT("Currency")); } else { OutRestJsonObj->SetStringField(TEXT("Currency"), request.Currency); } if (request.OrderId.IsEmpty() || request.OrderId == "") { OutRestJsonObj->SetFieldNull(TEXT("OrderId")); } else { OutRestJsonObj->SetStringField(TEXT("OrderId"), request.OrderId); } if (request.ProviderName.IsEmpty() || request.ProviderName == "") { OutRestJsonObj->SetFieldNull(TEXT("ProviderName")); } else { OutRestJsonObj->SetStringField(TEXT("ProviderName"), request.ProviderName); } if (request.ProviderTransactionId.IsEmpty() || request.ProviderTransactionId == "") { OutRestJsonObj->SetFieldNull(TEXT("ProviderTransactionId")); } else { OutRestJsonObj->SetStringField(TEXT("ProviderTransactionId"), request.ProviderTransactionId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperPayForPurchase(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessPayForPurchase.IsBound()) { FClientPayForPurchaseResult ResultStruct = UPlayFabClientModelDecoder::decodePayForPurchaseResultResponse(response.responseData); OnSuccessPayForPurchase.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Buys a single item with virtual currency. You must specify both the virtual currency to use to purchase, as well as what the client believes the price to be. This lets the server fail the purchase if the price has changed. */ UPlayFabClientAPI* UPlayFabClientAPI::PurchaseItem(FClientPurchaseItemRequest request, FDelegateOnSuccessPurchaseItem onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessPurchaseItem = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperPurchaseItem); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/PurchaseItem"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.ItemId.IsEmpty() || request.ItemId == "") { OutRestJsonObj->SetFieldNull(TEXT("ItemId")); } else { OutRestJsonObj->SetStringField(TEXT("ItemId"), request.ItemId); } OutRestJsonObj->SetNumberField(TEXT("Price"), request.Price); if (request.StoreId.IsEmpty() || request.StoreId == "") { OutRestJsonObj->SetFieldNull(TEXT("StoreId")); } else { OutRestJsonObj->SetStringField(TEXT("StoreId"), request.StoreId); } if (request.VirtualCurrency.IsEmpty() || request.VirtualCurrency == "") { OutRestJsonObj->SetFieldNull(TEXT("VirtualCurrency")); } else { OutRestJsonObj->SetStringField(TEXT("VirtualCurrency"), request.VirtualCurrency); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperPurchaseItem(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessPurchaseItem.IsBound()) { FClientPurchaseItemResult ResultStruct = UPlayFabClientModelDecoder::decodePurchaseItemResultResponse(response.responseData); OnSuccessPurchaseItem.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Adds the virtual goods associated with the coupon to the user's inventory. Coupons can be generated via the Economy->Catalogs tab in the PlayFab Game Manager. */ UPlayFabClientAPI* UPlayFabClientAPI::RedeemCoupon(FClientRedeemCouponRequest request, FDelegateOnSuccessRedeemCoupon onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRedeemCoupon = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRedeemCoupon); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RedeemCoupon"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.CouponCode.IsEmpty() || request.CouponCode == "") { OutRestJsonObj->SetFieldNull(TEXT("CouponCode")); } else { OutRestJsonObj->SetStringField(TEXT("CouponCode"), request.CouponCode); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRedeemCoupon(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRedeemCoupon.IsBound()) { FClientRedeemCouponResult ResultStruct = UPlayFabClientModelDecoder::decodeRedeemCouponResultResponse(response.responseData); OnSuccessRedeemCoupon.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Creates an order for a list of items from the title catalog */ UPlayFabClientAPI* UPlayFabClientAPI::StartPurchase(FClientStartPurchaseRequest request, FDelegateOnSuccessStartPurchase onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessStartPurchase = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperStartPurchase); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/StartPurchase"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.Items.Num() == 0) { OutRestJsonObj->SetFieldNull(TEXT("Items")); } else { OutRestJsonObj->SetObjectArrayField(TEXT("Items"), request.Items); } if (request.StoreId.IsEmpty() || request.StoreId == "") { OutRestJsonObj->SetFieldNull(TEXT("StoreId")); } else { OutRestJsonObj->SetStringField(TEXT("StoreId"), request.StoreId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperStartPurchase(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessStartPurchase.IsBound()) { FClientStartPurchaseResult ResultStruct = UPlayFabClientModelDecoder::decodeStartPurchaseResultResponse(response.responseData); OnSuccessStartPurchase.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Decrements the user's balance of the specified virtual currency by the stated amount. It is possible to make a VC balance negative with this API. */ UPlayFabClientAPI* UPlayFabClientAPI::SubtractUserVirtualCurrency(FClientSubtractUserVirtualCurrencyRequest request, FDelegateOnSuccessSubtractUserVirtualCurrency onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessSubtractUserVirtualCurrency = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperSubtractUserVirtualCurrency); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/SubtractUserVirtualCurrency"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("Amount"), request.Amount); if (request.VirtualCurrency.IsEmpty() || request.VirtualCurrency == "") { OutRestJsonObj->SetFieldNull(TEXT("VirtualCurrency")); } else { OutRestJsonObj->SetStringField(TEXT("VirtualCurrency"), request.VirtualCurrency); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperSubtractUserVirtualCurrency(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessSubtractUserVirtualCurrency.IsBound()) { FClientModifyUserVirtualCurrencyResult ResultStruct = UPlayFabClientModelDecoder::decodeModifyUserVirtualCurrencyResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessSubtractUserVirtualCurrency.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Opens the specified container, with the specified key (when required), and returns the contents of the opened container. If the container (and key when relevant) are consumable (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of ConsumeItem. */ UPlayFabClientAPI* UPlayFabClientAPI::UnlockContainerInstance(FClientUnlockContainerInstanceRequest request, FDelegateOnSuccessUnlockContainerInstance onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlockContainerInstance = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlockContainerInstance); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlockContainerInstance"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.ContainerItemInstanceId.IsEmpty() || request.ContainerItemInstanceId == "") { OutRestJsonObj->SetFieldNull(TEXT("ContainerItemInstanceId")); } else { OutRestJsonObj->SetStringField(TEXT("ContainerItemInstanceId"), request.ContainerItemInstanceId); } if (request.KeyItemInstanceId.IsEmpty() || request.KeyItemInstanceId == "") { OutRestJsonObj->SetFieldNull(TEXT("KeyItemInstanceId")); } else { OutRestJsonObj->SetStringField(TEXT("KeyItemInstanceId"), request.KeyItemInstanceId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlockContainerInstance(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlockContainerInstance.IsBound()) { FClientUnlockContainerItemResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlockContainerItemResultResponse(response.responseData); OnSuccessUnlockContainerInstance.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Searches target inventory for an ItemInstance matching the given CatalogItemId, if necessary unlocks it using an appropriate key, and returns the contents of the opened container. If the container (and key when relevant) are consumable (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of ConsumeItem. */ UPlayFabClientAPI* UPlayFabClientAPI::UnlockContainerItem(FClientUnlockContainerItemRequest request, FDelegateOnSuccessUnlockContainerItem onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUnlockContainerItem = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUnlockContainerItem); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UnlockContainerItem"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.CharacterId.IsEmpty() || request.CharacterId == "") { OutRestJsonObj->SetFieldNull(TEXT("CharacterId")); } else { OutRestJsonObj->SetStringField(TEXT("CharacterId"), request.CharacterId); } if (request.ContainerItemId.IsEmpty() || request.ContainerItemId == "") { OutRestJsonObj->SetFieldNull(TEXT("ContainerItemId")); } else { OutRestJsonObj->SetStringField(TEXT("ContainerItemId"), request.ContainerItemId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUnlockContainerItem(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUnlockContainerItem.IsBound()) { FClientUnlockContainerItemResult ResultStruct = UPlayFabClientModelDecoder::decodeUnlockContainerItemResultResponse(response.responseData); ResultStruct.Request = RequestJsonObj; OnSuccessUnlockContainerItem.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // PlayStream ////////////////////////////////////////////////////// /** List all segments that a player currently belongs to at this moment in time. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerSegments(FClientGetPlayerSegmentsRequest request, FDelegateOnSuccessGetPlayerSegments onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerSegments = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerSegments); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerSegments"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerSegments(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerSegments.IsBound()) { FClientGetPlayerSegmentsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerSegmentsResultResponse(response.responseData); OnSuccessGetPlayerSegments.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Get all tags with a given Namespace (optional) from a player profile. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerTags(FClientGetPlayerTagsRequest request, FDelegateOnSuccessGetPlayerTags onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerTags = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerTags); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerTags"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Namespace.IsEmpty() || request.Namespace == "") { OutRestJsonObj->SetFieldNull(TEXT("Namespace")); } else { OutRestJsonObj->SetStringField(TEXT("Namespace"), request.Namespace); } if (request.PlayFabId.IsEmpty() || request.PlayFabId == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabId")); } else { OutRestJsonObj->SetStringField(TEXT("PlayFabId"), request.PlayFabId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerTags(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerTags.IsBound()) { FClientGetPlayerTagsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerTagsResultResponse(response.responseData); OnSuccessGetPlayerTags.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Server-Side Cloud Script ////////////////////////////////////////////////////// /** Executes a CloudScript function, with the 'currentPlayerId' set to the PlayFab ID of the authenticated player. */ UPlayFabClientAPI* UPlayFabClientAPI::ExecuteCloudScript(FClientExecuteCloudScriptRequest request, FDelegateOnSuccessExecuteCloudScript onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessExecuteCloudScript = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperExecuteCloudScript); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/ExecuteCloudScript"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.FunctionName.IsEmpty() || request.FunctionName == "") { OutRestJsonObj->SetFieldNull(TEXT("FunctionName")); } else { OutRestJsonObj->SetStringField(TEXT("FunctionName"), request.FunctionName); } if (request.FunctionParameter != nullptr) OutRestJsonObj->SetObjectField(TEXT("FunctionParameter"), request.FunctionParameter); OutRestJsonObj->SetBoolField(TEXT("GeneratePlayStreamEvent"), request.GeneratePlayStreamEvent); FString temp_RevisionSelection; if (GetEnumValueToString(TEXT("ECloudScriptRevisionOption"), request.RevisionSelection, temp_RevisionSelection)) OutRestJsonObj->SetStringField(TEXT("RevisionSelection"), temp_RevisionSelection); OutRestJsonObj->SetNumberField(TEXT("SpecificRevision"), request.SpecificRevision); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperExecuteCloudScript(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessExecuteCloudScript.IsBound()) { FClientExecuteCloudScriptResult ResultStruct = UPlayFabClientModelDecoder::decodeExecuteCloudScriptResultResponse(response.responseData); OnSuccessExecuteCloudScript.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Shared Group Data ////////////////////////////////////////////////////// /** Adds users to the set of those able to update both the shared data, as well as the set of users in the group. Only users in the group can add new members. Shared Groups are designed for sharing data between a very small number of players, please see our guide: https://api.playfab.com/docs/tutorials/landing-players/shared-groups */ UPlayFabClientAPI* UPlayFabClientAPI::AddSharedGroupMembers(FClientAddSharedGroupMembersRequest request, FDelegateOnSuccessAddSharedGroupMembers onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAddSharedGroupMembers = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAddSharedGroupMembers); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AddSharedGroupMembers"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.PlayFabIds.IsEmpty() || request.PlayFabIds == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabIds")); } else { TArray PlayFabIdsArray; FString(request.PlayFabIds).ParseIntoArray(PlayFabIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("PlayFabIds"), PlayFabIdsArray); } if (request.SharedGroupId.IsEmpty() || request.SharedGroupId == "") { OutRestJsonObj->SetFieldNull(TEXT("SharedGroupId")); } else { OutRestJsonObj->SetStringField(TEXT("SharedGroupId"), request.SharedGroupId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAddSharedGroupMembers(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAddSharedGroupMembers.IsBound()) { FClientAddSharedGroupMembersResult ResultStruct = UPlayFabClientModelDecoder::decodeAddSharedGroupMembersResultResponse(response.responseData); OnSuccessAddSharedGroupMembers.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Requests the creation of a shared group object, containing key/value pairs which may be updated by all members of the group. Upon creation, the current user will be the only member of the group. Shared Groups are designed for sharing data between a very small number of players, please see our guide: https://docs.microsoft.com/en-us/gaming/playfab/features/social/groups/using-shared-group-data */ UPlayFabClientAPI* UPlayFabClientAPI::CreateSharedGroup(FClientCreateSharedGroupRequest request, FDelegateOnSuccessCreateSharedGroup onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessCreateSharedGroup = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperCreateSharedGroup); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/CreateSharedGroup"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.SharedGroupId.IsEmpty() || request.SharedGroupId == "") { OutRestJsonObj->SetFieldNull(TEXT("SharedGroupId")); } else { OutRestJsonObj->SetStringField(TEXT("SharedGroupId"), request.SharedGroupId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperCreateSharedGroup(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessCreateSharedGroup.IsBound()) { FClientCreateSharedGroupResult ResultStruct = UPlayFabClientModelDecoder::decodeCreateSharedGroupResultResponse(response.responseData); OnSuccessCreateSharedGroup.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves data stored in a shared group object, as well as the list of members in the group. Non-members of the group may use this to retrieve group data, including membership, but they will not receive data for keys marked as private. Shared Groups are designed for sharing data between a very small number of players, please see our guide: https://api.playfab.com/docs/tutorials/landing-players/shared-groups */ UPlayFabClientAPI* UPlayFabClientAPI::GetSharedGroupData(FClientGetSharedGroupDataRequest request, FDelegateOnSuccessGetSharedGroupData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetSharedGroupData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetSharedGroupData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetSharedGroupData"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetBoolField(TEXT("GetMembers"), request.GetMembers); // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } if (request.SharedGroupId.IsEmpty() || request.SharedGroupId == "") { OutRestJsonObj->SetFieldNull(TEXT("SharedGroupId")); } else { OutRestJsonObj->SetStringField(TEXT("SharedGroupId"), request.SharedGroupId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetSharedGroupData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetSharedGroupData.IsBound()) { FClientGetSharedGroupDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetSharedGroupDataResultResponse(response.responseData); OnSuccessGetSharedGroupData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Removes users from the set of those able to update the shared data and the set of users in the group. Only users in the group can remove members. If as a result of the call, zero users remain with access, the group and its associated data will be deleted. Shared Groups are designed for sharing data between a very small number of players, please see our guide: https://api.playfab.com/docs/tutorials/landing-players/shared-groups */ UPlayFabClientAPI* UPlayFabClientAPI::RemoveSharedGroupMembers(FClientRemoveSharedGroupMembersRequest request, FDelegateOnSuccessRemoveSharedGroupMembers onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessRemoveSharedGroupMembers = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperRemoveSharedGroupMembers); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/RemoveSharedGroupMembers"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.PlayFabIds.IsEmpty() || request.PlayFabIds == "") { OutRestJsonObj->SetFieldNull(TEXT("PlayFabIds")); } else { TArray PlayFabIdsArray; FString(request.PlayFabIds).ParseIntoArray(PlayFabIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("PlayFabIds"), PlayFabIdsArray); } if (request.SharedGroupId.IsEmpty() || request.SharedGroupId == "") { OutRestJsonObj->SetFieldNull(TEXT("SharedGroupId")); } else { OutRestJsonObj->SetStringField(TEXT("SharedGroupId"), request.SharedGroupId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperRemoveSharedGroupMembers(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessRemoveSharedGroupMembers.IsBound()) { FClientRemoveSharedGroupMembersResult ResultStruct = UPlayFabClientModelDecoder::decodeRemoveSharedGroupMembersResultResponse(response.responseData); OnSuccessRemoveSharedGroupMembers.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Adds, updates, and removes data keys for a shared group object. If the permission is set to Public, all fields updated or added in this call will be readable by users not in the group. By default, data permissions are set to Private. Regardless of the permission setting, only members of the group can update the data. Shared Groups are designed for sharing data between a very small number of players, please see our guide: https://api.playfab.com/docs/tutorials/landing-players/shared-groups */ UPlayFabClientAPI* UPlayFabClientAPI::UpdateSharedGroupData(FClientUpdateSharedGroupDataRequest request, FDelegateOnSuccessUpdateSharedGroupData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessUpdateSharedGroupData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperUpdateSharedGroupData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/UpdateSharedGroupData"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.Data != nullptr) OutRestJsonObj->SetObjectField(TEXT("Data"), request.Data); // Check to see if string is empty if (request.KeysToRemove.IsEmpty() || request.KeysToRemove == "") { OutRestJsonObj->SetFieldNull(TEXT("KeysToRemove")); } else { TArray KeysToRemoveArray; FString(request.KeysToRemove).ParseIntoArray(KeysToRemoveArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("KeysToRemove"), KeysToRemoveArray); } FString temp_Permission; if (GetEnumValueToString(TEXT("EUserDataPermission"), request.Permission, temp_Permission)) OutRestJsonObj->SetStringField(TEXT("Permission"), temp_Permission); if (request.SharedGroupId.IsEmpty() || request.SharedGroupId == "") { OutRestJsonObj->SetFieldNull(TEXT("SharedGroupId")); } else { OutRestJsonObj->SetStringField(TEXT("SharedGroupId"), request.SharedGroupId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperUpdateSharedGroupData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessUpdateSharedGroupData.IsBound()) { FClientUpdateSharedGroupDataResult ResultStruct = UPlayFabClientModelDecoder::decodeUpdateSharedGroupDataResultResponse(response.responseData); OnSuccessUpdateSharedGroupData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Title-Wide Data Management ////////////////////////////////////////////////////// /** Retrieves the specified version of the title's catalog of virtual goods, including all defined properties */ UPlayFabClientAPI* UPlayFabClientAPI::GetCatalogItems(FClientGetCatalogItemsRequest request, FDelegateOnSuccessGetCatalogItems onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetCatalogItems = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetCatalogItems); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetCatalogItems"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetCatalogItems(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetCatalogItems.IsBound()) { FClientGetCatalogItemsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetCatalogItemsResultResponse(response.responseData); OnSuccessGetCatalogItems.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the key-value store of custom publisher settings */ UPlayFabClientAPI* UPlayFabClientAPI::GetPublisherData(FClientGetPublisherDataRequest request, FDelegateOnSuccessGetPublisherData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPublisherData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPublisherData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPublisherData"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPublisherData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPublisherData.IsBound()) { FClientGetPublisherDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetPublisherDataResultResponse(response.responseData); OnSuccessGetPublisherData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the set of items defined for the specified store, including all prices defined */ UPlayFabClientAPI* UPlayFabClientAPI::GetStoreItems(FClientGetStoreItemsRequest request, FDelegateOnSuccessGetStoreItems onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetStoreItems = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetStoreItems); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetStoreItems"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.CatalogVersion.IsEmpty() || request.CatalogVersion == "") { OutRestJsonObj->SetFieldNull(TEXT("CatalogVersion")); } else { OutRestJsonObj->SetStringField(TEXT("CatalogVersion"), request.CatalogVersion); } if (request.StoreId.IsEmpty() || request.StoreId == "") { OutRestJsonObj->SetFieldNull(TEXT("StoreId")); } else { OutRestJsonObj->SetStringField(TEXT("StoreId"), request.StoreId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetStoreItems(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetStoreItems.IsBound()) { FClientGetStoreItemsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetStoreItemsResultResponse(response.responseData); OnSuccessGetStoreItems.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the current server time */ UPlayFabClientAPI* UPlayFabClientAPI::GetTime(FClientGetTimeRequest request, FDelegateOnSuccessGetTime onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetTime = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetTime); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetTime"; manager->useSessionTicket = true; // Serialize all the request properties to json // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetTime(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetTime.IsBound()) { FClientGetTimeResult ResultStruct = UPlayFabClientModelDecoder::decodeGetTimeResultResponse(response.responseData); OnSuccessGetTime.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the key-value store of custom title settings */ UPlayFabClientAPI* UPlayFabClientAPI::GetTitleData(FClientGetTitleDataRequest request, FDelegateOnSuccessGetTitleData onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetTitleData = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetTitleData); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetTitleData"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.Keys.IsEmpty() || request.Keys == "") { OutRestJsonObj->SetFieldNull(TEXT("Keys")); } else { TArray KeysArray; FString(request.Keys).ParseIntoArray(KeysArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("Keys"), KeysArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetTitleData(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetTitleData.IsBound()) { FClientGetTitleDataResult ResultStruct = UPlayFabClientModelDecoder::decodeGetTitleDataResultResponse(response.responseData); OnSuccessGetTitleData.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Retrieves the title news feed, as configured in the developer portal */ UPlayFabClientAPI* UPlayFabClientAPI::GetTitleNews(FClientGetTitleNewsRequest request, FDelegateOnSuccessGetTitleNews onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetTitleNews = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetTitleNews); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetTitleNews"; manager->useSessionTicket = true; // Serialize all the request properties to json OutRestJsonObj->SetNumberField(TEXT("Count"), request.Count); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetTitleNews(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetTitleNews.IsBound()) { FClientGetTitleNewsResult ResultStruct = UPlayFabClientModelDecoder::decodeGetTitleNewsResultResponse(response.responseData); OnSuccessGetTitleNews.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /////////////////////////////////////////////////////// // Trading ////////////////////////////////////////////////////// /** Accepts an open trade (one that has not yet been accepted or cancelled), if the locally signed-in player is in the allowed player list for the trade, or it is open to all players. If the call is successful, the offered and accepted items will be swapped between the two players' inventories. */ UPlayFabClientAPI* UPlayFabClientAPI::AcceptTrade(FClientAcceptTradeRequest request, FDelegateOnSuccessAcceptTrade onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessAcceptTrade = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperAcceptTrade); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/AcceptTrade"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.AcceptedInventoryInstanceIds.IsEmpty() || request.AcceptedInventoryInstanceIds == "") { OutRestJsonObj->SetFieldNull(TEXT("AcceptedInventoryInstanceIds")); } else { TArray AcceptedInventoryInstanceIdsArray; FString(request.AcceptedInventoryInstanceIds).ParseIntoArray(AcceptedInventoryInstanceIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("AcceptedInventoryInstanceIds"), AcceptedInventoryInstanceIdsArray); } if (request.OfferingPlayerId.IsEmpty() || request.OfferingPlayerId == "") { OutRestJsonObj->SetFieldNull(TEXT("OfferingPlayerId")); } else { OutRestJsonObj->SetStringField(TEXT("OfferingPlayerId"), request.OfferingPlayerId); } if (request.TradeId.IsEmpty() || request.TradeId == "") { OutRestJsonObj->SetFieldNull(TEXT("TradeId")); } else { OutRestJsonObj->SetStringField(TEXT("TradeId"), request.TradeId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperAcceptTrade(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessAcceptTrade.IsBound()) { FClientAcceptTradeResponse ResultStruct = UPlayFabClientModelDecoder::decodeAcceptTradeResponseResponse(response.responseData); OnSuccessAcceptTrade.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Cancels an open trade (one that has not yet been accepted or cancelled). Note that only the player who created the trade can cancel it via this API call, to prevent griefing of the trade system (cancelling trades in order to prevent other players from accepting them, for trades that can be claimed by more than one player). */ UPlayFabClientAPI* UPlayFabClientAPI::CancelTrade(FClientCancelTradeRequest request, FDelegateOnSuccessCancelTrade onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessCancelTrade = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperCancelTrade); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/CancelTrade"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.TradeId.IsEmpty() || request.TradeId == "") { OutRestJsonObj->SetFieldNull(TEXT("TradeId")); } else { OutRestJsonObj->SetStringField(TEXT("TradeId"), request.TradeId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperCancelTrade(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessCancelTrade.IsBound()) { FClientCancelTradeResponse ResultStruct = UPlayFabClientModelDecoder::decodeCancelTradeResponseResponse(response.responseData); OnSuccessCancelTrade.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Gets all trades the player has either opened or accepted, optionally filtered by trade status. */ UPlayFabClientAPI* UPlayFabClientAPI::GetPlayerTrades(FClientGetPlayerTradesRequest request, FDelegateOnSuccessGetPlayerTrades onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetPlayerTrades = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetPlayerTrades); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetPlayerTrades"; manager->useSessionTicket = true; // Serialize all the request properties to json FString temp_StatusFilter; if (GetEnumValueToString(TEXT("ETradeStatus"), request.StatusFilter, temp_StatusFilter)) OutRestJsonObj->SetStringField(TEXT("StatusFilter"), temp_StatusFilter); // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetPlayerTrades(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetPlayerTrades.IsBound()) { FClientGetPlayerTradesResponse ResultStruct = UPlayFabClientModelDecoder::decodeGetPlayerTradesResponseResponse(response.responseData); OnSuccessGetPlayerTrades.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Gets the current status of an existing trade. */ UPlayFabClientAPI* UPlayFabClientAPI::GetTradeStatus(FClientGetTradeStatusRequest request, FDelegateOnSuccessGetTradeStatus onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessGetTradeStatus = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperGetTradeStatus); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/GetTradeStatus"; manager->useSessionTicket = true; // Serialize all the request properties to json if (request.OfferingPlayerId.IsEmpty() || request.OfferingPlayerId == "") { OutRestJsonObj->SetFieldNull(TEXT("OfferingPlayerId")); } else { OutRestJsonObj->SetStringField(TEXT("OfferingPlayerId"), request.OfferingPlayerId); } if (request.TradeId.IsEmpty() || request.TradeId == "") { OutRestJsonObj->SetFieldNull(TEXT("TradeId")); } else { OutRestJsonObj->SetStringField(TEXT("TradeId"), request.TradeId); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperGetTradeStatus(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessGetTradeStatus.IsBound()) { FClientGetTradeStatusResponse ResultStruct = UPlayFabClientModelDecoder::decodeGetTradeStatusResponseResponse(response.responseData); OnSuccessGetTradeStatus.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } /** Opens a new outstanding trade. Note that a given item instance may only be in one open trade at a time. */ UPlayFabClientAPI* UPlayFabClientAPI::OpenTrade(FClientOpenTradeRequest request, FDelegateOnSuccessOpenTrade onSuccess, FDelegateOnFailurePlayFabError onFailure, UObject* customData) { // Objects containing request data UPlayFabClientAPI* manager = NewObject(); if (manager->IsSafeForRootSet()) manager->AddToRoot(); UPlayFabJsonObject* OutRestJsonObj = NewObject(); manager->mCustomData = customData; // Assign delegates manager->OnSuccessOpenTrade = onSuccess; manager->OnFailure = onFailure; manager->OnPlayFabResponse.AddDynamic(manager, &UPlayFabClientAPI::HelperOpenTrade); // Setup the request manager->SetCallAuthenticationContext(request.AuthenticationContext); manager->PlayFabRequestURL = "/Client/OpenTrade"; manager->useSessionTicket = true; // Serialize all the request properties to json // Check to see if string is empty if (request.AllowedPlayerIds.IsEmpty() || request.AllowedPlayerIds == "") { OutRestJsonObj->SetFieldNull(TEXT("AllowedPlayerIds")); } else { TArray AllowedPlayerIdsArray; FString(request.AllowedPlayerIds).ParseIntoArray(AllowedPlayerIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("AllowedPlayerIds"), AllowedPlayerIdsArray); } // Check to see if string is empty if (request.OfferedInventoryInstanceIds.IsEmpty() || request.OfferedInventoryInstanceIds == "") { OutRestJsonObj->SetFieldNull(TEXT("OfferedInventoryInstanceIds")); } else { TArray OfferedInventoryInstanceIdsArray; FString(request.OfferedInventoryInstanceIds).ParseIntoArray(OfferedInventoryInstanceIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("OfferedInventoryInstanceIds"), OfferedInventoryInstanceIdsArray); } // Check to see if string is empty if (request.RequestedCatalogItemIds.IsEmpty() || request.RequestedCatalogItemIds == "") { OutRestJsonObj->SetFieldNull(TEXT("RequestedCatalogItemIds")); } else { TArray RequestedCatalogItemIdsArray; FString(request.RequestedCatalogItemIds).ParseIntoArray(RequestedCatalogItemIdsArray, TEXT(","), false); OutRestJsonObj->SetStringArrayField(TEXT("RequestedCatalogItemIds"), RequestedCatalogItemIdsArray); } // Add Request to manager manager->SetRequestObject(OutRestJsonObj); return manager; } // Implements FOnPlayFabClientRequestCompleted void UPlayFabClientAPI::HelperOpenTrade(FPlayFabBaseModel response, UObject* customData, bool successful) { FPlayFabError error = response.responseError; if (error.hasError && OnFailure.IsBound()) { OnFailure.Execute(error, customData); } else if (!error.hasError && OnSuccessOpenTrade.IsBound()) { FClientOpenTradeResponse ResultStruct = UPlayFabClientModelDecoder::decodeOpenTradeResponseResponse(response.responseData); OnSuccessOpenTrade.Execute(ResultStruct, mCustomData); } this->RemoveFromRoot(); } void UPlayFabClientAPI::OnProcessRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful) { // Be sure that we have no data from previous response ResetResponseData(); if (!IsValidLowLevel()) { UE_LOG(LogPlayFab, Error, TEXT("The request object is invalid during OnProcessRequestComplete.")); return; } if (!OnPlayFabResponse.IsBound()) { UE_LOG(LogPlayFab, Error, TEXT("OnPlayFabResponse has come un-bound during OnProcessRequestComplete.")); return; } FPlayFabBaseModel myResponse; // Check we have result to process further if (!bWasSuccessful) { UE_LOG(LogPlayFab, Error, TEXT("Request failed: %s"), *Request->GetURL()); // Broadcast the result event myResponse.responseError.hasError = true; myResponse.responseError.ErrorCode = 503; myResponse.responseError.ErrorName = "Unable to contact server"; myResponse.responseError.ErrorMessage = "Unable to contact server"; OnPlayFabResponse.Broadcast(myResponse, mCustomData, false); return; } // Save response data as a string ResponseContent = Response->GetContentAsString(); // Save response code as int32 ResponseCode = Response->GetResponseCode(); // Try to deserialize data to JSON TSharedRef> JsonReader = TJsonReaderFactory::Create(ResponseContent); FJsonSerializer::Deserialize(JsonReader, ResponseJsonObj->GetRootObject()); // Decide whether the request was successful bIsValidJsonResponse = bWasSuccessful && ResponseJsonObj->GetRootObject().IsValid(); // Log errors if (!bIsValidJsonResponse) UE_LOG(LogPlayFab, Warning, TEXT("JSON could not be decoded!")); // Log response state UE_LOG(LogPlayFab, Log, TEXT("Response : %s"), *ResponseContent); myResponse.responseError.decodeError(ResponseJsonObj); myResponse.responseData = ResponseJsonObj; IPlayFab* pfSettings = &(IPlayFab::Get()); if (returnsSessionTicket || returnsEntityToken) { CallAuthenticationContext = NewObject(); } if (returnsSessionTicket && !myResponse.responseError.hasError) { // Auth Tokens auto ResponseDataJSON = myResponse.responseData->GetObjectField("data"); { FString NewSessionTicket = ResponseDataJSON->GetStringField("SessionTicket"); pfSettings->setSessionTicket(NewSessionTicket); CallAuthenticationContext->SetClientSessionTicket(MoveTemp(NewSessionTicket)); } if (ResponseDataJSON->HasField("EntityToken")) { FString NewEntityToken = ResponseDataJSON->GetObjectField("EntityToken")->GetStringField("EntityToken"); pfSettings->setEntityToken(NewEntityToken); // Store entity token so that it can be added to the ResultStruct in the call-specific "Helper" callback // which is responsible for forming response JSON into a semantic struct, and passing it to user code CallAuthenticationContext->SetEntityToken(MoveTemp(NewEntityToken)); } // IDFA Attribution when relevant bool needsAttribution = myResponse.responseData->GetObjectField("data")->GetBoolField("SessionTicket"); if (needsAttribution && !pfSettings->getDisableAdvertising() && !pfSettings->getAdvertisingIdType().IsEmpty() && !pfSettings->getAdvertisingIdValue().IsEmpty()) { FClientAttributeInstallRequest request; bool makeAttrCall = true; if (pfSettings->getAdvertisingIdType() == pfSettings->getAD_TYPE_IDFA()) request.Idfa = pfSettings->getAdvertisingIdValue(); else if (pfSettings->getAdvertisingIdType() == pfSettings->getAD_TYPE_ANDROID_ID()) request.Adid = pfSettings->getAdvertisingIdValue(); else makeAttrCall = false; if (makeAttrCall) { FDelegateOnSuccessAttributeInstall onSuccess; FDelegateOnFailurePlayFabError onFailure; UPlayFabClientAPI* callObj = AttributeInstall(request, onSuccess, onFailure, mCustomData); callObj->Activate(); } } } if (returnsEntityToken) { FString NewEntityToken = myResponse.responseData->GetObjectField("data")->GetStringField("EntityToken"); pfSettings->setEntityToken(NewEntityToken); CallAuthenticationContext->SetEntityToken(MoveTemp(NewEntityToken)); } // Broadcast the result event OnPlayFabResponse.Broadcast(myResponse, mCustomData, !myResponse.responseError.hasError); pfSettings->ModifyPendingCallCount(-1); } void UPlayFabClientAPI::Activate() { IPlayFab* pfSettings = &(IPlayFab::Get()); FString RequestUrl; RequestUrl = pfSettings->getUrl(PlayFabRequestURL); TSharedRef HttpRequest = FHttpModule::Get().CreateRequest(); HttpRequest->SetURL(RequestUrl); HttpRequest->SetVerb(TEXT("POST")); // Headers if (useEntityToken) HttpRequest->SetHeader(TEXT("X-EntityToken"), CallAuthenticationContext != nullptr ? CallAuthenticationContext->GetEntityToken() : pfSettings->getEntityToken()); else if (useSessionTicket) HttpRequest->SetHeader(TEXT("X-Authorization"), CallAuthenticationContext != nullptr ? CallAuthenticationContext->GetClientSessionTicket() : pfSettings->getSessionTicket()); else if (useSecretKey) HttpRequest->SetHeader(TEXT("X-SecretKey"), CallAuthenticationContext != nullptr ? CallAuthenticationContext->GetDeveloperSecretKey() : pfSettings->getSecretApiKey()); HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json")); HttpRequest->SetHeader(TEXT("X-PlayFabSDK"), pfSettings->getVersionString()); HttpRequest->SetHeader(TEXT("X-ReportErrorAsSuccess"), TEXT("true")); // FHttpResponsePtr doesn't provide sufficient information when an error code is returned for (TMap::TConstIterator It(RequestHeaders); It; ++It) HttpRequest->SetHeader(It.Key(), It.Value()); // Serialize data to json string FString OutputString; TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString); FJsonSerializer::Serialize(RequestJsonObj->GetRootObject().ToSharedRef(), Writer); // Set Json content HttpRequest->SetContentAsString(OutputString); UE_LOG(LogPlayFab, Log, TEXT("Request: %s"), *OutputString); // Bind event HttpRequest->OnProcessRequestComplete().BindUObject(this, &UPlayFabClientAPI::OnProcessRequestComplete); // Execute the request pfSettings->ModifyPendingCallCount(1); HttpRequest->ProcessRequest(); } void UPlayFabClientAPI::ResetResponseData() { if (ResponseJsonObj != nullptr) ResponseJsonObj->Reset(); else ResponseJsonObj = NewObject(); bIsValidJsonResponse = false; } inetsrv/pop3/service/pop3perf/pop3perf.cpp10-100 /* - Pop3perf.cpp - * Purpose: * * Copyright: * * History: * */ #include #include #define PERF_DLL_ONCE #include #include #define SZ_POP3_SERVICE_NAME L"Pop3Svc" // Debugging registry key constant BOOL WINAPI DllMain( HINSTANCE hinstDLL, // handle to the DLL module DWORD fdwReason, // reason for calling function LPVOID lpvReserved) // reserved { if (DLL_PROCESS_ATTACH == fdwReason) { PERF_DATA_INFO pdi; // Configure Perfmon Counters // PERF_DATA_INFO have buffers of MAX_PATH characters pdi.cGlobalCounters = cntrMaxGlobalCntrs; pdi.rgdwGlobalCounterTypes = g_rgdwGlobalCntrType; pdi.rgdwGlobalCntrScale = g_rgdwGlobalCntrScale; wcsncpy(pdi.wszSvcName, SZ_POP3_SERVICE_NAME, MAX_PATH-1); wcsncpy(pdi.wszGlobalSMName, szPOP3PerfMem, MAX_PATH-1); pdi.wszSvcName[MAX_PATH-1]=0; pdi.wszGlobalSMName[MAX_PATH-1]=0; // NOTE: If your service does not require Instance // counters, you MUST set cInstCounters to zero! pdi.cInstCounters = cntrMaxInstCntrs; wcsncpy(pdi.wszInstSMName, szPOP3InstPerfMem, MAX_PATH-1); wcsncpy(pdi.wszInstMutexName, szPOP3InstPerfMutex, MAX_PATH-1); pdi.wszInstSMName[MAX_PATH-1]=0; pdi.wszInstMutexName[MAX_PATH-1]=0; pdi.rgdwInstCounterTypes = g_rgdwInstCntrType; if (FAILED(HrInitPerf(&pdi))) return FALSE; } if (DLL_PROCESS_DETACH == fdwReason) { HrShutdownPerf(); } return TRUE; } // Must have wrapper functions, otherwise the lib functions don't get // pulled into the executable (smart linking "saves us" again...) DWORD APIENTRY Pop3SvcOpenPerfProc(LPWSTR sz) { return OpenPerformanceData(sz); } DWORD APIENTRY Pop3SvcCollectPerfProc(LPWSTR sz, LPVOID *ppv, LPDWORD pdw1, LPDWORD pdw2) { return CollectPerformanceData(sz, ppv, pdw1, pdw2); } DWORD APIENTRY Pop3SvcClosePerfProc(void) { return ClosePerformanceData(); } HRESULT _stdcall DllRegisterServer(void) { return RegisterPerfDll( SZ_POP3_SERVICE_NAME, L"Pop3SvcOpenPerfProc", L"Pop3SvcCollectPerfProc", L"Pop3SvcClosePerfProc" ) ; } HRESULT _stdcall DllUnregisterServer(void) { return HrUninstallPerfDll( SZ_POP3_SERVICE_NAME ); } #include #define ll long long #define pb push_back using namespace std; int main(){ int n, k; string s; cin>>n>>k; cin>>s; int pos = 1, cnt = 1; string ans = s; while(cnt < k){ if(pos >= ans.size()){ ans += s; cnt++; }else{ int len = 0; bool ok = true; for (int i = 0; i < s.size(); ++i) { if(pos + i >= ans.size()) break; len++; if(ans[pos+i] != s[i]) ok = false; } if(ok){ ans += s.substr(len); cnt++; } } pos++; } cout< static constexpr const char* kFormat = "{{{bt:%zu:%p}}}\n"; void Backtrace::Print(FILE* file) const { print_backtrace_version_info(file); PrintWithoutVersion(file); } void Backtrace::PrintWithoutVersion(FILE* file) const { for (size_t i = 0; i < size_; ++i) { fprintf(file, kFormat, i, reinterpret_cast(pc_[i])); } } // coding: utf-8 // ---------------------------------------------------------------------------- /* Copyright (c) 2009, Roboterclub Aachen e.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Roboterclub Aachen e.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROBOTERCLHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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 #include "line_2d_test.hpp" void Line2DTest::testDefaultConstructor() { xpcc::Line2D line; TEST_ASSERT_EQUALS(line.getPoint(), xpcc::Vector2i(0, 0)); TEST_ASSERT_EQUALS(line.getDirectionVector(), xpcc::Vector2i(0, 0)); } void Line2DTest::testConstructor() { xpcc::Line2D line( xpcc::Vector2i(-20, -60), xpcc::Vector2i(90, 80)); TEST_ASSERT_EQUALS(line.getPoint(), xpcc::Vector2i(-20, -60)); TEST_ASSERT_EQUALS(line.getDirectionVector(), xpcc::Vector2i(90, 80)); } void Line2DTest::testAccessors() { xpcc::Line2D line; line.setPoint(xpcc::Vector2i(40, 780)); line.setDirectionVector(xpcc::Vector2i(-50, 16)); TEST_ASSERT_EQUALS(line.getPoint(), xpcc::Vector2i(40, 780)); TEST_ASSERT_EQUALS(line.getDirectionVector(), xpcc::Vector2i(-50, 16)); } void Line2DTest::testDistanceToPoint() { xpcc::Line2D line( xpcc::Vector2i(-20, -60), xpcc::Vector2i(10, 10)); int16_t distance = line.getDistanceTo(xpcc::Vector2i(10, 30)); // closest point is (40, 0) => sqrt(30^2 + 30^2) = 42.4264.. TEST_ASSERT_EQUALS(distance, 42); TEST_ASSERT_EQUALS(line.getPoint(), xpcc::Vector2i(-20, -60)); TEST_ASSERT_EQUALS(line.getDirectionVector(), xpcc::Vector2i(10, 10)); int16_t distance2 = line.getDistanceTo(xpcc::Vector2i(-50, -50)); // closest point is (-30, -70) => sqrt(20^2 + 20^2) = 28.28427.. TEST_ASSERT_EQUALS(distance2, 28); int16_t distance3 = line.getDistanceTo(xpcc::Vector2i(70, -70)); // closest point is (20, -20) => sqrt(50^2 + 50^2) = 70.7106.. TEST_ASSERT_EQUALS(distance3, 71); } void Line2DTest::testIntersectionPointsLine() { xpcc::Line2D line1( xpcc::Vector2i(0, 10), xpcc::Vector2i(10, 10)); xpcc::Line2D line2( xpcc::Vector2i(10, 0), xpcc::Vector2i(20, 20)); xpcc::PointSet2D points; // two parallel line TEST_ASSERT_FALSE(line1.getIntersections(line2, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 0U); // intersection at (10, 20) line2.setDirectionVector(xpcc::Vector2i(0, 10)); TEST_ASSERT_TRUE(line1.getIntersections(line2, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 1U); TEST_ASSERT_EQUALS(points[0].getX(), 10); TEST_ASSERT_EQUALS(points[0].getY(), 20); points.removeAll(); // intersection at (10, -30) line1.setDirectionVector(xpcc::Vector2i(-10, 30)); TEST_ASSERT_TRUE(line1.getIntersections(line2, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 1U); TEST_ASSERT_EQUALS(points[0].getX(), 10); TEST_ASSERT_EQUALS(points[0].getY(), -20); } void Line2DTest::testIntersectionPointsCircle() { xpcc::Line2D line( xpcc::Vector2i(-10, -10), xpcc::Vector2i(10, 10)); xpcc::Circle2D circle( xpcc::Vector2i(0, 0), 20); xpcc::PointSet2D points; // two intersections TEST_ASSERT_TRUE(line.getIntersections(circle, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 2U); TEST_ASSERT_EQUALS(points[0].getX(), -14); TEST_ASSERT_EQUALS(points[0].getY(), -14); TEST_ASSERT_EQUALS(points[1].getX(), 14); TEST_ASSERT_EQUALS(points[1].getY(), 14); points.removeAll(); // line is a tangent line.set(xpcc::Vector2i(20, 0), xpcc::Vector2i(0, -10)); TEST_ASSERT_TRUE(line.getIntersections(circle, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 1U); TEST_ASSERT_EQUALS(points[0].getX(), 20); TEST_ASSERT_EQUALS(points[0].getY(), 0); points.removeAll(); // no intersections line.set(xpcc::Vector2i(20, 20), xpcc::Vector2i(10, -10)); TEST_ASSERT_FALSE(line.getIntersections(circle, points)); TEST_ASSERT_EQUALS(points.getNumberOfPoints(), 0U); points.removeAll(); } #ifndef __MIDIPROBABILITY_H #define __MIDIPROBABILITY_H #include "../common/PizMidi.h" enum parameters { kPower, kStep1, kOffset1, kMode1, kProb1, kStep2, kOffset2, kMode2, kProb2, kRadius, kSkip, kOctUp, kOctDn, kRandT, kTransp, kRandV, kOffsetV, kChan, kTranspAmt, kVelAmt, kChCh, kChannel, kNumParams, numParamsPerSlot = kMode2-kMode1, numSlots = 2, kNumPrograms = 16 }; class MidiProbabilityProgram { friend class MidiProbability; public: MidiProbabilityProgram (); ~MidiProbabilityProgram () {} private: float param[kNumParams]; char name[kVstMaxProgNameLen]; }; class MidiProbability : public PizMidi { public: MidiProbability(audioMasterCallback audioMaster); ~MidiProbability(); virtual void setProgram (VstInt32 program); virtual void setProgramName (char *name); virtual void getProgramName (char *name); virtual bool getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text); virtual void setParameter(VstInt32 index, float value); virtual float getParameter(VstInt32 index); virtual void getParameterLabel(VstInt32 index, char *label); virtual void getParameterDisplay(VstInt32 index, char *text); virtual void getParameterName(VstInt32 index, char *text); protected: float param[kNumParams]; bool init(void); virtual void processMidiEvents(VstMidiEventVec *inputs, VstMidiEventVec *outputs, VstInt32 samples); virtual void preProcess(void); float stepsize[numSlots]; float _bpm; double _ppq; double _beatpos[numSlots]; VstInt32 samplesPerBeat; inline float closeness(long int samplepos); bool notePlaying[128][16]; enum effects { off=-1, disc=0, octup, octdown, randtr, transp, randvel, offsetvel, chan, multi, numEffects }; signed char noteAffected[128][16][numEffects]; char mode; bool wasplaying; bool isplaying; MidiProbabilityProgram *programs; }; #endif #include #include "myclasses.h" using namespace std; int main() { // Создаем переменную myClass типа класса MyClass, // она будет автоматически удалена при завершении программы // И так лучше не создавать объекты !!! MyClass myClass; cout << myClass.get_time() << endl; cout << myClass.getLastTime() << endl; cout << myClass.sum(12, 12) << endl; cout << myClass.sum(12.5, 12.5) << endl; //delete &myClass; // Нельзя так удалить автоматически созданный объект // Создаем переменную myClass2 через конструктор с параметром MyClass *myClass2 = new MyClass("TSN"); cout << myClass2->getLastTime() << endl; // Теперь вместо точки нужно использовать -> delete myClass2; // Удаляем сами созданный нами объект MyClass2 myClass3; cout << myClass.get_time() << endl; // Вызов метода предка myClass3.myPrint(); // Вызов собственного метода класса cout << "xxxx"; return 0; } // Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "fiddle/examples.h" // HASH=01ad6be9b7d15a2217daea273eb3d466 REG_FIDDLE(Path_destructor, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPath* path = new SkPath(); path->lineTo(20, 20); SkPath path2(*path); delete path; SkDebugf("path2 is " "%s" "empty", path2.isEmpty() ? "" : "not "); } } // END FIDDLE //=-- lsan_fuchsia.cpp ---------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===---------------------------------------------------------------------===// // // This file is a part of LeakSanitizer. // Standalone LSan RTL code specific to Fuchsia. // //===---------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_FUCHSIA #include #include "lsan.h" #include "lsan_allocator.h" using namespace __lsan; namespace __lsan { void LsanOnDeadlySignal(int signo, void *siginfo, void *context) {} ThreadContext::ThreadContext(int tid) : ThreadContextLsanBase(tid) {} struct OnCreatedArgs { uptr stack_begin, stack_end; }; // On Fuchsia, the stack bounds of a new thread are available before // the thread itself has started running. void ThreadContext::OnCreated(void *arg) { // Stack bounds passed through from __sanitizer_before_thread_create_hook // or InitializeMainThread. auto args = reinterpret_cast(arg); stack_begin_ = args->stack_begin; stack_end_ = args->stack_end; } struct OnStartedArgs { uptr cache_begin, cache_end; }; void ThreadContext::OnStarted(void *arg) { auto args = reinterpret_cast(arg); cache_begin_ = args->cache_begin; cache_end_ = args->cache_end; } void ThreadStart(u32 tid) { OnStartedArgs args; GetAllocatorCacheRange(&args.cache_begin, &args.cache_end); CHECK_EQ(args.cache_end - args.cache_begin, sizeof(AllocatorCache)); ThreadContextLsanBase::ThreadStart(tid, GetTid(), ThreadType::Regular, &args); } void InitializeMainThread() { OnCreatedArgs args; __sanitizer::GetThreadStackTopAndBottom(true, &args.stack_end, &args.stack_begin); u32 tid = ThreadCreate(0, GetThreadSelf(), true, &args); CHECK_EQ(tid, 0); ThreadStart(tid); } void GetAllThreadAllocatorCachesLocked(InternalMmapVector *caches) { GetThreadRegistryLocked()->RunCallbackForEachThreadLocked( [](ThreadContextBase *tctx, void *arg) { auto ctx = static_cast(tctx); static_cast(arg)->push_back(ctx->cache_begin()); }, caches); } } // namespace __lsan // These are declared (in extern "C") by . // The system runtime will call our definitions directly. // This is called before each thread creation is attempted. So, in // its first call, the calling thread is the initial and sole thread. void *__sanitizer_before_thread_create_hook(thrd_t thread, bool detached, const char *name, void *stack_base, size_t stack_size) { uptr user_id = reinterpret_cast(thread); ENSURE_LSAN_INITED; EnsureMainThreadIDIsCorrect(); OnCreatedArgs args; args.stack_begin = reinterpret_cast(stack_base); args.stack_end = args.stack_begin + stack_size; u32 parent_tid = GetCurrentThread(); u32 tid = ThreadCreate(parent_tid, user_id, detached, &args); return reinterpret_cast(static_cast(tid)); } // This is called after creating a new thread (in the creating thread), // with the pointer returned by __sanitizer_before_thread_create_hook (above). void __sanitizer_thread_create_hook(void *hook, thrd_t thread, int error) { u32 tid = static_cast(reinterpret_cast(hook)); // On success, there is nothing to do here. if (error != thrd_success) { // Clean up the thread registry for the thread creation that didn't happen. GetThreadRegistryLocked()->FinishThread(tid); } } // This is called in the newly-created thread before it runs anything else, // with the pointer returned by __sanitizer_before_thread_create_hook (above). void __sanitizer_thread_start_hook(void *hook, thrd_t self) { u32 tid = static_cast(reinterpret_cast(hook)); ThreadStart(tid); } // Each thread runs this just before it exits, // with the pointer returned by BeforeThreadCreateHook (above). // All per-thread destructors have already been called. void __sanitizer_thread_exit_hook(void *hook, thrd_t self) { ThreadFinish(); } #endif // SANITIZER_FUCHSIA laigor/sqlrelay-non-english-fixes- cur->prepareQuery("call exampleproc(?,?,?,?)"); cur->inputBind("1",1); cur->inputBind("2",1.1,2,1); cur->inputBind("3","hello"); cur->defineOutputBindInteger("4"); cur->executeQuery(); int64_t result=cur->getOutputBindInteger("4"); // // Created by matha on 16/03/2018. // #include "Renderer.h" Matrix4f Renderer::ProjMatrix3D; Matrix4f Renderer::ProjMatrix2D; void Renderer::Start2D() { } void Renderer::Start3D() { } // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include #include #include #include #include #include #include using namespace k4arecord; using namespace LIBMATROSKA_NAMESPACE; k4a_result_t k4a_record_create(const char *path, k4a_device_t device, const k4a_device_configuration_t device_config, k4a_record_t *recording_handle) { RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, path == NULL); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, recording_handle == NULL); k4a_record_context_t *context = NULL; logger_t logger_handle = NULL; k4a_result_t result = K4A_RESULT_SUCCEEDED; // Instantiate the logger as early as possible logger_config_t logger_config; logger_config_init_default(&logger_config); logger_config.env_var_log_to_a_file = K4A_RECORD_ENABLE_LOG_TO_A_FILE; result = TRACE_CALL(logger_create(&logger_config, &logger_handle)); if (K4A_SUCCEEDED(result)) { context = k4a_record_t_create(recording_handle); result = K4A_RESULT_FROM_BOOL(context != NULL); } if (K4A_SUCCEEDED(result)) { context->logger_handle = logger_handle; context->file_path = path; try { context->ebml_file = make_unique(path, MODE_CREATE); } catch (std::ios_base::failure &e) { LOG_ERROR("Unable to open file '%s': %s", path, e.what()); result = K4A_RESULT_FAILED; } } if (K4A_SUCCEEDED(result)) { context->device = device; context->device_config = device_config; context->timecode_scale = MATROSKA_TIMESCALE_NS; context->camera_fps = k4a_convert_fps_to_uint(device_config.camera_fps); if (context->camera_fps == 0) { // Set camera FPS to 30 if no cameras are enabled so IMU can still be written. context->camera_fps = 30; } } uint32_t color_width = 0; uint32_t color_height = 0; if (K4A_SUCCEEDED(result) && device_config.color_resolution != K4A_COLOR_RESOLUTION_OFF) { if (!k4a_convert_resolution_to_width_height(device_config.color_resolution, &color_width, &color_height)) { LOG_ERROR("Unsupported color_resolution specified in recording: %d", device_config.color_resolution); result = K4A_RESULT_FAILED; } } std::ostringstream color_mode_str; if (K4A_SUCCEEDED(result)) { if (device_config.color_resolution != K4A_COLOR_RESOLUTION_OFF) { switch (device_config.color_format) { case K4A_IMAGE_FORMAT_COLOR_NV12: color_mode_str << "NV12_" << color_height << "P"; break; case K4A_IMAGE_FORMAT_COLOR_YUY2: color_mode_str << "YUY2_" << color_height << "P"; break; case K4A_IMAGE_FORMAT_COLOR_MJPG: color_mode_str << "MJPG_" << color_height << "P"; break; default: LOG_ERROR("Unsupported color_format specified in recording: %d", device_config.color_format); result = K4A_RESULT_FAILED; } } else { color_mode_str << "OFF"; } } const char *depth_mode_str = "OFF"; uint32_t depth_width = 0; uint32_t depth_height = 0; if (K4A_SUCCEEDED(result)) { if (device_config.depth_mode != K4A_DEPTH_MODE_OFF) { for (size_t i = 0; i < arraysize(depth_modes); i++) { if (device_config.depth_mode == depth_modes[i].first) { if (!k4a_convert_depth_mode_to_width_height(depth_modes[i].first, &depth_width, &depth_height)) { LOG_ERROR("Unsupported depth_mode specified in recording: %d", device_config.depth_mode); result = K4A_RESULT_FAILED; } depth_mode_str = depth_modes[i].second.c_str(); break; } } if (depth_width == 0 || depth_height == 0) { LOG_ERROR("Unsupported depth_mode specified in recording: %d", device_config.depth_mode); result = K4A_RESULT_FAILED; } } } if (K4A_SUCCEEDED(result)) { context->file_segment = make_unique(); { // Setup segment info auto &segment_info = GetChild(*context->file_segment); GetChild(segment_info).SetValue(context->timecode_scale); GetChild(segment_info).SetValue(L"libmatroska-1.4.9"); std::ostringstream version_str; version_str << "k4arecord-" << K4A_VERSION_STR; GetChild(segment_info).SetValueUTF8(version_str.str()); GetChild(segment_info).SetEpochDate(time(0)); GetChild(segment_info).SetValue(L"Azure Kinect"); } auto &tags = GetChild(*context->file_segment); tags.EnableChecksum(); } if (K4A_SUCCEEDED(result) && device_config.color_resolution != K4A_COLOR_RESOLUTION_OFF) { BITMAPINFOHEADER codec_info = {}; result = TRACE_CALL( populate_bitmap_info_header(&codec_info, color_width, color_height, device_config.color_format)); context->color_track = add_track(context, "COLOR", track_video, "V_MS/VFW/FOURCC", reinterpret_cast(&codec_info), sizeof(codec_info)); set_track_info_video(context->color_track, color_width, color_height, context->camera_fps); uint64_t track_uid = GetChild(*context->color_track).GetValue(); std::ostringstream track_uid_str; track_uid_str << track_uid; add_tag(context, "K4A_COLOR_TRACK", track_uid_str.str().c_str(), TAG_TARGET_TYPE_TRACK, track_uid); add_tag(context, "K4A_COLOR_MODE", color_mode_str.str().c_str(), TAG_TARGET_TYPE_TRACK, track_uid); } if (K4A_SUCCEEDED(result)) { if (device_config.depth_mode == K4A_DEPTH_MODE_PASSIVE_IR) { add_tag(context, "K4A_DEPTH_MODE", depth_mode_str); } else if (device_config.depth_mode != K4A_DEPTH_MODE_OFF) { // Depth track BITMAPINFOHEADER codec_info = {}; result = TRACE_CALL( populate_bitmap_info_header(&codec_info, depth_width, depth_height, K4A_IMAGE_FORMAT_DEPTH16)); context->depth_track = add_track(context, "DEPTH", track_video, "V_MS/VFW/FOURCC", reinterpret_cast(&codec_info), sizeof(codec_info)); set_track_info_video(context->depth_track, depth_width, depth_height, context->camera_fps); uint64_t track_uid = GetChild(*context->depth_track).GetValue(); std::ostringstream track_uid_str; track_uid_str << track_uid; add_tag(context, "K4A_DEPTH_TRACK", track_uid_str.str().c_str(), TAG_TARGET_TYPE_TRACK, track_uid); add_tag(context, "K4A_DEPTH_MODE", depth_mode_str, TAG_TARGET_TYPE_TRACK, track_uid); } } if (K4A_SUCCEEDED(result) && device_config.depth_mode != K4A_DEPTH_MODE_OFF) { // IR Track BITMAPINFOHEADER codec_info = {}; result = TRACE_CALL(populate_bitmap_info_header(&codec_info, depth_width, depth_height, K4A_IMAGE_FORMAT_IR16)); context->ir_track = add_track(context, "IR", track_video, "V_MS/VFW/FOURCC", reinterpret_cast(&codec_info), sizeof(codec_info)); set_track_info_video(context->ir_track, depth_width, depth_height, context->camera_fps); uint64_t track_uid = GetChild(*context->ir_track).GetValue(); std::ostringstream track_uid_str; track_uid_str << track_uid; add_tag(context, "K4A_IR_TRACK", track_uid_str.str().c_str(), TAG_TARGET_TYPE_TRACK, track_uid); add_tag(context, "K4A_IR_MODE", device_config.depth_mode == K4A_DEPTH_MODE_PASSIVE_IR ? "PASSIVE" : "ACTIVE", TAG_TARGET_TYPE_TRACK, track_uid); } if (K4A_SUCCEEDED(result) && device_config.color_resolution != K4A_COLOR_RESOLUTION_OFF && device_config.depth_mode != K4A_DEPTH_MODE_OFF) { std::ostringstream delay_str; delay_str << device_config.depth_delay_off_color_usec * 1000; add_tag(context, "K4A_DEPTH_DELAY_NS", delay_str.str().c_str()); } if (K4A_SUCCEEDED(result)) { switch (device_config.wired_sync_mode) { case K4A_WIRED_SYNC_MODE_STANDALONE: add_tag(context, "K4A_WIRED_SYNC_MODE", "STANDALONE"); break; case K4A_WIRED_SYNC_MODE_MASTER: add_tag(context, "K4A_WIRED_SYNC_MODE", "MASTER"); break; case K4A_WIRED_SYNC_MODE_SUBORDINATE: add_tag(context, "K4A_WIRED_SYNC_MODE", "SUBORDINATE"); std::ostringstream delay_str; delay_str << device_config.subordinate_delay_off_master_usec * 1000; add_tag(context, "K4A_SUBORDINATE_DELAY_NS", delay_str.str().c_str()); break; } } if (K4A_SUCCEEDED(result) && device != NULL) { // Add the firmware version and device serial number to the recording k4a_hardware_version_t version_info; result = TRACE_CALL(k4a_device_get_version(device, &version_info)); std::ostringstream color_firmware_str; color_firmware_str << version_info.rgb.major << "." << version_info.rgb.minor << "." << version_info.rgb.iteration; std::ostringstream depth_firmware_str; depth_firmware_str << version_info.depth.major << "." << version_info.depth.minor << "." << version_info.depth.iteration; add_tag(context, "K4A_COLOR_FIRMWARE_VERSION", color_firmware_str.str().c_str()); add_tag(context, "K4A_DEPTH_FIRMWARE_VERSION", depth_firmware_str.str().c_str()); char serial_number_buffer[256]; size_t serial_number_buffer_size = sizeof(serial_number_buffer); // If reading the device serial number fails, just log the error and continue. The recording is still valid. if (TRACE_BUFFER_CALL(k4a_device_get_serialnum(device, serial_number_buffer, &serial_number_buffer_size)) == K4A_BUFFER_RESULT_SUCCEEDED) { add_tag(context, "K4A_DEVICE_SERIAL_NUMBER", serial_number_buffer); } } if (K4A_SUCCEEDED(result) && device != NULL) { // Add calibration.json to the recording size_t calibration_size = 0; k4a_buffer_result_t buffer_result = TRACE_BUFFER_CALL( k4a_device_get_raw_calibration(device, NULL, &calibration_size)); if (buffer_result == K4A_BUFFER_RESULT_TOO_SMALL) { std::vector calibration_buffer = std::vector(calibration_size); buffer_result = TRACE_BUFFER_CALL( k4a_device_get_raw_calibration(device, calibration_buffer.data(), &calibration_size)); if (buffer_result == K4A_BUFFER_RESULT_SUCCEEDED) { // Remove the null-terminated byte from the file before writing it. if (calibration_size > 0 && calibration_buffer[calibration_size - 1] == '\0') { calibration_size--; } KaxAttached *attached = add_attachment(context, "calibration.json", "application/octet-stream", calibration_buffer.data(), calibration_size); add_tag(context, "K4A_CALIBRATION_FILE", "calibration.json", TAG_TARGET_TYPE_ATTACHMENT, get_attachment_uid(attached)); } else { result = K4A_RESULT_FAILED; } } else { result = K4A_RESULT_FAILED; } } if (K4A_SUCCEEDED(result)) { auto &cues = GetChild(*context->file_segment); cues.SetGlobalTimecodeScale(context->timecode_scale); } else { if (context && context->ebml_file) { try { context->ebml_file->close(); } catch (std::ios_base::failure &) { // The file is empty at this point, ignore any close failures. } } if (logger_handle) { logger_destroy(logger_handle); } k4a_record_t_destroy(*recording_handle); *recording_handle = NULL; } return result; } k4a_result_t k4a_record_add_tag(const k4a_record_t recording_handle, const char *name, const char *value) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, name == NULL || value == NULL); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); if (context->header_written) { LOG_ERROR("Tags must be added before the recording header is written.", 0); return K4A_RESULT_FAILED; } add_tag(context, name, value); return K4A_RESULT_SUCCEEDED; } k4a_result_t k4a_record_add_imu_track(const k4a_record_t recording_handle) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); if (context->header_written) { LOG_ERROR("The IMU track must be added before the recording header is written.", 0); return K4A_RESULT_FAILED; } if (context->imu_track != NULL) { LOG_ERROR("The IMU track has already been added to this recording.", 0); return K4A_RESULT_FAILED; } context->imu_track = add_track(context, "IMU", track_subtitle, "S_K4A/IMU"); uint64_t track_uid = GetChild(*context->imu_track).GetValue(); std::ostringstream track_uid_str; track_uid_str << track_uid; add_tag(context, "K4A_IMU_TRACK", track_uid_str.str().c_str(), TAG_TARGET_TYPE_TRACK, track_uid); add_tag(context, "K4A_IMU_MODE", "ON", TAG_TARGET_TYPE_TRACK, track_uid); return K4A_RESULT_SUCCEEDED; } k4a_result_t k4a_record_write_header(const k4a_record_t recording_handle) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); if (context->header_written) { LOG_ERROR("The header for this recording has already been written.", 0); return K4A_RESULT_FAILED; } try { // Make sure we're at the beginning of the file in case we're rewriting a file. context->ebml_file->setFilePointer(0, libebml::seek_beginning); { // Render Ebml header EbmlHead file_head; GetChild(file_head).SetValue("matroska"); GetChild(file_head).SetValue(MATROSKA_VERSION); GetChild(file_head).SetValue(2); file_head.Render(*context->ebml_file, true); } // Recordings can get very large, so pad the length field up to 8 bytes from the start. context->file_segment->WriteHead(*context->ebml_file, 8); { // Write void blocks to reserve space for seeking metadata and the segment info so they can be updated at // the end context->seek_void = make_unique(); context->seek_void->SetSize(1024); context->seek_void->Render(*context->ebml_file); context->segment_info_void = make_unique(); context->segment_info_void->SetSize(256); context->segment_info_void->Render(*context->ebml_file); } { // Write tracks auto &tracks = GetChild(*context->file_segment); tracks.Render(*context->ebml_file); } { // Write attachments auto &attachments = GetChild(*context->file_segment); attachments.Render(*context->ebml_file); } { // Write tags with a void block after to make editing easier auto &tags = GetChild(*context->file_segment); tags.Render(*context->ebml_file); context->tags_void = make_unique(); context->tags_void->SetSize(1024); context->tags_void->Render(*context->ebml_file); } } catch (std::ios_base::failure &e) { LOG_ERROR("Failed to write recording header '%s': %s", context->file_path, e.what()); return K4A_RESULT_FAILED; } RETURN_IF_ERROR(start_matroska_writer_thread(context)); context->header_written = true; return K4A_RESULT_SUCCEEDED; } k4a_result_t k4a_record_write_capture(const k4a_record_t recording_handle, k4a_capture_t capture) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); if (!context->header_written) { LOG_ERROR("The recording header needs to be written before any captures.", 0); return K4A_RESULT_FAILED; } // Arrays used to map image formats to tracks, these 3 arrays are order dependant. k4a_image_t images[] = { k4a_capture_get_color_image(capture), k4a_capture_get_depth_image(capture), k4a_capture_get_ir_image(capture), }; k4a_image_format_t expected_formats[] = { context->device_config.color_format, K4A_IMAGE_FORMAT_DEPTH16, K4A_IMAGE_FORMAT_IR16 }; KaxTrackEntry *tracks[] = { context->color_track, context->depth_track, context->ir_track }; static_assert(arraysize(images) == arraysize(tracks), "Invalid mapping from images to track"); static_assert(arraysize(images) == arraysize(expected_formats), "Invalid mapping from images to formats"); k4a_result_t result = K4A_RESULT_SUCCEEDED; for (size_t i = 0; i < arraysize(images); i++) { if (images[i]) { size_t buffer_size = k4a_image_get_size(images[i]); uint8_t *image_buffer = k4a_image_get_buffer(images[i]); if (image_buffer != NULL && buffer_size > 0) { k4a_image_format_t image_format = k4a_image_get_format(images[i]); if (image_format == expected_formats[i]) { // Create a copy of the image buffer for writing to file. assert(buffer_size <= UINT32_MAX); DataBuffer *data_buffer = new (std::nothrow) DataBuffer(image_buffer, (uint32)buffer_size, NULL, true); if (image_format == K4A_IMAGE_FORMAT_DEPTH16 || image_format == K4A_IMAGE_FORMAT_IR16) { // 16 bit grayscale needs to be converted to big-endian in the file. assert(data_buffer->Size() % sizeof(uint16_t) == 0); uint16_t *data_buffer_raw = reinterpret_cast(data_buffer->Buffer()); for (size_t j = 0; j < data_buffer->Size() / sizeof(uint16_t); j++) { data_buffer_raw[j] = swap_bytes_16(data_buffer_raw[j]); } } uint64_t timestamp_ns = k4a_image_get_device_timestamp_usec(images[i]) * 1000; k4a_result_t tmp_result = TRACE_CALL( write_track_data(context, tracks[i], timestamp_ns, data_buffer)); if (K4A_FAILED(tmp_result)) { // Write as many of the image buffers as possible, even if some fail due to timestamp. result = tmp_result; data_buffer->FreeBuffer(*data_buffer); delete data_buffer; } } else { LOG_ERROR("Tried to write capture with unexpected image format.", 0); result = K4A_RESULT_FAILED; } } k4a_image_release(images[i]); } } return result; } k4a_result_t k4a_record_write_imu_sample(const k4a_record_t recording_handle, k4a_imu_sample_t imu_sample) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); if (!context->header_written) { LOG_ERROR("The recording header needs to be written before any imu samples.", 0); return K4A_RESULT_FAILED; } matroska_imu_sample_t sample_data = { 0 }; sample_data.acc_timestamp_ns = imu_sample.acc_timestamp_usec * 1000; sample_data.gyro_timestamp_ns = imu_sample.gyro_timestamp_usec * 1000; for (size_t i = 0; i < 3; i++) { sample_data.acc_data[i] = imu_sample.acc_sample.v[i]; sample_data.gyro_data[i] = imu_sample.gyro_sample.v[i]; } DataBuffer *data_buffer = new (std::nothrow) DataBuffer(reinterpret_cast(&sample_data), sizeof(matroska_imu_sample_t), NULL, true); k4a_result_t result = write_track_data(context, context->imu_track, sample_data.acc_timestamp_ns, data_buffer); if (K4A_FAILED(result)) { data_buffer->FreeBuffer(*data_buffer); delete data_buffer; return result; } return K4A_RESULT_SUCCEEDED; } k4a_result_t k4a_record_flush(const k4a_record_t recording_handle) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, k4a_record_t, recording_handle); k4a_result_t result = K4A_RESULT_SUCCEEDED; k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, context == NULL); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, !context->header_written); try { // Lock the writer thread first so we don't have conflicts std::lock_guard writer_lock(context->writer_lock); LargeFileIOCallback *file_io = dynamic_cast(context->ebml_file.get()); if (file_io != NULL) { file_io->setOwnerThread(); } std::lock_guard cluster_lock(context->pending_cluster_lock); if (!context->pending_clusters.empty()) { for (cluster_t *cluster : context->pending_clusters) { k4a_result_t write_result = TRACE_CALL( write_cluster(context, cluster, &context->last_written_timestamp)); if (K4A_FAILED(write_result)) { // Try to flush as much of the recording as possible to disk before returning any errors. result = write_result; } } context->pending_clusters.clear(); } auto &segment_info = GetChild(*context->file_segment); uint64_t current_position = context->ebml_file->getFilePointer(); // Update segment info GetChild(segment_info) .SetValue( (double)((context->most_recent_timestamp - context->start_timestamp_offset) / context->timecode_scale)); context->segment_info_void->ReplaceWith(segment_info, *context->ebml_file); // Render cues auto &cues = GetChild(*context->file_segment); cues.Render(*context->ebml_file); // Update tags auto &tags = GetChild(*context->file_segment); if (tags.GetElementPosition() > 0) { context->ebml_file->setFilePointer((int64_t)tags.GetElementPosition()); tags.Render(*context->ebml_file); if (tags.GetEndPosition() != context->tags_void->GetElementPosition()) { // Rewrite the void block after tags EbmlVoid tags_void; tags_void.SetSize(context->tags_void->GetSize() - (tags.GetEndPosition() - context->tags_void->GetElementPosition())); tags_void.Render(*context->ebml_file); } } { // Update seek info auto &seek_head = GetChild(*context->file_segment); // RemoveAll() has a bug and does not free the elements before emptying the list. for (auto element : seek_head.GetElementList()) { delete element; } seek_head.RemoveAll(); // Remove any seek entries from previous flushes seek_head.IndexThis(segment_info, *context->file_segment); auto &tracks = GetChild(*context->file_segment); if (tracks.GetElementPosition() > 0) { seek_head.IndexThis(tracks, *context->file_segment); } auto &attachments = GetChild(*context->file_segment); if (attachments.GetElementPosition() > 0) { seek_head.IndexThis(attachments, *context->file_segment); } if (tags.GetElementPosition() > 0) { seek_head.IndexThis(tags, *context->file_segment); } if (cues.GetElementPosition() > 0) { seek_head.IndexThis(cues, *context->file_segment); } context->seek_void->ReplaceWith(seek_head, *context->ebml_file); } // Update the file segment head to write the current size context->ebml_file->setFilePointer(0, seek_end); uint64 segment_size = context->ebml_file->getFilePointer() - context->file_segment->GetElementPosition() - context->file_segment->HeadSize(); // Segment size can only be set once normally, so force the flag. context->file_segment->SetSizeInfinite(true); if (!context->file_segment->ForceSize(segment_size)) { LOG_ERROR("Failed set file segment size.", 0); } context->file_segment->OverwriteHead(*context->ebml_file); // Set the write pointer back in case we're not done recording yet. assert(current_position <= INT64_MAX); context->ebml_file->setFilePointer((int64_t)current_position); } catch (std::ios_base::failure &e) { LOG_ERROR("Failed to write recording '%s': %s", context->file_path, e.what()); return K4A_RESULT_FAILED; } catch (std::system_error &e) { LOG_ERROR("Failed to flush recording '%s': %s", context->file_path, e.what()); return K4A_RESULT_FAILED; } return result; } void k4a_record_close(const k4a_record_t recording_handle) { RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, k4a_record_t, recording_handle); k4a_record_context_t *context = k4a_record_t_get_context(recording_handle); if (context != NULL) { // If the recording was started, flush any unwritten data. if (context->header_written) { // If these fail, there's nothing we can do but log. (void)TRACE_CALL(k4a_record_flush(recording_handle)); stop_matroska_writer_thread(context); } try { context->ebml_file->close(); } catch (std::ios_base::failure &e) { LOG_ERROR("Failed to close recording '%s': %s", context->file_path, e.what()); } // After this destroy, logging will no longer happen. if (context->logger_handle) { logger_destroy(context->logger_handle); } } k4a_record_t_destroy(recording_handle); } #include #include #include #include #include #include #include #include NAMESPACE_BEGIN(mitsuba) // #define TIME_FRESNEL namespace { template MatrixS extended_sparse_diagonal(const VectorType &vec, MatrixS::Index ml) { MatrixS::Index n = vec.size(); MatrixS result(n * ml, n * ml); for (MatrixS::Index l = 0; l < ml; ++l) { for (MatrixS::Index i = 0; i < vec.size(); ++i) { result.insert(l*n + i, l*n + i) = vec[i]; } } result.makeCompressed(); return result; } void scale_columns(Layer &layer, const VectorX &d) { if ((size_t) d.size() != layer.resolution()) Throw("scale_columns(): size mismatch!"); size_t ml = layer.fourier_orders().first + layer.fourier_orders().second - 1; MatrixS scale = extended_sparse_diagonal(d.head(d.size()/2), ml); layer.reflection_top() = mmul(layer.reflection_top(), scale); layer.transmission_bottom_top() = mmul(layer.transmission_bottom_top(), scale); scale = extended_sparse_diagonal(d.tail(d.size()/2), ml); layer.reflection_bottom() = mmul(layer.reflection_bottom(), scale); layer.transmission_top_bottom() = mmul(layer.transmission_top_bottom(), scale); } inline void apply_surface_integration_weights(Layer &layer) { scale_columns(layer, layer.weights().cwiseProduct(layer.nodes().cwiseAbs()) * 2 * math::Pi); } inline void remove_surface_integration_weights(Layer &layer) { VectorX ones(layer.nodes().size()); ones.setOnes(); scale_columns(layer, ones.cwiseQuotient(layer.weights().cwiseProduct(layer.nodes().cwiseAbs()) * 2 * math::Pi)); } inline void apply_medium_integration_weights(Layer &layer) { scale_columns(layer, layer.weights() * 2 * math::Pi); } }; Layer::Layer(const VectorX &nodes, const VectorX &weights, size_t fourier_orders_s, size_t fourier_orders_d) : m_nodes(nodes), m_weights(weights), m_fourier_orders_s(fourier_orders_s), m_fourier_orders_d(fourier_orders_d) { if (nodes.size() < 2) Throw("Need at least 2 integration nodes!"); else if (nodes.size() % 2 == 1) Throw("The number of integration nodes must be even!"); for (int i = 0; i < nodes.size(); ++i) if (nodes[i] == 0) Throw("The set of integrations includes mu=0 -- this is not allowed."); if (fourier_orders_s % 2 == 0 || fourier_orders_d % 2 == 0) Throw("The number of Fourier orders must be odd!"); if (nodes[0] < nodes[1]) { size_t n = (size_t) nodes.size(); /* Order integration weights so that they are usable for adding-doubling */ m_weights.head(n/2).reverseInPlace(); m_nodes.head(n/2).reverseInPlace(); } size_t matrix_size = (m_nodes.size() / 2) * (fourier_orders_d + fourier_orders_s - 1); m_reflection_top.resize(matrix_size, matrix_size); m_reflection_bottom.resize(matrix_size, matrix_size); m_transmission_top_bottom.resize(matrix_size, matrix_size); m_transmission_bottom_top.resize(matrix_size, matrix_size); } void Layer::clear() { m_reflection_top.setZero(); m_reflection_bottom.setZero(); m_transmission_top_bottom.setZero(); m_transmission_bottom_top.setZero(); } void Layer::clear_backside() { m_reflection_bottom.setZero(); } void Layer::set_empty() { m_reflection_top.setZero(); m_reflection_bottom.setZero(); m_transmission_top_bottom.setIdentity(); m_transmission_bottom_top.setIdentity(); } void Layer::set_diffuse(double albedo) { std::vector quintets; quintets.reserve(resolution() * resolution() / 2); size_t n = resolution(), h = n/2; for (size_t i = 0; i < n; ++i) { for (size_t o = 0; o < n; ++o) { if ((i < h && o >= h) || (o < h && i >= h)) quintets.emplace_back(0, 0, o, i, albedo * math::InvPi); } } set_quintets(quintets); apply_surface_integration_weights(*this); } void Layer::set_microfacet(std::complex eta, double alpha_u, double alpha_v, size_t target_fourier_orders_s, size_t target_fourier_orders_d, int component, int n_samples_phi_s, bool svd_reg) { size_t n = resolution(); std::vector quintets; tbb::spin_mutex mutex; target_fourier_orders_s = std::max(target_fourier_orders_s, fourier_orders().first); target_fourier_orders_d = std::max(target_fourier_orders_d, fourier_orders().second); size_t total_fourier_orders = target_fourier_orders_s * target_fourier_orders_d; while (true) { double tmp = microfacet_timer; if (microfacet_timer.compare_exchange_strong(tmp, 0.0)) break; } #ifdef TIME_FRESNEL auto start = std::chrono::high_resolution_clock::now(); #endif #if 1 // Multithreaded tbb::parallel_for( tbb::blocked_range(0, resolution()), [&](const tbb::blocked_range &range) { std::vector local_quintets; local_quintets.reserve(total_fourier_orders * resolution()); MatrixX result; for (size_t i = range.begin(); i < range.end(); ++i) { for (size_t o = 0; o < n; ++o) { /* Sign flip due to different convention (depth values * increase opposite to the normal direction) */ microfacet_fourier_series(-m_nodes[o], -m_nodes[i], alpha_u, alpha_v, eta, (int) target_fourier_orders_s, (int) target_fourier_orders_d, ERROR_GOAL, result, component, n_samples_phi_s, svd_reg); int ms = result.rows(); int md = result.cols(); int msh = ms / 2; int mdh = md / 2; for (int d = -mdh; d <= mdh; ++d) { for (int s = -msh; s <= msh; ++s) { double value = result(s + msh, d + mdh); if (std::abs(value) > DROP_THRESHOLD) local_quintets.emplace_back(s, d, o, i, value); } } } } tbb::spin_mutex::scoped_lock lock(mutex); quintets.insert(quintets.end(), local_quintets.begin(), local_quintets.end()); } ); #else // Singlethrading for debugging std::vector local_quintets; local_quintets.reserve(total_fourier_orders * resolution()); MatrixX result; for (size_t i = 0; i < n; ++i) { for (size_t o = 0; o < n; ++o) { /* Sign flip due to different convention (depth values * increase opposite to the normal direction) */ microfacet_fourier_series(-m_nodes[o], -m_nodes[i], alpha_u, alpha_v, eta, target_fourier_orders_s, target_fourier_orders_d, ERROR_GOAL, result, component, n_samples_phi_s, svd_reg); int ms = result.rows(); int md = result.cols(); int msh = ms / 2; int mdh = md / 2; for (int d = -mdh; d <= mdh; ++d) { for (int s = -msh; s <= msh; ++s) { double value = result(s + msh, d + mdh); if (std::abs(value) > DROP_THRESHOLD) local_quintets.emplace_back(s, d, o, i, value); } } } } quintets.insert(quintets.end(), local_quintets.begin(), local_quintets.end()); #endif set_quintets(quintets); #ifdef TIME_FRESNEL auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration diff = (end-start); std::cout << "Layer creation took " << diff.count() << "s" << std::endl; std::cout << " Fresnel component was " << microfacet_timer << "s" << std::endl; #endif apply_surface_integration_weights(*this); } void Layer::set_isotropic(double albedo) { std::vector quintets; quintets.reserve(resolution() * resolution()); size_t n = resolution(); for (size_t i = 0; i < n; ++i) { for (size_t o = 0; o < n; ++o) { quintets.emplace_back(0, 0, o, i, albedo * math::InvFourPi); } } set_quintets(quintets); apply_medium_integration_weights(*this); } void Layer::set_henyey_greenstein(double albedo, double g) { std::vector quintets; tbb::spin_mutex mutex; tbb::parallel_for( tbb::blocked_range(0, resolution()), [&](const tbb::blocked_range &range) { std::vector local_quintets; local_quintets.reserve(fourier_orders().second * resolution()); VectorX result; for (size_t i = range.begin(); i < range.end(); ++i) { for (size_t o = 0; o <= i; ++o) { henyey_greenstein_fourier_series(m_nodes[o], m_nodes[i], g, (int) fourier_orders().second, ERROR_GOAL, result); int mdh = result.size() / 2; for (int d = -mdh; d <= mdh; ++d) { local_quintets.emplace_back(0, d, o, i, result[d + mdh] * albedo); if (i != o) { local_quintets.emplace_back(0, d, i, o, result[d + mdh] * albedo); } } } tbb::spin_mutex::scoped_lock lock(mutex); quintets.insert(quintets.end(), local_quintets.begin(), local_quintets.end()); } } ); set_quintets(quintets); apply_medium_integration_weights(*this); } void Layer::set_von_mises_fisher(double albedo, double kappa) { std::vector quintets; tbb::spin_mutex mutex; double scale; if (kappa == 0) { scale = albedo / (4 * math::Pi); } else { scale = albedo * kappa / (4 * math::Pi * std::sinh(kappa)); } tbb::parallel_for( tbb::blocked_range(0, resolution()), [&](const tbb::blocked_range &range) { std::vector local_quintets; local_quintets.reserve(fourier_orders().second * resolution()); VectorX result; for (size_t i = range.begin(); i < range.end(); ++i) { for (size_t o = 0; o <= i; ++o) { von_mises_fisher_fourier_series(m_nodes[o], m_nodes[i], kappa, ERROR_GOAL, result); int mdh = result.size() / 2; for (int d = -mdh; d <= mdh; ++d) { local_quintets.emplace_back(0, d, o, i, result[d + mdh] * scale); if (i != o) { local_quintets.emplace_back(0, d, i, o, result[d + mdh] * scale); } } } tbb::spin_mutex::scoped_lock lock(mutex); quintets.insert(quintets.end(), local_quintets.begin(), local_quintets.end()); } } ); set_quintets(quintets); apply_medium_integration_weights(*this); } void Layer::set_fourier_coeffs(std::vector coeffs) { std::vector quintets; tbb::spin_mutex mutex; size_t n = resolution(); if (coeffs.size() != n*n) Throw("Layer::set_fourier_coeffs(): incompatible size of elevation angles!"); tbb::parallel_for( tbb::blocked_range(0, n), [&](const tbb::blocked_range &range) { std::vector local_quintets; local_quintets.reserve(fourier_orders().first * fourier_orders().second * resolution()); for (size_t i = range.begin(); i < range.end(); ++i) { for (size_t o = 0; o < n; ++o) { const MatrixX &coeffs_io = coeffs[i*n + o]; int ms = coeffs_io.rows(), md = coeffs_io.cols(); if (coeffs_io.rows() % 2 == 0 || coeffs_io.cols() % 2 == 0) Throw("Layer::set_fourier_coeffs(): require odd dimensions Fourier coefficient matrix!"); int msh = ms / 2, mdh = md / 2; for (int d = -mdh; d <= mdh; ++d) { for (int s = -msh; s <= msh; ++s) { double value = coeffs_io(s + msh, d + mdh); if (std::abs(value) > 1e-10) local_quintets.emplace_back(s, d, o, i, value); } } } tbb::spin_mutex::scoped_lock lock(mutex); quintets.insert(quintets.end(), local_quintets.begin(), local_quintets.end()); } } ); set_quintets(quintets); apply_surface_integration_weights(*this); } void Layer::add(const Layer &l1, const Layer &l2, Layer &output, bool homogeneous, double eps) { #if !defined(HAVE_UMFPACK) (void) l1; (void) l2; (void) output; (void) homogeneous; (void) eps; Throw("Layer::add: You need to recompile with support for UMFPACK!"); #else if (output.resolution() != l1.resolution() || output.resolution() != l2.resolution() || output.fourier_orders().second != l1.fourier_orders().second || output.fourier_orders().second != l2.fourier_orders().second) { Throw("Layer::add(): incompatible sizes!"); } if (homogeneous) { const MatrixS &Rt_1 = l1.reflection_top(); const MatrixS &Rb_1 = l1.reflection_bottom(); const MatrixS &Tbt_1 = l1.transmission_bottom_top(); const MatrixS &Ttb_1 = l1.transmission_top_bottom(); const MatrixS &Rt_2 = l2.reflection_top(); const MatrixS &Ttb_2 = l2.transmission_top_bottom(); MatrixS I(Rt_1.rows(), Rt_1.cols()); I.setIdentity(); MatrixS RR = I - mmul(Rb_1, Rt_2, 0.0); RR.prune(1.0, eps); MatrixS tmp = UMFPack(RR).solve_sparse(Ttb_1, eps); MatrixS Rt = Rt_1 + mmul(Tbt_1, mmul(Rt_2, tmp, eps), eps); MatrixS Ttb = mmul(Ttb_2, tmp); output.reflection_top() = Rt; output.reflection_bottom() = Rt; output.transmission_top_bottom() = Ttb; output.transmission_bottom_top() = Ttb; } else { const MatrixS &Rt_1 = l1.reflection_top(); const MatrixS &Rb_1 = l1.reflection_bottom(); const MatrixS &Tbt_1 = l1.transmission_bottom_top(); const MatrixS &Ttb_1 = l1.transmission_top_bottom(); const MatrixS &Rt_2 = l2.reflection_top(); const MatrixS &Rb_2 = l2.reflection_bottom(); const MatrixS &Tbt_2 = l2.transmission_bottom_top(); const MatrixS &Ttb_2 = l2.transmission_top_bottom(); MatrixS I(Rt_1.rows(), Rt_1.cols()); I.setIdentity(); MatrixS RR1 = I - mmul(Rb_1, Rt_2, 0.0); MatrixS RR2 = I - mmul(Rt_2, Rb_1, 0.0); RR1.prune(1.0, eps); RR2.prune(1.0, eps); MatrixS tmp0 = UMFPack(RR1).solve_sparse(Ttb_1, eps); MatrixS tmp1 = UMFPack(RR2).solve_sparse(Tbt_2, eps); MatrixS Rt = Rt_1 + mmul(Tbt_1, mmul(Rt_2, tmp0, eps), eps); MatrixS Rb = Rb_2 + mmul(Ttb_2, mmul(Rb_1, tmp1, eps), eps); MatrixS Ttb = mmul(Ttb_2, tmp0, eps); MatrixS Tbt = mmul(Tbt_1, tmp1, eps); output.reflection_top() = Rt; output.reflection_bottom() = Rb; output.transmission_top_bottom() = Ttb; output.transmission_bottom_top() = Tbt; } #endif } void Layer::subtract(const Layer &ladd, const Layer &l1, Layer &l2, double eps) { #if !defined(HAVE_UMFPACK) (void) ladd; (void) l1; (void) l2; (void) eps; (void) remove_surface_integration_weights; Throw("Layer::subtract: You need to recompile with support for UMFPACK!"); #else const MatrixS &Rt_add = ladd.reflection_top(); const MatrixS &Rt_1 = l1.reflection_top(); const MatrixS &Rb_1 = l1.reflection_bottom(); const MatrixS &Tbt_1 = l1.transmission_bottom_top(); const MatrixS &Ttb_1 = l1.transmission_top_bottom(); double drop_threshold = 1e-5; MatrixS I(Rt_1.rows(), Rt_1.cols()); I.setIdentity(); MatrixS W = eps * I; /* Invert transmission from top layer */ MatrixS Ttb_1_t = Ttb_1.transpose(); MatrixS Tbt_1_t = Tbt_1.transpose(); MatrixS Ttb_1_i = UMFPack(mmul(Ttb_1_t, Ttb_1) + W).solve_sparse(Ttb_1_t, drop_threshold); MatrixS Tbt_1_i = UMFPack(mmul(Tbt_1_t, Tbt_1) + W).solve_sparse(Tbt_1_t, drop_threshold); /* Compute top reflection of new bottom layer */ MatrixS X = mmul(Tbt_1_i, mmul((Rt_add - Rt_1), Ttb_1_i)); MatrixS Y = UMFPack(I + mmul(Rb_1, X)).solve_sparse(I, drop_threshold); MatrixS Z = mmul(X, Y); l2.reflection_top() = Z; remove_surface_integration_weights(l2); Z = l2.reflection_top(); /* The rows/columns close to normal (mu ~= 1) or grazing (mu ~= 0) incidence are especially tricky */ int ms, md; std::tie(ms, md) = l1.fourier_orders(); int n = l1.resolution(); int size = n / 2; int blocks = ms + md - 1; /* At normal incidence, we extrapolate the last few columns and then copy them to the rows */ int nn = 4; for (int b = 0; b < blocks; ++b) { int start_col = b * size; for (int j = 0; j < nn; ++j) { Z.col(start_col + size - nn + j) = Z.col(start_col + size - nn - 1); } } MatrixS Zt = Z.transpose(); for (int b = 0; b < blocks; ++b) { int start_col = b * size; for (int j = 0; j < nn; ++j) { Zt.col(start_col + size - nn + j) = Zt.col(start_col + size - nn - 1); } } Z = Zt.transpose(); /* For grazing incidence, we copy the first few rows to the columns */ nn = 2; for (int b = 0; b < blocks; ++b) { int start_col = b * size; for (int j = 0; j < nn; ++j) { Z.col(start_col + j) = Zt.col(start_col + j); } } Z.prune(1.0, drop_threshold); l2.reflection_top() = Z; apply_surface_integration_weights(l2); #endif } void Layer::expand(double target_tau) { /* Heuristic for choosing the initial width of a layer based on "Discrete Space Theory of Radiative Transfer" by Proc. R. Soc. London 1969 */ double tau = std::min(m_nodes.cwiseAbs().minCoeff() * 2, std::pow(2.0, -15.0)); size_t doublings = (size_t) std::ceil(std::log(target_tau / tau) / std::log(2.0)); tau = target_tau * std::pow(2.0, -(double) doublings); size_t ml = fourier_orders().first + fourier_orders().second - 1; size_t n = resolution() / 2; MatrixS I(ml * n, ml * n); I.setIdentity(); MatrixS row_scale = extended_sparse_diagonal(m_nodes.tail(n).cwiseInverse() * tau, ml); MatrixS Rt = row_scale * m_reflection_top; MatrixS Ttb = I + row_scale * (m_transmission_top_bottom - I); m_reflection_top = Rt; m_reflection_bottom = Rt; m_transmission_top_bottom = Ttb; m_transmission_bottom_top = Ttb; for (size_t i = 0; i < (size_t) doublings; ++i) { add(*this, *this, *this, true); } } double Layer::scatter_coeff(int s, int d, size_t o, size_t i) const { size_t n = resolution() / 2; int ms = (int) fourier_orders().first, md = (int) fourier_orders().second, ml = ms + md - 1; int mlh = ml / 2; int block_i = d + s + mlh, block_j = d - s + mlh; if (o < n && i < n) return m_transmission_bottom_top.coeff(block_i*n + o, block_j*n + i); else if (o >= n && i >= n) return m_transmission_top_bottom.coeff(block_i*n + o-n, block_j*n + i-n); else if (o < n && i >= n) return m_reflection_top.coeff(block_i*n + o, block_j*n + i-n); else if (o >= n && i < n) return m_reflection_bottom.coeff(block_i*n + o-n, block_j*n + i); else Log(Error, "Layer::coeff(): out of bounds!"); return -1.0; } void Layer::reverse() { m_reflection_top.swap(m_reflection_bottom); m_transmission_top_bottom.swap(m_transmission_bottom_top); } double Layer::eval(double mu_o, double mu_i, double phi_s, double phi_d, bool clamp) const { int n = m_nodes.size(), h = n / 2; double knot_weights_o[4], knot_weights_i[4]; ssize_t knot_offset_o, knot_offset_i; if (mu_o < 0 || (mu_o == 0 && mu_i > 0)) { auto spline_weights_o = spline::eval_spline_weights(m_nodes.data() + h, h, -mu_o, knot_weights_o); knot_offset_o = spline_weights_o.second; } else { auto spline_weights_o = spline::eval_spline_weights(m_nodes.data() + h, h, mu_o, knot_weights_o); knot_offset_o = spline_weights_o.second + h; } if (mu_i < 0 || (mu_i == 0 && mu_o > 0)) { auto spline_weights_i = spline::eval_spline_weights(m_nodes.data() + h, h, -mu_i, knot_weights_i); knot_offset_i = spline_weights_i.second; } else { auto spline_weights_i = spline::eval_spline_weights(m_nodes.data() + h, h, mu_i, knot_weights_i); knot_offset_i = spline_weights_i.second + h; } int msh = (int) fourier_orders().first / 2, mdh = (int) fourier_orders().second / 2; std::complex exp_s = std::exp(1i * phi_s); std::complex exp_d = std::exp(1i * phi_d); std::complex start_exp_s = std::exp(-1i * (double) msh * phi_s); std::complex cur_exp_d = std::exp(-1i * (double) mdh * phi_d); double result = 0.0; for (int d = -mdh; d <= mdh; ++d) { std::complex cur_exp = start_exp_s * cur_exp_d; for (int s = -msh; s <= msh; ++s) { std::complex coeff(0); for (int o = 0; o < 4; ++o) { for (int i = 0; i < 4; ++i) { double weight = knot_weights_o[o] * knot_weights_i[i]; if (weight == 0) continue; weight /= 2 * math::Pi * std::abs(m_nodes[knot_offset_i + i]) * m_weights[knot_offset_i + i]; coeff += weight * scatter_coeff(s, d, knot_offset_o + o, knot_offset_i + i); } } result += std::real(coeff * cur_exp); cur_exp *= exp_s; } cur_exp_d *= exp_d; } return clamp ? std::max(0.0, result) : result; } void Layer::find_truncation(MatrixS::Index o, MatrixS::Index i, double error, size_t &ms_trunc, size_t &md_trunc) const { int n = m_nodes.size(); int h = n / 2; i = (MatrixS::Index) (i < h ? (h-i-1) : i); o = (MatrixS::Index) (o < h ? (h-o-1) : o); ms_trunc = 0, md_trunc = 0; int ms = (int) fourier_orders().first; int md = (int) fourier_orders().second; int msh = ms / 2, mdh = md / 2; #if 1 // Cut out rectangle, s.t. all entries are > eps * error // This can be done by doing two independent passes through the data double ref = std::abs(scatter_coeff(0, 0, o, i)) * error; // Check in phi_s dimension for (int s = 0; s <= msh; ++s) { bool keep = false; for (int d = -mdh; d <= mdh; ++d) { double value = std::abs(scatter_coeff(s, d, o, i)); if (value > ref) keep = true; } if (keep) { ms_trunc = 2*s+1; } else { break; } } // Check in phi_d dimension for (int d = 0; d <= mdh; ++d) { bool keep = false; for (int s = -msh; s <= msh; ++s) { double value = std::abs(scatter_coeff(s, d, o, i)); if (value > ref) keep = true; } if (keep) { md_trunc = 2*d+1; } else { break; } } #else // Cut out rectangle that minimizes full truncation error // (sum of elements outside) // Computed using summed area tables double ref = std::abs(scatter_coeff(0, 0, o, i)) * error; MatrixX val(ms, md); val.setZero(); // Build summed area table sigma (recursive formulation) MatrixX sigma(ms, md); sigma.setZero(); for (int d = -mdh; d <= mdh; ++d) { for (int s = -msh; s <= msh; ++s) { int os = s + msh; int od = d + mdh; double value = std::abs(scatter_coeff(s, d, o, i)); if (value < 1e-6) value = 0; val(os, od) = value; if (os - 1 >= 0) value += sigma(os - 1, od); if (od - 1 >= 0) value += sigma(os, od - 1); if (os - 1 >= 0 && od - 1 >= 0) value -= sigma(os - 1, od - 1); sigma(os, od) = value; } } // For each possible size, consider truncation error, keep rectangle // with minimal number of entries ms_trunc = 0; md_trunc = 0; int min_coeffs = std::numeric_limits::max(); double total = sigma(ms-1, md-1); if (ref != 0) { ms_trunc = ms; md_trunc = md; for (int d = 0; d <= mdh; ++d) { for (int s = 0; s <= msh; ++s) { int os = s + msh; int od = d + mdh; int coeffs = (2*s+1)*(2*d+1); double value = total; value -= sigma(os, od); if (-s+msh-1 >= 0) value += sigma(-s+msh-1, od); if (-d+mdh-1 >= 0) value += sigma(os, -d+mdh-1); if (-s+msh-1 >= 0 && -d+mdh-1 >= 0) value -= sigma(-s+msh-1, -d+mdh-1); if (value < ref && coeffs < min_coeffs) { ms_trunc = 2*s+1; md_trunc = 2*d+1; min_coeffs = coeffs; } } } } #endif } void Layer::fourier_slice(int o, int i, MatrixX &coeffs) const { int n = m_nodes.size(); int h = n / 2; i = (MatrixS::Index) (i < h ? (h-i-1) : i); o = (MatrixS::Index) (o < h ? (h-o-1) : o); int msh = (int) fourier_orders().first / 2, mdh = (int) fourier_orders().second / 2; coeffs.resize(2*msh+1, 2*mdh+1); coeffs.setZero(); for (int d = -mdh; d <= mdh; ++d) { int od = d + mdh; for (int s = -msh; s <= msh; ++s) { int os = s + msh; coeffs(os, od) = scatter_coeff(s, d, o, i); } } } void Layer::fourier_slice_interpolated(double mu_o, double mu_i, MatrixX &coeffs) const { int n = m_nodes.size(), h = n / 2; double knot_weights_o[4], knot_weights_i[4]; ssize_t knot_offset_o, knot_offset_i; if (mu_o < 0 || (mu_o == 0 && mu_i > 0)) { auto spline_weights_o = spline::eval_spline_weights(m_nodes.data() + h, h, -mu_o, knot_weights_o); knot_offset_o = spline_weights_o.second; } else { auto spline_weights_o = spline::eval_spline_weights(m_nodes.data() + h, h, mu_o, knot_weights_o); knot_offset_o = spline_weights_o.second + h; } if (mu_i < 0 || (mu_i == 0 && mu_o > 0)) { auto spline_weights_i = spline::eval_spline_weights(m_nodes.data() + h, h, -mu_i, knot_weights_i); knot_offset_i = spline_weights_i.second; } else { auto spline_weights_i = spline::eval_spline_weights(m_nodes.data() + h, h, mu_i, knot_weights_i); knot_offset_i = spline_weights_i.second + h; } int msh = (int) fourier_orders().first / 2, mdh = (int) fourier_orders().second / 2; coeffs.resize(2*msh+1, 2*mdh+1); coeffs.setZero(); for (int d = -mdh; d <= mdh; ++d) { int od = d + mdh; for (int s = -msh; s <= msh; ++s) { int os = s + msh; for (int o = 0; o < 4; ++o) { for (int i = 0; i < 4; ++i) { double weight = knot_weights_o[o] * knot_weights_i[i]; if (weight == 0) continue; weight /= 2 * math::Pi * std::abs(m_nodes[knot_offset_i + i]) * m_weights[knot_offset_i + i]; coeffs(os, od) = weight * scatter_coeff(s, d, knot_offset_o + o, knot_offset_i + i); } } } } } std::string Layer::to_string() const { size_t nz_max = resolution() * resolution() * fourier_orders().first * fourier_orders().second; size_t nz = m_reflection_top.nonZeros() + m_reflection_bottom.nonZeros() + m_transmission_top_bottom.nonZeros() + m_transmission_bottom_top.nonZeros(); std::ostringstream oss; oss.precision(2); oss << "Layer[" << std::endl << " resolution = " << resolution() << "x" << resolution() << std::endl << " fourier_orders = " << fourier_orders().first << "x" << fourier_orders().second << "," << std::endl << " non_zeros=" << nz << "/" << nz_max << " (" << ((float) nz / (float) nz_max * 100) << "%)" << std::endl << "]"; return oss.str(); } void Layer::set_quintets(const std::vector &quintets) { int ms = (int) fourier_orders().first, md = (int) fourier_orders().second, ml = ms + md - 1; int msh = ms / 2, mdh = md / 2, mlh = ml / 2; std::vector> triplets_t, triplets_b, triplets_tb, triplets_bt; size_t approx_size = quintets.size() / (4*ms*md); triplets_t.reserve(approx_size); triplets_b.reserve(approx_size); triplets_tb.reserve(approx_size); triplets_bt.reserve(approx_size); size_t n = resolution() / 2; for (auto const &quintet: quintets) { typedef MatrixS::Index Index; // Only keep & store the Fourier coefficients smaller than fourier_orders() int os = msh + quintet.s; int od = mdh + quintet.d; if (os < 0 || os >= ms) continue; if (od < 0 || od >= md) continue; int block_i = quintet.d + quintet.s + mlh, block_j = quintet.d - quintet.s + mlh; // Note the reordering inside the blocks s.t. adding makes sense if (quintet.o < n && quintet.i < n) triplets_bt.emplace_back(Index(block_i*n + quintet.o), Index(block_j*n + quintet.i), quintet.value); else if (quintet.o >= n && quintet.i >= n) triplets_tb.emplace_back(Index(block_i*n + quintet.o-n), Index(block_j*n + quintet.i-n), quintet.value); else if (quintet.o < n && quintet.i >= n) triplets_t.emplace_back(Index(block_i*n + quintet.o), Index(block_j*n + quintet.i-n), quintet.value); else if (quintet.o >= n && quintet.i < n) triplets_b.emplace_back(Index(block_i*n + quintet.o-n), Index(block_j*n + quintet.i), quintet.value); else Throw("Layer::setFromQuintets(): internal error!"); } m_reflection_top.setFromTriplets(triplets_t.begin(), triplets_t.end()); m_reflection_bottom.setFromTriplets(triplets_b.begin(), triplets_b.end()); m_transmission_top_bottom.setFromTriplets(triplets_tb.begin(), triplets_tb.end()); m_transmission_bottom_top.setFromTriplets(triplets_bt.begin(), triplets_bt.end()); } std::tuple microfacet_parameter_heuristic(double alpha_u, double alpha_v, std::complex &eta) { /* Isotropic heuristic: need to be able to represent smaller roughness parameter */ double alpha = std::min(alpha_u, alpha_v); alpha = std::min(alpha, 1.0); if (eta.real() < 1 && eta.imag() == 0) eta = std::complex(1) / eta; static const double c[][9] = { /* IOR A_n B_n C_n D_n A_m B_m C_m D_m */ { 0.0, 35.275, 14.136, 29.287, 1.8765, 39.814, 88.992, -98.998, 39.261 }, /* Generic conductor */ { 1.1, 256.47, -73.180, 99.807, 37.383, 110.782, 57.576, 94.725, 14.001 }, /* Dielectric, eta = 1.1 */ { 1.3, 100.264, 28.187, 64.425, 14.850, 45.809, 17.785, -7.8543, 12.892 }, /* Dielectric, eta = 1.3 */ { 1.5, 74.176, 27.470, 42.454, 9.6437, 31.700, 44.896, -45.016, 19.643 }, /* Dielectric, eta = 1.5 */ { 1.7, 80.098, 17.016, 50.656, 7.2798, 46.549, 58.592, -73.585, 25.473 }, /* Dielectric, eta = 1.7 */ }; int i0 = 0, i1 = 0; if (eta.imag() == 0) { /* Dielectric case */ for (int i = 1; i < 4; ++i) { if (eta.real() >= c[i][0] && eta.real() <= c[i+1][0]) { if (std::abs(eta.real() - c[i][0]) < 0.05) { i1 = i0 = i; } else if (std::abs(eta - c[i+1][0]) < 0.05) { i0 = i1 = i+1; } else { i0 = i; i1 = i+1; } } } if (!i0) Throw("Index of refraction is out of bounds (must be between 1.1 and 1.7)!"); } double n0 = std::max(c[i0][1] + c[i0][2]*std::pow(std::log(alpha), 4.0)*alpha, c[i0][3]+c[i0][4]*std::pow(alpha, -1.2)); double n1 = std::max(c[i1][1] + c[i1][2]*std::pow(std::log(alpha), 4.0)*alpha, c[i1][3]+c[i1][4]*std::pow(alpha, -1.2)); double d0 = std::max(c[i0][5] + c[i0][6]*std::pow(std::log(alpha), 4.0)*alpha, c[i0][7]+c[i0][8]*std::pow(alpha, -1.2)); double d1 = std::max(c[i1][5] + c[i1][6]*std::pow(std::log(alpha), 4.0)*alpha, c[i1][7]+c[i1][8]*std::pow(alpha, -1.2)); int n_i = (int) std::ceil(std::max(n0, n1)), d_i = (int) std::ceil(std::max(d0, d1)); if (n_i % 2 == 1) n_i += 1; d_i = 2*d_i - 1; /* Anisotropic heuristic: based on a linear fit along the ratio of roughness parameters */ int s_i = 1; if (alpha_u != alpha_v) { double A = 5.16, B = -2.63; double ratio = alpha_u / alpha_v; if (ratio < 1) ratio = 1.0 / ratio; s_i = std::ceil(A*ratio + B); if (s_i % 2 == 0) s_i += 1; } return std::make_tuple(n_i, s_i, d_i); } std::tuple henyey_greenstein_parameter_heuristic(double g) { g = std::abs(g); double d = 5.4 / (1.0 - g) - 1.3; double n = 8.6 / (1.0 - g) - 0.2; int n_i = (int) std::ceil(n), d_i = (int) std::ceil(d); if (n_i % 2 == 1) n_i += 1; d_i = 2*d_i - 1; return std::make_tuple(n_i, 1, d_i); } NAMESPACE_END(mitsuba) /** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * 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 "common/formats/format_transfers/format_transfer_nhwc_nc1hwc0.h" #include #include #include "common/formats/utils/formats_definitions.h" #include "common/formats/utils/formats_trans_utils.h" #include "framework/common/debug/ge_log.h" #include "graph/utils/type_utils.h" namespace ge { namespace formats { namespace { bool CheckDataTypeSupported(const DataType &data_type) { return GetSizeByDataType(data_type) > 0; } Status TransShapeNhwcToNc1hwc0(const std::vector &src_shape, DataType data_type, std::vector &dst_shape) { int64_t c0 = GetCubeSizeByDataType(data_type); if (c0 <= 0) { GELOGE(PARAM_INVALID, "Failed to get cube size, the data type is invalid"); return PARAM_INVALID; } dst_shape.clear(); dst_shape.push_back(src_shape.at(kNhwcN)); dst_shape.push_back((src_shape.at(kNhwcC) - 1) / c0 + 1); dst_shape.push_back(src_shape.at(kNhwcH)); dst_shape.push_back(src_shape.at(kNhwcW)); dst_shape.push_back(c0); if (!CheckShapeValid(dst_shape, kNc1hwc0DimsNum)) { GELOGE(PARAM_INVALID, "Failed to check dst shape %s", ShapeToString(dst_shape).c_str()); return PARAM_INVALID; } return SUCCESS; } Status CheckArgsForNhwcToNc1hwc0(const TransArgs &args) { if (args.src_format != FORMAT_NHWC || args.dst_format != FORMAT_NC1HWC0) { GELOGE(UNSUPPORTED, "Does not support trans format from %s to %s", TypeUtils::FormatToSerialString(args.src_format).c_str(), TypeUtils::FormatToSerialString(args.dst_format).c_str()); return UNSUPPORTED; } if (!CheckDataTypeSupported(args.src_data_type)) { GELOGE(UNSUPPORTED, "Failed to trans shape from NHWC to NC1HWC0, invalid data type %s", TypeUtils::DataTypeToSerialString(args.src_data_type).c_str()); return UNSUPPORTED; } if (!CheckShapeValid(args.src_shape, kNhwcDimsNum)) { GELOGE(PARAM_INVALID, "Failed to check src shape %s", ShapeToString(args.src_shape).c_str()); return PARAM_INVALID; } if (!CheckShapeValid(args.dst_shape, kNc1hwc0DimsNum)) { GELOGE(PARAM_INVALID, "Failed to check dst shape %s", ShapeToString(args.dst_shape).c_str()); return PARAM_INVALID; } std::vector expect_dst_shape; auto ret = TransShapeNhwcToNc1hwc0(args.src_shape, args.src_data_type, expect_dst_shape); if (ret != SUCCESS) { return ret; } if (args.dst_shape != expect_dst_shape) { GELOGE(PARAM_INVALID, "Failed to trans format, the src and dst shape are not compatible. src shape %s, dst shape %s, " "expect dst shape %s", ShapeToString(args.src_shape).c_str(), ShapeToString(args.dst_shape).c_str(), ShapeToString(expect_dst_shape).c_str()); return PARAM_INVALID; } return SUCCESS; } Status GetDstDataAfterTrans(const TransArgs &args, TransResult &result, const int size, const int64_t total_size) { std::shared_ptr dst(new (std::nothrow) uint8_t[total_size], std::default_delete()); if (dst == nullptr) { GELOGE(OUT_OF_MEMORY, "Failed to trans format from %s to %s, can not alloc the memory for dst buf %ld, shape %s", TypeUtils::FormatToSerialString(args.src_format).c_str(), TypeUtils::FormatToSerialString(args.dst_format).c_str(), total_size, ShapeToString(args.dst_shape).c_str()); return OUT_OF_MEMORY; } auto n = args.src_shape.at(kNhwcN); auto h = args.src_shape.at(kNhwcH); auto w = args.src_shape.at(kNhwcW); auto c = args.src_shape.at(kNhwcC); auto c1 = args.dst_shape.at(kNc1hwc0C1); auto c0 = args.dst_shape.at(kNc1hwc0C0); int64_t wc = w * c; int64_t hwc = h * wc; int64_t wc0 = w * c0; int64_t hwc0 = h * wc0; int64_t c1hwc0 = c1 * hwc0; for (int64_t n_idx = 0; n_idx < n; n_idx++) { int64_t n_head_addr = n_idx * c1hwc0; for (int64_t c1_idx = 0; c1_idx < c1; c1_idx++) { int64_t c1_head_addr = n_head_addr + c1_idx * hwc0; for (int64_t h_idx = 0; h_idx < h; h_idx++) { int64_t h_head_addr = c1_head_addr + h_idx * wc0; for (int64_t w_idx = 0; w_idx < w; w_idx++) { int64_t w_head_addr = h_head_addr + w_idx * c0; for (int64_t c0_idx = 0; c0_idx < c0; c0_idx++) { int64_t dst_idx = c0_idx + w_head_addr; int64_t dst_offset = dst_idx * size; auto protected_size = total_size - dst_offset < static_cast(SECUREC_MEM_MAX_LEN) ? total_size - dst_offset : static_cast(SECUREC_MEM_MAX_LEN); int64_t c_idx = c0_idx + c1_idx * c0; int64_t src_idx = n_idx * hwc + h_idx * wc + w_idx * c + c_idx; auto src_offset = src_idx * size; if (c_idx < c) { auto ret = memcpy_s(dst.get() + dst_offset, protected_size, args.data + src_offset, size); if (ret != EOK) { GELOGE(INTERNAL_ERROR, "Failed to copy data from NHWC[%ld, %ld, %ld, %ld] offset %ld to " "NC1HWC0[%ld, %ld, %ld, %ld, %ld] offset %ld err-code %d", n_idx, h_idx, w_idx, c_idx, src_offset, n_idx, c1_idx, h_idx, w_idx, c0_idx, dst_offset, ret); return INTERNAL_ERROR; } } else { auto ret = memset_s(dst.get() + dst_offset, protected_size, 0, size); if (ret != EOK) { GELOGE(INTERNAL_ERROR, "Failed to set 0 to NC1HWC0[%ld, %ld, %ld, %ld, %ld] offset %ld base err-code %d", n_idx, c1_idx, h_idx, w_idx, c0_idx, dst_offset, ret); return INTERNAL_ERROR; } } } } } } } result.data = dst; result.length = static_cast(total_size); return SUCCESS; } } // namespace Status FormatTransferNhwcNc1hwc0::TransFormat(const TransArgs &args, TransResult &result) { if (CheckArgsForNhwcToNc1hwc0(args) != SUCCESS) { return PARAM_INVALID; } int size = GetSizeByDataType(args.src_data_type); auto total_size = GetItemNumByShape(args.dst_shape) * size; if (total_size <= 0) { GELOGE(INTERNAL_ERROR, "Get %ld total size from dst shape %s, src shape %s", total_size, ShapeToString(args.dst_shape).c_str(), ShapeToString(args.src_shape).c_str()); return PARAM_INVALID; } GELOGD("Begin to trans format from NHWC to NC1HWC0, src shape %s, data type %s, dst shape %s, memory size %ld", ShapeToString(args.src_shape).c_str(), TypeUtils::DataTypeToSerialString(args.src_data_type).c_str(), ShapeToString(args.dst_shape).c_str(), total_size); if (GetDstDataAfterTrans(args, result, size, total_size) != SUCCESS) { GELOGE(INTERNAL_ERROR, "Failed to get data after trans, src shape %s, data type %s, dst shape %s, memory size %ld", ShapeToString(args.src_shape).c_str(), TypeUtils::DataTypeToSerialString(args.src_data_type).c_str(), ShapeToString(args.dst_shape).c_str(), total_size); return INTERNAL_ERROR; } return SUCCESS; } Status FormatTransferNhwcNc1hwc0::TransShape(Format src_format, const std::vector &src_shape, DataType data_type, Format dst_format, std::vector &dst_shape) { if (src_format == FORMAT_NHWC && CheckDataTypeSupported(data_type)) { if (!CheckShapeValid(src_shape, kNhwcDimsNum)) { GELOGE(PARAM_INVALID, "Failed to check src shape %s", ShapeToString(src_shape).c_str()); return PARAM_INVALID; } return TransShapeNhwcToNc1hwc0(src_shape, data_type, dst_shape); } else { return UNSUPPORTED; } } REGISTER_FORMAT_TRANSFER(FormatTransferNhwcNc1hwc0, FORMAT_NHWC, FORMAT_NC1HWC0) } // namespace formats } // namespace ge #pragma once #pragma region Operators template <> constexpr Angle::operator Angle() const noexcept { return Angle(static_cast(*this) * 180.0F / Constants::pi); } template <> constexpr Angle::operator Angle() const noexcept { return Angle(static_cast(*this) * Constants::pi / 180.0F); } constexpr Degrees operator"" _deg(RkLdouble const in_angle) noexcept { return Degrees(static_cast(in_angle)); } constexpr Degrees operator"" _deg(RkSize const in_angle) noexcept { return Degrees(static_cast(in_angle)); } constexpr Radians operator"" _rad(RkLdouble const in_angle) noexcept { return Radians(static_cast(in_angle)); } constexpr Radians operator"" _rad(RkSize const in_angle) noexcept { return Radians(static_cast(in_angle)); } #pragma endregionTerricide/MixedReality-WebRTClibs/mrwebrtc/src/utils.cpp // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "interop_api.h" #include "mrs_errors.h" #include "result.h" #include "utils.h" namespace Microsoft { namespace MixedReality { namespace WebRTC { Result ResultFromRTCErrorType(webrtc::RTCErrorType type) { using namespace webrtc; switch (type) { case RTCErrorType::NONE: return Result::kSuccess; case RTCErrorType::UNSUPPORTED_OPERATION: case RTCErrorType::UNSUPPORTED_PARAMETER: return Result::kUnsupported; case RTCErrorType::INVALID_PARAMETER: case RTCErrorType::INVALID_RANGE: return Result::kInvalidParameter; case RTCErrorType::INVALID_STATE: return Result::kNotInitialized; default: return Result::kUnknownError; } } Error ErrorFromRTCError(const webrtc::RTCError& error) { return Error(ResultFromRTCErrorType(error.type()), error.message()); } Error ErrorFromRTCError(webrtc::RTCError&& error) { // Ideally would move the std::string out of |error|, but doesn't look // possible at the moment. return Error(ResultFromRTCErrorType(error.type()), error.message()); } mrsMediaKind MediaKindFromRtc(cricket::MediaType media_type) { switch (media_type) { case cricket::MediaType::MEDIA_TYPE_AUDIO: return mrsMediaKind::kAudio; case cricket::MediaType::MEDIA_TYPE_VIDEO: return mrsMediaKind::kVideo; default: RTC_LOG(LS_ERROR) << "Invalid media type, expected audio or video."; RTC_NOTREACHED(); // Silence error about uninitialized variable when assigning the result of // this function, and return some visibly invalid value. return (mrsMediaKind)-1; } } cricket::MediaType MediaKindToRtc(mrsMediaKind media_kind) { switch (media_kind) { case mrsMediaKind::kAudio: return cricket::MediaType::MEDIA_TYPE_AUDIO; case mrsMediaKind::kVideo: return cricket::MediaType::MEDIA_TYPE_VIDEO; default: RTC_LOG(LS_ERROR) << "Unknown media kind, expected audio or video."; RTC_NOTREACHED(); // Silence error about uninitialized variable when assigning the result of // this function, and return some visibly invalid value (mrsMediaKind is // audio or video only). return cricket::MediaType::MEDIA_TYPE_DATA; } } const char* ToString(cricket::MediaType media_type) { switch (media_type) { case cricket::MediaType::MEDIA_TYPE_AUDIO: return "audio"; case cricket::MediaType::MEDIA_TYPE_VIDEO: return "video"; case cricket::MediaType::MEDIA_TYPE_DATA: return "data"; default: return ""; } } const char* ToString(webrtc::RtpTransceiverDirection dir) { switch (dir) { case webrtc::RtpTransceiverDirection::kSendRecv: return "kSendRecv"; case webrtc::RtpTransceiverDirection::kSendOnly: return "kSendOnly"; case webrtc::RtpTransceiverDirection::kRecvOnly: return "kRecvOnly"; case webrtc::RtpTransceiverDirection::kInactive: return "kInactive"; default: return ""; } } const char* ToString(bool value) { return (value ? "true" : "false"); } } // namespace WebRTC } // namespace MixedReality } // namespace Microsoft #ifndef LV_DEMO_GRAPHING #define LV_DEMO_GRAPHING // #ifdef __cplusplus // extern "C" { // #endif #include #include // #ifdef __cplusplus // } // #endif void create_graph(lv_obj_t *parent); lv_obj_t* get_functionTextArea(); //void create_graph(void); #endif 10-100 #include "types.hh" function f(complex c) { return [c] (complex z) { return z*z + c; }; } bool pred(complex z) { return std::norm(z) < 4.0; } client/cotsb/map_renderer.cpp #include "map_renderer.h" #include "map.h" #include "game_object.h" #include "tile.h" namespace cotsb { MapRenderer::MapRenderer() : _map(nullptr), _verticies(sf::Triangles) { } void MapRenderer::map(Map *map) { _map = map; create_vertex_array(); } Map *MapRenderer::map() const { return _map; } void MapRenderer::draw( sf::RenderTarget &target, sf::RenderStates states ) { if (_map == nullptr) { return; } target.draw(_verticies, states); const auto game_objects = _map->game_objects(); for (auto obj : game_objects) { target.draw(*obj, states); } } void MapRenderer::create_vertex_array() { _verticies.clear(); if (_map == nullptr) { return; } auto total = _map->width() * _map->height() * 6u; _verticies.resize(total); auto i = 0u; for (auto y = 0u; y < _map->height(); y++) { for (auto x = 0u; x < _map->width(); x++) { const auto tile = _map->tile(x, y); const auto c = tile->colour(); set_vertex(_verticies[i++], x, y, 0, 0, c); set_vertex(_verticies[i++], x, y, 1, 0, c); set_vertex(_verticies[i++], x, y, 0, 1, c); set_vertex(_verticies[i++], x, y, 0, 1, c); set_vertex(_verticies[i++], x, y, 1, 0, c); set_vertex(_verticies[i++], x, y, 1, 1, c); } } } void MapRenderer::set_vertex(sf::Vertex &vert, float x, float y, float offsetX, float offsetY, sf::Color colour) { vert.position = sf::Vector2f(x + offsetX, y + offsetY); vert.texCoords = sf::Vector2f(offsetX, offsetY); vert.color = colour; } } DQMOffline/Trigger/src/EgHLTComCodes.cc1-10 #include "DQMOffline/Trigger/interface/EgHLTComCodes.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" using namespace egHLT; void ComCodes::setCode(const char* descript,int code) { bool found=false; for(size_t i=0;i<_codeDefs.size() && !found;i++){ if(_codeDefs[i].first==descript) found=true; } if(!found) _codeDefs.emplace_back(descript,code); //_codeDefs[descript] = code; } int ComCodes::getCode(const char* descript)const { int code = 0x0000; char const * const end = descript+strlen(descript); char const * codeKey = descript; char const * token = nullptr; do { token = std::find(codeKey, end, ':'); bool found = false; for(auto const& c: _codeDefs) { if(0==c.first.compare(0,std::string::npos,codeKey, token-codeKey)){ code |= c.second; found = true; break; } } if(!found) edm::LogWarning("EgHLTComCodes") <<"ComCodes::getCode : Error, Key "<& lhs,const std::pair& rhs) { return lhs.first < rhs.first; } void ComCodes::getCodeName(int code,std::string& id)const { id.clear(); for(auto const & _codeDef : _codeDefs){ if((code&_codeDef.second)==_codeDef.second){ if(!id.empty()) id+=":";//seperating entries by a ':' id+=_codeDef.first; } } } 0 /** * @authors Moe_Sakiya * @date 2017-12-08 18:00:48 * */ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(void) { string str1, str2; int a, b, i; bool flag; while (cin >> str1 >> str2) { a = 0; b = 0; flag = false; for (i = 0; i < (int)str1.length(); i++) { if (str1[i] != ',' && str1[i] != '-') a = a * 10 + str1[i] - '0'; else if (str1[i] == '-') flag = true; } if (flag == true) a = -a; flag = false; for (i = 0; i < (int)str2.length(); i++) { if (str2[i] != ',' && str2[i] != '-') b = b * 10 + str2[i] - '0'; else if (str2[i] == '-') flag = true; } if (flag == true) b = -b; cout << a + b << endl; } return 0; }Maple/fpsclass.cpp /////////////////////////////////////////////////////////////////////////////// // Filename: fpsclass.cpp /////////////////////////////////////////////////////////////////////////////// #include "fpsclass.h" FpsClass::FpsClass() { } FpsClass::FpsClass(const FpsClass& other) { } FpsClass::~FpsClass() { } void FpsClass::Initialize(float window) { m_window = window; return; } void FpsClass::Frame() { unsigned long currentTime, cutoffTime; // Create a window of time which we care about. currentTime = timeGetTime(); cutoffTime = currentTime - ((unsigned long)m_window * 1000); // Add the current frame to the list. m_frametimes.push_front(currentTime); // Remove old frames from the list that are no longer in our window. while (m_frametimes.back() < cutoffTime) { m_frametimes.pop_back(); } } float FpsClass::GetFps() { float fps, framesInWindow; // Get number of frames that have been drawn during our rolling window. framesInWindow = (float)m_frametimes.size(); // Calculate the average framerate over that window. fps = framesInWindow / m_window; return fps; } /// Copyright (c) 2019 /// /// 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 "texture_manager_impl.hpp" #include #include "assets/texture_id.hpp" #include "res_path.hpp" namespace { void load_textures(asset::Texture_map& texture_map) { sf::Texture ship_tex; if (ship_tex.loadFromFile(asset::resource_path + "textures/ship.png")) { texture_map[asset::texture::ship_tex] = std::move(ship_tex); } } } // namespace namespace asset { Texture_manager_impl::Texture_manager_impl() { // TODO: open an interface to switch assets // TODO: generate asset path from cmake // TODO: think how the path should be generated for release // Now depends on git // Load a texture from a file load_textures(m_textures); } const sf::Texture& Texture_manager_impl::get_texture(const Texture_id id) const { auto iter = m_textures.find(id); if (iter == m_textures.end()) { static const sf::Texture invalid_texture; return invalid_texture; } return iter->second; } } // namespace asset std::unique_ptr make_texture_manager() { return std::make_unique(); } clang/test/Layout/aix-bitfield-alignment.cpp // RUN: %clang_cc1 -triple powerpc-ibm-aix-xcoff -fdump-record-layouts \ // RUN: -fsyntax-only -fxl-pragma-pack -x c++ %s | \ // RUN: FileCheck --check-prefixes=CHECK %s // RUN: %clang_cc1 -triple powerpc64-ibm-aix-xcoff -fdump-record-layouts \ // RUN: -fsyntax-only -fxl-pragma-pack -x c++ %s | \ // RUN: FileCheck --check-prefixes=CHECK %s struct A { bool b : 3; }; int a = sizeof(A); // CHECK: *** Dumping AST Record Layout // CHECK-NEXT: 0 | struct A // CHECK-NEXT: 0:0-2 | _Bool b // CHECK-NEXT: | [sizeof=4, dsize=4, align=4, preferredalign=4, // CHECK-NEXT: | nvsize=4, nvalign=4, preferrednvalign=4] enum class Bool : bool { False = 0, True = 1 }; struct B { Bool b : 1; }; int b = sizeof(B); // CHECK: *** Dumping AST Record Layout // CHECK-NEXT: 0 | struct B // CHECK-NEXT: 0:0-0 | enum Bool b // CHECK-NEXT: | [sizeof=4, dsize=4, align=4, preferredalign=4, // CHECK-NEXT: | nvsize=4, nvalign=4, preferrednvalign=4] enum LL : unsigned long long { val = 1 }; http://www.8sec.cc/archives/596 http://www.8sec.cc/archives/601 http://www.8sec.cc/archives/619 http://www.8sec.cc/cmseasy_addarticle.txt 1-10 #pragma once #include #include #include "natalie/env.hpp" #include "natalie/forward.hpp" #include "natalie/global_env.hpp" #include "natalie/macros.hpp" #include "natalie/value.hpp" namespace Natalie { struct ModuleValue : Value { ModuleValue(Env *); ModuleValue(Env *, const char *); ModuleValue(Env *, Type, ClassValue *); ModuleValue(Env *env, ClassValue *klass) : ModuleValue { env, Type::Module, klass } { } ModuleValue(ModuleValue &other) : Value { other.type(), other.klass() } , m_class_name { GC_STRDUP(other.m_class_name) } , m_superclass { other.m_superclass } { copy_hashmap(m_constants, other.m_constants); copy_hashmap(m_methods, other.m_methods); for (ModuleValue *module : const_cast(other).m_included_modules) { m_included_modules.push(module); } } Value *extend(Env *, size_t argc, Value **args); void extend_once(Env *, ModuleValue *); Value *include(Env *, size_t argc, Value **args); void include_once(Env *, ModuleValue *); Value *prepend(Env *, size_t argc, Value **args); void prepend_once(Env *, ModuleValue *); virtual Value *const_get(const char *) override; virtual Value *const_fetch(const char *) override; virtual Value *const_find(Env *, const char *, ConstLookupSearchMode = ConstLookupSearchMode::Strict, ConstLookupFailureMode = ConstLookupFailureMode::Raise) override; virtual Value *const_set(Env *, const char *, Value *) override; virtual void alias(Env *, const char *, const char *) override; Value *eval_body(Env *, Value *(*)(Env *, Value *)); const char *class_name() { return m_class_name; } void set_class_name(const char *name) { m_class_name = name ? GC_STRDUP(name) : nullptr; } ClassValue *superclass() { return m_superclass; } void set_superclass_DANGEROUSLY(ClassValue *superclass) { m_superclass = superclass; } Value *included_modules(Env *); Vector included_modules() { return m_included_modules; } bool does_include_module(Env *, Value *); virtual Value *cvar_get_or_null(Env *, const char *) override; virtual Value *cvar_set(Env *, const char *, Value *) override; Value *define_method(Env *, Value *, Block *); virtual void define_method(Env *, const char *, MethodFnPtr) override; virtual void define_method_with_block(Env *, const char *, Block *) override; virtual void undefine_method(Env *, const char *) override; void methods(Env *, ArrayValue *); Method *find_method(const char *, ModuleValue **); Method *find_method_without_undefined(const char *, ModuleValue **); Value *call_method(Env *, Value *, const char *, Value *, size_t, Value **, Block *); ArrayValue *ancestors(Env *); bool is_method_defined(Env *, Value *); Value *inspect(Env *); Value *name(Env *); Value *attr_reader(Env *, size_t, Value **); Value *attr_writer(Env *, size_t, Value **); Value *attr_accessor(Env *, size_t, Value **); static Value *attr_reader_block_fn(Env *, Value *, size_t, Value **, Block *); static Value *attr_writer_block_fn(Env *, Value *, size_t, Value **, Block *); Value *module_eval(Env *, Block *); Value *private_method(Env *, Value *method_name); Value *protected_method(Env *, Value *method_name); Value *public_method(Env *, Value *method_name); bool const_defined(Env *, Value *); Value *alias_method(Env *, Value *, Value *); bool eqeqeq(Env *env, Value *other) { return other->is_a(env, this); } protected: hashmap m_constants {}; const char *m_class_name { nullptr }; ClassValue *m_superclass { nullptr }; hashmap m_methods {}; hashmap m_class_vars {}; Vector m_included_modules {}; }; } 1-10 /* Project: SSBRenderer File: Geometry.cpp Copyright (c) 2015, Christoph "Youka" Spanknebel This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Geometry.hpp" #include #include "../utils/memory.hpp" #include #include #define DEG_TO_RAD(x) (x * M_PI / 180.0) namespace SSB{ std::vector points_to_path(const Points* points, double size){ std::vector result; if(size == 1.0) // Special rule: size-1 points become pixels/1x1 rectangles for(const Point& point : points->points) result.push_back({GUtils::PathSegment::Type::MOVE, point.x-0.5, point.y-0.5}), result.push_back({GUtils::PathSegment::Type::LINE, point.x+0.5, point.y-0.5}), result.push_back({GUtils::PathSegment::Type::LINE, point.x+0.5, point.y+0.5}), result.push_back({GUtils::PathSegment::Type::LINE, point.x-0.5, point.y+0.5}), result.push_back({GUtils::PathSegment::Type::CLOSE}); else for(const Point& point : points->points){ static constexpr const double pi_2 = M_PI * 2; const GUtils::PathSegment start = {GUtils::PathSegment::Type::MOVE, point.x - size / 2, point.y}; const std::vector curves = GUtils::path_by_arc(start.x, start.y, point.x, point.y, pi_2); result.push_back(start), result.insert(result.end(), curves.begin(), curves.end()), result.push_back({GUtils::PathSegment::Type::CLOSE}); } return result; } std::vector path_to_path(const Path* path){ std::vector result; result.reserve(path->segments.size()); for(auto segment_iter = path->segments.begin(), segment_iter_end = path->segments.end(); segment_iter != segment_iter_end; ++segment_iter){ const Path::Segment& segment = *segment_iter; switch(segment.type){ case Path::SegmentType::MOVE_TO: result.push_back({GUtils::PathSegment::Type::MOVE, segment.point.x, segment.point.y}); break; case Path::SegmentType::LINE_TO: result.push_back({GUtils::PathSegment::Type::LINE, segment.point.x, segment.point.y}); break; case Path::SegmentType::CURVE_TO: result.push_back({GUtils::PathSegment::Type::CURVE, segment.point.x, segment.point.y}); break; case Path::SegmentType::ARC_TO: if(!result.empty() && result.back().type != GUtils::PathSegment::Type::CLOSE && segment_iter+1 != segment_iter_end && (segment_iter+1)->type == Path::SegmentType::ARC_TO){ const GUtils::PathSegment& last_segment = result.back(); const Point& cur_point = segment.point; const std::vector curves = GUtils::path_by_arc(last_segment.x, last_segment.y, cur_point.x, cur_point.y, DEG_TO_RAD((++segment_iter)->angle)); result.insert(result.end(), curves.begin(), curves.end()); } break; case Path::SegmentType::CLOSE: result.push_back({GUtils::PathSegment::Type::CLOSE}); break; } } return result; } void path_deform(std::vector& path, const std::string& x_formula, const std::string& y_formula, double progress){ // Static resources struct ParserPack{ // Parsers + variables to reference mu::Parser x_parser, y_parser; double x, y, t; }; static stdex::Cache, std::shared_ptr, MAX_CACHE> parsers_cache; // Cache for reusable parsers static std::mutex mut; // Lock object for thread-safe usage of parsers // Make parsers usage thread-safe std::unique_lock lock(mut); // Pick parser(s) std::shared_ptr parser; std::pair formula(x_formula, y_formula); if(parsers_cache.contains(formula)) parser = parsers_cache.get(formula); else{ std::shared_ptr new_parser(new ParserPack); new_parser->x_parser.DefineVar("x", &parser->x), new_parser->x_parser.DefineVar("y", &parser->y), new_parser->x_parser.DefineVar("t", &parser->t), new_parser->x_parser.SetExpr(x_formula), new_parser->y_parser.DefineVar("x", &parser->x), new_parser->y_parser.DefineVar("y", &parser->y), new_parser->y_parser.DefineVar("t", &parser->t), new_parser->y_parser.SetExpr(y_formula), parsers_cache.add(formula, new_parser), parser = new_parser; } // Apply parsers to path points parser->t = progress; for(GUtils::PathSegment& segment : path) if(segment.type != GUtils::PathSegment::Type::CLOSE){ parser->x = segment.x, parser->y = segment.y; try{ segment.x = parser->x_parser.Eval(), segment.y = parser->y_parser.Eval(); }catch(...){} } } void get_2d_scale(unsigned src_width, unsigned src_height, unsigned dst_width, unsigned dst_height, double& scale_x, double& scale_y){ if(dst_width > 0 && dst_height > 0) scale_x = static_cast(src_width) / dst_width, scale_y = static_cast(src_height) / dst_height; else scale_x = scale_y = 0; } Point get_auto_pos(Align::Position align, Coord margin_h, Coord margin_v, unsigned frame_width, unsigned frame_height, double scale_x, double scale_y){ if(scale_x && scale_y) switch(align){ case Align::Position::LEFT_BOTTOM: return {margin_h * scale_x, frame_height - margin_v * scale_y}; case Align::Position::CENTER_BOTTOM: return {frame_width / 2.0, frame_height - margin_v * scale_y}; case Align::Position::RIGHT_BOTTOM: return {frame_width - margin_h * scale_x, frame_height - margin_v * scale_y}; case Align::Position::LEFT_MIDDLE: return {margin_h * scale_x, frame_height / 2.0}; case Align::Position::CENTER_MIDDLE: return {frame_width / 2.0, frame_height / 2.0}; case Align::Position::RIGHT_MIDDLE: return {frame_width - margin_h * scale_x, frame_height / 2.0}; case Align::Position::LEFT_TOP: return {margin_h * scale_x, margin_v * scale_y}; case Align::Position::CENTER_TOP: return {frame_width / 2.0, margin_v * scale_y}; case Align::Position::RIGHT_TOP: return {frame_width - margin_h * scale_x, margin_v * scale_y}; default: return {0, 0}; } else switch(align){ case Align::Position::LEFT_BOTTOM: return {margin_h, frame_height - margin_v}; case Align::Position::CENTER_BOTTOM: return {frame_width / 2.0, frame_height - margin_v}; case Align::Position::RIGHT_BOTTOM: return {frame_width - margin_h, frame_height - margin_v}; case Align::Position::LEFT_MIDDLE: return {margin_h, frame_height / 2.0}; case Align::Position::CENTER_MIDDLE: return {frame_width / 2.0, frame_height / 2.0}; case Align::Position::RIGHT_MIDDLE: return {frame_width - margin_h, frame_height / 2.0}; case Align::Position::LEFT_TOP: return {margin_h, margin_v}; case Align::Position::CENTER_TOP: return {frame_width / 2.0, margin_v}; case Align::Position::RIGHT_TOP: return {frame_width - margin_h, margin_v}; default: return {0, 0}; } } Point get_line_offset(Align::Position align, Direction::Mode direction, const GeometriesBlock& geometries, unsigned line_i){ // Output storage Point offset; // By geometries flow switch(direction){ case Direction::Mode::LTR: // Set horizontal offset switch(align){ case Align::Position::LEFT_BOTTOM: case Align::Position::LEFT_MIDDLE: case Align::Position::LEFT_TOP: offset.x = 0; break; case Align::Position::CENTER_BOTTOM: case Align::Position::CENTER_MIDDLE: case Align::Position::CENTER_TOP: offset.x = -geometries.lines[line_i].width / 2; break; case Align::Position::RIGHT_BOTTOM: case Align::Position::RIGHT_MIDDLE: case Align::Position::RIGHT_TOP: offset.x = -geometries.lines[line_i].width; break; } // Set vertical offset switch(align){ case Align::Position::LEFT_BOTTOM: case Align::Position::CENTER_BOTTOM: case Align::Position::RIGHT_BOTTOM: offset.y = -geometries.height; break; case Align::Position::LEFT_MIDDLE: case Align::Position::CENTER_MIDDLE: case Align::Position::RIGHT_MIDDLE: offset.y = -geometries.height / 2; break; case Align::Position::LEFT_TOP: case Align::Position::CENTER_TOP: case Align::Position::RIGHT_TOP: offset.y = 0; break; } break; case Direction::Mode::TTB: // Set horizontal offset switch(align){ case Align::Position::LEFT_BOTTOM: case Align::Position::LEFT_MIDDLE: case Align::Position::LEFT_TOP: offset.x = 0; break; case Align::Position::CENTER_BOTTOM: case Align::Position::CENTER_MIDDLE: case Align::Position::CENTER_TOP: offset.x = -geometries.width / 2; break; case Align::Position::RIGHT_BOTTOM: case Align::Position::RIGHT_MIDDLE: case Align::Position::RIGHT_TOP: offset.x = -geometries.width; break; } // Set vertical offset switch(align){ case Align::Position::LEFT_BOTTOM: case Align::Position::CENTER_BOTTOM: case Align::Position::RIGHT_BOTTOM: offset.y = -geometries.lines[line_i].height; break; case Align::Position::LEFT_MIDDLE: case Align::Position::CENTER_MIDDLE: case Align::Position::RIGHT_MIDDLE: offset.y = -geometries.lines[line_i].height / 2; break; case Align::Position::LEFT_TOP: case Align::Position::CENTER_TOP: case Align::Position::RIGHT_TOP: offset.y = 0; break; } break; } // Return whatever was set return offset; } } #include using namespace std; // Return a integer of integers having all the nodes in both the BSTs in a sorted order. void traversal(Node *node, queue &q) { if (node->left) traversal(node->left, q); q.push(node->data); if (node->right) traversal(node->right, q); } vector merge(Node *root1, Node *root2) { queue q1, q2; vector vec; traversal(root1, q1); traversal(root2, q2); while (!q1.empty() || !q2.empty()) { if (q1.empty()) { vec.push_back(q2.front()); q2.pop(); continue; } if (q2.empty()) { vec.push_back(q1.front()); q1.pop(); continue; } if (q1.front() < q2.front()) { vec.push_back(q1.front()); q1.pop(); } else { vec.push_back(q2.front()); q2.pop(); } } return vec; } 0 #include "tgbot/net/BoostHttpOnlySslClientAlive.h" #include "tgbot/net/SocketSslData.h" #include "tgbot/tools/BoostTools.h" #include #include #include #include #include #include #include using namespace std; using namespace boost::asio; using namespace boost::asio::ip; using namespace BoostTools; namespace TgBot { BoostHttpOnlySslClientAlive::BoostHttpOnlySslClientAlive() : _httpParser(), socket_data_(new SocketSslData()) {} BoostHttpOnlySslClientAlive::~BoostHttpOnlySslClientAlive() {} string BoostHttpOnlySslClientAlive::makeRequest(const Url& url, const vector& args) const { const static char DELIMETER[] = "\r\n\r\n"; const static uint32_t HEADER_TIMEOUT = 5; //5 seconds timeout to get HTTP header const static uint32_t DATA_TIMEOUT = 10; //10 seconds timeout to get HTTP data start_work_socket_(url.host); string requestText = _httpParser.generateRequest(url, args, true); boost::asio::streambuf b(1024 * 1024); boost::system::error_code error; write(socket_data_->sock(), buffer(requestText.c_str(), requestText.length()), error); if (error) { //try reopen socket start_work_socket_(url.host); //this throw exception if error write(socket_data_->sock(), buffer(requestText.c_str(), requestText.length())); } read_until_timeout(socket_data_->service(), socket_data_->sock(), b, DELIMETER, HEADER_TIMEOUT, error); if (error) { //in some cases it is possible to write to socket but not read from it //(if "Connection: close" in http and we continue use socket), and I don't know the //behaviour of the server: Is it close connection or just stop send response messages? //so try reopen socket and do write and read again start_work_socket_(url.host); //throw exception if error write(socket_data_->sock(), buffer(requestText.c_str(), requestText.length())); //remove characters that read_until_timeout() write to buffer b.consume(b.size() + 1); //throw exception if error read_until_timeout(socket_data_->service(), socket_data_->sock(), b, DELIMETER, HEADER_TIMEOUT); } std::istream is(&b); std::string line; uint16_t content_length = 0; bool close_socket = true; bool found_connection = false; while ((0 == content_length || !found_connection) && std::getline(is, line)) { const static char CONTENT_LENGTH[] = "content-length:"; const static char CONNECTION[] = "connection:"; const static char KEEP_ALIVE[] = "keep-alive"; boost::to_lower(line); if (0 == content_length) { auto pos = line.find(CONTENT_LENGTH); if (std::string::npos != pos) { auto size_str = line.substr(pos + sizeof(CONTENT_LENGTH)); boost::trim(size_str); content_length = boost::lexical_cast(size_str); continue; } } if (!found_connection) { auto pos = line.find(CONNECTION); if (std::string::npos != pos) { found_connection = true; pos = line.find(KEEP_ALIVE, pos + sizeof(CONNECTION)); close_socket = std::string::npos == pos; } } } if (0 == content_length) { throw std::logic_error("Content-Length not found in header or it is 0"); } std::string remain{ (std::istreambuf_iterator(&b)), std::istreambuf_iterator() }; auto delimeter_pos = remain.find(DELIMETER); if (std::string::npos == delimeter_pos) throw std::logic_error("std::string::npos == delimeter_pos"); //must never happened auto response = remain.substr(delimeter_pos + sizeof(DELIMETER) - 1); if (response.size() < content_length) { read_timeout(socket_data_->service(), socket_data_->sock(), b, boost::asio::transfer_exactly(content_length - response.size()), DATA_TIMEOUT); response += std::string{ (std::istreambuf_iterator(&b)), std::istreambuf_iterator() }; } end_work_socket_(close_socket); //can occurred when server send some invalid data and //read_until_timeout read a lot of data if (response.size() > content_length) { response.resize(content_length); } return response; } void BoostHttpOnlySslClientAlive::start_work_socket_(const std::string& host) const { socket_data_->start_work(host); } void BoostHttpOnlySslClientAlive::end_work_socket_(bool close_socket) const { socket_data_->end_work(close_socket); } } 0 // // key idea is to answe each query trying to find a cycle // through firstColumn->firstColumn transitions only // to update we obtain which range in first column do I change // and its new firstColumn destination // *we update those cells that now choose me, and those that stop // choosing me // if you have a super quick query, and a slow update // try to hit a middle point #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define loop(i,a,b) for(int i = a; i < b; ++i) #define loopi(i,a,b) for(int i = a; i <= b; ++i) #define MOD(a,b) (a%b + b)%b const int maxR = 2005, maxC = 2005; int r, c; int mat[maxR][maxC]; struct pos{ int row, col; pos(int i, int j){row = i; col = j;} pos(){row = 0; col = 0;} }; pos current; bool operator > (const pos &a, const pos &b){ return mat[a.row][a.col] > mat[b.row][b.col]; } bool operator < (const pos &a, const pos &b){ return mat[a.row][a.col] < mat[b.row][b.col]; } pos move(pos p){ int nextCol = MOD(p.col+1, c); pos next = pos( MOD(p.row-1, r), nextCol ); next = max(next, pos( MOD(p.row , r), nextCol)); next = max(next, pos( MOD(p.row+1, r), nextCol)); return next; } //nextRow[i] stores the next row position (i,0) arrives when taking c steps int nextRow[maxR]; void precalculo(){ loop(i, 0, r){ pos aux = pos(i, 0); loop(j, 0, c) aux = move(aux); nextRow[i] = aux.row; } } // =================== Para la query struct cycleInfo{ int stepsToCycle, cycleLength, startingRow; cycleInfo(int a, int b, int c){stepsToCycle = a; cycleLength = b; startingRow = c;} }; //we return the info about the first cycle we encounter starting from position // (row, 0) cycleInfo findCycle(int row){ int visited[maxR]; fill(visited, visited + maxR, -1); int indxVisited = 0; visited[row] = indxVisited; while(visited[ nextRow[row] ] == -1){ row = nextRow[row]; visited[row] = ++indxVisited; } row = nextRow[row]; // return cycleInfo(visited[row]*c, (indxVisited+1 - visited[row])*c, row); } void query(int steps){ //me muevo a la primera columna while(steps>0 && current.col != 0){ current = move(current); --steps; } if(steps == 0) return; //we detect cycle cycleInfo ci = findCycle(current.row); if(ci.stepsToCycle <= steps){ current = pos(ci.startingRow, 0); steps -= ci.stepsToCycle; steps %= ci.cycleLength; } while(steps >= c){ current = pos(nextRow[current.row], 0); steps-=c; } while(steps){ current = move(current); --steps; } } void update(pos p, int newVal){ p.col = MOD(p.col, c); p.row = MOD(p.row, r); if(newVal > 0) mat[p.row][p.col] = newVal; //we obtain the range we have to update //t for top, b for bottom, col for column int t, b, col; col = p.col; t = b = p.row; do{ int newT = t, newB = b; //we update bottom of the range int mayores2 = max(mat[MOD(b-1,r)][col], mat[MOD(b-2, r)][col]); if( mat[MOD(b,r)][col] > mayores2) --newB; else{ int mis2 = b==t? mat[MOD(b,r)][col] : max(mat[MOD(b,r)][col], mat[MOD(b+1,r)][col]); if(mis2 < mat[MOD(b-1, r)][col]) ++newB; } //We update top of the range mayores2 = max(mat[MOD(t+1,r)][col], mat[MOD(t+2, r)][col]); if( mat[MOD(t,r)][col] > mayores2) ++newT; else{ int mis2 = b==t? mat[MOD(t,r)][col] : max(mat[MOD(t,r)][col], mat[MOD(t-1,r)][col]); if(mis2 < mat[MOD(t+1, r)][col]) --newT; } col = MOD(col-1, c); if(newT < newB) return; t = newT; b = newB; }while(col != 0); //we obtain the new row in column 1 to which the range is going to arrive while(p.col != 0) p = move(p); //we update the range if(t-b >= r-1){b = 0; t = r-1;} loopi(i, b, t) nextRow[MOD(i, r)] = p.row; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); current = pos(0,0); cin>>r>>c; loop(i, 0, r) loop(j, 0, c) cin>>mat[i][j]; precalculo(); int m; cin>>m; loop(i, 0, m){ string event; cin>>event; if(event == "move"){ int steps; cin>>steps; query(steps); cout<>row>>col>>newVal; --row; --col; update( pos(row, col), newVal); update( pos(row+1, col), -1); update( pos(row-1, col), -1); update( pos(row-2, col), -1); update( pos(row+2, col), -1); } } return 0; } src/main/cpp/inverted_penguin/terms/LowerCaseMapper.hpp #ifndef __INVERTED_PENGUIN__TERMS__LOWERCASEMAPPER_HPP__ #define __INVERTED_PENGUIN__TERMS__LOWERCASEMAPPER_HPP__ #include #include #include #include #include namespace inverted_penguin { namespace terms { class LowerCaseMapper : public TermStreamModifier { public: static constexpr bool isStateful() { return false; } template Term next(TermStream& stream) const { return this->apply(stream.self().next()); } Term apply(const Term& t) const { if (t.isEmpty()) { return t; } else { std::vector lowered; lowered.reserve(t.text.size()); transformUtf8Sequence(t.text.begin(), t.text.end(), std::back_inserter(lowered), [](uint32_t c) { return toLowerCase(c); }); return Term(std::string(lowered.begin(), lowered.end()), t.position); } } bool reset() { return true; } }; typedef DynamicTermStreamModifierWrapper DynamicLowerCaseMapper; } } #endif oliverlee/biketest #include #include #include #include #include "bicycle/whipple.h" #include "lqr.h" #include "kalman.h" #include "parameters.h" namespace { const double fs = 200; // sample rate [Hz] const double dt = 1.0/fs; // sample time [s] const double v0 = 4.0; // forward speed [m/s] const size_t N = 1000; // length of simulation in samples const size_t n = 100; // length of horizon in samples model::BicycleWhipple::state_t x( (model::BicycleWhipple::state_t() << 0, 5, 5, 0, 0).finished() * constants::as_radians); std::array system_state; std::array system_state_estimate; std::random_device rd; // used only to seed rng } // namespace int main(int argc, char* argv[]) { (void)argc; (void)argv; std::mt19937 gen(rd()); std::normal_distribution<> rn0(0, parameters::defaultvalue::kalman::R(0, 0)); std::normal_distribution<> rn1(0, parameters::defaultvalue::kalman::R(1, 1)); model::BicycleWhipple bicycle(v0, dt); controller::Lqr lqr(bicycle, controller::Lqr::state_cost_t::Identity(), 0.1 * controller::Lqr::input_cost_t::Identity(), model::BicycleWhipple::state_t::Zero(), n); observer::Kalman kalman(bicycle, model::BicycleWhipple::state_t::Zero(), // starts at zero state parameters::defaultvalue::kalman::Q(dt), parameters::defaultvalue::kalman::R, std::pow(x[1]/2, 2) * model::BicycleWhipple::state_matrix_t::Identity()); std::cout << "initial state: [" << x.transpose() * constants::as_degrees << "]' deg" << std::endl; std::cout << "initial state estimate: [" << kalman.x().transpose() * constants::as_degrees << "]' deg" << std::endl; std::cout << std::endl << "simulating with observer and controller..." << std::endl; auto it_x = system_state.begin(); auto it_xh = system_state_estimate.begin(); *it_x++ = x; *it_xh++ = kalman.x(); auto start = std::chrono::system_clock::now(); for (; it_x != system_state.end(); ++it_x, ++it_xh) { // compute control law auto u = lqr.control_calculate(kalman.x()); // system simulate x = bicycle.update_state(x, u); // measure output with noise auto y = bicycle.calculate_output(x); auto z = y; z(0) += rn0(gen); z(1) += rn1(gen); // observer time/measurement update kalman.time_update(u); kalman.measurement_update(z); //auto error = x - kalman.x(); //std::cout << error.transpose() * constants::as_degrees << std::endl; *it_x = x; *it_xh = kalman.x(); } auto stop = std::chrono::system_clock::now(); auto duration = stop - start; std::cout << "duration for simulation: " << std::chrono::duration_cast(duration).count() << " ms" << std::endl; std::cout << "time per iteration: " << std::chrono::duration_cast(duration/N).count() << " us" << std::endl << std::endl; std::cout << "state at end of simulation (" << N << " steps @ " << fs << " Hz)" << std::endl; std::cout << "final state: [" << system_state.back().transpose() * constants::as_degrees << "]' deg" << std::endl; std::cout << "final state estimate: [" << system_state_estimate.back().transpose() * constants::as_degrees << "]'" << std::endl; return EXIT_SUCCESS; } #include #include #include "mspass/utility/Metadata.h" #include "mspass/utility/MsPASSError.h" #include "mspass/utility/utility.h" #include "mspass/seismic/CoreTimeSeries.h" #include "mspass/algorithms/deconvolution/MultiTaperXcorDecon.h" #include "mspass/algorithms/deconvolution/dpss.h" #include "mspass/algorithms/deconvolution/common_multitaper.h" namespace mspass::algorithms::deconvolution { using namespace std; using namespace mspass::seismic; using namespace mspass::utility; MultiTaperXcorDecon::MultiTaperXcorDecon(const Metadata &md) : FFTDeconOperator(md) { try { this->read_metadata(md,false); } catch(...) { throw; }; /* assume tapers matrix is created in read_metadata. We call reserve on the three stl vector containers for efficiency. */ data.reserve(nfft); wavelet.reserve(nfft); noise.reserve(nfft); } MultiTaperXcorDecon::MultiTaperXcorDecon(const MultiTaperXcorDecon &parent) : FFTDeconOperator(parent), tapers(parent.tapers) { /* wavelet and data vectors are copied in ScalarDecon copy constructor. This method needs a noise vector so we have explicitly copy it here. */ noise=parent.noise; /* ditto for shaping wavelet vector */ shapingwavelet=parent.shapingwavelet; /* multitaper parameters to copy */ nw=parent.nw; taperlen=parent.taperlen; damp=parent.damp; } int MultiTaperXcorDecon::read_metadata(const Metadata &md,bool refresh) { try { const string base_error("MultiTaperXcorDecon::read_metadata method: "); int i,j,ii; /* We use these temporaries to test for changes when we are not initializing */ int nfft_old,nseq_old, tl_old; double nw_old; if(refresh) { nfft_old=nfft; nseq_old=nseq; tl_old=taperlen; nw_old=nw; } taperlen=ComputeTaperLength(md); int nfft_from_win=ComputeFFTLength(md); //window based nfft always overrides that extracted directly from md */ if(nfft_from_win!=nfft) { this->change_size(nfft_from_win); } damp=md.get_double("damping_factor"); nw=md.get_double("time_bandwidth_product"); /* Wang originally had this as nw*2-2 but Park and Levin say the maximum is nw*2-1 which we use here. P&L papers all use mw=2.5 with K(seql here) of 3 */ //seql=md.get_int("lower_dpss"); nseq=md.get_int("number_tapers"); int nseqtest=static_cast(2.0*nw); if(nseq>nseqtest || (nseq<1)) { cerr << base_error << "(WARNING) Illegal value for number_of tapers parameter="<nfft) throw MsPASSError(base_error + "Illegal input parameters. Vector of data received is larger than the fft buffer space allocated", ErrorSeverity::Invalid); /* The tapered data are stored in this vector of arrays */ int i,j; vector tdata; int ntapers=tapers.rows(); tdata.reserve(ntapers); for(i=0; i tdata; tdata=taper_data(data); /* Apply fft to each tapered data vector */ for(i=0; i wdata; wdata=taper_data(wavelet); for(i=0; i ndata; ndata=taper_data(noise); for(i=0; i noise_spectrum(ndata[0].abs()); for(i=1; i nwork(ndata[i].abs()); for(j=0; j::iterator nptr; double scale=damp/(static_cast(nseq)); //DEBUG //cerr << "scale computed from damp="<df(0.01); //dt for test data vector specwork(rf_fft.abs()); for(i=0;i(i)<<" "<(i)<<" "<0) { for(int k=sample_shift; k>0; k--) result.push_back(rf_fft[nfft-k].real()); for(int k=0; k ao; ao.reserve(nfft); for(int k=0; kshapingwavelet.sample_interval(); /* t0 is time of sample zero - hence normally negative*/ /* Old API result.t0=dt*(-(double)i0); result.dt=dt; result.live=true; result.tref=TimeReferenceType::Relative; result.ns=nfft; */ result.set_t0(dt*(-(double)i0)); result.set_dt(dt); result.set_live(); result.set_tref(TimeReferenceType::Relative); result.set_npts(nfft); for(int k=0;kshapingwavelet.sample_interval(); return (this->FFTDeconOperator::FourierInverse(this->winv, *shapingwavelet.wavelet(),dt,t0parent)); } catch(...) { throw; }; } CoreTimeSeries MultiTaperXcorDecon::inverse_wavelet() { try{ return this->inverse_wavelet(0.0); }catch(...){throw;}; } Metadata MultiTaperXcorDecon::QCMetrics() { try { throw MsPASSError("MultiTaperXcorDecon::QCMetrics method not yet implemented", ErrorSeverity::Invalid); } catch(...) { throw; }; } } //End namespace CrazyCanvas/Source/ECS/Systems/Misc/DestructionSystem.cpp #include "ECS/Systems/Misc/DestructionSystem.h" #include "ECS/Components/Misc/DestructionComponent.h" #include "ECS/ECSCore.h" DestructionSystem::DestructionSystem() { } DestructionSystem::~DestructionSystem() { } bool DestructionSystem::Init() { using namespace LambdaEngine; // Register system { SystemRegistration systemReg = {}; systemReg.SubscriberRegistration.EntitySubscriptionRegistrations = { { .pSubscriber = &m_DestructionEntities, .ComponentAccesses = { {RW, DestructionComponent::Type()} }, } }; systemReg.Phase = 1u; RegisterSystem(TYPE_NAME(DestructionSystem), systemReg); } return true; } void DestructionSystem::Tick(LambdaEngine::Timestamp deltaTime) { using namespace LambdaEngine; ECSCore* pECS = ECSCore::GetInstance(); ComponentArray* pDestructionComponents = pECS->GetComponentArray(); for (Entity entity : m_DestructionEntities) { DestructionComponent& destructionComp = pDestructionComponents->GetData(entity); if (destructionComp.Active) { destructionComp.TimeLeft -= float(deltaTime.AsSeconds()); if (destructionComp.TimeLeft <= 0.0f) { // Destroy Entity pECS->RemoveEntity(entity); } } } } /*** * Author: zephyr * Date: 2020-12-22 15:24:45 * LastEditors: zephyr * LastEditTime: 2020-12-22 15:27:07 * FilePath: \undefinedd:\GithubWorkSpace\LeetCodeSolution\tree\429_N-ary_Tree_Level_Order_Traversal.cpp */ #include #include #include /* // Definition for a Node. class Node { public: int val; vector children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector _children) { val = _val; children = _children; } }; */ vector> levelOrder(Node* root) { vector> res; queue qnode; if(!root) return res; qnode.push(root); while(!qnode.empty()) { int size = qnode.size(); vector temp; for(int i = 0; i < size; i++) { auto node = qnode.front(); qnode.pop(); temp.emplace_back(node->val); for(auto c : node->children) { if(!c) continue; qnode.push(c); } } res.emplace_back(temp); } return res; }1-10 /* file: kmeans_init_input_types.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * 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. *******************************************************************************/ /* //++ // Implementation of kmeans classes. //-- */ #include "algorithms/kmeans/kmeans_init_types.h" #include "daal_defines.h" #include "kmeans_init_impl.h" #include "row_merged_numeric_table.h" #include "memory_block.h" #include "daal_strings.h" using namespace daal::data_management; using namespace daal::services; namespace daal { namespace algorithms { namespace kmeans { namespace init { namespace interface1 { Input::Input() : InputIface(lastInputId + 1) {} Input::Input(size_t nElements): InputIface(nElements) {}; /** * Returns input objects for computing initial clusters for the K-Means algorithm * \param[in] id Identifier of the input object * \return %Input object that corresponds to the given identifier */ NumericTablePtr Input::get(InputId id) const { return staticPointerCast(Argument::get(id)); } /** * Sets an input object for computing initial clusters for the K-Means algorithm * \param[in] id Identifier of the input object * \param[in] ptr Pointer to the input object */ void Input::set(InputId id, const NumericTablePtr &ptr) { Argument::set(id, ptr); } /** * Returns the number of features in the Input data table * \return Number of features in the Input data table */ size_t Input::getNumberOfFeatures() const { NumericTablePtr inTable = get(data); return inTable->getNumberOfColumns(); } static bool isCSRMethod(int method) { return (method == kmeans::init::deterministicCSR || method == kmeans::init::randomCSR || method == kmeans::init::plusPlusCSR || method == kmeans::init::parallelPlusCSR); } /** * Checks an input object for computing initial clusters for the K-Means algorithm * \param[in] par %Input object * \param[in] method Method of the algorithm */ services::Status Input::check(const daal::algorithms::Parameter *parameter, int method) const { if(isParallelPlusMethod(method)) { //check parallel plus method parameters const daal::algorithms::kmeans::init::Parameter* prm = (const daal::algorithms::kmeans::init::Parameter*)(parameter); DAAL_CHECK_EX(prm->oversamplingFactor > 0, ErrorIncorrectParameter, ParameterName, oversamplingFactorStr()); DAAL_CHECK_EX(prm->nRounds > 0, ErrorIncorrectParameter, ParameterName, nRoundsStr()); size_t L(prm->oversamplingFactor*prm->nClusters); if(L*prm->nRounds <= prm->nClusters) { return services::Status(services::Error::create(ErrorIncorrectParameter, ParameterName, nRoundsStr())); } } services::Status s; if(isCSRMethod(method)) { const int expectedLayout = (int)NumericTableIface::csrArray; s = checkNumericTable(get(data).get(), dataStr(), 0, expectedLayout); } else { s = checkNumericTable(get(data).get(), dataStr()); } return s; } DistributedStep2LocalPlusPlusInput::DistributedStep2LocalPlusPlusInput() : Input(lastDistributedStep2LocalPlusPlusInputId + 1){} DistributedStep2LocalPlusPlusInput::DistributedStep2LocalPlusPlusInput(const DistributedStep2LocalPlusPlusInput& o) { for(size_t i = 0; i < size(); ++i) Argument::set(i, o.Argument::get(i)); } NumericTablePtr DistributedStep2LocalPlusPlusInput::get(InputId id) const { return Input::get(id); } void DistributedStep2LocalPlusPlusInput::set(InputId id, const NumericTablePtr &ptr) { Input::set(id, ptr); } DataCollectionPtr DistributedStep2LocalPlusPlusInput::get(DistributedLocalPlusPlusInputDataId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep2LocalPlusPlusInput::set(DistributedLocalPlusPlusInputDataId id, const DataCollectionPtr &ptr) { Argument::set(id, ptr); } services::Status DistributedStep2LocalPlusPlusInput::check(const daal::algorithms::Parameter *par, int method) const { services::Status s = Input::check(par, method); if(!s) return s; const auto nFeatures = get(data)->getNumberOfColumns(); const DistributedStep2LocalPlusPlusParameter* stepPar = (const DistributedStep2LocalPlusPlusParameter*)(par); const size_t nRows = (stepPar->firstIteration || !(isParallelPlusMethod(method)) ? 1 : size_t(stepPar->oversamplingFactor*stepPar->nClusters)); s = checkNumericTable(get(inputOfStep2).get(), inputOfStep2Str(), (int)packed_mask, 0, nFeatures, nRows); if(!stepPar->firstIteration) s = internal::checkLocalData(get(internalInput).get(), stepPar, internalInputStr(), get(data).get(), isParallelPlusMethod(method)); return s; } NumericTablePtr DistributedStep2LocalPlusPlusInput::get(DistributedStep2LocalPlusPlusInputId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep2LocalPlusPlusInput::set(DistributedStep2LocalPlusPlusInputId id, const NumericTablePtr &ptr) { Argument::set(id, ptr); } DistributedStep3MasterPlusPlusInput::DistributedStep3MasterPlusPlusInput() : Input(lastDistributedStep3MasterPlusPlusInputId + 1) { set(inputOfStep3FromStep2, KeyValueDataCollectionPtr(new KeyValueDataCollection())); } DistributedStep3MasterPlusPlusInput::DistributedStep3MasterPlusPlusInput(const DistributedStep3MasterPlusPlusInput& o) { set(inputOfStep3FromStep2, o.get(inputOfStep3FromStep2)); } KeyValueDataCollectionPtr DistributedStep3MasterPlusPlusInput::get(DistributedStep3MasterPlusPlusInputId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep3MasterPlusPlusInput::set(DistributedStep3MasterPlusPlusInputId id, const KeyValueDataCollectionPtr &ptr) { Input::set(id, ptr); } void DistributedStep3MasterPlusPlusInput::add(DistributedStep3MasterPlusPlusInputId id, size_t key, const NumericTablePtr &ptr) { KeyValueDataCollectionPtr pColl = get(inputOfStep3FromStep2); (*pColl)[key] = ptr; } services::Status DistributedStep3MasterPlusPlusInput::check(const daal::algorithms::Parameter *par, int method) const { services::Status s = Input::check(par, method); if(!s) return s; KeyValueDataCollectionPtr pColl = get(inputOfStep3FromStep2); DAAL_CHECK_EX(pColl.get(), ErrorNullInputDataCollection, ArgumentName, inputOfStep3FromStep2Str()); DAAL_CHECK_EX(pColl->size() > 0, ErrorIncorrectNumberOfElementsInInputCollection, ArgumentName, inputOfStep3FromStep2Str()); for(size_t i = 0; i < pColl->size(); ++i) { SerializationIfacePtr pVal = pColl->getValueByIndex(i); DAAL_CHECK_EX(pVal.get(), ErrorNullInput, ArgumentName, inputOfStep3FromStep2Str()); NumericTablePtr pTbl = NumericTable::cast(pVal); s |= checkNumericTable(pTbl.get(), inputOfStep3FromStep2Str(), (int)packed_mask, 0, 1, 1); } return s; } DistributedStep4LocalPlusPlusInput::DistributedStep4LocalPlusPlusInput() : Input(lastDistributedStep4LocalPlusPlusInputId + 1){} DistributedStep4LocalPlusPlusInput::DistributedStep4LocalPlusPlusInput(const DistributedStep4LocalPlusPlusInput& o) { for(size_t i = 0; i < size(); ++i) Argument::set(i, o.Argument::get(i)); } NumericTablePtr DistributedStep4LocalPlusPlusInput::get(InputId id) const { return Input::get(id); } void DistributedStep4LocalPlusPlusInput::set(InputId id, const NumericTablePtr &ptr) { Input::set(id, ptr); } DataCollectionPtr DistributedStep4LocalPlusPlusInput::get(DistributedLocalPlusPlusInputDataId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep4LocalPlusPlusInput::set(DistributedLocalPlusPlusInputDataId id, const DataCollectionPtr &ptr) { Argument::set(id, ptr); } NumericTablePtr DistributedStep4LocalPlusPlusInput::get(DistributedStep4LocalPlusPlusInputId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep4LocalPlusPlusInput::set(DistributedStep4LocalPlusPlusInputId id, const NumericTablePtr &ptr) { Argument::set(id, ptr); } services::Status DistributedStep4LocalPlusPlusInput::check(const daal::algorithms::Parameter *par, int method) const { services::Status s = Input::check(par, method); if(!s) return s; const Parameter* stepPar = (const Parameter*)(par); s = internal::checkLocalData(get(internalInput).get(), stepPar, internalInputStr(), get(data).get(), isParallelPlusMethod(method)); s |= checkNumericTable(get(inputOfStep4FromStep3).get(), inputOfStep4FromStep3Str(), (int)packed_mask, 0, 0, 1); return s; } DistributedStep5MasterPlusPlusInput::DistributedStep5MasterPlusPlusInput() : Input(lastDistributedStep5MasterPlusPlusInputDataId + 1) { set(inputCentroids, DataCollectionPtr(new DataCollection())); set(inputOfStep5FromStep2, DataCollectionPtr(new DataCollection())); } DistributedStep5MasterPlusPlusInput::DistributedStep5MasterPlusPlusInput(const DistributedStep5MasterPlusPlusInput& o) { for(size_t i = 0; i < size(); ++i) Argument::set(i, o.Argument::get(i)); } DataCollectionPtr DistributedStep5MasterPlusPlusInput::get(DistributedStep5MasterPlusPlusInputId id) const { return staticPointerCast(Argument::get(id)); } void DistributedStep5MasterPlusPlusInput::set(DistributedStep5MasterPlusPlusInputId id, const DataCollectionPtr &ptr) { daal::algorithms::Input::set(id, ptr); } SerializationIfacePtr DistributedStep5MasterPlusPlusInput::get(DistributedStep5MasterPlusPlusInputDataId id) const { return Argument::get(id); } void DistributedStep5MasterPlusPlusInput::set(DistributedStep5MasterPlusPlusInputDataId id, const SerializationIfacePtr &ptr) { Argument::set(id, ptr); } void DistributedStep5MasterPlusPlusInput::add(DistributedStep5MasterPlusPlusInputId id, const NumericTablePtr &ptr) { DataCollectionPtr pColl = get(id); if(pColl.get()) pColl->push_back(ptr); } services::Status DistributedStep5MasterPlusPlusInput::check(const daal::algorithms::Parameter *par, int method) const { services::Status s = Input::check(par, method); if(!s) return s; const Parameter* stepPar = (const Parameter*)(par); const size_t nMaxCandidates = size_t(stepPar->oversamplingFactor*stepPar->nClusters)*stepPar->nRounds + 1; for(size_t i = 0; i < 2; ++i) { size_t nCandidates = 0; const auto pArg = Argument::get(i ? inputOfStep5FromStep2 : inputCentroids); const char* argName = (i ? inputOfStep5FromStep2Str() : inputCentroidsStr()); DAAL_CHECK_EX(pArg.get(), ErrorNullInput, ArgumentName, argName); DataCollectionPtr pColl = DataCollection::cast(pArg); DAAL_CHECK_EX(pColl.get(), ErrorNullInputDataCollection, ArgumentName, argName); DAAL_CHECK_EX(pColl->size() > 0, ErrorIncorrectNumberOfElementsInInputCollection, ArgumentName, argName); for(size_t j = 0; j < pColl->size(); ++j) { const auto pItem = (*pColl)[j]; DAAL_CHECK_EX(pItem.get(), ErrorNullInputNumericTable, ArgumentName, argName); const NumericTablePtr pTbl = NumericTable::cast(pItem); DAAL_CHECK_EX(pTbl.get(), ErrorIncorrectItemInDataCollection, ArgumentName, argName); s |= checkNumericTable(pTbl.get(), argName, (int)packed_mask, 0, i ? nMaxCandidates : 0, i ? 1 : 0); if(!s) return s; if(i == 0) nCandidates += pTbl->getNumberOfRows(); } if(i == 0) DAAL_CHECK(nCandidates == nMaxCandidates, ErrorIncorrectTotalNumberOfPartialClusters); } const auto pArg = Argument::get(inputOfStep5FromStep3); DAAL_CHECK_EX(pArg.get(), ErrorNullInput, ArgumentName, inputOfStep5FromStep3Str()); MemoryBlockPtr pMemBlock = MemoryBlock::cast(pArg); DAAL_CHECK_EX(pMemBlock.get(), ErrorIncorrectItemInDataCollection, ArgumentName, rngStateStr()); return s; } } // namespace interface1 namespace internal { services::Status checkLocalData(const DataCollection* pInput, const Parameter* par, const char* dataName, const NumericTable* pData, bool bParallelPlus) { const auto nRows = pData->getNumberOfRows(); DAAL_CHECK_EX(pInput != nullptr, ErrorIncorrectInputNumericTable, ArgumentName, dataName); //TODO DAAL_CHECK_EX(pInput->size() == (bParallelPlus ? localDataSize : localDataSize - 1), ErrorIncorrectDataCollectionSize, ArgumentName, dataName); const auto pClosestClusterDistance = NumericTable::cast(pInput->get(closestClusterDistance)); services::Status s = checkNumericTable(pClosestClusterDistance.get(), closestClusterDistanceStr(), (int)packed_mask, 0, nRows, 1); const auto pClosestCluster = NumericTable::cast(pInput->get(closestCluster)); s |= checkNumericTable(pClosestCluster.get(), closestClusterStr(), (int)packed_mask, 0, nRows, 1); const auto pNClusters = NumericTable::cast(pInput->get(numberOfClusters)); s |= checkNumericTable(pNClusters.get(), numberOfClustersStr(), (int)packed_mask, 0, 1, 1); if(!bParallelPlus) return s; const size_t nMaxCandidates = size_t(par->oversamplingFactor*par->nClusters)*par->nRounds + 1; const auto pRating = NumericTable::cast(pInput->get(candidateRating)); s |= checkNumericTable(pRating.get(), candidateRatingStr(), (int)packed_mask, 0, nMaxCandidates, 1); return s; } }//internal } // namespace init } // namespace kmeans } // namespace algorithm } // namespace daal embrosyn/ja2-stracciatella-mpslsm #include "Text.h" #ifdef WITH_UNITTESTS #include "gtest/gtest.h" #endif /* ****************************************************************************************************** ** IMPORTANT TRANSLATION NOTES ** ****************************************************************************************************** GENERAL TOPWARE INSTRUCTIONS - Always be aware that German strings should be of equal or shorter length than the English equivalent. I know that this is difficult to do on many occasions due to the nature of the German language when compared to English. By doing so, this will greatly reduce the amount of work on both sides. In most cases (but not all), JA2 interfaces were designed with just enough space to fit the English word. The general rule is if the string is very short (less than 10 characters), then it's short because of interface limitations. On the other hand, full sentences commonly have little limitations for length. Strings in between are a little dicey. - Never translate a string to appear on multiple lines. All strings L"This is a really long string...", must fit on a single line no matter how long the string is. All strings start with L" and end with ", - Never remove any extra spaces in strings. In addition, all strings containing multiple sentences only have one space after a period, which is different than standard typing convention. Never modify sections of strings contain combinations of % characters. These are special format characters and are always used in conjunction with other characters. For example, %ls means string, and is commonly used for names, locations, items, etc. %d is used for numbers. %c%d is a character and a number (such as A9). %% is how a single % character is built. There are countless types, but strings containing these special characters are usually commented to explain what they mean. If it isn't commented, then if you can't figure out the context, then feel free to ask SirTech. - Comments are always started with // Anything following these two characters on the same line are considered to be comments. Do not translate comments. Comments are always applied to the following string(s) on the next line(s), unless the comment is on the same line as a string. - All new comments made by SirTech will use "//@@@ comment" (without the quotes) notation. By searching for @@@ everytime you recieve a new version, it will simplify your task and identify special instructions. Commonly, these types of comments will be used to ask you to abbreviate a string. Please leave the comments intact, and SirTech will remove them once the translation for that particular area is resolved. - If you have a problem or question with translating certain strings, please use "//!!! comment" (without the quotes). The syntax is important, and should be identical to the comments used with @@@ symbols. SirTech will search for !!! to look for Topware problems and questions. This is a more efficient method than detailing questions in email, so try to do this whenever possible. FAST HELP TEXT -- Explains how the syntax of fast help text works. ************** 1) BOLDED LETTERS The popup help text system supports special characters to specify the hot key(s) for a button. Anytime you see a '|' symbol within the help text string, that means the following key is assigned to activate the action which is usually a button. EX: L"|Map Screen" This means the 'M' is the hotkey. In the game, when somebody hits the 'M' key, it activates that button. When translating the text to another language, it is best to attempt to choose a word that uses 'M'. If you can't always find a match, then the best thing to do is append the 'M' at the end of the string in this format: EX: L"Ecran De Carte (|M)" (this is the French translation) Other examples are used multiple times, like the Esc key or "|E|s|c" or Space -> (|S|p|a|c|e) 2) NEWLINE Any place you see a \n within the string, you are looking at another string that is part of the fast help text system. \n notation doesn't need to be precisely placed within that string, but whereever you wish to start a new line. EX: L"Clears all the mercs' positions,\nand allows you to re-enter them manually." Would appear as: Clears all the mercs' positions, and allows you to re-enter them manually. NOTE: It is important that you don't pad the characters adjacent to the \n with spaces. If we did this in the above example, we would see WRONG WAY -- spaces before and after the \n EX: L"Clears all the mercs' positions, \n and allows you to re-enter them manually." Would appear as: (the second line is moved in a character) Clears all the mercs' positions, and allows you to re-enter them manually. @@@ NOTATION ************ Throughout the text files, you'll find an assortment of comments. Comments are used to describe the text to make translation easier, but comments don't need to be translated. A good thing is to search for "@@@" after receiving new version of the text file, and address the special notes in this manner. !!! NOTATION ************ As described above, the "!!!" notation should be used by Topware to ask questions and address problems as SirTech uses the "@@@" notation. */ static StrPointer s_rus_WeaponType[WeaponType_SIZE] = { L"Другое", L"Пистолет", L"Автом. пистолет", L"Пистолет-пулемет", L"Винтовка", L"Снайп. винтовка", L"Автомат", L"Легкий пулемет", L"Дробовик" }; static StrPointer s_rus_TeamTurnString[TeamTurnString_SIZE] = { L"Ход игрока", // player's turn L"Ход противника", L"Ход существ", L"Ход ополчения", L"Ход жителей" // planning turn }; static StrPointer s_rus_Message[Message_SIZE] = { // In the following 8 strings, the %ls is the merc's name, and the %d (if any) is a number. L"%ls получает ранение в голову и теряет в мудрости!", L"%ls получает ранение в плечо и теряет в ловкости!", L"%ls получает ранение в грудь и теряет в силе!", L"%ls получает ранение ног и теряет в проворности!", L"%ls получает ранение в голову и теряет %d очков мудрости!", L"%ls получает ранение в плечо и теряет %d очков ловкости!", L"%ls получает ранение в грудь и теряет %d очков силы!", L"%ls получает ранение ног и теряет %d очков проворности!", L"Перехват инициативы!", L"К вам на помощь прибыло подкрепление!", // In the following four lines, all %ls's are merc names L"%ls перезаряжает оружие.", L"%ls: недостаточно очков действия!", // the following 17 strings are used to create lists of gun advantages and disadvantages // (separated by commas) L"надежность", L"ненадежность", L"легко починить", L"трудно починить", L"сильный урон", L"слабый урон", L"скорострельность", L"медленный огонь", L"дальний бой", L"ближний бой", L"малый вес", L"большой вес", L"малые размеры", L"авто-огонь", L"только одиночными", L"большой магазин", L"маленький магазин", // In the following two lines, all %ls's are merc names L"%ls: камуфляж изношен.", L"%ls: окраска камуфляжа смыта.", // The first %ls is a merc name and the second %ls is an item name L"У второго оружия закончились патроны!", L"%ls крадет %ls.", // The %ls is a merc name L"%ls: оружие не стреляет очередями.", L"Это уже присоединено!", L"Соединить?", // Both %ls's are item names L"Нельзя присоединить %ls к %ls.", L"Ничего", L"Разрядить", L"Приспособления", //You cannot use "item(s)" and your "other item" at the same time. //Ex: You cannot use sun goggles and you gas mask at the same time. L"Нельзя использовать %ls и %ls одновременно.", L"Этот предмет можно присоединить к другим предметам, поместив его в одну из ячеек приспособлений.", L"Этот предмет можно присоединить к другим предметам, поместив его в одну из ячеек приспособлений. (Однако данные предметы несовместимы.)", L"В секторе еще остались враги!", L"%ls должен получить еще %ls", ///TRNSL_ASSUME all doctors who can get money are male L"%ls: попадание в голову!", L"Выйти из боя?", L"Соединение будет неразборно. Соединить?", L"%ls чувствует прилив энергии!", L"%ls поскальзывается на шариках!", L"%ls не удается взять %ls!", L"%ls чинит %ls", L"На перехвате ", L"Сдаться?", L"Человек отвергает вашу помощь.", L"Ни за что!",//refuse to heal monster creature L"Чтобы воспользоваться вертолетом Всадника, нужно дать бойцам ЗАДАНИЕ сесть в ТРАНСПОРТ.", L"%ls успевает зарядить только одно оружие", L"Ход кошек-убийц", }; // the names of the towns in the game static const wchar_t *s_rus_pTownNames[pTownNames_SIZE] = { L"", L"Омерта", L"Драссен", L"Альма", L"Грам", L"Тикса", L"Камбрия", L"", L"Эстони", L"Орта", L"Балайм", L"Медуна", L"Читзена", }; static const wchar_t *s_rus_g_towns_locative[g_towns_locative_SIZE] = { L"", L"Омерте", L"Драссене", L"Альма", // TODO fill in correct forms L"Грам", L"Тикса", L"Камбрия", L"", L"Эстони", L"Орта", L"Балайм", L"Медуна", L"Читзена", }; // the types of time compression. For example: is the timer paused? at normal speed, 5 minutes per second, etc. // min is an abbreviation for minutes static const wchar_t *s_rus_sTimeStrings[sTimeStrings_SIZE] = { L"Пауза", L"Норма", L"5 мин", L"30 мин", L"60 мин", L"6 час", }; // Assignment Strings: what assignment does the merc have right now? For example, are they on a squad, training, // administering medical aid (doctor) or training a town. All are abbreviated. 8 letters is the longest it can be. static const wchar_t *s_rus_pAssignmentStrings[pAssignmentStrings_SIZE] = { L"Отряд 1", L"Отряд 2", L"Отряд 3", L"Отряд 4", L"Отряд 5", L"Отряд 6", L"Отряд 7", L"Отряд 8", L"Отряд 9", L"Отряд 10", L"Отряд 11", L"Отряд 12", L"Отряд 13", L"Отряд 14", L"Отряд 15", L"Отряд 16", L"Отряд 17", L"Отряд 18", L"Отряд 19", L"Отряд 20", L"На службе", // on active duty L"Доктор", // оказывает медпомощь L"Пациент", //принимает медпомощь L"Транспорт", // in a vehicle L"В пути", //транзитом - сокращение L"Ремонт", // ремонтируются L"Практика", // тренируются L"Ополчение", //готовят восстание среди горожан L"Тренер", // training a teammate L"Ученик", // being trained by someone else L"Труп", // мертв L"Без созн.", // abbreviation for incapacitated L"В плену", // Prisoner of war - captured L"Госпиталь", // patient in a hospital L"Пуст", // Vehicle is empty }; static const wchar_t *s_rus_pMilitiaString[pMilitiaString_SIZE] = { L"Ополчение", // the title of the militia box L"не распределено:", //the number of unassigned militia troops L"Нельзя перераспределять ополчение, когда кругом враги!", }; static const wchar_t *s_rus_pMilitiaButtonString[pMilitiaButtonString_SIZE] = { L"Авто", // auto place the militia troops for the player L"Готово", // done placing militia troops }; static const wchar_t *s_rus_pConditionStrings[pConditionStrings_SIZE] = { L"Отлично", //состояние солдата..отличное здоровье L"Хорошо", //хорошее здоровье L"Норма", //нормальное здоровье L"Ранение", //раны L"Без сил", // усталый L"Кровоточит", // истекает кровью L"Без созн.", // в обмороке L"Умирает", //умирает L"Труп", // мертв }; static const wchar_t *s_rus_pEpcMenuStrings[pEpcMenuStrings_SIZE] = { L"На службе", // set merc on active duty L"Пациент", // set as a patient to receive medical aid L"Транспорт", // tell merc to enter vehicle L"Без эскорта", // охрана покидает героя L"Отмена", // выход из этого меню }; // look at pAssignmentString above for comments static const wchar_t *s_rus_pLongAssignmentStrings[pLongAssignmentStrings_SIZE] = { L"Отряд 1", L"Отряд 2", L"Отряд 3", L"Отряд 4", L"Отряд 5", L"Отряд 6", L"Отряд 7", L"Отряд 8", L"Отряд 9", L"Отряд 10", L"Отряд 11", L"Отряд 12", L"Отряд 13", L"Отряд 14", L"Отряд 15", L"Отряд 16", L"Отряд 17", L"Отряд 18", L"Отряд 19", L"Отряд 20", L"На службе", L"Доктор", L"Пациент", L"Транспорт", L"В пути", L"Ремонт", L"Практика", L"Ополчение", L"Тренер", L"Ученик", L"Труп", L"Без сознания", L"В плену", L"Госпиталь", // patient in a hospital L"Пуст", // Vehicle is empty }; // the contract options static const wchar_t *s_rus_pContractStrings[pContractStrings_SIZE] = { L"Действия по контракту:", L"", // a blank line, required L"Продлить на 1 день", // offer merc a one day contract extension L"Продлить на 7 дней", // 1 week L"Продлить на 14 дней", // 2 week L"Уволить", // end merc's contract L"Отмена", // stop showing this menu }; static const wchar_t *s_rus_pPOWStrings[pPOWStrings_SIZE] = { L"В плену", //an acronym for Prisoner of War L"??", }; static const wchar_t *s_rus_pInvPanelTitleStrings[pInvPanelTitleStrings_SIZE] = { L"Броня", // the armor rating of the merc L"Груз", // the weight the merc is carrying L"Камуфляж", // the merc's camouflage rating }; static const wchar_t *s_rus_pShortAttributeStrings[pShortAttributeStrings_SIZE] = { L"Прв", // the abbreviated version of : agility L"Лов", // dexterity L"Сил", // strength L"Лид", // leadership L"Мдр", // wisdom L"Опт", // experience level L"Мтк", // marksmanship skill L"Взр", // explosive skill L"Мех", // mechanical skill L"Мед", // medical skill}; }; static const wchar_t *s_rus_pUpperLeftMapScreenStrings[pUpperLeftMapScreenStrings_SIZE] = { L"Задание", // the mercs current assignment L"Здоровье", // the health level of the current merc L"Настрой", // the morale of the current merc L"Сост.", // the condition of the current vehicle }; static const wchar_t *s_rus_pTrainingStrings[pTrainingStrings_SIZE] = { L"Практика", // tell merc to train self L"Ополчение", // tell merc to train town L"Тренер", // tell merc to act as trainer L"Ученик", // tell merc to be train by other }; static const wchar_t *s_rus_pAssignMenuStrings[pAssignMenuStrings_SIZE] = { L"На службе", // merc is on active duty L"Доктор", // the merc is acting as a doctor L"Пациент", // the merc is receiving medical attention L"Транспорт", // the merc is in a vehicle L"Ремонт", // the merc is repairing items L"Тренинг", // the merc is training L"Отмена", // cancel this menu }; static const wchar_t *s_rus_pRemoveMercStrings[pRemoveMercStrings_SIZE] = { L"Исключить из команды", // remove dead or captured by enemy merc from team L"Отмена", }; static const wchar_t *s_rus_pAttributeMenuStrings[pAttributeMenuStrings_SIZE] = { L"Сила", L"Ловкость", L"Проворность", L"Здоровье", L"Меткость", L"Медицина", L"Механика", L"Лидерство", L"Взрывник", L"Отмена", }; static const wchar_t *s_rus_pTrainingMenuStrings[pTrainingMenuStrings_SIZE] = { L"Практика", // train yourself L"Ополчение", // train the town L"Тренер", // train your teammates L"Ученик", // be trained by an instructor L"Отмена", // cancel this menu }; static const wchar_t *s_rus_pSquadMenuStrings[pSquadMenuStrings_SIZE] = { L"Отряд 1", L"Отряд 2", L"Отряд 3", L"Отряд 4", L"Отряд 5", L"Отряд 6", L"Отряд 7", L"Отряд 8", L"Отряд 9", L"Отряд 10", L"Отряд 11", L"Отряд 12", L"Отряд 13", L"Отряд 14", L"Отряд 15", L"Отряд 16", L"Отряд 17", L"Отряд 18", L"Отряд 19", L"Отряд 20", L"Отмена", }; static const wchar_t *s_rus_pPersonnelScreenStrings[pPersonnelScreenStrings_SIZE] = { L"Медицинский депозит:", // amount of medical deposit put down on the merc L"Срок контракта:", // time of remaining contract L"Убийства", // number of kills by merc L"Помощь в бою", // number of assists on kills by merc L"Стоимость в день:", // daily cost of merc L"Гонорар:", // total cost of merc L"Контракт:", // cost of current contract L"На службе:", // total service rendered by merc L"Долг по оплате:", // amount left on MERC merc to be paid L"Процент попаданий:", // percentage of shots that hit target L"Битвы", // number of battles fought L"Ранения", // number of times merc has been wounded L"Навыки:", L"Нет навыков", }; //These string correspond to enums used in by the SkillTrait enums in SoldierProfileType.h static const wchar_t *s_rus_gzMercSkillText[gzMercSkillText_SIZE] = { L"Нет навыков", L"Взлом", L"Рукопашная", L"Электроника", L"Ночной бой", L"Броски", L"Учитель", L"Тяжелое вооружение", L"Автоматы", L"Скрытность", L"Амбидекстрия", L"Вор", L"Боевые искусства", L"Бой с ножом", L"Стрельба с крыш", L"Маскировка", L"(Эксперт)", }; // This is pop up help text for the options that are available to the merc static const wchar_t *s_rus_pTacticalPopupButtonStrings[pTacticalPopupButtonStrings_SIZE] = { L"Стоять/Идти (|S)", L"Присядью (|C)", L"Стоять/Бегом (|R)", L"Лечь/Ползти (|P)", L"Поворот (|L)", L"Действие", L"Поговорить", L"Осмотреть (|C|t|r|l)", // Pop up door menu L"Открыть", L"Искать ловушки", L"Вскрыть отмычками", L"Взломать", L"Обезвредить", L"Запереть", L"Отпереть", L"Взорвать замок", L"Взломать ломом", L"Отмена (|E|s|c)", L"Закрыть", }; // Door Traps. When we examine a door, it could have a particular trap on it. These are the traps. static const wchar_t *s_rus_pDoorTrapStrings[pDoorTrapStrings_SIZE] = { L"нет ловушки", L"мина", L"электроловушка", L"сирена", L"сигнализация" }; // On the map screen, there are four columns. This text is popup help text that identifies the individual columns. static const wchar_t *s_rus_pMapScreenMouseRegionHelpText[pMapScreenMouseRegionHelpText_SIZE] = { L"Выбрать наемника", L"Дать задание", L"Проложить маршрут", L"Управление контрактом (|C)", L"Убрать бойца", L"Спать", }; // volumes of noises static const wchar_t *s_rus_pNoiseVolStr[pNoiseVolStr_SIZE] = { L"ТИХИЙ", L"ЧЕТКИЙ", L"ГРОМКИЙ", L"ОГЛУШИТЕЛЬНЫЙ" }; // types of noises static const wchar_t *s_rus_pNoiseTypeStr[pNoiseTypeStr_SIZE] = // OBSOLETE { L"НЕЗНАКОМЫЙ", L"звук ДВИЖЕНИЯ", L"СКРИП", L"ПЛЕСК", L"УДАР", L"ВЫСТРЕЛ", L"ВЗРЫВ", L"КРИК", L"УДАР", L"УДАР", L"ЗВОН", L"ГРОХОТ" }; // Directions that are used to report noises static const wchar_t *s_rus_pDirectionStr[pDirectionStr_SIZE] = { L"с СЕВ-ВОСТОКА", L"с ВОСТОКА", L"с ЮГО-ВОСТОКА", L"с ЮГА", L"с ЮГО-ЗАПАДА", L"с ЗАПАДА", L"с СЕВ-ЗАПАДА", L"с СЕВЕРА" }; // These are the different terrain types. static const wchar_t *s_rus_pLandTypeStrings[pLandTypeStrings_SIZE] = { L"Город", L"Дорога", L"Равнина", L"Пустыня", L"Леса", L"Роща", L"Болото", L"Вода", L"Холмы", L"Непроходимо", L"Река", //river from north to south L"Река", //river from east to west L"Чужая страна", //NONE of the following are used for directional travel, just for the sector description. L"Тропики", L"Фермы", L"Поля, дорога", L"Леса, дорога", L"Фермы, дорога", L"Тропики, дорога", L"Роща, дорога", L"Берег", L"Горы, дорога", L"Побережье, дорога", L"Пустыня, дорога", L"Болото, дорога", L"Леса, ПВО", L"Пустыня, ПВО", L"Тропики, ПВО", L"Медуна, ПВО", //These are descriptions for special sectors L"Госпиталь Камбрии", L"Аэропорт Драссена", L"Аэропорт Медуны", L"База ПВО", L"База повстанцев", //The rebel base underground in sector A10 L"Подземелья Тиксы", //The basement of the Tixa Prison (J9) L"Логово существ", //Any mine sector with creatures in it L"Подвалы Орты", //The basement of Orta (K4) L"Туннель", //The tunnel access from the maze garden in Meduna //leading to the secret shelter underneath the palace L"Убежище", //The shelter underneath the queen's palace L"", //Unused }; static const wchar_t *s_rus_gpStrategicString[gpStrategicString_SIZE] = { L"%ls обнаружены в секторе %c%d и вот-вот прибудет еще один отряд.", //STR_DETECTED_SINGULAR L"%ls обнаружены в секторе %c%d и вот-вот прибудут еще отряды.", //STR_DETECTED_PLURAL L"Хотите координировать одновременное прибытие?", //STR_COORDINATE //Dialog strings for enemies. L"Враг предлагает сдаться.", //STR_ENEMY_SURRENDER_OFFER L"Враг взял в плен наемников без сознания.", //STR_ENEMY_CAPTURED //The text that goes on the autoresolve buttons L"Отступить", //The retreat button //STR_AR_RETREAT_BUTTON L"Готово", //The done button //STR_AR_DONE_BUTTON //The headers are for the autoresolve type (MUST BE UPPERCASE) L"ОБОРОНА", //STR_AR_DEFEND_HEADER L"АТАКА", //STR_AR_ATTACK_HEADER L"СТОЛКНОВЕНИЕ", //STR_AR_ENCOUNTER_HEADER L"Сектор", //The Sector A9 part of the header //STR_AR_SECTOR_HEADER //The battle ending conditions L"ПОБЕДА!", //STR_AR_OVER_VICTORY L"ПОРАЖЕНИЕ!", //STR_AR_OVER_DEFEAT ///TRNSL_CHECK_INGAME LENGTH L"СДАЧА!", //STR_AR_OVER_SURRENDERED L"В ПЛЕНУ!", //STR_AR_OVER_CAPTURED L"ОТСТУПЛЕНИЕ!", //STR_AR_OVER_RETREATED //These are the labels for the different types of enemies we fight in autoresolve. L"Ополчение", //STR_AR_MILITIA_NAME, L"Элита", //STR_AR_ELITE_NAME, L"Солдат", //STR_AR_TROOP_NAME, L"Админ", //STR_AR_ADMINISTRATOR_NAME, L"Существо", //STR_AR_CREATURE_NAME, //Label for the length of time the battle took L"Бой шел", //STR_AR_TIME_ELAPSED, //Labels for status of merc if retreating. (UPPERCASE) L"ОТСТУПИЛ", //STR_AR_MERC_RETREATED, L"ОТСТУПАЕТ", //STR_AR_MERC_RETREATING, L"ОТСТУПЛЕНИЕ", //STR_AR_MERC_RETREAT, //PRE BATTLE INTERFACE STRINGS //Goes on the three buttons in the prebattle interface. The Auto resolve button represents //a system that automatically resolves the combat for the player without having to do anything. //These strings must be short (two lines -- 6-8 chars per line) L"Ав", //STR_PB_AUTORESOLVE_BTN, L"Идти в сектор", //STR_PB_GOTOSECTOR_BTN, L"Уйти", //STR_PB_RETREATMERCS_BTN, //The different headers(titles) for the prebattle interface. L"СТОЛКНОВЕНИЕ", //STR_PB_ENEMYENCOUNTER_HEADER, L"НАПАДЕНИЕ", //STR_PB_ENEMYINVASION_HEADER, // 30 L"ЗАСАДА", //STR_PB_ENEMYAMBUSH_HEADER L"ВРАЖЕСКИЙ СЕКТОР", //STR_PB_ENTERINGENEMYSECTOR_HEADER L"АТАКА СУЩЕСТВ", //STR_PB_CREATUREATTACK_HEADER L"ЗАСАДА КОШЕК-УБИЙЦ", //STR_PB_BLOODCATAMBUSH_HEADER L"ЛОГОВО КОШЕК-УБИЙЦ", //STR_PB_ENTERINGBLOODCATLAIR_HEADER //Various single words for direct translation. The Civilians represent the civilian //militia occupying the sector being attacked. Limited to 9-10 chars L"Место", L"Враги", L"Наемники", L"Ополченцы", L"Существа", L"Кошки", L"Сектор", L"Никого", //If there are no uninvolved mercs in this fight. L"Н/П", //Acronym of Not Applicable L"д", //One letter abbreviation of day L"ч", //One letter abbreviation of hour //TACTICAL PLACEMENT USER INTERFACE STRINGS //The four buttons L"Очистить", L"Порознь", L"Группой", L"Готово", //The help text for the four buttons. Use \n to denote new line (just like enter). L"Отменить размещение и начать заново (|C)", L"Равномерно распределить бойцов (|S)", L"Сгруппировать бойцов в заданной точке (|G)", L"Нажмите эту кнопку, когда закончите\nвыбор позиций для бойцов (|E|n|t|e|r).", L"Нужно разместить ВСЕХ наемников\nперед началом битвы.", //Various strings (translate word for word) L"Сектор", L"выберите исходные позиции", //Strings used for various popup message boxes. Can be as long as desired. L"Не очень-то хорошее место. Туда не пройти. Выберите другую позицию.", L"Разместите своих наемников в выделенной области.", //These entries are for button popup help text for the prebattle interface. All popup help //text supports the use of \n to denote new line. Do not use spaces before or after the \n. L"Битва разрешается автоматически\nбез вашего участия (|A)", L"Нельзя использовать авто битву\nкогда вы нападаете", L"Войти в сектор: стычка с врагом (|E)", L"Отступить в исходный сектор (|R)", //singular version L"Отступить всем отрядам на исходные позиции (|R)", //multiple groups with same previous sector //!!!What about repeated "R" as hotkey? //various popup messages for battle conditions. //%c%d is the sector -- ex: A9 L"Враги атакуют ваше ополчение в секторе %c%d.", //%c%d сектор -- напр: A9 L"Существа напали на ополчение в секторе %c%d.", //1st %d refers to the number of civilians eaten by monsters, %c%d is the sector -- ex: A9 //Note: the minimum number of civilians eaten will be two. L"Существа напали на гражданских, убито %d в секторе %ls.", //%ls is the sector location -- ex: A9: Omerta L"Враги атакуют ваш отряд секторе %ls. Никто из наемников не может сражаться!", //%ls is the sector location -- ex: A9: Omerta L"Существа атакуют ваш отряд в секторе %ls. Никто из наемников не может сражаться!", }; //This is the day represented in the game clock. Must be very short, 4 characters max. static const wchar_t s_rus_gpGameClockString[] = L"День"; //When the merc finds a key, they can get a description of it which //tells them where and when they found it. static const wchar_t *s_rus_sKeyDescriptionStrings[sKeyDescriptionStrings_SIZE] = { L"Найден в:", L"День находки:", }; //The headers used to describe various weapon statistics. static StrPointer s_rus_gWeaponStatsDesc[ gWeaponStatsDesc_SIZE] = { L"Вес (%ls):", L"Состояние:", L"Патроны:", // Number of bullets left in a magazine L"Дист:", // Range L"Урон:", // Damage L"ОД:", // abbreviation for Action Points L"=" }; //The headers used for the merc's money. static const wchar_t *s_rus_gMoneyStatsDesc[gMoneyStatsDesc_SIZE] = { L"Денег в", L"пачке:", //this is the overall balance L"Отделить", L"сумму:", // the amount he wants to separate from the overall balance to get two piles of money L"Текущий", L"баланс", L"Взять со", L"счета", }; //The health of various creatures, enemies, characters in the game. The numbers following each are for comment //only, but represent the precentage of points remaining. static const wchar_t *s_rus_zHealthStr[zHealthStr_SIZE] = ///TRNSL_BAD (GENDER) { L"УМИРАЕТ", // >= 0 L"КРИТИЧНО", // >= 15 L"ПЛОХ", // >= 30 L"РАНЕН", // >= 45 L"ЗДОРОВ", // >= 60 L"СИЛЕН", // >= 75 L"ОТЛИЧНО", // >= 90 }; static const wchar_t *s_rus_gzMoneyAmounts[gzMoneyAmounts_SIZE] = { L"1000$", L"100$", L"10$", L"OK", L"Отделить", L"Взять" }; // short words meaning "Advantages" for "Pros" and "Disadvantages" for "Cons." static const wchar_t s_rus_gzProsLabel[] = L"Плюсы:"; static const wchar_t s_rus_gzConsLabel[] = L"Минусы:"; //Conversation options a player has when encountering an NPC static StrPointer s_rus_zTalkMenuStrings[zTalkMenuStrings_SIZE] = { L"Еще раз?", //meaning "Repeat yourself" L"Дружески", //approach in a friendly L"Прямо", //approach directly - let's get down to business L"Угрожать", //approach threateningly - talk now, or I'll blow your face off L"Дать", L"Нанять" }; //Some NPCs buy, sell or repair items. These different options are available for those NPCs as well. static StrPointer s_rus_zDealerStrings[zDealerStrings_SIZE] = { L"Торговля", L"Купить", L"Продать", L"Ремонт", }; static const wchar_t s_rus_zDialogActions[] = L"Готово"; //These are vehicles in the game. static const wchar_t *s_rus_pVehicleStrings[pVehicleStrings_SIZE] = { L"Эльдорадо", L"Хаммер", // a hummer jeep/truck -- military vehicle L"Минивэн", L"Джип", L"Танк", L"Вертолет", }; static const wchar_t *s_rus_pShortVehicleStrings[pVehicleStrings_SIZE] = { L"Эльдор", L"Хаммер", // the HMVV L"Вэн", L"Джип", L"Танк", L"Верт.", // the helicopter }; static const wchar_t *s_rus_zVehicleName[pVehicleStrings_SIZE] = { L"Эльдорадо", L"Хаммер", //a military jeep. This is a brand name. L"Вэн", // Ice cream truck L"Джип", L"Танк", L"Верт.", //an abbreviation for Helicopter }; //These are messages Used in the Tactical Screen static StrPointer s_rus_TacticalStr[TacticalStr_SIZE] = { L"Воздушный налет", L"Оказать первую помощь?", // CAMFIELD NUKE THIS and add quote #66. L"%ls замечает недостачу товара в ящике.", // The %ls is a string from pDoorTrapStrings L"К замку присоединена %ls.", ///TRNSL_ASSUME all traps are female gender words L"Тут нет замка.", L"Замок без ловушки.", // The %ls is a merc name L"%ls не имеет нужного ключа.", L"Замок без ловушки.", L"Заперто.", L"ДВЕРЬ", L"С ЛОВУШКОЙ", L"ЗАПЕРТАЯ", L"НЕЗАПЕРТАЯ", L"СЛОМАНАЯ", L"Тут есть выключатель. Нажать?", L"Обезвредить ловушку?", L"Еще предметы...", // In the next 2 strings, %ls is an item name L"%ls теперь на земле.", L"Предмет \'%ls\' получает %ls.", // In the next 2 strings, %ls is a name L"%ls получил(а) всю сумму.", L"%ls ожидает от вас уплаты еще %d.", L"Выберите частоту детонатора:", //in this case, frequency refers to a radio signal L"Количество ходов перед взрывом:", //how much time, in turns, until the bomb blows L"Выберите частоту подрыва:", //in this case, frequency refers to a radio signal L"Разрядить ловушку?", L"Убрать флажок?", L"Установить флажок?", L"Завершение хода", // In the next string, %ls is a name. Stance refers to way they are standing. L"%ls на вашей стороне! Атаковать?", L"Ох, транспорт не может менять положения.", L"Робот не может менять положения.", // In the next 3 strings, %ls is a name L"%ls не может здесь поменять положение.", L"%ls не может быть перевязан.", L"%ls не нуждается в перевязке.", L"Туда идти нельзя.", L"Команда набрана. Нет места для новобранца.", //there's no room for a recruit on the player's team // In the next string, %ls is a name L"%ls теперь в команде.", // Here %ls is a name and %d is a number L"%ls ожидает уплаты еще $%d.", // In the next string, %ls is a name L"%ls будет сопровождаться в составе вашего отряда. Согласны?", // In the next string, the first %ls is a name and the second %ls is an amount of money (including $ sign) L"%ls может вступить в ваш отряд за %ls в день. Нанять?", // This line is used repeatedly to ask player if they wish to participate in a boxing match. L"Хотите драться?", // In the next string, the first %ls is an item name and the // second %ls is an amount of money (including $ sign) L"Купить %ls за %ls?", // In the next string, %ls is a name L"%ls теперь сопровождается отрядом %d.", // These messages are displayed during play to alert the player to a particular situation L"ЗАКЛИНИЛО", //weapon is jammed. L"Роботу нужны патроны %ls.", //Robot is out of ammo L"Бросить туда? Не получится.", //Merc can't throw to the destination he selected // These are different buttons that the player can turn on and off. L"Режим скрытности (|Z)", L"Окно карты (|M)", L"Завершить ход (|D)", L"Говорить", L"Запретить отзывы", L"Подняться (|P|g|U|p)", L"Уровень курсора (|T|a|b)", L"Залезть/Слезть", L"Опуститься (|P|g|D|n)", L"Осмотреть (|C|t|r|l)", L"Предыдущий боец", L"Следующий боец (|S|p|a|c|e)", L"Настройки (|O)", L"Стрелять очередью (|B)", L"Смотреть/Повернуться (|L)", L"Здоровье: %d/%d\nЭнергия.: %d/%d\nНастрой: %ls", L"Чего?", //this means "what?" L"Продолж.", //an abbrieviation for "Continued" L"%ls будет говорить.", L"%ls будет молчать.", L"Состояние: %d/%d\nТопливо: %d/%d", L"Выйти из машины", L"Поменять отряд (|S|h|i|f|t |S|p|a|c|e)", L"Вести машину", L"Н/П", //this is an acronym for "Not Applicable." L"Применить (Рукопашная)", L"Применить (Оружие)", L"Применить (Нож)", L"Применить (Взрывчатка)", L"Применить (Аптечка)", L"(Ловит)", L"(Перезарядка)", ///TRNSL_CHECK_INGAME LENGTH L"(Дать)", L"Сработала %ls.", // The %ls here is a string from pDoorTrapStrings ASSUME all traps are female gender L"%ls прибыл(a).", L"%ls: нет очков действия.", L"%ls: наемник недоступен.", L"%ls: успешная перевязка.", L"%ls: нет бинтов.", L"Враг в секторе!", L"Нет врагов в поле зрения.", L"Не хватает очков действия.", L"Никто не использует дистанционное управление.", L"Обойма опустела!", L"СОЛДАТ", L"РЕПТИОН", L"ОПОЛЧЕНЕЦ", L"ЖИТЕЛЬ", L"Выход из сектора", L"OK", L"ОТМЕНА", L"Выбранный боец", L"Весь отряд", L"Идти в сектор", L"Идти на карту", L"Этот сектор нельзя покинуть здесь.", L"%ls слишком далеко.", L"Вершины деревьев скрыты", L"Вершины деревьев отображены", L"ВОРОНА", //Crow, as in the large black bird L"ШЕЯ", L"ГОЛОВА", L"ГРУДЬ", L"НОГИ", L"Сказать королеве то, что она хочет знать?", L"Отпечатки пальцев получены", L"Отпечатки неверны. Оружие заблокировано", L"Цель захвачена", L"Путь блокирован", L"Положить/Взять деньги", //Help text over the $ button on the Single Merc Panel L"Некого лечить.", L"Слом.", // Short form of JAMMED, for small inv slots L"Туда не добраться.", // used ( now ) for when we click on a cliff L"Человек отказывается двигаться.", // In the following message, '%ls' would be replaced with a quantity of money (e.g. $200) L"Заплатить %ls?", L"Согласиться на бесплатное лечение?", L"Согласны женить Дэррела?", L"Ключи", L"С эскортируемыми этого сделать нельзя.", L"Пощадить Кротта?", L"Цель вне зоны эффективного огня.", L"Шахтер", L"Транспорт передвигается только между секторами.", L"Автоперевязку сделать сейчас нельзя", L"%ls не может пройти, путь блокирован.", L"Здесь томятся ваши бойцы, захваченные армией Дейдраны!", L"Попадание в замок", L"Замок разрушен", L"Кто-то еще пытается воспользоваться этой дверью.", L"Состояние: %d/%d\nТопливо: %d/%d", L"%ls и %ls не видят друг друга.", // Cannot see person trying to talk to }; //Varying helptext explains (for the "Go to Sector/Map" checkbox) what will happen given different circumstances in the "exiting sector" interface. static const wchar_t *s_rus_pExitingSectorHelpText[pExitingSectorHelpText_SIZE] = { //Helptext for the "Go to Sector" checkbox button, that explains what will happen when the box is checked. L"Если выбрана эта опция, вы сразу перейдете в смежный сектор.", L"Если выбрана эта опция, вы выйдете\nна карту, пока ваши бойцы в пути.", //If you attempt to leave a sector when you have multiple squads in a hostile sector. L"Сектор занят врагами и оставлять здесь бойцов нельзя.\nРазберитесь с противником прежде чем идти в другие сектора.", //Because you only have one squad in the sector, and the "move all" option is checked, the "go to sector" option is locked to on. //The helptext explains why it is locked. L"Выведя всех наемников из сектора,\nвы автоматически перейдете в смежный сектор.", L"Выведя всех наемников из сектора,\nвы автоматически выйдете на карту,\nпока ваши бойцы в пути.", //If an EPC is the selected merc, it won't allow the merc to leave alone as the merc is being escorted. The "single" button is disabled. L"%ls не может покинуть этот сектор без сопровождения.", //If only one conscious merc is left and is selected, and there are EPCs in the squad, the merc will be prohibited from leaving alone. //There are several strings depending on the gender of the merc and how many EPCs are in the squad. //DO NOT USE THE NEWLINE HERE AS IT IS USED FOR BOTH HELPTEXT AND SCREEN MESSAGES! L"%ls не может покинуть сектор один - он сопровождает %ls.", //male singular L"%ls не может покинуть сектор одна - она сопровождает %ls.", //female singular L"%ls не может покинуть сектор один - он сопровождает группу.", //male plural L"%ls не может покинуть сектор одна - она сопровождает группу.", //female plural //If one or more of your mercs in the selected squad aren't in range of the traversal area, then the "move all" option is disabled, //and this helptext explains why. L"Для перемещения отряда\nвсе ваши наемники дожны быть рядом.", //Standard helptext for single movement. Explains what will happen (splitting the squad) L"Если выбрана эта опция, %ls пойдет в одиночку и\nавтоматически попадет в отдельный отряд.", //Standard helptext for all movement. Explains what will happen (moving the squad) L"Если выбрана эта опция, текущий \nотряд покинет этот сектор.", //This strings is used BEFORE the "exiting sector" interface is created. If you have an EPC selected and you attempt to tactically //traverse the EPC while the escorting mercs aren't near enough (or dead, dying, or unconscious), this message will appear and the //"exiting sector" interface will not appear. This is just like the situation where //This string is special, as it is not used as helptext. Do not use the special newline character (\n) for this string. L"%ls не может покинуть этот сектор без сопровождения. Для этого ваш отряд должен быть рядом.", }; static const wchar_t *s_rus_pRepairStrings[pRepairStrings_SIZE] = { L"Вещи", // tell merc to repair items in inventory L"ПВО", // tell merc to repair SAM site - SAM is an acronym for Surface to Air Missile L"Отмена", // cancel this menu L"Робот", // repair the robot }; // NOTE: combine prestatbuildstring with statgain to get a line like the example below. // "John has gained 3 points of marksmanship skill." static const wchar_t *s_rus_sPreStatBuildString[sPreStatBuildString_SIZE] = { L"теряет", // the merc has lost a statistic L"получает", // the merc has gained a statistic L"очко", // singular L"очка", // plural L"уровень", // singular L"уровня", // plural }; static const wchar_t *s_rus_sStatGainStrings[sStatGainStrings_SIZE] = { L"здоровья.", L"подвижности.", L"проворности.", L"мудрости.", L"медицины.", L"умения взрывника.", L"умения механика.", L"меткости.", L"опыта.", L"силы.", L"лидерства.", }; static const wchar_t *s_rus_pHelicopterEtaStrings[pHelicopterEtaStrings_SIZE] = { L"Общее расстояние: ", // total distance for helicopter to travel L" Безопасно: ", // distance to travel to destination L" Опасно:", // distance to return from destination to airport L"Цена полета: ", // total cost of trip by helicopter L"ОВП: ", // ETA is an acronym for "estimated time of arrival" L"У вертолета мало топлива, придется сесть на территории врага!", // warning that the sector the helicopter is going to use for refueling is under enemy control -> L"Пассажиры: ", L"Высадить Всадника или прибывающих?", L"Всадник", L"Прибывающие", }; static const wchar_t s_rus_sMapLevelString[] = L"Подуровень "; // what level below the ground is the player viewing in mapscreen static const wchar_t s_rus_gsLoyalString[] = L"Отношение %d%%"; // the loyalty rating of a town ie : Loyal 53% // error message for when player is trying to give a merc a travel order while he's underground. static const wchar_t s_rus_gsUndergroundString[] = L"не может двигаться по карте, находясь под землей."; static const wchar_t *s_rus_gsTimeStrings[gsTimeStrings_SIZE] = { L"ч", // hours abbreviation L"м", // minutes abbreviation L"с", // seconds abbreviation L"д", // days abbreviation }; // text for the various facilities in the sector static const wchar_t *s_rus_sFacilitiesStrings[sFacilitiesStrings_SIZE] = { L"Нет", L"Госпиталь", L"Заводы", L"Тюрьма", L"База армии", L"Аэропорт", L"Стрельбище", // a field for soldiers to practise their shooting skills }; // text for inventory pop up button static const wchar_t *s_rus_pMapPopUpInventoryText[pMapPopUpInventoryText_SIZE] = { L"Предметы", L"Выход", }; // town strings static const wchar_t *s_rus_pwTownInfoStrings[pwTownInfoStrings_SIZE] = { L"Размер", // size of the town in sectors L"Контроль над городом", // how much of town is controlled L"Шахта города", // mine associated with this town L"Отношение", // the loyalty level of this town L"Сооружения", // main facilities in this town L"Подготовка жителей", // state of civilian training in town L"Ополчение", // the state of the trained civilians in the town }; // Mine strings static const wchar_t *s_rus_pwMineStrings[pwMineStrings_SIZE] = { L"Шахта", // 0 L"Серебро", L"Золото", L"Выработка в день", L"Максимум выработки", L"Заброшена", // 5 L"Закрыта", L"Истощена", L"Работает", L"Состояние", L"Производительность", L"Тип руды", // 10 L"Контроль над городом", L"Отношение города", }; // blank sector strings static const wchar_t *s_rus_pwMiscSectorStrings[pwMiscSectorStrings_SIZE] = { L"Силы врага", L"Сектор", L"Количество предметов", L"?", L"Сектор захвачен", L"Да", L"Нет", }; // error strings for inventory static const wchar_t *s_rus_pMapInventoryErrorString[pMapInventoryErrorString_SIZE] = { L"Нельзя выбрать этого бойца.", //MARK CARTER L"%ls не в этом секторе, и не может взять этот предмет.", L"Во время битвы надо подбирать предметы вручную", L"Во время битвы надо бросать предметы вручную.", L"%ls не в этом секторе, и не может бросить этот предмет.", }; static const wchar_t *s_rus_pMapInventoryStrings[pMapInventoryStrings_SIZE] = { L"Сектор", // sector these items are in L"Всего предметов", // total number of items in sector }; // movement menu text static const wchar_t *s_rus_pMovementMenuStrings[pMovementMenuStrings_SIZE] = { L"Отправить бойцов из сектора %ls", // title for movement box L"Проложить маршрут", // done with movement menu, start plotting movement L"Отмена", // cancel this menu L"Другие", // title for group of mercs not on squads nor in vehicles }; static const wchar_t *s_rus_pUpdateMercStrings[pUpdateMercStrings_SIZE] = { L"Ой!:", // an error has occured L"Контракты закончились:", // this pop up came up due to a merc contract ending L"Бойцы выполнили задание:", // this pop up....due to more than one merc finishing assignments L"Бойцы снова в строю:", // this pop up ....due to more than one merc waking up and returing to work L"Бойцы идут спать:", // this pop up ....due to more than one merc being tired and going to sleep L"Контракты скоро кончатся:", // this pop up came up due to a merc contract ending }; // map screen map border buttons help text static const wchar_t *s_rus_pMapScreenBorderButtonHelpText[pMapScreenBorderButtonHelpText_SIZE] = { L"Показать города (|W)", L"Показать шахты (|M)", L"Показать отряды и врагов (|T)", L"Показать воздушное пространство (|A)", L"Показать предметы (|I)", L"Показать ополчение и врагов (|Z)", }; static const wchar_t *s_rus_pMapScreenBottomFastHelp[pMapScreenBottomFastHelp_SIZE] = { L"Лэптоп (|L)", L"Тактика (|E|s|c)", L"Настройки (|O)", L"Ускорение времени (|+)", // time compress more L"Замедление времени (|-)", // time compress less L"Предыдущее сообщение (|U|p)\nПредыдущая страница (|P|g|U|p)", // previous message in scrollable list L"Следующее сообщение (|D|o|w|n)\nСледующая страница (|P|g|D|n)", // next message in the scrollable list L"Пауза/Снять с паузы (|S|p|a|c|e)", // start/stop time compression }; static const wchar_t s_rus_pMapScreenBottomText[] = L"Текущий баланс"; // current balance in player bank account static const wchar_t s_rus_pMercDeadString[] = L"%ls мертв(а)."; static const wchar_t s_rus_pDayStrings[] = L"День"; // the list of email sender names static const wchar_t *s_rus_pSenderNameList[pSenderNameList_SIZE] = // GOLD and BUKA use slightly different names { L"Энрико", L".", L"Помощь", L".", L"Спек", L"R.I.S.", //5 L"Барри", L"Блад", L"Рысь", L"Гризли", L"Вики", //10 L"Тревер", L"Хряп", L"Иван", L"Анаболик", L"Игорь", //15 L"Тень", L"Рыжий", L"Потрошитель", L"Фидель", L"Лиска", //20 L"Сидней", L"Гас", L"Сдоба", L"Айс", L"Паук", //25 L"Клифф", L"Бык", L"Стрелок", L"Тоска", L"Рейдер", //30 L"Сова", L"Статик", L"Лен", L"Данни", L"Маг", L"Стэфен", L"Лысый", L"Злобный", L"", L"Гвоздь", L"Тор", L"Стрелка", L"Волк", L"ЭмДи", L"Лава", //---------- L"", L"", L"Босс", L"", L"А.I.М.", }; static const wchar_t *s_rusGold_pSenderNameList[pSenderNameList_SIZE] = // GOLD and BUKA use slightly different names { L"Энрико", L"нк.", L"Помощь", L"нк.", L"Спек", L"R.I.S.", //5 L"Барри", L"Блад", L"Рысь", L"Гризли", L"Вики", //10 L"Тревор", L"Хряп", L"Иван", L"Анаболик", L"Игорь", //15 L"Тень", L"Рыжий", L"Жнец", L"Фидель", L"Лиска", //20 L"Сидней", L"Гас", L"Сдоба", L"Айс", L"Паук", //25 L"Скала", L"Бык", L"Стрелок", L"Тоска", L"Рейдер", //30 L"Сова", L"Статик", L"Лен", L"Данни", L"Маг", L"Стефан", L"Лысый", L"Злобный", L"", L"Гвоздь", L"Тор", L"Стрелка", L"Волк", L"ЭмДи", L"Лава", //---------- L"", L"", L"Босс", L"", L"А.I.М.", }; // new mail notify string static const wchar_t s_rus_pNewMailStrings[] = L"Получена новая почта..."; // confirm player's intent to delete messages static const wchar_t *s_rus_pDeleteMailStrings[pDeleteMailStrings_SIZE] = { L"Стереть сообщение?", L"Стереть НЕПРОЧТЕННЫЕ?", }; // the sort header strings static const wchar_t *s_rus_pEmailHeaders[pEmailHeaders_SIZE] = { L"От:", L"Тема:", L"Дата:", }; // email titlebar text static const wchar_t s_rus_pEmailTitleText[] = L"Почтовый ящик"; // the financial screen strings static const wchar_t s_rus_pFinanceTitle[] = L"Бухгалтер Плюс"; // the name we made up for the financial program in the game static const wchar_t *s_rus_pFinanceSummary[pFinanceSummary_SIZE] = { L"Расход:", // credit (subtract from) to player's account L"Приход:", // debit (add to) to player's account L"Прибыль за вчерашний день:", L"Другие вклады за вчерашний день:", L"Приход за вчерашний день:", L"Баланс на конец дня:", L"Приход за сегодня:", L"Другие вклады за сегодня:", L"Приход на сегодня:", L"Текущий баланс:", L"Предполагаемый приход:", L"Предполагаемый баланс:", // projected balance for player for tommorow }; // headers to each list in financial screen static const wchar_t *s_rus_pFinanceHeaders[pFinanceHeaders_SIZE] = { L"День", // the day column L"Приход", // the credits column L"Расход", // the debits column L"Операция", // transaction type - see TransactionText below L"Баланс", // balance at this point in time L"Стр.", // page number L"Дн.", // the day(s) of transactions this page displays }; static const wchar_t *s_rus_pTransactionText[pTransactionText_SIZE] = { L"Проценты", // interest the player has accumulated so far L"Анонимный вклад", L"Плата за перевод", L"%ls нанят(а) в AIM", // Merc was hired L"Покупки у ", // is the name of an arms dealer L"Оплата по счетам M.E.R.C.", L"%ls: оплачен мед. депозит", // medical deposit for merc L"Профилирование в IMP", // IMP is the acronym for International Mercenary Profiling L"Застрахован(а) %ls", L"%ls: cнижена страховка", L"%ls: продлена страховка", // johnny contract extended L"%ls: отмена страховки", L"%ls: выплата cтраховки", // insurance claim for merc L"%ls: контракт продлен на 1 день", // entend mercs contract by a day L"%ls: контракт продлен на 7 дней", L"%ls: контракт продлен на 14 дней", L"Доход с шахт", L"", //String nuked L"Приобретение цветов", L"%ls: возврат депозита", L"%ls: возврат части депозита", L"%ls: удержание депозита", L"Выплаты %ls", // %ls is the name of the npc being paid L"Перевод средств на имя %ls", // transfer funds to a merc L"Перевод средств от %ls", // transfer funds from a merc L"Ополчение в %ls", // initial cost to equip a town's militia L"%ls: оплата покупок.", //is used for the Shop keeper interface. The dealers name will be appended to the end of the string. L"%ls: вклад наличными.", }; // helicopter pilot payment static const wchar_t *s_rus_pSkyriderText[pSkyriderText_SIZE] = { L"Всаднику выплачено $%d", // skyrider was paid an amount of money L"Всаднику недоплачено $%d", // skyrider is still owed an amount of money L"У Всадника нет пассажиров. Если вы собирались перевозить бойцов - назначьте им ЗАДАНИЕ ТРАНСПОРТ." }; // strings for different levels of merc morale static const wchar_t *s_rus_pMoralStrings[pMoralStrings_SIZE] = { L"Боевой", L"Бодрый", L"Норма", L"Уныние", L"Паника", L"Разгром", }; // Mercs equipment has now arrived and is now available in Omerta or Drassen. static const wchar_t s_rus_str_left_equipment[] = L"%ls оставляет снаряжение в %ls (%c%d)."; // Status that appears on the Map Screen static const wchar_t *s_rus_pMapScreenStatusStrings[pMapScreenStatusStrings_SIZE] = { L"Здоровье", L"Энергия", L"Настрой", L"Состояние", // the condition of the current vehicle (its "health") L"Бензин", // the fuel level of the current vehicle (its "energy") }; static const wchar_t *s_rus_pMapScreenPrevNextCharButtonHelpText[pMapScreenPrevNextCharButtonHelpText_SIZE] = { L"Предыдущий наемник (|L|e|f|t)", // previous merc in the list L"Следующий наемник (|R|i|g|h|t)", // next merc in the list }; static const wchar_t s_rus_pEtaString[] = L"ОВП:"; // eta is an acronym for Estimated Time of Arrival static const wchar_t *s_rus_pTrashItemText[pTrashItemText_SIZE] = { L"Вы потеряете этот предмет навсегда. Выбросить?", // do you want to continue and lose the item forever L"Похоже, это действительно ВАЖНАЯ вещь. Вы ТОЧНО уверены, что хотите ее выбросить?", // does the user REALLY want to trash this item }; static const wchar_t *s_rus_pMapErrorString[pMapErrorString_SIZE] = { L"Отряд не может двигаться, пока бойцы спят.", //1-5 L"Сперва выведите отряд на поверхность.", L"Приказ двигаться? Тут же кругом враги!", L"Боец должен быть членом отряда или пассажиром, чтобы путешествовать.", L"У вас в команде пока никого нет", // you have no members, can't do anything L"Боец не может выполнить приказ.", // merc can't comply with your order //6-10 L"%ls нуждается в сопровождении. Назначьте его в отряд.", // merc can't move unescorted .. for a male L"%ls нуждается в сопровождении. Назначьте ее в отряд.", // for a female L"Наемник еще не прибыл в Арулько!", L"Кажется, сначала нужно уладить некоторые проблемы с контрактом.", L"", //11-15 L"Приказ двигаться? Тут же битва идет!", L"Вы попали в засаду кошек-убийц в секторе %ls!", L"Вы попали в логово кошек-убийц в секторе I16!", L"", L"База ПВО в %ls захвачена врагом.", //16-20 L"%ls: шахта захвачена. Ваш ежедневный доход упал до %ls в день.", L"Противник взял сектор %ls, не встретив сопротивления.", L"Как минимум одного из ваших бойцов нельзя назначить на это задание.", L"%ls не может вступить в %ls. Отряд полон.", L"%ls не может вступить в %ls. Слишком далеко.", //21-25 L"%ls: шахта захвачена войсками Дейдраны!", L"Войска Дейдраны захватили базу ПВО в %ls", L"%ls: в город вошли войска Дейдраны!", L"Войска Дейдраны были замечены в %ls.", L"Войска Дейдраны захватили %ls.", //26-30 L"Как минимум одного из ваших бойцов невозможно уложить спать.", L"Как минимум одного из ваших бойцов невозможно разбудить.", L"Ополчение небоеспособно, пока не закончится его обучение.", L"%ls не может передвигаться прямо сейчас.", L"Ополчение, которое находится вне города, нельзя переместить в другой сектор.", //31-35 L"%ls не может иметь ополчения.", L"Машине нужен водитель!", L"%ls слишком изранен(а), чтобы идти!", L"Сперва надо покинуть музей!", L"%ls мертв(а)!", //36-40 L"%ls не может перейти к %ls: он в движении", ///TRNSL_CHECK MEANING L"%ls не может сесть в машину так",///TRNSL_CHECK MEANING L"%ls не может присоединиться к %ls",///TRNSL_CHECK MEANING L"Нельзя ускорять время, пока у вас нет бойцов!", L"Эта машина может ездить только по дорогам!", //41-45 L"Нельзя переназначать наемников в пути",///TRNSL_CHECK MEANING L"У транспорта кончился бензин!", L"%ls не может передвигаться из-за усталости.", L"Никто из сидящих в машине не может управлять ею.", L"Один или более бойцов этого отряда сейчас не могут перемещаться.", //46-50 L"Один или более ДРУГИХ бойцов сейчас не могут перемещаться.",///TRNSL_CHECK MEANING L"Транспорт слишком сильно поврежден!", L"Тренировать ополчение может не больше 2 бойцов на сектор.", L"Робот не может двигаться без оператора. Поместите их в один отряд.", }; // help text used during strategic route plotting static const wchar_t *s_rus_pMapPlotStrings[pMapPlotStrings_SIZE] = { L"Кликните на секторе еще раз чтобы направить туда отряд, или щелкните по другому сектору для прокладки маршрута.", L"Маршрут движения проложен.", L"Маршрут не изменился.", L"Маршрут отменен.", L"Маршрут укорочен.", }; // help text used when moving the merc arrival sector static const wchar_t *s_rus_pBullseyeStrings[pBullseyeStrings_SIZE] = { L"Выберите сектор высадки прибывающих наемников.", L"Теперь прибывающие наемники будут высаживаться в %ls", L"Сюда нельзя лететь, воздух контролирует враг!", L"Отмена. Сектор прибытия тот же.", L"Полет над %ls опасен! Сектор прибытия перемещен в %ls.", }; // help text for mouse regions static const wchar_t *s_rus_pMiscMapScreenMouseRegionHelpText[pMiscMapScreenMouseRegionHelpText_SIZE] = { L"Просмотр инвентаря (|E|n|t|e|r)", L"Выкинуть предмет", L"Выйти из инвентаря (|E|n|t|e|r)", }; static const wchar_t s_rus_str_he_leaves_where_drop_equipment[] = L"%ls должен оставить снаряжение в (%ls) или потом, в %ls (%ls), перед вылетом из Арулько?"; static const wchar_t s_rus_str_she_leaves_where_drop_equipment[] = L"%ls должна оставить свое снаряжение в (%ls) или потом, в %ls (%ls), перед вылетом из Арулько?"; static const wchar_t s_rus_str_he_leaves_drops_equipment[] = L"%ls собрался уйти, оставив свое снаряжение в %ls."; static const wchar_t s_rus_str_she_leaves_drops_equipment[] = L"%ls собралась уйти, оставив свое снаряжение в %ls."; // Text used on IMP Web Pages static const wchar_t *s_rus_pImpPopUpStrings[pImpPopUpStrings_SIZE] = { L"Неверный код авторизации!", L"Вы уверены, что хотите начать процесс профилирования заново?", L"Укажите полное имя и пол", L"Изучение вашего счета показало, что у вас нет средств для оплаты профилирования.", L"Сейчас вы не можете это выбрать.", L"Чтобы закончить анализ, нужно иметь место еще хотя бы для одного члена команды.", L"Анализ уже пройден.", }; // button labels used on the IMP site static const wchar_t *s_rus_pImpButtonText[pImpButtonText_SIZE] = { L"Подробнее", // about the IMP site L"НАЧАТЬ", // begin profiling L"Личность", // personality section L"Свойства", // personal stats/attributes section L"Портрет", // the personal portrait selection L"Голос %d", // the voice selection L"Готово", // done profiling L"Заново", // start over profiling L"Да, выбрать выделенный ответ.", L"Да", L"Нет", L"Закончить", // finished answering questions L"Назад", // previous question..abbreviated form L"Дальше", // next question L"ДА.", // yes, I am certain L"НЕТ, ХОЧУ НАЧАТЬ СНАЧАЛА.", // no, I want to start over the profiling process L"ДА.", L"НЕТ", L"Назад", // back one page L"Отмена", // cancel selection L"Да, так и есть.", L"Нет, просмотреть еще раз.", L"Регистрация", // the IMP site registry..when name and gender is selected L"Анализ", // analyzing your profile results L"OK", L"Голос", }; static const wchar_t *s_rus_pExtraIMPStrings[pExtraIMPStrings_SIZE] = { L"Чтобы начать профилирование, протестируйте свои личные качества.", L"Личные качества оценены, переходите к свойствам.", L"Свойства зафиксированы, выберите наиболее подходящее вам лицо.", L"Чтобы завершить процесс, выберите подходящий голос." }; static const wchar_t s_rus_pFilesTitle[] = L"Просмотр файлов"; static const wchar_t *s_rus_pFilesSenderList[pFilesSenderList_SIZE] = { L"Отчет разведки", // the recon report sent to the player. Recon is an abbreviation for reconissance L"Перехват #1", // first intercept file .. Intercept is the title of the organization sending the file...similar in function to INTERPOL/CIA/KGB..refer to fist record in files.txt for the translated title L"Перехват #2", // second intercept file L"Перехват #3", // third intercept file L"Перехват #4", // fourth intercept file L"Перехват #5", // fifth intercept file L"Перехват #6", // sixth intercept file }; // Text having to do with the History Log static const wchar_t s_rus_pHistoryTitle[] = L"События"; static const wchar_t *s_rus_pHistoryHeaders[pHistoryHeaders_SIZE] = { L"День", // the day the history event occurred L"Стр.", // the current page in the history report we are in L"День", // the days the history report occurs over L"Место", // location (in sector) the event occurred L"Событие", // the event label }; // various history events // THESE STRINGS ARE "HISTORY LOG" STRINGS AND THEIR LENGTH IS VERY LIMITED. // PLEASE BE MINDFUL OF THE LENGTH OF THESE STRINGS. ONE WAY TO "TEST" THIS // IS TO TURN "CHEAT MODE" ON AND USE CONTROL-R IN THE TACTICAL SCREEN, THEN // GO INTO THE LAPTOP/HISTORY LOG AND CHECK OUT THE STRINGS. CONTROL-R INSERTS // MANY (NOT ALL) OF THE STRINGS IN THE FOLLOWING LIST INTO THE GAME. static const wchar_t *s_rus_pHistoryStrings[pHistoryStrings_SIZE] = { L"", // leave this line blank //1-5 L"%ls нанят(а) в A.I.M.", // merc was hired from the aim site L"%ls нанят(а) в M.E.R.C.", // merc was hired from the aim site L"%ls мертв(а).", // merc was killed L"Оплата счетов M.E.R.C.", // paid outstanding bills at MERC L"Принято задание от ", //6-10 L"Прошел профилирование в IMP", L"%ls: жизнь застрахована", // insurance contract purchased L"%ls: страховка отменена", // insurance contract canceled L"%ls: страховка выплачена", // insurance claim payout for merc L"%ls: контракт продлен на день.", // Extented "mercs name"'s for a day //11-15 L"%ls: контракт продлен на 7 дней", // Extented "mercs name"'s for a week L"%ls: контракт продлен на 14 дней", // Extented "mercs name"'s 2 weeks L"%ls уволен(а).", // "merc's name" was dismissed. L"%ls ушел.", // "merc's name" quit. L"начат.", // a particular quest started //16-20 L"завершен.", L"%ls: состоялся разговор с начальником шахты.", // talked to head miner of town L"%ls освобожден(а).", L"Читы включены.", L"Провизия завтра будет в Омерте.", //21-25 L"%ls ушла из команды и вышла замуж за Хика", L"%ls: контракт окончен.", L"%ls в команде.", L"Энрико недоволен отсутствием прогресса.", L"Битва выиграна.", //26-30 L"%ls: в шахте кончается руда", L"%ls: шахта выработана", L"%ls: шахта закрыта", L"%ls: шахта вновь открыта", L"Получил сведения о тюрьме Тикса.", //31-35 L"Услышал о секретном военном заводе Орта.", L"Ученый из Орты помог с ракетным ружьем.", L"Дейдранна что-то делает с трупами.", L"Фрэнк рассказал о поединках в Сан Моне.", L"Пациент думает, что видел в шахтах что-то.", //36-40 L"Встретил какого-то Девина - торгует взрывчаткой.", L"Столкнулся со знаменитым Майком!", L"Встретил Тони - он занимается оружием.", L"Получил ракетное ружье от сержанта Кротта.", L"Передал Кайлу закладную на магазин Энжела.", //41-45 L"Шиз предлагает сделать робота.", L"Болтун может сделать состав против жуков.", L"Кейт больше не при делах.", L"Говард обеспечивает Дейдрану цианидом.", L"Встретил Кейта - барыжит всем подряд в Камбрии.", //46-50 L"Встретил Говарда - фармацевта из Балайма.", L"Встретил Перко - у него маленький ремонтный бизнес.", L"Встретил Сэма из Балайма, у него компьютерный магазин.", L"Франц торгует электроникой и другими вещами.", L"У Арнольда ремонтная мастерская в Граме.", //51-55 L"Фредо ремонтирует электронику в Граме.", L"Получил пожертвование от богача из Балайма.", L"Встретил старьевщика по имени Джейк.", L"Бродяга дал нам электронный ключ.", L"Подкупил Вальтера, чтобы он открыл дверь в подвал.", //56-60 L"Дэвид заправит нас даром, если у него есть бензин.", L"Дал на лапу Пабло.", L"Босс хранит деньги в шахте Сан Моны.", L"%ls выиграл кулачный бой", L"%ls проиграл кулачный бой", //61-65 L"%ls: дисквалификация в кулачном бою", L"Нашел много денег в заброшенной шахте.", L"Столкнулся с убийцей, посланным Боссом.", L"Утрачен контроль над сектором", //ENEMY_INVASION_CODE L"Успешная оборона сектора", //66-70 L"Поражение в бою", //ENEMY_ENCOUNTER_CODE L"Засада", //ENEMY_AMBUSH_CODE L"Победа над засадой врага", L"Безуспешная атака", //ENTERING_ENEMY_SECTOR_CODE L"Успешная атака!", //71-75 L"Нападение существ!", //CREATURE_ATTACK_CODE L"Атака кошек-убийц", //BLOODCAT_AMBUSH_CODE L"Перебил кошек-убийц", L"%ls убит(а)", L"Отдал голову террориста Кармену", L"Убийца ушел", L"Убил %ls", }; static const wchar_t s_rus_pHistoryLocations[] = L"Н/П"; // N/A is an acronym for Not Applicable // icon text strings that appear on the laptop static const wchar_t *s_rus_pLaptopIcons[pLaptopIcons_SIZE] = { L"Почта", L"Сеть", L"Финансы", L"Команда", L"Журнал", L"Файлы", L"Выключить", L"сир-ФЕР 4.0", // our play on the company name (Sirtech) and web surFER }; // bookmarks for different websites // IMPORTANT make sure you move down the Cancel string as bookmarks are being added static const wchar_t *s_rus_pBookMarkStrings[pBookMarkStrings_SIZE] = { L"А.I.M.", L"", L"I.M.P.", L"М.Е.R.С.", L"Похороны", L"Цветы", L"Страховка", L"Отмена", }; // When loading or download a web page static const wchar_t *s_rus_pDownloadString[pDownloadString_SIZE] = { L"Загрузка...", L"Перегрузка...", }; //This is the text used on the bank machines, here called ATMs for Automatic Teller Machine static const wchar_t *s_rus_gsAtmStartButtonText[gsAtmStartButtonText_SIZE] = { L"Параметры", // view stats of the merc L"Снаряжение", // view the inventory of the merc L"Контракт", }; // Web error messages. Please use German equivilant for these messages. // DNS is the acronym for Domain Name Server // URL is the acronym for Uniform Resource Locator static const wchar_t s_rus_pErrorStrings[] = L"Плохое соединение. Попробуйте позднее."; static const wchar_t s_rus_pPersonnelString[] = L"Бойцов:"; // mercs we have static const wchar_t s_rus_pWebTitle[] = L"сир-ФЕР 4.0"; // our name for the version of the browser, play on company name // The titles for the web program title bar, for each page loaded static const wchar_t *s_rus_pWebPagesTitles[pWebPagesTitles_SIZE] = { L"А.I.M.", L"A.I.M. - Наемники", L"A.I.M. - Фотографии ", // a mug shot is another name for a portrait L"A.I.M. - Сортировка", L"A.I.M.", L"A.I.M. - Бывшие члены", L"A.I.M. - Правила", L"A.I.M. - История", L"A.I.M. - Ссылки", L"M.E.R.C.", L"M.E.R.C. - Счета", L"M.E.R.C. - Регистрация", L"M.E.R.C. - Индекс", L"", L" - Оружие", L" - Боеприпасы", L" - Броня", L" - Разное", //misc is an abbreviation for miscellaneous L" - Бывшее в Употреблении", L" - Бланк заказа", L"I.M.P.", L"I.M.P.", L"Цветы по Всему Миру", L"Цветы по Всему Миру - Галерея", L"Цветы по Всему Миру - Бланк Заказа", L"Цветы по Всему Миру - Открытки", L"Страховые агенты Малеус, Инкус и Стэйпс", L"Информация", L"Контракт", L"Комментарии", L"Похоронное агенство Макгилликати", L"URL не найден.", L" - Последние поставки",//@@@3 Translate new text L"", L"", }; static const wchar_t *s_rus_pShowBookmarkString[pShowBookmarkString_SIZE] = { L"Sir-Помощь", L"Закладки: кликните на кнопке Сеть еще раз.", }; static const wchar_t *s_rus_pLaptopTitles[pLaptopTitles_SIZE] = { L"Почтовый ящик", L"Просмотр файлов", L"Команда", L"Б", L"Журнал", }; static const wchar_t *s_rus_pPersonnelDepartedStateStrings[pPersonnelDepartedStateStrings_SIZE] = { //reasons why a merc has left. L"Убит в бою", L"Уволен", L"Замужем",///TRNSL ASSUME only female merc can depart from team by marrying somebody L"Контракт истек", L"Ушел", }; // personnel strings appearing in the Personnel Manager on the laptop static const wchar_t *s_rus_pPersonelTeamStrings[pPersonelTeamStrings_SIZE] = { L"В команде", L"Убывшие", L"Гонорар в день:", L"Макс. гонорар:", L"Мин. гонорар:", L"Погибли в бою:", L"Уволены:", L"Другое:", }; static const wchar_t *s_rus_pPersonnelCurrentTeamStatsStrings[pPersonnelCurrentTeamStatsStrings_SIZE] = { L"Минимум", L"Среднее", L"Максимум", }; static const wchar_t *s_rus_pPersonnelTeamStatsStrings[pPersonnelTeamStatsStrings_SIZE] = { L"ЗДОР", L"ПРВ", L"ЛОВ", L"СИЛ", L"ЛДР", L"МДР", L"ОПЫТ", L"МТК", L"МЕХ", L"ВЗРВ", L"МЕД", }; // horizontal and vertical indices on the map screen static const wchar_t *s_rus_pMapVertIndex[pMapVertIndex_SIZE] = { L"X", L"A", L"B", L"C", L"D", L"E", L"F", L"G", L"H", L"I", L"J", L"K", L"L", L"M", L"N", L"O", L"P", }; static const wchar_t *s_rus_pMapHortIndex[pMapHortIndex_SIZE] = { L"X", L"1", L"2", L"3", L"4", L"5", L"6", L"7", L"8", L"9", L"10", L"11", L"12", L"13", L"14", L"15", L"16", }; static const wchar_t *s_rus_pMapDepthIndex[pMapDepthIndex_SIZE] = { L"", L"-1", L"-2", L"-3", }; // text that appears on the contract button static const wchar_t s_rus_pContractButtonString[] = L"Контракт"; // text that appears on the update panel buttons static const wchar_t *s_rus_pUpdatePanelButtons[pUpdatePanelButtons_SIZE] = { L"Дальше", L"Стоп", }; // Text which appears when everyone on your team is incapacitated and incapable of battle static StrPointer s_rus_LargeTacticalStr[LargeTacticalStr_SIZE] = { L"В этом секторе вам нанесли поражение!", L"Враг, без тени сожаления, пожрет всех до единого!", L"Члены вашей команды захвачены (без сознания)!", L"Члены вашей команды захвачены в плен врагом.", }; //Insurance Contract.c //The text on the buttons at the bottom of the screen. static const wchar_t *s_rus_InsContractText[InsContractText_SIZE] = { L"Назад", L"Далее", L"ОК", L"Очистить", }; //Insurance Info // Text on the buttons on the bottom of the screen static const wchar_t *s_rus_InsInfoText[InsInfoText_SIZE] = { L"Назад", L"Далее" }; //For use at the M.E.R.C. web site. Text relating to the player's account with MERC static const wchar_t *s_rus_MercAccountText[MercAccountText_SIZE] = { // Text on the buttons on the bottom of the screen L"Оплатить", L"Главная", L"Счет #:", L"Наемник", L"Дни", L"Ставка", //5 L"Плата", L"Всего:", L"Подтверждаете выплату %ls?", //the %ls is a string that contains the dollar amount ( ex. "$150" ) }; //For use at the M.E.R.C. web site. Text relating a MERC mercenary static const wchar_t *s_rus_MercInfo[MercInfo_SIZE] = { L"Назад", L"Нанять", L"Дальше", L"Дополнительная информация", L"На главную", L"В команде", L"Зарплата:", L"/день", L"Мертв(а)", L"Похоже, вы увлеклись набором наемников. Не более 18 бойцов в команде.", L"Отсутствует", }; // For use at the M.E.R.C. web site. Text relating to opening an account with MERC static const wchar_t *s_rus_MercNoAccountText[MercNoAccountText_SIZE] = { //Text on the buttons at the bottom of the screen L"Открыть счет", L"Отмена", L"У вас нет счета. Хотите открыть?" }; // For use at the M.E.R.C. web site. MERC Homepage static const wchar_t *s_rus_MercHomePageText[MercHomePageText_SIZE] = { //Description of various parts on the MERC page L"Спек Т. Клайн, основатель", L"Открытие счета", L"Просмотр счета", L"Личные дела", // The version number on the video conferencing system that pops up when Speck is talking L"Спек Ком v3.2" }; // For use at MiGillicutty's Web Page. static const wchar_t *s_rus_sFuneralString[sFuneralString_SIZE] = { L"Похоронное агенство Макгилликати: скорбим вместе с семьями усопших с 1983 года.", L"Директор по похоронам и бывший наемник \"Папаша\" Макгилликати - специалист по части похорон.", L"Всю жизнь Папашу сопровождали смерть и утраты, поэтому он, как никто, познал их тяжесть.", L"Агенство Макгилликати предлагает широкий спектр похоронных услуг - от жилетки, в которую можно поплакать, до восстановления сильно поврежденных останков.", L"Доверьтесь похоронному агенству Макгилликати, и ваши родственники почиют в мире.", // Text for the various links available at the bottom of the page L"ДОСТАВКА ЦВЕТОВ", L"КОЛЛЕКЦИЯ УРН И ГРОБОВ", L"УСЛУГИ ПО КРЕМАЦИИ", L"ПОМОЩЬ В ПРОВЕДЕНИИ ПОХОРОН", L"ПОХОРОННЫЕ РИТУАЛЫ", // The text that comes up when you click on any of the links ( except for send flowers ). L"К сожалению, наш сайт не закончен, в связи с утратой в семье. Мы постараемся продолжить работу после прочтения завещания и выплат долгов умершего.", L"Однако, мы все равно скорбим вместе с вами. Пожалуйста, приходите еще." }; // Text for the florist Home page static const wchar_t *s_rus_sFloristText[sFloristText_SIZE] = { //Text on the button on the bottom of the page L"Галерея", //Address of United Florist L"\"Авиадоставка по всему миру\"", L"1-555-SCENT-ME", L"333 , Семябург, КА США 90210", L"http://www.scent-me.com", // detail of the florist page L"Работаем быстро и эффективно!", L"Гарантированная доставка в течение одного дня в любую точку земного шара. Есть ограничения.", L"Самые низкие в мире цены!", L"Покажите нам рекламу подобных услуг, которые стоят дешевле и получите букет роз бесплатно.", L"Летающая Флора, Фауна & Цветы с 1981.", L"Наши летчики, в прошлом военные бомбардировщики, сбросят ваш букет в радиусе 10 км от цели. В любое время! Всегда!", L"Позвольте нам воплотить ваши цветочные фантазии в жизнь.", L"Брюс, наш всемирно известный флорист, собственноручно соберет вам букет свежайших цветов из наших оранжерей.", L"И помните, если у нас чего-то нет - мы это вырастим! И быстро!" }; //Florist OrderForm static const wchar_t *s_rus_sOrderFormText[sOrderFormText_SIZE] = { //Text on the buttons L"Назад", L"Послать", L"Очистить", L"Галерея", L"Букет:", L"Цена:", //5 L"Номер заказа:", L"Срочность", L"завтра", L"дойдет, когда дойдет", L"Место доставки", //10 L"Доп. услуги", L"Сломанные цветы($10)", L"Черные розы($20)", L"Увядший букет($10)", L"Фруктовый пирог(если есть)($10)", //15 L"Ваше пожелание:", L"Ввиду небольшого размера открыток - не более 75 символов.", L"...или выберите из наших", L"СТАНДАРТНЫХ ПОЖЕЛАНИЙ", L"Информация о дарителе",//20 //The text that goes beside the area where the user can enter their name L"Имя:", }; //Florist Gallery.c static const wchar_t *s_rus_sFloristGalleryText[sFloristGalleryText_SIZE] = { //text on the buttons L"Назад", //abbreviation for previous L"Далее", //abbreviation for next L"Кликните по желаемому букету.", L"Примечание: можно заказать увядший или сломанный букет за дополнительные $10.", //text on the button L"Главная", }; //Florist Cards static const wchar_t *s_rus_sFloristCards[sFloristCards_SIZE] = { L"Кликните для выбора", L"Назад" }; // Text for Bobby Ray's Mail Order Site static const wchar_t *s_rus_BobbyROrderFormText[BobbyROrderFormText_SIZE] = { L"Бланк заказа", //Title of the page L"Шт.", // The number of items ordered L"Вес (%ls)", // The weight of the item L"Наименование", // The name of the item L"Цена", // the item's price L"Всего", //5 // The total price of all of items of the same type L"Цена товаров", // The sub total of all the item totals added L"Доставка и упаковка", // S&H is an acronym for Shipping and Handling L"Цена с доставкой", // The grand total of all item totals + the shipping and handling L"Место доставки", L"Тип доставки", //10 // See below L"Цена (за %ls.)", // The cost to ship the items L"Доставка наутро", // Gets deliverd the next day L"2 рабочих дня", // Gets delivered in 2 days L"Стандартный срок", // Gets delivered in 3 days L"Очистить",//15 // Clears the order page L"Принять заказ", // Accept the order L"Назад", // text on the button that returns to the previous page L"Главная", // Text on the button that returns to the home page L"* обозначает товары Б/У", // Disclaimer stating that the item is used L"У вас нет на это средств.", //20 // A popup message that to warn of not enough money L"<ПУСТО>", // Gets displayed when there is no valid city selected L"Место доставки заказа %ls. Уверены?", // A popup that asks if the city selected is the correct one L"Вес товаров**", // Displays the weight of the package L"** минимальный вес заказа", // Disclaimer states that there is a minimum weight for the package L"Заказы", }; // This text is used when on the various Bobby Ray Web site pages that sell items static const wchar_t *s_rus_BobbyRText[BobbyRText_SIZE] = { L"Правила:", // Title // instructions on how to order L"Кликните на предмет. Хотите больше - кликайте еще. Убрать предмет из заказа - правый клик. Закончив выбор покупок, заполните бланк заказа.", //Text on the buttons to go the various links L"Назад", // L"Оружие", //3 L"Амуниция", //4 L"Броня", //5 L"Разное", //6 //misc is an abbreviation for miscellaneous L"Б/У", //7 L"Дальше", L"ЗАКАЗАТЬ", L"Главная", //10 //The following lines provide information on the items L"Вес:", // Weight of all the items of the same type L"Калибр:", // the caliber of the gun L"Магаз.:", // number of rounds of ammo the Magazine can hold L"Дальноб.:", // The range of the gun L"Урон:", // Damage of the weapon L"Скор.:", // Weapon's Rate Of Fire, acronym ROF L"Цена:", // Cost of the item L"Склад:", // The number of items still in the store's inventory L"Заказано, шт:", // The number of items on order L"Повреждение", // If the item is damaged L"Итого:", // The total cost of all items on order L"* процент исправности", // if the item is damaged, displays the percent function of the item //Popup that tells the player that they can only order 10 items at a time L"Дорогие клиенты! Онлайновая форма позволяет заказать не более 10 позиций за раз. Если вы хотите заказать больше, (а мы надемся, что так и есть), заполните еще один бланк и примите наши извинения.", // A popup that tells the user that they are trying to order more items then the store has in stock L"Извините. Этот товар закончился на складе. Попробуйте заказать его позже.", //A popup that tells the user that the store is temporarily sold out L"Извините, но все товары этого типа закончились на складе.", }; /* The following line is used on the Ammunition page. It is used for help text * to display how many items the player's merc has that can use this type of * ammo. */ static const wchar_t s_rus_str_bobbyr_guns_num_guns_that_use_ammo[] = L"Количество единиц оружия у вашей команды, использующих этот боеприпас: %d"; // Text for Bobby Ray's Home Page static const wchar_t *s_rus_BobbyRaysFrontText[BobbyRaysFrontText_SIZE] = { //Details on the web site L"Только у нас можно приобрести последние новинки в оружейном деле", L"Прекрасный выбор взрывчатки и аксессуаров на любой вкус", L"Б/У", //Text for the various links to the sub pages L"РАЗНОЕ", L"ОРУЖИЕ", L"АМУНИЦИЯ", //5 L"БРОНЯ", //Details on the web site L"Нет у нас - нет нигде!", L"В разработке", }; // Text for the AIM page. // This is the text used when the user selects the way to sort the aim mercanaries on the AIM mug shot page static const wchar_t *s_rus_AimSortText[AimSortText_SIZE] = { L"Наемники А.I.M.", // Title // Title for the way to sort L"Сортировка:", //Text of the links to other AIM pages L"Просмотреть фото наемников", L"Просмотреть характеристики наемников", L"Просмотреть галерею бывших членов А.I.M." }; // text to display how the entries will be sorted static const wchar_t s_rus_str_aim_sort_price[] = L"Цена"; static const wchar_t s_rus_str_aim_sort_experience[] = L"Опытность"; static const wchar_t s_rus_str_aim_sort_marksmanship[] = L"Меткость"; static const wchar_t s_rus_str_aim_sort_medical[] = L"Медицина"; static const wchar_t s_rus_str_aim_sort_explosives[] = L"Взрывчатка"; static const wchar_t s_rus_str_aim_sort_mechanical[] = L"Механика"; static const wchar_t s_rus_str_aim_sort_ascending[] = L"по возрастанию"; static const wchar_t s_rus_str_aim_sort_descending[] = L"по убыванию "; //Aim Policies.c //The page in which the AIM policies and regulations are displayed static const wchar_t *s_rus_AimPolicyText[AimPolicyText_SIZE] = { // The text on the buttons at the bottom of the page L"Назад", L"Главная", L"Правила", L"Дальше", L"Не согласен", L"Согласен" }; //Aim Member.c //The page in which the players hires AIM mercenaries // Instructions to the user to either start video conferencing with the merc, or to go the mug shot index static const wchar_t *s_rus_AimMemberText[AimMemberText_SIZE] = { L"Левый щелчок", L"связаться", L"Правый щелчок", L"назад к фото", }; //Aim Member.c //The page in which the players hires AIM mercenaries static const wchar_t *s_rus_CharacterInfo[CharacterInfo_SIZE] = { // the contract expenses' area L"Плата", L"Срок", L"1 день", L"7 дней", L"14 дней", // text for the buttons that either go to the previous merc, // start talking to the merc, or go to the next merc L"<<<<", L"Связь", L">>>>", L"Дополнительная информация", // Title for the additional info for the merc's bio L"Действующие наемники A.I.M.", // Title of the page L"Цена снаряжения:", // Displays the optional gear cost L"медицинский депозит", // If the merc required a medical deposit, this is displayed }; //Aim Member.c //The page in which the player's hires AIM mercenaries //The following text is used with the video conference popup static const wchar_t *s_rus_VideoConfercingText[VideoConfercingText_SIZE] = { L"Цена контракта:", //Title beside the cost of hiring the merc //Text on the buttons to select the length of time the merc can be hired L"1 день", L"7 дней", L"14 дней", //Text on the buttons to determine if you want the merc to come with the equipment L"Без снаряжения", L"Со снаряжением", // Text on the Buttons L"ОПЛАТИТЬ", // to actually hire the merc L"ОТМЕНА", // go back to the previous menu L"НАНЯТЬ", // go to menu in which you can hire the merc L"ОТБОЙ", // stops talking with the merc L"OK", L"СООБЩЕНИЕ", // if the merc is not there, you can leave a message //Text on the top of the video conference popup L"Видеоконференция, абонент", L"Соединение. . .", L"с депозитом" // Displays if you are hiring the merc with the medical deposit }; //Aim Member.c //The page in which the player hires AIM mercenaries // The text that pops up when you select the TRANSFER FUNDS button static const wchar_t *s_rus_AimPopUpText[AimPopUpText_SIZE] = { L"ЭЛЕКТРОННЫЙ ПЛАТЕЖ ПРОШЕЛ УСПЕШНО", // You hired the merc L"ОШИБКА! НЕТ", // Player doesn't have enough money, message 1 L"СРЕДСТВ НА СЧЕТУ!", // Player doesn't have enough money, message 2 // if the merc is not available, one of the following is displayed over the merc's face L"На задании", L"Оставьте сообщение", L"Скончался", //If you try to hire more mercs than game can support L"У вас уже набрано 18 наемников - полная команда.", L"АВТО ОТВЕТЧИК", L"Сообщение записано", }; //AIM Link.c static const wchar_t s_rus_AimLinkText[] = L"Ссылки A.I.M."; // The title of the AIM links page //Aim History // This page displays the history of AIM static const wchar_t *s_rus_AimHistoryText[AimHistoryText_SIZE] = { L"История A.I.M.", //Title // Text on the buttons at the bottom of the page L"Назад", L"Главная", L"Галерея", L"Дальше" }; //Aim Mug Shot Index //The page in which all the AIM members' portraits are displayed in the order selected by the AIM sort page. static const wchar_t *s_rus_AimFiText[AimFiText_SIZE] = { // displays the way in which the mercs were sorted L"цены", L"опытности", L"меткости", L"медицины", L"саперных навыков", L"навыков механика", // The title of the page, the above text gets added at the end of this text L"Список наемников по возрастанию %ls", L"Список наемников по убыванию %ls", // Instructions to the players on what to do L"Левый щелчок", L"выбор наемника", //10 L"Правый щелчок", L"настройка сортировки", // Gets displayed on top of the merc's portrait if they are... L"Скончался", //14 L"На задании", }; //AimArchives. // The page that displays information about the older AIM alumni merc... mercs who are no longer with AIM static const wchar_t *s_rus_AimAlumniText[AimAlumniText_SIZE] = { // Text of the buttons L"СТР 1", L"СТР 2", L"СТР 3", L"Галерея бывших членов A.I.M.", // Title of the page //$$ L"ОК" // Stops displaying information on selected merc }; //AIM Home Page static const wchar_t *s_rus_AimScreenText[AimScreenText_SIZE] = { // AIM disclaimers L"A.I.M. и логотип A.I.M. - зарегистрированные во многих странах торговые марки.", L"Поэтому даже и не думайте нас копировать.", L"Копирайт 1998-1999 A.I.M.,Ltd. Все права защищены.", //Text for an advertisement that gets displayed on the AIM page L"Цветы по Всему Миру", L"\"Авиадоставка куда угодно\"", //10 L"Сделай как надо", L"... первый раз", L"Если у нас чего-то нет - оно вам и не нужно.", }; //Aim Home Page static const wchar_t *s_rus_AimBottomMenuText[AimBottomMenuText_SIZE] = { //Text for the links at the bottom of all AIM pages L"Главная", L"Наемники", L"Галерея", //$$ L"Правила", L"История", L"Ссылки" }; //ShopKeeper Interface // The shopkeeper interface is displayed when the merc wants to interact with // the various store clerks scattered through out the game. static const wchar_t *s_rus_SKI_Text[SKI_SIZE ] = { L"ТОВАРЫ В ПРОДАЖЕ", //Header for the merchandise available L"СТР", //The current store inventory page being displayed L"ОБЩАЯ ЦЕНА", //The total cost of the the items in the Dealer inventory area L"ОБЩАЯ ЦЕНА", //The total value of items player wishes to sell L"ОЦЕНКА", //Button text for dealer to evaluate items the player wants to sell L"ПО РУКАМ", //Button text which completes the deal. Makes the transaction. L"ГОТОВО", //Text for the button which will leave the shopkeeper interface. L"ЦЕНА РЕМОНТА", //The amount the dealer will charge to repair the merc's goods L"1 ЧАС", // SINGULAR! The text underneath the inventory slot when an item is given to the dealer to be repaired L"%d ЧАСОВ", // PLURAL! The text underneath the inventory slot when an item is given to the dealer to be repaired L"ОТРЕМОНТИРОВАНО", // Text appearing over an item that has just been repaired by a NPC repairman dealer L"Вам уже некуда класть вещи.", //Message box that tells the user there is no more room to put there stuff L"%d МИНУТ", // The text underneath the inventory slot when an item is given to the dealer to be repaired L"Бросить на землю", //hint about dropping item on the ground from ShopKeeper screen }; static const wchar_t *s_rus_SkiMessageBoxText[SkiMessageBoxText_SIZE] = { L"Cнять %ls со своего основного счета, чтобы покрыть разницу?", L"Недостаточно денег. Не хватает %ls", L"Cнять %ls со своего основного счета, чтобы оплатить покупку?", L"Предложить торговцу совершить сделку", L"Попросить торговца починить выбранные вещи", L"Закончить разговор", L"Текущий баланс", }; //OptionScreen.c static const wchar_t *s_rus_zOptionsText[zOptionsText_SIZE] = { //button Text L"Сохранить", L"Загрузить", L"Выход", L"Готово", //Text above the slider bars L"Звуки", L"Речь", L"Музыка", //Confirmation pop when the user selects.. L"Выйти из игры и вернуться в главное меню?", L"Нужно выбрать либо РЕЧЬ, либо СУБТИТРЫ.", }; //SaveLoadScreen static const wchar_t *s_rus_zSaveLoadText[zSaveLoadText_SIZE] = { L"Сохранить", L"Загрузить", L"Отмена", L"Сохранить выбранную.", //string arent used in game L"Загрузить выбранную", //string arent used in game L"Игра сохранена", L"Ошибка при сохранении!", L"Игра загружена", L"Ошибка при загрузке: \"%hs\"", L"Версия сохраненной игры отличается от текущей. Скорее всего, игра загрузится нормально. Загрузить?", L"Файлы сохраненной игры возможно испорчены. Стереть все?", //Translators, the next two strings are for the same thing. The first one is for beta version releases and the second one //is used for the final version. Please don't modify the "#ifdef JA2BETAVERSION" or the "#else" or the "#endif" as they are //used by the compiler and will cause program errors if modified/removed. It's okay to translate the strings though. #ifdef JA2BETAVERSION L"Версия сохранения изменилась. Сообщите, если будут проблемы. Продолжить?", #else L"Попытка загрузки старой версии сохранения. Обновить автоматически и загрузить?", #endif //Translators, the next two strings are for the same thing. The first one is for beta version releases and the second one //is used for the final version. Please don't modify the "#ifdef JA2BETAVERSION" or the "#else" or the "#endif" as they are //used by the compiler and will cause program errors if modified/removed. It's okay to translate the strings though. #ifdef JA2BETAVERSION L"Версия сохранения изменилась. Сообщите, если будут проблемы. Продолжить?", #else L"Попытка загрузки старой версии сохранения. Обновить автоматически и загрузить?", #endif L"Вы уверены, что хотите перезаписать сохраненную игру #%d?", //The first %d is a number that contains the amount of free space on the users hard drive, //the second is the recommended amount of free space. L"У вас кончается дисковое пространство. Осталось всего %d Mбайт. Нужно как минимум %d свободных Mбайт.", L"Сохранение...", //When saving a game, a message box with this string appears on the screen L"Оружие: реализм", L"Оружие: тонны", L"Стиль: реализм", L"Стиль: фантаст.", L"", }; //MapScreen static const wchar_t *s_rus_zMarksMapScreenText[zMarksMapScreenText_SIZE] = { L"Уровень карты", L"У вас нет ополчения. Подготовьте его из гражданского населения.", L"Доход в день", L"Жизнь наемника застрахована", L"%ls не устал(а).", L"%ls движется и спать не может", L"%ls слишком устал(а), попробуйте позже.", L"%ls за рулем.", L"Отряд не может двигаться, пока кто-то из бойцов спит.", // stuff for contracts L"Вы можете платить по контракту, но у вас нет денег на оплату страхования жизни.", L"%ls застрахован(а) на случай гибели. Для продления страховки надо доплатить %ls за %d дней. Согласны?", L"Предметы в секторе", L"У наемника есть медицинский депозит", // other items L"Медики", // people acting a field medics and bandaging wounded mercs L"Пациенты", // people who are being bandaged by a medic L"Готово", // Continue on with the game after autobandage is complete L"Стоп", // Stop autobandaging of patients by medics now L"%ls не может этого сделать, нет инструментов для ремонта.", L"%ls не может этого сделать, нет медицинских принадлежностей.", L"Недостаточно желающих пройти подготовку.", L"%ls: слишком много ополченцев.", L"У наемника ограниченный по времени контракт", L"У наемника нет страховки", }; static const wchar_t s_rus_pLandMarkInSectorString[] = L"Отряд %d заметил кого-то в секторе %ls"; // confirm the player wants to pay X dollars to build a militia force in town static const wchar_t *s_rus_pMilitiaConfirmStrings[pMilitiaConfirmStrings_SIZE] = { L"Тренировка отряда ополчения будет стоить $", // telling player how much it will cost L"Оплатить расходы?", // asking player if they wish to pay the amount requested L"У вас нет такой суммы.", // telling the player they can't afford to train this town L"Продолжить тренировку ополчения в %ls (%ls %d)?", // continue training this town? L"Стоимость $", // the cost in dollars to train militia L"(Д/Н)", // abbreviated yes/no L"Тренировка ополчения в %d секторах будет стоить $ %d. %ls", // cost to train sveral sectors at once L"У вас нет $%d на тренировку здесь ополчения.", L"%ls: нужно %d%% отношения к вам, чтобы продолжить тренировку ополчения.", L"%ls: невозможно продолжить подготовку ополчения.", }; //Strings used in the popup box when withdrawing, or depositing money from the $ sign at the bottom of the single merc panel static const wchar_t *s_rus_gzMoneyWithdrawMessageText[gzMoneyWithdrawMessageText_SIZE] = { L"За один раз можно снять со счета не более $20,000.", L"Вы уверены, что хотите положить %ls на свой счет?", }; static const wchar_t s_rus_gzCopyrightText[] = L"Авторские права(C) 1999 Sir-Tech Canada Ltd. Все права защищены. Распространение на территории стран СНГ компания БУКА."; static const wchar_t s_rusGold_gzCopyrightText[] = L"(C) 2002 Strategy First и компания Акелла. Все права защищены."; //option Text static const wchar_t *s_rus_zOptionsToggleText[zOptionsToggleText_SIZE] = { L"Речь", L"Заглушить отзывы", L"Субтитры", L"Диалоги с паузами", L"Анимированный дым", L"Кровища", L"Не трожь мою мышь!", L"Старый способ выбора", L"Показывать путь", L"Показывать промахи", L"Подтверждение движения", L"Оповещение о сне/бодрствовании", L"Метрическая система мер", L"Подсветка земли", L"Переводить курсор на наемников", L"Переводить курсор на двери", L"Подсветка вещей", L"Показывать верхушки деревьев", L"Показывать каркасы", L"Трехмерный курсор", }; //This is the help text associated with the above toggles. static const wchar_t *s_rus_zOptionsScreenHelpText[zOptionsToggleText_SIZE] = { //speech L"Включите эту опцию, если хотите слышать диалоги персонажей.", //Mute Confirmation L"Включите эту опцию, чтобы заглушить отзывы на команды.", //Subtitles L"Показывать тексты диалогов.", //Key to advance speech L"Включите эту опцию, чтобы субтитры переходили к следующей фразе по нажатию клавиши.", //Toggle smoke animation L"Отключите эту опцию, если анимированный дым тормозит игру.", //Blood n Gore L"Отключите эту опцию, если вам не нравится вид крови.", //Never move my mouse L"Отключите эту опцию, чтобы курсор автоматически перемещался к всплывающим окнам.", //Old selection method L"Включает выбор персонажей, как в Jagged Alliance 1 (иначе выбор происходит наоборот).", //Show movement path L"Включает отображение пути бойца в реальном времени (или отключите эту опцию и используйте SHIFT).", //show misses L"Включите эту опцию, чтобы видеть, куда попадают пули при \"промахе\".", //Sleep/Wake notification L"При включенной опции для движения в реальном времени необходим дополнительный клик мышью.", //Display the enemy indicator L"Включает отображение оповещений о том, что ваш боец засыпает или просыпается.", //Use the metric system L"Когда опция включена, игра использует метрическую систему мер, иначе - британскую.", //Merc Lighted movement L"Когда опция включена, боец \"освещает\" землю при движении. Отключите для улучшения производительности.", //Smart cursor L"Когда опция включена, бойцы выбираются, если курсор рядом с ними.", //snap cursor to the door L"Когда опция включена, курсор перескакивает на дверь, если он рядом с ней.", //glow items L"Включает постоянную подсветку предметов на земле (|I).", //toggle tree tops L"Включает отображение верхушек деревьев (|Е).", //toggle wireframe L"Включает отображение \"каркасов\" домов (|W).", L"Включает \"трехмерный\" курсор движения (|H|o|m|e).", }; static const wchar_t *s_rus_gzGIOScreenText[gzGIOScreenText_SIZE] = { L"ИГРОВЫЕ НАСТРОЙКИ", L"Стиль игры", L"Реалистичный", L"Фантастичный", L"Количество оружия", L"Сотни стволов", L"Как в жизни", L"Уровень сложности", L"НОВОБРАНЕЦ", L"СОЛДАТ", L"ВЕТЕРАН", L"Ok", L"Отмена", L"Дополнительная сложность", L"Сохранение где угодно", L"СТАЛЬНАЯ ВОЛЯ" }; static const wchar_t *s_rus_pDeliveryLocationStrings[pDeliveryLocationStrings_SIZE] = { L"Остин", //Austin, Texas, USA L"Багдад", //Baghdad, Iraq (Suddam Hussein's home) L"Драссен", //The main place in JA2 that you can receive items. The other towns are dummy names... L"Гонконг", //Hong Kong, Hong Kong L"Бейрут", //Beirut, Lebanon (Middle East) L"Лондон", //London, England L"", //Los Angeles, California, USA (SW corner of USA) L"Медуна", //Meduna -- the other airport in JA2 that you can receive items. L"Метавира", //The island of Metavira was the fictional location used by JA1 L"Майами", //Miami, Florida, USA (SE corner of USA) L"Москва", //Moscow, USSR L"Нью-Йорк", //New York, New York, USA L"Оттава", //Ottawa, Ontario, Canada -- where JA2 was made! L"Париж", //Paris, France L"Триполи", //Tripoli, Libya (eastern Mediterranean) L"Токио", //Tokyo, Japan L"Ванкувер", //Vancouver, British Columbia, Canada (west coast near US border) }; /* This string is used in the IMP character generation. It is possible to * select 0 ability in a skill meaning you can't use it. This text is * confirmation to the player. */ static const wchar_t s_rus_pSkillAtZeroWarning[] = L"Уверены? Ноль означает отсутствие навыка."; static const wchar_t s_rus_pIMPBeginScreenStrings[] = L"(не более 8 букв)"; static const wchar_t s_rus_pIMPFinishButtonText[] = L"Анализ"; static const wchar_t s_rus_pIMPFinishStrings[] = L"Спасибо, %ls"; //%ls is the name of the merc static const wchar_t s_rus_pIMPVoicesStrings[] = L"Голос"; // the strings for imp voices screen // title for program static const wchar_t s_rus_pPersTitleText[] = L"Кадры"; // paused game strings static const wchar_t *s_rus_pPausedGameText[pPausedGameText_SIZE] = { L"Пауза", L"Снять с паузы (|P|a|u|s|e)", L"Поставить на паузу (|P|a|u|s|e)", }; static const wchar_t *s_rus_pMessageStrings[pMessageStrings_SIZE] = { L"Выйти из игры?", L"OK", L"ДА", L"НЕТ", L"ОТМЕНА", L"НАНЯТЬ", L"ЛОЖЬ", L"Нет описания", //Save slots that don't have a description. L"Игра сохранена", L"День", L"Наемников", L"Пустая ячейка сохранения", //An empty save game slot L"в/м", //Abbreviation for Rounds per minute -- the potential # of bullets fired in a minute. L"мин", //Abbreviation for minute. L"м", //One character abbreviation for meter (metric distance measurement unit). L"пуль", //Abbreviation for rounds (# of bullets) L"кг", //Abbreviation for kilogram (metric weight measurement unit) L"ф", //Abbreviation for pounds (Imperial weight measurement unit) L"Главная страница", //Home as in homepage on the internet. Used on M.I.S. insurance web page L"USD", //Abbreviation to US dollars L"н/п", //Lowercase acronym for not applicable. L"Тем временем", //Meanwhile L"%ls теперь в секторе %ls%ls", //Name/Squad has arrived in sector A9. Order must not change without notifying //SirTech L"Версия", L"Пустая ячейка быстрого сохр", L"Эта ячейка предназначена для быстрого сохранения игры (с помощью ALT+S).", L"Открытая", //doors definitions L"Закрытая", //doors definitions L"У вас кончается дисковое пространство. У вас осталось %lsМБ свободных, а для игры требуется %lsMБ.", L"%ls ловит %ls.", //'Merc name' has caught 'item' -- let SirTech know if name comes after item. L"%ls принимает препарат.", //'Merc name' has taken the drug L"%ls не имеет медицинских навыков",//'Merc name' has no medical skill. //CDRom errors (such as ejecting CD while attempting to read the CD) L"Нарушена целостность программы.", L"ОШИБКА: Вынут CD-ROM", //When firing heavier weapons in close quarters, you may not have enough room to do so. L"Мало места для стрельбы.", //Can't change stance due to objects in the way... L"Сейчас изменить положение нельзя.", //Simple text indications that appear in the game, when the merc can do one of these things. L"Уронить", L"Бросить", L"Передать", L"%ls передан %ls.", //"Item" passed to "merc". Please try to keep the item %ls before the merc %ls, otherwise, //must notify SirTech. L"Нельзя передать %ls %ls.", //pass "item" to "merc". Same instructions as above. //A list of attachments appear after the items. Ex: Kevlar vest ( Ceramic Plate 'Attached )' L" присоединен)", //Cheat modes L"Достигнут чит-уровень один", L"Достигнут чит-уровень два", //Toggling various stealth modes L"Отряд в режиме скрытности.", L"Отряд в обычном режиме.", L"%ls в режиме скрытности.", L"%ls в обычном режиме.", //Wireframes are shown through buildings to reveal doors and windows that can't otherwise be seen in //an isometric engine. You can toggle this mode freely in the game. L"Отображение каркасов зданий включено", L"Отображение каркасов зданий выключено", //These are used in the cheat modes for changing levels in the game. Going from a basement level to //an upper level, etc. L"Нельзя подняться с этого уровня...", L"Ниже уровней нет...", L"Входим в подвальный уровень %d...", L"Уходим из подвала...", L".", // used in the shop keeper inteface to mark the ownership of the item eg Red's gun L"Режим слежения выключен.", L"Режим слежения включен.", L"Курсор трехмерный.", L"Курсор обычный.", L"Отряд %d действует.", L"У вас нет денег, чтобы ежедневно выплачивать %ls %ls", //first %ls is the mercs name, the seconds is a string containing the salary L"Пропуск", L"%ls не может идти в одиночку.", L"Игра была сохранена под именем SaveGame99.sav. Для загрузки переименуйте ее в SaveGame01-SaveGame10.", L"%ls пъет %ls", L"Груз снаряжения прибыл в Драссен.", L"%ls прибудет в указанное место высадки (сектор %ls) в день %d, примерно в %ls.", //first %ls is mercs name, next is the sector location and name where they will be arriving in, lastely is the day an the time of arrival L"Журнал событий обновлен.", #ifdef JA2BETAVERSION L"Игра сохранена в ячейку авто-сохранения.", #endif }; static const wchar_t *s_rus_ItemPickupHelpPopup[ItemPickupHelpPopup_SIZE] = { L"Взять выделенные", L"Листать вверх", L"Выделить все", L"Листать вниз", L"Отмена" }; static const wchar_t *s_rus_pDoctorWarningString[pDoctorWarningString_SIZE] = { L"%ls слишком далеко для лечения.", L"Медики не смогли перевязать всех.", }; static const wchar_t *s_rus_pMilitiaButtonsHelpText[pMilitiaButtonsHelpText_SIZE] = { L"Взять новобранцев (Правый клик)/Распределить (Левый клик)", // button help text informing player they can pick up or drop militia with this button L"Взять солдат (Правый клик)/Распределить (Левый клик)", L"Взять ветеранов (Правый клик)/Распределить (Левый клик)", L"Поровну распределить доступное ополчение по всем секторам", }; // to inform the player to hire some mercs to get things going static const wchar_t s_rus_pMapScreenJustStartedHelpText[] = L"Сходите на сайт АIM и наймите наемников (*Подсказка* через ноутбук)"; static const wchar_t s_rus_pAntiHackerString[] = L"Ошибка. Испорченные или отсутствующие файлы. Игра завершает работу."; static const wchar_t *s_rus_gzLaptopHelpText[gzLaptopHelpText_SIZE] = { //Buttons: L"Просмотреть электроные письма", L"Посетить Интернет сайты", L"Просмотреть файлы", L"Просмотреть журнал событий", L"Информация о команде", L"Просмотреть финансовые отчеты", L"Выключить лэптоп", //Bottom task bar icons (if they exist): L"Получена новая почта", L"Получены новые файлы", //Bookmarks: L"Международная Ассоци", L" - заказ оружия в сети", L"", L"M.E.R.C - Экономичный Рекрутинговый Центр", L"Похоронное агенство Макгилликати", L"Цветы по Всему Миру", L"Страховые агенты по контрактам A.I.M.", }; static const wchar_t s_rus_gzHelpScreenText[] = L"Закрыть помощь"; static const wchar_t *s_rus_gzNonPersistantPBIText[gzNonPersistantPBIText_SIZE] = { L"Идет бой. Отступить можно только с тактической карты", L"Войти в сектор, чтобы продолжить бой (|E)", L"Продолжить бой в автоматическом режиме (|A)", L"Нельзя провести авто-бой, когда вы нападаете", L"Нельзя провести авто-бой, когда вы попали в засаду", L"Нельзя провести авто-бой, когда вы сражаетесь с существами в шахтах", L"Нельзя провести авто-бой, если рядом враждебные жители", L"Нельзя провести авто-бой, если рядом кошки-убийцы", L"ИДЕТ БОЙ", L"Сейчас отступить нельзя", }; static const wchar_t *s_rus_gzMiscString[gzMiscString_SIZE] = { L"Ваше ополчение сражается без помощи наемников...", L"Транспорт полностью заправлен.", L"Бензобак заправлен на %d%%.", L"А полностью захватила %ls.", L"Вы потеряли заправку.", }; static const wchar_t s_rus_gzIntroScreen[] = L"Невозможно найти вступительный ролик"; // These strings are combined with a merc name, a volume string (from pNoiseVolStr), // and a direction (either "above", "below", or a string from pDirectionStr) to // report a noise. // e.g. "Sidney hears a loud sound of MOVEMENT coming from the SOUTH." static const wchar_t *s_rus_pNewNoiseStr[pNewNoiseStr_SIZE] = { L"%ls слышит %ls звук, идущий %ls.", L"%ls слышит %ls звук ДВИЖЕНИЯ, идущий %ls.", L"%ls слышит %ls СКРИП, идущий %ls.", L"%ls слышит %ls ПЛЕСК, идущий %ls.", L"%ls слышит %ls УДАР, идущий %ls.", //$$ L"%ls слышит %ls ВЗРЫВ %ls.", L"%ls слышит %ls КРИК %ls.", L"%ls слышит %ls УДАР %ls.", L"%ls слышит %ls УДАР %ls.", L"%ls слышит %ls ЗВОН, идущий %ls.", L"%ls слышит %ls ГРОХОТ, идущий %ls.", }; static const wchar_t *s_rus_wMapScreenSortButtonHelpText[wMapScreenSortButtonHelpText_SIZE] = { L"Сортировка по имени (|F|1)", L"Сортировка по заданию (|F|2)", L"Сортировка по сну/бодрствованию (|F|3)", L"Сортировка по месту (|F|4)", L"Сортировка по цели (|F|5)", L"Сортировка по времени контракта (|F|6)", }; static const wchar_t *s_rus_BrokenLinkText[BrokenLinkText_SIZE] = { L"Ошибка 404", L"URL не найден.", }; static const wchar_t *s_rus_gzBobbyRShipmentText[gzBobbyRShipmentText_SIZE] = { L"Последние заказы", L"Заказ #", L"Предметов", L"Дата", }; static const wchar_t *s_rus_gzCreditNames[gzCreditNames_SIZE]= { L"", L"", L"", L"", L"", L"Eric \"WTF\" Cheng", L"", L"Norman \"NRG\" Olsen", L"", L"", L"", L"Andrew \"Big Cheese\" Emmons", L"Dave \"The Feral\" French", L"", L"Joey \"Joeker\" Whelan", }; static const wchar_t *s_rus_gzCreditNameTitle[gzCreditNameTitle_SIZE]= { L"Ведущий программист игры", // !!! L"Дизайн/Сценарий", // L"Программист стратегической части и редактора", // L"Продюсер/Дизайн", // L"Дизайн/Дизайн карт", // L"Художник", // Eric \"WTF\" Cheng L"Бета-координатор, техподдержка", // L"Художник от Бога", // Norman \"NRG\" Olsen L"Гуру звука", // L"Дизайн экранов/Художник", // L"Главный художник/Аниматор", // L"Главный программист", // Andrew \"Big Cheese Doddle\" Emmons L"Программист", // L"Программист стратегической части и баланса игры", // L"Художник по портретам", // Joey \"Joeker\" Whelan", }; static const wchar_t *s_rus_gzCreditNameFunny[gzCreditNameFunny_SIZE]= { L"", // L"(все еще зубрит правила пунктуации)", // L"(\"Оно работает. Я просто чиню\")", //Kris \"The Cow Rape Man\" Marnes L"(слишком стар для всего этого)", // L"(работает и над Wizardry 8)", // L"(принужденный заниматься тестированием)", // Eric \"WTF\" Cheng L"(Ушла от нас в CFSA - вот тебе на...)", // L"", // Norman \"NRG\" Olsen L"", // L"( и любитель джаза)", // L"(его настоящее имя Роберт)", // L"(единственное ответственное лицо)", // Andrew \"Big Cheese Doddle\" Emmons L"(может опять заняться мотогонками)", // L"(украден с работы над Wizardry 8)", // L"(делал предметы и загрузочные экраны!)", // Joey \"Joeker\" Whelan", }; static const wchar_t *s_rus_sRepairsDoneString[sRepairsDoneString_SIZE] = { L"%ls отремонтировал(а) свои вещи", L"%ls отремонтировал(а) оружие и броню команды", L"%ls отремонтировал(а) снаряжение команды", L"%ls отремонтировал(а) транспортируемые командой вещи", }; static const wchar_t *s_rus_zGioDifConfirmText[zGioDifConfirmText_SIZE]= { L"Вы выбрали сложность НОВОБРАНЕЦ. Это подходит для новичков в Jagged Alliance, для новичков в жанре стратегий вообще, или для тех, кто желает сократить битвы в игре. Ваш выбор скажется на игре в целом, так что выбирайте с умом. Уверены, что хотите играть новобранцем?", L"Вы выбрали сложность СОЛДАТ. Это подходит для игроков, уже знакомых с играми Jagged Alliance или с подобными им. Ваш выбор скажется на игре в целом, так что выбирайте с умом. Уверены, что хотите играть солдатом?", L"Вы выбрали сложность ВЕТЕРАН. Мы Вас предупредили. Нечего на нас пенять, если вас доставят назад в цинковом гробу. Ваш выбор скажется на игре в целом, так что выбирайте с умом. Уверены, что хотите играть ветераном?", }; static const wchar_t *s_rus_gzLateLocalizedString[gzLateLocalizedString_SIZE] = { //1-5 L"Робот не может покинуть сектор, если им никто не управляет.", //This message comes up if you have pending bombs waiting to explode in tactical. L"Сейчас ускорять время нельзя. Подождите фейерверка!", //'Name' refuses to move. L"%ls отказывается двигаться.", //%ls a merc name L"%ls без сил и не может поменять положение.", //A message that pops up when a vehicle runs out of gas. L"У %lsа кончилось топливо и он остается в %c%d.",///TRNSL Assumes that all vehicle names are male gender words //6-10 // the following two strings are combined with the pNewNoise[] strings above to report noises // heard above or below the merc L"сверху", L"снизу", //The following strings are used in autoresolve for autobandaging related feedback. L"Никто из ваших бойцов не умеет оказывать первую помощь.", L"Для оказания первой помощи нет аптечек.", L"Не хватает медикаментов и бинтов, чтобы перевязать всех.", L"Ваши бойцы не нуждаются в первой помощи.", L"Перевязать наемников автоматически", L"Всем бойцам оказана первая помощь.", //14 L"Арулько", L"(на крыше)", L"Здоровье: %d/%d", //In autoresolve if there were 5 mercs fighting 8 enemies the text would be "5 vs. 8" //"vs." is the abbreviation of versus. L"%d против %d", L"В %lsе нет места!", //(ex "The ice cream truck is full")///TRNSL_ASSUME vehicle gender is male L"%ls нуждается не в перевязке и первой помощи, а в основательном медицинском обследовании и/или отдыхе.", //20 //Happens when you get shot in the legs, and you fall down. L"%ls получает ранение в ногу и падает!", //Name can't speak right now. L"%ls не может сейчас говорить.", //22-24 plural versions @@@2 elite to veteran L"Несколько (%d) ополченцев-новобранцев стали ветеранами.", L"Несколько (%d) ополченцев-новобранецев стали солдатами.", L"Несколько (%d) ополченцев-солдат стали ветеранами.", //25 L"Перекл.", ///TRNSL_CHECK_INGAME LENGTH //26 //Name has gone psycho -- when the game forces the player into burstmode (certain unstable characters) L"%ls впадает в безумие!", //27-28 //Messages why a player can't time compress. L"Нельзя ускорять время, поскольку у вас есть бойцы в секторе %ls.", // L"Нельзя ускорять время, когда бойцы находятся в шахтах с монстрами.", // //29-31 singular versions @@@2 elite to veteran L"Один ополченец-новобранец стал ветераном.", L"Один ополченец-новобранец стал солдатом.", L"Один ополченец-солдат стал ветераном.", //32-34 L"%ls ничего не говорит.", L"Выбраться на поверхность?", L"(Отряд %d)", //35 //Ex: "Red has repaired Scope's MP5K". Careful to maintain the proper order (Red before Scope, Scope before MP5K) L"%ls починил для %ls %ls", //36 L"КОШКА-УБИЙЦА", //37-38 "Name trips and falls" L"%ls спотыкается и падает", L"Эту вещь нельзя взять отсюда.", //39 L"Ваши бойцы не в состоянии сражаться. Ополчение ведет бой с существами само.", //40-43 //%ls is the name of merc. L"%ls истратил(а) все медикаменты!", L"%ls не обладает навыками, чтобы лечить кого-либо!", L"%ls без инструментов!", L"%ls не обладает навыками, чтобы ремонтировать что-либо!", //44-45 L"Время ремонта", L"%ls не видит этого человека.", //46-48 L"%ls ломает удлинитель ствола!", L"Не разрешается больше %d тренеров ополчения на сектор.", L"Вы уверены?", //49-50 L"Ускорение времени", L"Бак теперь заправлен.", //51-52 Fast help text in mapscreen. L"Продолжить ускорение времени (|S|p|a|c|e)", L"Прекратить ускорение времени (|E|s|c)", //53-54 "Magic has unjammed the Glock 18" or "Magic has unjammed Raven's H&K G11" L"%ls расклинил %ls", L"%ls расклинил для %ls %ls", //55 L"Невозможно сжимать время при просмотре предметов сектора.", //56 //Displayed with the version information when cheats are enabled. L"Текущий/Максимальный: %d%%/%d%%", //57 L"Сопроводить Джона и Мэри?", L"Выключатель нажат." }; static const wchar_t s_rus_str_ceramic_plates_smashed[] = L"%ls: в бронежилете разбились пластины!"; static const wchar_t s_rus_str_arrival_rerouted[] = L"Место высадки новоприбывших наемников перенесено в сектор %ls; ранее заданный сектор %ls захвачен врагом."; static const wchar_t s_rus_str_stat_health[] = L"Здоровье"; static const wchar_t s_rus_str_stat_agility[] = L"Проворность"; static const wchar_t s_rus_str_stat_dexterity[] = L"Ловкость"; static const wchar_t s_rus_str_stat_strength[] = L"Сила"; static const wchar_t s_rus_str_stat_leadership[] = L"Лидерство"; static const wchar_t s_rus_str_stat_wisdom[] = L"Мудрость"; static const wchar_t s_rus_str_stat_exp_level[] = L"Опытность"; // Уровень опыта static const wchar_t s_rus_str_stat_marksmanship[] = L"Меткость"; static const wchar_t s_rus_str_stat_mechanical[] = L"Механика"; static const wchar_t s_rus_str_stat_explosive[] = L"Взрывник"; static const wchar_t s_rus_str_stat_medical[] = L"Медицина"; static const wchar_t *s_rus_str_stat_list[str_stat_list_SIZE] = { s_rus_str_stat_health, s_rus_str_stat_agility, s_rus_str_stat_dexterity, s_rus_str_stat_strength, s_rus_str_stat_leadership, s_rus_str_stat_wisdom, s_rus_str_stat_exp_level, s_rus_str_stat_marksmanship, s_rus_str_stat_mechanical, s_rus_str_stat_explosive, s_rus_str_stat_medical }; static const wchar_t *s_rus_str_aim_sort_list[str_aim_sort_list_SIZE] = { s_rus_str_aim_sort_price, s_rus_str_aim_sort_experience, s_rus_str_aim_sort_marksmanship, s_rus_str_aim_sort_medical, s_rus_str_aim_sort_explosives, s_rus_str_aim_sort_mechanical, s_rus_str_aim_sort_ascending, s_rus_str_aim_sort_descending, }; static const wchar_t * s_rus_zNewTacticalMessages[] = { L"Расстояние до цели: %d клеток", L"Дальнобойность оружия: %d клеток, расстояние до цели: %d клеток", L"Отобразить укрытия", L"Зона обзора", L"Это игра для человека со СТАЛЬНОЙ ВОЛЕЙ. Нельзя сохраняться, когда рядом враги!", L"(Нельзя сохранять игру в бою)", }; static const wchar_t s_rus_str_iron_man_mode_warning[] = L"Вы выбрали режим СТАЛЬНОЙ ВОЛИ. Эта настройка сильно усложняет игру, так как вы не сможете сохраняться, когда в секторе есть враги. ЖЕЛЕЗНАЯ ВОЛЯ действует в течение всей игры. Уверены, что хотите включить этот режим?"; /** Russian language resources. */ LanguageRes g_LanguageResRussian = { s_rus_WeaponType, s_rus_Message, s_rus_TeamTurnString, s_rus_pAssignMenuStrings, s_rus_pTrainingStrings, s_rus_pTrainingMenuStrings, s_rus_pAttributeMenuStrings, s_rus_pVehicleStrings, s_rus_pShortAttributeStrings, s_rus_pContractStrings, s_rus_pAssignmentStrings, s_rus_pConditionStrings, s_rus_pTownNames, s_rus_g_towns_locative, s_rus_pPersonnelScreenStrings, s_rus_pUpperLeftMapScreenStrings, s_rus_pTacticalPopupButtonStrings, s_rus_pSquadMenuStrings, s_rus_pDoorTrapStrings, s_rus_pLongAssignmentStrings, s_rus_pMapScreenMouseRegionHelpText, s_rus_pNoiseVolStr, s_rus_pNoiseTypeStr, s_rus_pDirectionStr, s_rus_pRemoveMercStrings, s_rus_sTimeStrings, s_rus_pLandTypeStrings, s_rus_pInvPanelTitleStrings, s_rus_pPOWStrings, s_rus_pMilitiaString, s_rus_pMilitiaButtonString, s_rus_pEpcMenuStrings, s_rus_pRepairStrings, s_rus_sPreStatBuildString, s_rus_sStatGainStrings, s_rus_pHelicopterEtaStrings, s_rus_sMapLevelString, s_rus_gsLoyalString, s_rus_gsUndergroundString, s_rus_gsTimeStrings, s_rus_sFacilitiesStrings, s_rus_pMapPopUpInventoryText, s_rus_pwTownInfoStrings, s_rus_pwMineStrings, s_rus_pwMiscSectorStrings, s_rus_pMapInventoryErrorString, s_rus_pMapInventoryStrings, s_rus_pMovementMenuStrings, s_rus_pUpdateMercStrings, s_rus_pMapScreenBorderButtonHelpText, s_rus_pMapScreenBottomFastHelp, s_rus_pMapScreenBottomText, s_rus_pMercDeadString, s_rus_pSenderNameList, s_rus_pNewMailStrings, s_rus_pDeleteMailStrings, s_rus_pEmailHeaders, s_rus_pEmailTitleText, s_rus_pFinanceTitle, s_rus_pFinanceSummary, s_rus_pFinanceHeaders, s_rus_pTransactionText, s_rus_pMoralStrings, s_rus_pSkyriderText, s_rus_str_left_equipment, s_rus_pMapScreenStatusStrings, s_rus_pMapScreenPrevNextCharButtonHelpText, s_rus_pEtaString, s_rus_pShortVehicleStrings, s_rus_pTrashItemText, s_rus_pMapErrorString, s_rus_pMapPlotStrings, s_rus_pBullseyeStrings, s_rus_pMiscMapScreenMouseRegionHelpText, s_rus_str_he_leaves_where_drop_equipment, s_rus_str_she_leaves_where_drop_equipment, s_rus_str_he_leaves_drops_equipment, s_rus_str_she_leaves_drops_equipment, s_rus_pImpPopUpStrings, s_rus_pImpButtonText, s_rus_pExtraIMPStrings, s_rus_pFilesTitle, s_rus_pFilesSenderList, s_rus_pHistoryLocations, s_rus_pHistoryStrings, s_rus_pHistoryHeaders, s_rus_pHistoryTitle, s_rus_pShowBookmarkString, s_rus_pWebPagesTitles, s_rus_pWebTitle, s_rus_pPersonnelString, s_rus_pErrorStrings, s_rus_pDownloadString, s_rus_pBookMarkStrings, s_rus_pLaptopIcons, s_rus_gsAtmStartButtonText, s_rus_pPersonnelTeamStatsStrings, s_rus_pPersonnelCurrentTeamStatsStrings, s_rus_pPersonelTeamStrings, s_rus_pPersonnelDepartedStateStrings, s_rus_pMapHortIndex, s_rus_pMapVertIndex, s_rus_pMapDepthIndex, s_rus_pLaptopTitles, s_rus_pDayStrings, s_rus_pMilitiaConfirmStrings, s_rus_pDeliveryLocationStrings, s_rus_pSkillAtZeroWarning, s_rus_pIMPBeginScreenStrings, s_rus_pIMPFinishButtonText, s_rus_pIMPFinishStrings, s_rus_pIMPVoicesStrings, s_rus_pPersTitleText, s_rus_pPausedGameText, s_rus_zOptionsToggleText, s_rus_zOptionsScreenHelpText, s_rus_pDoctorWarningString, s_rus_pMilitiaButtonsHelpText, s_rus_pMapScreenJustStartedHelpText, s_rus_pLandMarkInSectorString, s_rus_gzMercSkillText, s_rus_gzNonPersistantPBIText, s_rus_gzMiscString, s_rus_wMapScreenSortButtonHelpText, s_rus_pNewNoiseStr, s_rus_gzLateLocalizedString, s_rus_pAntiHackerString, s_rus_pMessageStrings, s_rus_ItemPickupHelpPopup, s_rus_TacticalStr, s_rus_LargeTacticalStr, s_rus_zDialogActions, s_rus_zDealerStrings, s_rus_zTalkMenuStrings, s_rus_gzMoneyAmounts, s_rus_gzProsLabel, s_rus_gzConsLabel, s_rus_gMoneyStatsDesc, s_rus_gWeaponStatsDesc, s_rus_sKeyDescriptionStrings, s_rus_zHealthStr, s_rus_zVehicleName, s_rus_pExitingSectorHelpText, s_rus_InsContractText, s_rus_InsInfoText, s_rus_MercAccountText, s_rus_MercInfo, s_rus_MercNoAccountText, s_rus_MercHomePageText, s_rus_sFuneralString, s_rus_sFloristText, s_rus_sOrderFormText, s_rus_sFloristGalleryText, s_rus_sFloristCards, s_rus_BobbyROrderFormText, s_rus_BobbyRText, s_rus_str_bobbyr_guns_num_guns_that_use_ammo, s_rus_BobbyRaysFrontText, s_rus_AimSortText, s_rus_str_aim_sort_price, s_rus_str_aim_sort_experience, s_rus_str_aim_sort_marksmanship, s_rus_str_aim_sort_medical, s_rus_str_aim_sort_explosives, s_rus_str_aim_sort_mechanical, s_rus_str_aim_sort_ascending, s_rus_str_aim_sort_descending, s_rus_AimPolicyText, s_rus_AimMemberText, s_rus_CharacterInfo, s_rus_VideoConfercingText, s_rus_AimPopUpText, s_rus_AimLinkText, s_rus_AimHistoryText, s_rus_AimFiText, s_rus_AimAlumniText, s_rus_AimScreenText, s_rus_AimBottomMenuText, s_rus_zMarksMapScreenText, s_rus_gpStrategicString, s_rus_gpGameClockString, s_rus_SKI_Text, s_rus_SkiMessageBoxText, s_rus_zSaveLoadText, s_rus_zOptionsText, s_rus_gzGIOScreenText, s_rus_gzHelpScreenText, s_rus_gzLaptopHelpText, s_rus_gzMoneyWithdrawMessageText, s_rus_gzCopyrightText, s_rus_BrokenLinkText, s_rus_gzBobbyRShipmentText, s_rus_zGioDifConfirmText, s_rus_gzCreditNames, s_rus_gzCreditNameTitle, s_rus_gzCreditNameFunny, s_rus_pContractButtonString, s_rus_gzIntroScreen, s_rus_pUpdatePanelButtons, s_rus_sRepairsDoneString, s_rus_str_ceramic_plates_smashed, s_rus_str_arrival_rerouted, s_rus_str_stat_health, s_rus_str_stat_agility, s_rus_str_stat_dexterity, s_rus_str_stat_strength, s_rus_str_stat_leadership, s_rus_str_stat_wisdom, s_rus_str_stat_exp_level, s_rus_str_stat_marksmanship, s_rus_str_stat_mechanical, s_rus_str_stat_explosive, s_rus_str_stat_medical, s_rus_str_stat_list, s_rus_str_aim_sort_list, s_rus_zNewTacticalMessages, s_rus_str_iron_man_mode_warning, }; /** Russian Gold language resources. */ LanguageRes g_LanguageResRussianGold = { s_rus_WeaponType, s_rus_Message, s_rus_TeamTurnString, s_rus_pAssignMenuStrings, s_rus_pTrainingStrings, s_rus_pTrainingMenuStrings, s_rus_pAttributeMenuStrings, s_rus_pVehicleStrings, s_rus_pShortAttributeStrings, s_rus_pContractStrings, s_rus_pAssignmentStrings, s_rus_pConditionStrings, s_rus_pTownNames, s_rus_g_towns_locative, s_rus_pPersonnelScreenStrings, s_rus_pUpperLeftMapScreenStrings, s_rus_pTacticalPopupButtonStrings, s_rus_pSquadMenuStrings, s_rus_pDoorTrapStrings, s_rus_pLongAssignmentStrings, s_rus_pMapScreenMouseRegionHelpText, s_rus_pNoiseVolStr, s_rus_pNoiseTypeStr, s_rus_pDirectionStr, s_rus_pRemoveMercStrings, s_rus_sTimeStrings, s_rus_pLandTypeStrings, s_rus_pInvPanelTitleStrings, s_rus_pPOWStrings, s_rus_pMilitiaString, s_rus_pMilitiaButtonString, s_rus_pEpcMenuStrings, s_rus_pRepairStrings, s_rus_sPreStatBuildString, s_rus_sStatGainStrings, s_rus_pHelicopterEtaStrings, s_rus_sMapLevelString, s_rus_gsLoyalString, s_rus_gsUndergroundString, s_rus_gsTimeStrings, s_rus_sFacilitiesStrings, s_rus_pMapPopUpInventoryText, s_rus_pwTownInfoStrings, s_rus_pwMineStrings, s_rus_pwMiscSectorStrings, s_rus_pMapInventoryErrorString, s_rus_pMapInventoryStrings, s_rus_pMovementMenuStrings, s_rus_pUpdateMercStrings, s_rus_pMapScreenBorderButtonHelpText, s_rus_pMapScreenBottomFastHelp, s_rus_pMapScreenBottomText, s_rus_pMercDeadString, s_rusGold_pSenderNameList, s_rus_pNewMailStrings, s_rus_pDeleteMailStrings, s_rus_pEmailHeaders, s_rus_pEmailTitleText, s_rus_pFinanceTitle, s_rus_pFinanceSummary, s_rus_pFinanceHeaders, s_rus_pTransactionText, s_rus_pMoralStrings, s_rus_pSkyriderText, s_rus_str_left_equipment, s_rus_pMapScreenStatusStrings, s_rus_pMapScreenPrevNextCharButtonHelpText, s_rus_pEtaString, s_rus_pShortVehicleStrings, s_rus_pTrashItemText, s_rus_pMapErrorString, s_rus_pMapPlotStrings, s_rus_pBullseyeStrings, s_rus_pMiscMapScreenMouseRegionHelpText, s_rus_str_he_leaves_where_drop_equipment, s_rus_str_she_leaves_where_drop_equipment, s_rus_str_he_leaves_drops_equipment, s_rus_str_she_leaves_drops_equipment, s_rus_pImpPopUpStrings, s_rus_pImpButtonText, s_rus_pExtraIMPStrings, s_rus_pFilesTitle, s_rus_pFilesSenderList, s_rus_pHistoryLocations, s_rus_pHistoryStrings, s_rus_pHistoryHeaders, s_rus_pHistoryTitle, s_rus_pShowBookmarkString, s_rus_pWebPagesTitles, s_rus_pWebTitle, s_rus_pPersonnelString, s_rus_pErrorStrings, s_rus_pDownloadString, s_rus_pBookMarkStrings, s_rus_pLaptopIcons, s_rus_gsAtmStartButtonText, s_rus_pPersonnelTeamStatsStrings, s_rus_pPersonnelCurrentTeamStatsStrings, s_rus_pPersonelTeamStrings, s_rus_pPersonnelDepartedStateStrings, s_rus_pMapHortIndex, s_rus_pMapVertIndex, s_rus_pMapDepthIndex, s_rus_pLaptopTitles, s_rus_pDayStrings, s_rus_pMilitiaConfirmStrings, s_rus_pDeliveryLocationStrings, s_rus_pSkillAtZeroWarning, s_rus_pIMPBeginScreenStrings, s_rus_pIMPFinishButtonText, s_rus_pIMPFinishStrings, s_rus_pIMPVoicesStrings, s_rus_pPersTitleText, s_rus_pPausedGameText, s_rus_zOptionsToggleText, s_rus_zOptionsScreenHelpText, s_rus_pDoctorWarningString, s_rus_pMilitiaButtonsHelpText, s_rus_pMapScreenJustStartedHelpText, s_rus_pLandMarkInSectorString, s_rus_gzMercSkillText, s_rus_gzNonPersistantPBIText, s_rus_gzMiscString, s_rus_wMapScreenSortButtonHelpText, s_rus_pNewNoiseStr, s_rus_gzLateLocalizedString, s_rus_pAntiHackerString, s_rus_pMessageStrings, s_rus_ItemPickupHelpPopup, s_rus_TacticalStr, s_rus_LargeTacticalStr, s_rus_zDialogActions, s_rus_zDealerStrings, s_rus_zTalkMenuStrings, s_rus_gzMoneyAmounts, s_rus_gzProsLabel, s_rus_gzConsLabel, s_rus_gMoneyStatsDesc, s_rus_gWeaponStatsDesc, s_rus_sKeyDescriptionStrings, s_rus_zHealthStr, s_rus_zVehicleName, s_rus_pExitingSectorHelpText, s_rus_InsContractText, s_rus_InsInfoText, s_rus_MercAccountText, s_rus_MercInfo, s_rus_MercNoAccountText, s_rus_MercHomePageText, s_rus_sFuneralString, s_rus_sFloristText, s_rus_sOrderFormText, s_rus_sFloristGalleryText, s_rus_sFloristCards, s_rus_BobbyROrderFormText, s_rus_BobbyRText, s_rus_str_bobbyr_guns_num_guns_that_use_ammo, s_rus_BobbyRaysFrontText, s_rus_AimSortText, s_rus_str_aim_sort_price, s_rus_str_aim_sort_experience, s_rus_str_aim_sort_marksmanship, s_rus_str_aim_sort_medical, s_rus_str_aim_sort_explosives, s_rus_str_aim_sort_mechanical, s_rus_str_aim_sort_ascending, s_rus_str_aim_sort_descending, s_rus_AimPolicyText, s_rus_AimMemberText, s_rus_CharacterInfo, s_rus_VideoConfercingText, s_rus_AimPopUpText, s_rus_AimLinkText, s_rus_AimHistoryText, s_rus_AimFiText, s_rus_AimAlumniText, s_rus_AimScreenText, s_rus_AimBottomMenuText, s_rus_zMarksMapScreenText, s_rus_gpStrategicString, s_rus_gpGameClockString, s_rus_SKI_Text, s_rus_SkiMessageBoxText, s_rus_zSaveLoadText, s_rus_zOptionsText, s_rus_gzGIOScreenText, s_rus_gzHelpScreenText, s_rus_gzLaptopHelpText, s_rus_gzMoneyWithdrawMessageText, s_rusGold_gzCopyrightText, s_rus_BrokenLinkText, s_rus_gzBobbyRShipmentText, s_rus_zGioDifConfirmText, s_rus_gzCreditNames, s_rus_gzCreditNameTitle, s_rus_gzCreditNameFunny, s_rus_pContractButtonString, s_rus_gzIntroScreen, s_rus_pUpdatePanelButtons, s_rus_sRepairsDoneString, s_rus_str_ceramic_plates_smashed, s_rus_str_arrival_rerouted, s_rus_str_stat_health, s_rus_str_stat_agility, s_rus_str_stat_dexterity, s_rus_str_stat_strength, s_rus_str_stat_leadership, s_rus_str_stat_wisdom, s_rus_str_stat_exp_level, s_rus_str_stat_marksmanship, s_rus_str_stat_mechanical, s_rus_str_stat_explosive, s_rus_str_stat_medical, s_rus_str_stat_list, s_rus_str_aim_sort_list, s_rus_zNewTacticalMessages, s_rus_str_iron_man_mode_warning, }; #ifdef WITH_UNITTESTS #define ARR_SIZE(x) (sizeof(x)/sizeof(x[0])) TEST(WideStringEncodingTest, RusianTextFile) { // This test checks that the wide string literals in this file are correctly // interpreted by the compiler. Visual Studio requires BOM (byte-order mark) // to correctly identify file encoding. Failed test means that the compiler // cannot correctly interpret the string literals. const wchar_t str[] = L"тест"; ASSERT_EQ(ARR_SIZE(str), 5) << "Compiler cannot correctly interpret wide string literals"; EXPECT_EQ(str[0], 0x0442); EXPECT_EQ(str[1], 0x0435); EXPECT_EQ(str[2], 0x0441); EXPECT_EQ(str[3], 0x0442); EXPECT_EQ(str[4], 0x00); } #endif NPS-TECH/luacxx #include "../ncurses.hpp" #include "../thread.hpp" // http://invisible-island.net/ncurses/man/curs_clear.3x.html void lua::ncurses_curs_clear(lua_State* const state) { lua::thread env(state); env["erase"] = erase; env["werase"] = werase; env["clear"] = ::clear; env["wclear"] = wclear; env["clrtobot"] = clrtobot; env["wclrtobot"] = wclrtobot; env["clrtoeol"] = clrtoeol; env["wclrtoeol"] = wclrtoeol; } /* Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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. */ // The following .h files contain function definitions in order that those functions are compiled in the same compilation unit // as this dsstnemodule.c file. A single compilation unit is necessary so that NumPy functions such as PyArray_SimpleNew() appear // in the same compilation unit as the import_matrix() function that is called from the initdsstne() function below; otherwise, // a segmentation fault will occur. #include "dsstnemodule.h" #include "dsstnecalculate.h" #include "CDLAccessors.h" #include "utilities.h" #include "NNNetworkFunctions.h" #include "NNNetworkAccessors.h" #include "NNLayerAccessors.h" #include "NNWeightAccessors.h" #include "NNDataSetAccessors.h" #include "utilities.h" // See section 1.4 of https://docs.python.org/3/extending/extending.html static PyMethodDef dsstneMethods[] = { {"GetCDLRandomSeed", CDLAccessors::GetRandomSeed, METH_VARARGS, "Get random seed from the source CDL"}, {"SetCDLRandomSeed", CDLAccessors::SetRandomSeed, METH_VARARGS, "Set random seed in the destination CDL"}, {"GetCDLEpochs", CDLAccessors::GetEpochs, METH_VARARGS, "Get epochs from the source CDL"}, {"SetCDLEpochs", CDLAccessors::SetEpochs, METH_VARARGS, "Set epochs in the destination CDL"}, {"GetCDLBatch", CDLAccessors::GetBatch, METH_VARARGS, "Get batch from the source CDL"}, {"SetCDLBatch", CDLAccessors::SetBatch, METH_VARARGS, "Set batch in the destination CDL"}, {"GetCDLCheckpointInterval", CDLAccessors::GetCheckpointInterval, METH_VARARGS, "Get checkpoint interval from the source CDL"}, {"SetCDLCheckpointInterval", CDLAccessors::SetCheckpointInterval, METH_VARARGS, "Set checkpoint interval in the destination CDL"}, {"GetCDLAlphaInterval", CDLAccessors::GetAlphaInterval, METH_VARARGS, "Get alpha interval from the source CDL"}, {"SetCDLAlphaInterval", CDLAccessors::SetAlphaInterval, METH_VARARGS, "Set alpha interval in the destination CDL"}, {"GetCDLShuffleIndexes", CDLAccessors::GetShuffleIndexes, METH_VARARGS, "Get shuffle indexes from the source CDL"}, {"SetCDLShuffleIndexes", CDLAccessors::SetShuffleIndexes, METH_VARARGS, "Set shuffle indexes in the destination CDL"}, {"GetCDLAlpha", CDLAccessors::GetAlpha, METH_VARARGS, "Get alpha from the source CDL"}, {"SetCDLAlpha", CDLAccessors::SetAlpha, METH_VARARGS, "Set alpha in the destination CDL"}, {"GetCDLLambda", CDLAccessors::GetLambda, METH_VARARGS, "Get lambda from the source CDL"}, {"SetCDLLambda", CDLAccessors::SetLambda, METH_VARARGS, "Set lambda in the destination CDL"}, {"GetCDLMu", CDLAccessors::GetMu, METH_VARARGS, "Get mu from the source CDL"}, {"SetCDLMu", CDLAccessors::SetMu, METH_VARARGS, "Set mu in the destination CDL"}, {"GetCDLAlphaMultiplier", CDLAccessors::GetAlphaMultiplier, METH_VARARGS, "Get alpha multiplier from the source CDL"}, {"SetCDLAlphaMultiplier", CDLAccessors::SetAlphaMultiplier, METH_VARARGS, "Set alpha multiplier in the destination CDL"}, {"GetCDLMode", CDLAccessors::GetMode, METH_VARARGS, "Get the mode enumerator from the source CDL"}, {"SetCDLMode", CDLAccessors::SetMode, METH_VARARGS, "Set the mode enumerator in the destination CDL"}, {"GetCDLOptimizer", CDLAccessors::GetOptimizer, METH_VARARGS, "Get the training mode enumerator from the source CDL"}, {"SetCDLOptimizer", CDLAccessors::SetOptimizer, METH_VARARGS, "Set the training mode enumerator in the destination CDL"}, {"GetCDLNetworkFileName", CDLAccessors::GetNetworkFileName, METH_VARARGS, "Get network filename from the source CDL"}, {"SetCDLNetworkFileName", CDLAccessors::SetNetworkFileName, METH_VARARGS, "Set network filename in the destination CDL"}, {"GetCDLDataFileName", CDLAccessors::GetDataFileName, METH_VARARGS, "Get data filename from the source CDL"}, {"SetCDLDataFileName", CDLAccessors::SetDataFileName, METH_VARARGS, "Set data filename in the destination CDL"}, {"GetCDLCheckpointFileName", CDLAccessors::GetCheckpointFileName, METH_VARARGS, "Get checkpoint filename from the source CDL"}, {"SetCDLCheckpointFileName", CDLAccessors::SetCheckpointFileName, METH_VARARGS, "Set checkpoint filename in the destination CDL"}, {"GetCDLResultsFileName", CDLAccessors::GetResultsFileName, METH_VARARGS, "Get results filename from the source CDL"}, {"SetCDLResultsFileName", CDLAccessors::SetResultsFileName, METH_VARARGS, "Set results filename in the destination CDL"}, {"Startup", Utilities::Startup, METH_VARARGS, "Initialize the GPUs and MPI"}, {"Shutdown", Utilities::Shutdown, METH_VARARGS, "Shutdown the GPUs"}, {"CreateCDLFromJSON", Utilities::CreateCDLFromJSON, METH_VARARGS, "Create a CDL instance and initialize it from a JSON file"}, {"CreateCDLFromDefaults", Utilities::CreateCDLFromDefaults, METH_VARARGS, "Create a CDL instance and initialize it with default values"}, {"DeleteCDL", Utilities::DeleteCDL, METH_VARARGS, "Delete a CDL instance"}, {"LoadNetCDF", Utilities::LoadDataSetFromNetCDF, METH_VARARGS, "Load a Python array (i.e. a list) of data sets from a CDF file"}, {"DeleteDataSet", Utilities::DeleteDataSet, METH_VARARGS, "Delete a data set"}, {"LoadNeuralNetworkNetCDF", Utilities::LoadNeuralNetworkFromNetCDF, METH_VARARGS, "Load a neural network from a CDF file"}, {"LoadNeuralNetworkJSON", Utilities::LoadNeuralNetworkFromJSON, METH_VARARGS, "Load a neural network from a JSON config file, a batch number, and a Python list of data sets"}, {"DeleteNNNetwork", Utilities::DeleteNNNetwork, METH_VARARGS, "Delete a neural network"}, {"OpenFile", Utilities::OpenFile, METH_VARARGS, "Open a FILE* stream"}, {"CloseFile", Utilities::CloseFile, METH_VARARGS, "Close a FILE* stream"}, {"SetRandomSeed", Utilities::SetRandomSeed, METH_VARARGS, "Set random seed in the GPU"}, {"GetMemoryUsage", Utilities::GetMemoryUsage, METH_VARARGS, "Get the GPU and CPU memory usage"}, {"Transpose", Utilities::Transpose, METH_VARARGS, "Transpose a NumPy 2D matrix to create a contiguous matrix"}, {"CreateFloatGpuBuffer", Utilities::CreateFloatGpuBuffer, METH_VARARGS, "Create a GPU Buffer of type NNFloat and of the specified size"}, {"DeleteFloatGpuBuffer", Utilities::DeleteFloatGpuBuffer, METH_VARARGS, "Delete a GPU Buffer of type NNFloat"}, {"CreateUnsignedGpuBuffer", Utilities::CreateUnsignedGpuBuffer, METH_VARARGS, "Create a GPU Buffer of type uint32_t and of the specified size"}, {"DeleteUnsignedGpuBuffer", Utilities::DeleteUnsignedGpuBuffer, METH_VARARGS, "Delete a GPU Buffer of type uint32_te"}, {"ClearDataSets", NNNetworkFunctions::ClearDataSets, METH_VARARGS, "Clear the data sets from the neural network"}, {"LoadDataSets", NNNetworkFunctions::LoadDataSets, METH_VARARGS, "Load a Python list of data sets into the neural network"}, {"Randomize", NNNetworkFunctions::Randomize, METH_VARARGS, "Randomize a neural network"}, {"Validate", NNNetworkFunctions::Validate, METH_VARARGS, "Validate the network gradients numerically for the neural network"}, {"Train", NNNetworkFunctions::Train, METH_VARARGS, "Train the neural network"}, {"PredictBatch", NNNetworkFunctions::PredictBatch, METH_VARARGS, "Predict batch for the neural network"}, {"CalculateTopK", NNNetworkFunctions::CalculateTopK, METH_VARARGS, "Calculate the top K results for the neural network"}, {"PredictTopK", NNNetworkFunctions::PredictTopK, METH_VARARGS, "Do a prediction calculation and return the top K results for a neural network"}, {"CalculateMRR", NNNetworkFunctions::CalculateMRR, METH_VARARGS, "Calculate the MRR for a neural network"}, {"SaveBatch", NNNetworkFunctions::SaveBatch, METH_VARARGS, "Save the batch to a file for the neural network"}, {"DumpBatch", NNNetworkFunctions::DumpBatch, METH_VARARGS, "Dump the batch to a FILE for the neural network"}, {"SaveLayer", NNNetworkFunctions::SaveLayer, METH_VARARGS, "Save the specified layer to a file for the neural network"}, {"DumpLayer", NNNetworkFunctions::DumpLayer, METH_VARARGS, "Dump the specified layer to a FILE for the neural network"}, {"SaveWeights", NNNetworkFunctions::SaveWeights, METH_VARARGS, "Save the weights connecting two layers to a file for the neural network"}, {"LockWeights", NNNetworkFunctions::LockWeights, METH_VARARGS, "Lock the weights connecting two layers for the neural network"}, {"UnlockWeights", NNNetworkFunctions::UnlockWeights, METH_VARARGS, "Unlock the weights connecting two layers for the neural network"}, {"SaveNetCDF", NNNetworkFunctions::SaveNetCDF, METH_VARARGS, "Save training results to a CDF file for the neural network"}, {"P2P_Bcast", NNNetworkFunctions::P2P_Bcast, METH_VARARGS, "Broadcast data from process 0 to all other processes for the neural network"}, {"P2P_Allreduce", NNNetworkFunctions::P2P_Allreduce, METH_VARARGS, "Reduce a buffer across all processes for the neural network"}, {"GetBatch", NNNetworkAccessors::GetBatch, METH_VARARGS, "Get the batch from the source neural network"}, {"SetBatch", NNNetworkAccessors::SetBatch, METH_VARARGS, "Set the batch in the destination neural network"}, {"GetPosition", NNNetworkAccessors::GetPosition, METH_VARARGS, "Get the position from the source neural network"}, {"SetPosition", NNNetworkAccessors::SetPosition, METH_VARARGS, "Set the position in the destination neural network"}, {"GetShuffleIndices", NNNetworkAccessors::GetShuffleIndices, METH_VARARGS, "Get the shuffle indices from the source neural network; unwrap the unnecessary tuple"}, {"SetShuffleIndices", NNNetworkAccessors::SetShuffleIndices, METH_VARARGS, "Set the shuffle indices boolean in the destination neural network"}, {"GetSparsenessPenalty", NNNetworkAccessors::GetSparsenessPenalty, METH_VARARGS, "Get the sparseness penalty p and beta from the source neural network"}, {"SetSparsenessPenalty", NNNetworkAccessors::SetSparsenessPenalty, METH_VARARGS, "Set the sparseness penalty p and beta in the destination neural network"}, {"GetDenoising", NNNetworkAccessors::GetDenoising, METH_VARARGS, "Get the denoising p from the source neural network and unwrap the unnecessary tuple"}, {"SetDenoising", NNNetworkAccessors::SetDenoising, METH_VARARGS, "Set the denoising p in the destination neural network"}, {"GetDeltaBoost", NNNetworkAccessors::GetDeltaBoost, METH_VARARGS, "Get the delta boost one and zero from the source neural network"}, {"SetDeltaBoost", NNNetworkAccessors::SetDeltaBoost, METH_VARARGS, "Set the delta boost one and zero in the destination neural network"}, {"GetDebugLevel", NNNetworkAccessors::GetDebugLevel, METH_VARARGS, "Get the debug level from the source neural network"}, {"SetDebugLevel", NNNetworkAccessors::SetDebugLevel, METH_VARARGS, "Set the debug level in the destination neural network"}, {"GetCheckpoint", NNNetworkAccessors::GetCheckpoint, METH_VARARGS, "Get the checkpoint file name and interval from the source neural network"}, {"SetCheckpoint", NNNetworkAccessors::SetCheckpoint, METH_VARARGS, "Set the checkpoint filename and interval in the destination neural network"}, {"GetLRN", NNNetworkAccessors::GetLRN, METH_VARARGS, "Get the local response network (LRN) k, n, alpha, and beta from the source neural network"}, {"SetLRN", NNNetworkAccessors::SetLRN, METH_VARARGS, "Set the local response network (LRN) k, n, alpha, and beta in the destination neural network"}, {"GetSMCE", NNNetworkAccessors::GetSMCE, METH_VARARGS, "Get the scaled marginal cross entropy (SMCE) oneTarget, zeroTarget, oneScale, and zeroScale from the source neural network"}, {"SetSMCE", NNNetworkAccessors::SetSMCE, METH_VARARGS, "Set the scaled marginal cross entropy (SMCE) oneTarget, zeroTarget, oneScale, and zeroScale in the destination neural network"}, {"GetMaxout", NNNetworkAccessors::GetMaxout, METH_VARARGS, "Get the maxout k from the source neural network and unwrap the unnecessary tuple"}, {"SetMaxout", NNNetworkAccessors::SetMaxout, METH_VARARGS, "Set the maxout k in the destination neural network"}, {"GetExamples", NNNetworkAccessors::GetExamples, METH_VARARGS, "Get the examples from the source neural network"}, {"GetWeight", NNNetworkAccessors::GetWeight, METH_VARARGS, "Get the set of weights connecting the specified input and output layers from the source neural network"}, {"GetBufferSize", NNNetworkAccessors::GetBufferSize, METH_VARARGS, "Get the buffer size of the specified layer for the source neural network"}, {"GetLayer", NNNetworkAccessors::GetLayer, METH_VARARGS, "Get the specified layer from the source neural network"}, {"GetLayers", NNNetworkAccessors::GetLayers, METH_VARARGS, "Get the list of layer names from the source neural network"}, {"GetName", NNNetworkAccessors::GetName, METH_VARARGS, "Get the name of the source neural network"}, {"GetUnitBuffer", NNNetworkAccessors::GetUnitBuffer, METH_VARARGS, "Get the unit buffer for the specified layer from the source neural network"}, {"GetDeltaBuffer", NNNetworkAccessors::GetDeltaBuffer, METH_VARARGS, "Get the delta buffer for the specified layer from the source neural network"}, {"GetWeightBuffer", NNNetworkAccessors::GetWeightBuffer, METH_VARARGS, "Get the weight buffer for the specified input and output layers from the source neural network"}, {"GetScratchBuffer", NNNetworkAccessors::GetScratchBuffer, METH_VARARGS, "Get the current scratch buffer from the source neural network and resize it if necessary"}, {"GetP2PSendBuffer", NNNetworkAccessors::GetP2PSendBuffer, METH_VARARGS, "Get the current local send buffer from the source neural network"}, {"GetP2PReceiveBuffer", NNNetworkAccessors::GetP2PReceiveBuffer, METH_VARARGS, "Get the current local receive buffer from the source neural network"}, {"GetP2PCPUBuffer", NNNetworkAccessors::GetP2PCPUBuffer, METH_VARARGS, "Get the system memory work buffer from the source neural network"}, {"GetPeerBuffer", NNNetworkAccessors::GetPeerBuffer, METH_VARARGS, "Get the current adjacent peer receive buffer from the source neural network"}, {"GetPeerBackBuffer", NNNetworkAccessors::GetPeerBackBuffer, METH_VARARGS, "Get the current adjacent peer send buffer from the source neural network"}, {"SetClearVelocity", NNNetworkAccessors::SetClearVelocity, METH_VARARGS, "Set the clear velocity flag in the destination neural network"}, {"SetTrainingMode", NNNetworkAccessors::SetTrainingMode, METH_VARARGS, "Set the training mode enumerator in the destination neural network"}, {"GetLayerName", NNLayerAccessors::GetName, METH_VARARGS, "Get the name from the source layer"}, {"GetKind", NNLayerAccessors::GetKind, METH_VARARGS, "Get the kind enumerator from the source layer"}, {"GetType", NNLayerAccessors::GetType, METH_VARARGS, "Get the type enumerator from the source layer"}, {"GetAttributes", NNLayerAccessors::GetAttributes, METH_VARARGS, "Get the attributes from the source layer"}, {"GetDataSetBase", NNLayerAccessors::GetDataSet, METH_VARARGS, "Get the data set from the source layer"}, {"GetNumDimensions", NNLayerAccessors::GetNumDimensions, METH_VARARGS, "Get the number of dimensions from the source layer"}, {"GetDimensions", NNLayerAccessors::GetDimensions, METH_VARARGS, "Get dimensions from the source layer"}, {"GetLocalDimensions", NNLayerAccessors::GetLocalDimensions, METH_VARARGS, "Get local dimensions from the source layer"}, {"GetKernelDimensions", NNLayerAccessors::GetKernelDimensions, METH_VARARGS, "Get kernel dimensions from the source layer"}, {"GetKernelStride", NNLayerAccessors::GetKernelStride, METH_VARARGS, "Get kernel stride from the source layer"}, {"GetUnits", NNLayerAccessors::GetUnits, METH_VARARGS, "Modify the destination float32 NumPy array beginning at a specified index by copying the units from the source layer"}, {"SetUnits", NNLayerAccessors::SetUnits, METH_VARARGS, "Set the units of the destination layer by copying the units from a source float32 Numpy array"}, {"GetDeltas", NNLayerAccessors::GetDeltas, METH_VARARGS, "Modify the destination float32 NumPy array beginning at a specified index by copying the deltas from the source layer"}, {"SetDeltas", NNLayerAccessors::SetDeltas, METH_VARARGS, "Set the deltas of the destination layer by copying the deltas from a source float32 Numpy array"}, {"CopyWeights", NNWeightAccessors::CopyWeights, METH_VARARGS, "Copy the weights from the specified source weight to the destination weight"}, {"SetWeights", NNWeightAccessors::SetWeights, METH_VARARGS, "Set the weights in the destination weight from a source NumPy array of weights"}, {"SetBiases", NNWeightAccessors::SetBiases, METH_VARARGS, "Set the biases in the destination weight from a source NumPy array of biases"}, {"GetWeights", NNWeightAccessors::GetWeights, METH_VARARGS, "Get the weights from the source weight"}, {"GetBiases", NNWeightAccessors::GetBiases, METH_VARARGS, "Get the biases from the source weight"}, {"SetNorm", NNWeightAccessors::SetNorm, METH_VARARGS, "Set the norm for the destination weight"}, {"GetDataSetName", NNDataSetAccessors::GetDataSetName, METH_VARARGS, "Get the name from the source NNDataSetBase*"}, {"CreateDenseDataSet", NNDataSetAccessors::CreateDenseDataSet, METH_VARARGS, "Create an encapsulated NNDataSetBase* from a dense NumPy array"}, {"CreateSparseDataSet", NNDataSetAccessors::CreateSparseDataSet, METH_VARARGS, "Create an encapsulated NNDataSetBase* from a compressed sparse row (CSR) SciPy two-dimensional matrix"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; // See https://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html PyMODINIT_FUNC initdsstne(void) { (void) Py_InitModule("dsstne", dsstneMethods); import_array(); // Add initialization code here } powerchain-ltd/greenpower-blockchain /* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define GET_REQUIRED_FEES_MAX_RECURSION 4 namespace graphene { namespace app { typedef std::map< std::pair, std::vector > market_queue_type; class database_api_impl; class database_api_impl : public std::enable_shared_from_this { public: explicit database_api_impl( graphene::chain::database& db, const application_options* app_options ); ~database_api_impl(); // Objects fc::variants get_objects(const vector& ids)const; // Subscriptions void set_subscribe_callback( std::function cb, bool notify_remove_create ); void set_pending_transaction_callback( std::function cb ); void set_block_applied_callback( std::function cb ); void cancel_all_subscriptions(); // Blocks and transactions optional get_block_header(uint32_t block_num)const; map> get_block_header_batch(const vector block_nums)const; optional get_block(uint32_t block_num)const; vector get_blocks(uint32_t block_num, uint32_t count) const; vector get_blocks_with_virtual_operations(uint32_t start_block_num, uint32_t count, std::vector& virtual_operation_ids) const; processed_transaction get_transaction( uint32_t block_num, uint32_t trx_in_block )const; // Globals chain_property_object get_chain_properties()const; global_property_object get_global_properties()const; fc::variant_object get_config()const; chain_id_type get_chain_id()const; dynamic_global_property_object get_dynamic_global_properties()const; optional get_total_cycles() const; optional get_queue_projection() const; // Keys vector> get_key_references( vector key )const; // Accounts vector> get_accounts(const vector& account_ids)const; std::map get_full_accounts( const vector& names_or_ids, bool subscribe ); optional get_account_by_name( string name )const; vector get_account_references( account_id_type account_id )const; vector> lookup_account_names(const vector& account_names)const; map lookup_accounts(const string& lower_bound_name, uint32_t limit)const; uint64_t get_account_count()const; // Balances vector get_account_balances(account_id_type id, const flat_set& assets)const; vector get_named_account_balances(const std::string& name, const flat_set& assets)const; vector get_balance_objects( const vector
& addrs )const; vector get_vested_balances( const vector& objs )const; vector get_vesting_balances( account_id_type account_id )const; tethered_accounts_balances_collection get_tethered_accounts_balances( account_id_type id, asset_id_type asset )const; vector get_tethered_accounts_balances( account_id_type account, const flat_set& assets )const; // Assets asset_id_type get_web_asset_id() const; vector> get_assets(const vector& asset_ids)const; vector list_assets(const string& lower_bound_symbol, uint32_t limit)const; vector> lookup_asset_symbols(const vector& symbols_or_ids)const; optional lookup_asset_symbol(const string& symbol_or_id) const; optional get_issued_asset_record(const string& unique_id, asset_id_type asset_id) const; bool check_issued_asset(const string& unique_id, const string& asset) const; bool check_issued_webeur(const string& unique_id) const; // Markets / feeds vector get_limit_orders(asset_id_type a, asset_id_type b, uint32_t limit)const; vector get_limit_orders_for_account(account_id_type id, asset_id_type a, asset_id_type b, uint32_t limit)const; template using repack_function = std::function&, std::map &, bool)>; template T get_limit_orders_grouped_by_price(asset_id_type a, asset_id_type b, uint32_t limit, uint32_t precision, repack_function)const; vector get_call_orders(asset_id_type a, uint32_t limit)const; vector get_settle_orders(asset_id_type a, uint32_t limit)const; vector get_margin_positions( const account_id_type& id )const; void subscribe_to_market(std::function callback, asset_id_type a, asset_id_type b); void unsubscribe_from_market(asset_id_type a, asset_id_type b); market_ticker get_ticker( const string& base, const string& quote )const; market_hi_low_volume get_24_hi_low_volume( const string& base, const string& quote )const; order_book get_order_book( const string& base, const string& quote, unsigned limit = 50 )const; vector get_trade_history( const string& base, const string& quote, fc::time_point_sec start, fc::time_point_sec stop, unsigned limit = 100 )const; vector get_trade_history_by_sequence( const string& base, const string& quote, int64_t start, fc::time_point_sec stop, unsigned limit = 100 )const; // Witnesses vector> get_witnesses(const vector& witness_ids)const; fc::optional get_witness_by_account(account_id_type account)const; map lookup_witness_accounts(const string& lower_bound_name, uint32_t limit)const; uint64_t get_witness_count()const; // Committee members vector> get_committee_members(const vector& committee_member_ids)const; fc::optional get_committee_member_by_account(account_id_type account)const; map lookup_committee_member_accounts(const string& lower_bound_name, uint32_t limit)const; // Authority / validation std::string get_transaction_hex(const signed_transaction& trx)const; set get_required_signatures( const signed_transaction& trx, const flat_set& available_keys )const; set get_potential_signatures( const signed_transaction& trx )const; set
get_potential_address_signatures( const signed_transaction& trx )const; bool verify_authority( const signed_transaction& trx )const; bool verify_account_authority( const string& name_or_id, const flat_set& signers )const; processed_transaction validate_transaction( const signed_transaction& trx )const; vector< fc::variant > get_required_fees( const vector& ops, asset_id_type id )const; // Proposed transactions vector get_proposed_transactions( account_id_type id )const; // Blinded balances vector get_blinded_balances( const flat_set& commitments )const; // Licenses: optional get_license_type(license_type_id_type license_id) const; vector get_license_types() const; vector> get_license_types(const vector& license_type_ids) const; vector> get_license_type_names_ids() const; vector get_license_type_names_ids_grouped_by_kind() const; vector get_license_objects_grouped_by_kind() const; vector> get_license_information(const vector& account_ids) const; vector get_upgrade_events() const; // Access: acc_id_share_t_res get_free_cycle_balance(account_id_type account_id) const; acc_id_vec_cycle_agreement_res get_all_cycle_balances(account_id_type account_id) const; acc_id_share_t_res get_dascoin_balance(account_id_type id) const; vector get_free_cycle_balances_for_accounts(vector ids) const; vector get_all_cycle_balances_for_accounts(vector ids) const; vector get_dascoin_balances_for_accounts(vector ids) const; vector get_reward_queue() const; vector get_reward_queue_by_page(uint32_t from, uint32_t amount) const; acc_id_queue_subs_w_pos_res get_queue_submissions_with_pos(account_id_type account_id) const; vector get_queue_submissions_with_pos_for_accounts(vector ids) const; uint32_t get_reward_queue_size() const; // Vault info: optional get_vault_info(account_id_type vault_id) const; vector get_vaults_info(vector vault_ids) const; optional calculate_cycle_price(share_type cycle_amount, asset_id_type asset_id) const; vector get_top_dasc_holders() const; optional get_withdrawal_limit(account_id_type account, asset_id_type asset_id) const; // DasPay: vector get_payment_service_providers() const; optional> get_daspay_authority_for_account(account_id_type account) const; vector get_delayed_operations_for_account(account_id_type account) const; // Das33 vector get_das33_pledges(das33_pledge_holder_id_type from, uint32_t limit, optional phase) const; das33_pledges_by_account_result get_das33_pledges_by_account(account_id_type account) const; vector get_das33_pledges_by_project(das33_project_id_type project, das33_pledge_holder_id_type from, uint32_t limit, optional phase) const; vector get_das33_projects(const string& lower_bound_name, uint32_t limit) const; vector get_amount_of_assets_pledged_to_project(das33_project_id_type project) const; vector get_amount_of_assets_pledged_to_project_in_phase(das33_project_id_type project, uint32_t phase) const; das33_project_tokens_amount get_amount_of_project_tokens_received_for_asset(das33_project_id_type project, asset to_pledge) const; das33_project_tokens_amount get_amount_of_asset_needed_for_project_token(das33_project_id_type project, asset_id_type asset_id, asset tokens) const; // Prices: vector get_last_prices() const; vector get_external_prices() const; template void subscribe_to_item( const T& i )const { auto vec = fc::raw::pack(i); if( !_subscribe_callback ) return; if( !is_subscribed_to_item(i) ) _subscribe_filter.insert( vec.data(), vec.size() ); } template bool is_subscribed_to_item( const T& i )const { if( !_subscribe_callback ) return false; return _subscribe_filter.contains( i ); } bool is_impacted_account( const flat_set& accounts) { if( !_subscribed_accounts.size() || !accounts.size() ) return false; return std::any_of(accounts.begin(), accounts.end(), [this](const account_id_type& account) { return _subscribed_accounts.find(account) != _subscribed_accounts.end(); }); } // TODO: figure out some way to use copy. template vector list_objects( size_t limit ) const { const auto& idx = _db.get_index_type().indices().template get(); vector result; result.reserve(limit); auto itr = idx.begin(); while(limit-- && itr != idx.end()) result.emplace_back(*itr++); return result; } template vector list_bounded_objects_indexed_by_string( const string& lower_bound, uint32_t limit ) { vector result; result.reserve(limit); const auto& idx = _db.get_index_type().indices().template get(); auto itr = idx.lower_bound(lower_bound); if( lower_bound == "" ) itr = idx.begin(); while(limit-- && itr != idx.end()) result.emplace_back(*itr++); return result; } // TODO: refactor into template methods. template vector list_bounded_objects_indexed_by_num( const uint32_t amount, uint32_t limit ) { vector result; result.reserve(limit); const auto& idx = _db.get_index_type().indices().template get(); auto itr = idx.lower_bound(amount); if( amount == 0 ) itr = idx.begin(); while(limit-- && itr != idx.end()) result.emplace_back(*itr++); return result; } template vector > lookup_string_or_id(const vector& str_or_id) const { const auto& idx = _db.get_index_type().indices().template get(); vector > result; result.reserve(str_or_id.size()); std::transform(str_or_id.begin(), str_or_id.end(), std::back_inserter(result), [this, &idx](const string& str_or_id) -> optional { if( !str_or_id.empty() && std::isdigit(str_or_id[0]) ) { auto ptr = _db.find(variant(str_or_id).as(1)); return ptr == nullptr ? optional() : *ptr; } auto itr = idx.find(str_or_id); return itr == idx.end() ? optional() : *itr; }); return result; } template vector list_all_objects() const { const auto& idx = _db.get_index_type().indices().template get(); auto itr = idx.begin(); vector result; while( itr != idx.end() ) result.emplace_back(*itr++); return result; } template vector> fetch_optionals_from_ids(const vector& ids) const { const auto& idx = _db.get_index_type().indices().template get(); vector > result; result.reserve(ids.size()); std::transform(ids.begin(), ids.end(), std::back_inserter(result), [this, &idx](IdType id) -> optional { auto itr = idx.find(id); return itr == idx.end() ? optional() : *itr; }); return result; } template void enqueue_if_subscribed_to_market(const object* obj, market_queue_type& queue, bool full_object=true) { const T* order = dynamic_cast(obj); FC_ASSERT( order != nullptr); auto market = order->get_market(); auto sub = _market_subscriptions.find( market ); if( sub != _market_subscriptions.end() ) { queue[market].emplace_back( full_object ? obj->to_variant() : fc::variant(obj->id, 1) ); } } void broadcast_updates( const vector& updates ); void broadcast_market_updates( const market_queue_type& queue); void handle_object_changed(bool force_notify, bool full_object, const vector& ids, const flat_set& impacted_accounts, std::function find_object); /** called every time a block is applied to report the objects that were changed */ void on_objects_new(const vector& ids, const flat_set& impacted_accounts); void on_objects_changed(const vector& ids, const flat_set& impacted_accounts); void on_objects_removed(const vector& ids, const vector& objs, const flat_set& impacted_accounts); void on_applied_block(); bool _notify_remove_create = false; mutable fc::bloom_filter _subscribe_filter; std::set _subscribed_accounts; std::function _subscribe_callback; std::function _pending_trx_callback; std::function _block_applied_callback; boost::signals2::scoped_connection _new_connection; boost::signals2::scoped_connection _change_connection; boost::signals2::scoped_connection _removed_connection; boost::signals2::scoped_connection _applied_block_connection; boost::signals2::scoped_connection _pending_trx_connection; map< pair, std::function > _market_subscriptions; graphene::chain::database& _db; database_access_layer _dal; const application_options* _app_options = nullptr; template void func_re_pack(Iter helper_itr, Iter end, std::vector& ret, uint32_t limit_group, uint32_t limit_per_group) const; }; ////////////////////////////////////////////////////////////////////// // // // Constructors // // // ////////////////////////////////////////////////////////////////////// database_api::database_api( graphene::chain::database& db, const application_options* app_options ) : my( new database_api_impl( db, app_options ) ) {} database_api::~database_api() {} database_api_impl::database_api_impl( graphene::chain::database& db, const application_options* app_options ) : _db(db), _dal(db), _app_options(app_options) { wlog("creating database api ${x}", ("x",int64_t(this)) ); _new_connection = _db.new_objects.connect([this](const vector& ids, const flat_set& impacted_accounts) { on_objects_new(ids, impacted_accounts); }); _change_connection = _db.changed_objects.connect([this](const vector& ids, const flat_set& impacted_accounts) { on_objects_changed(ids, impacted_accounts); }); _removed_connection = _db.removed_objects.connect([this](const vector& ids, const vector& objs, const flat_set& impacted_accounts) { on_objects_removed(ids, objs, impacted_accounts); }); _applied_block_connection = _db.applied_block.connect([this](const signed_block&){ on_applied_block(); }); _pending_trx_connection = _db.on_pending_transaction.connect([this](const signed_transaction& trx ){ if( _pending_trx_callback ) _pending_trx_callback( fc::variant(trx, GRAPHENE_MAX_NESTED_OBJECTS) ); }); } database_api_impl::~database_api_impl() { elog("freeing database api ${x}", ("x",int64_t(this)) ); } ////////////////////////////////////////////////////////////////////// // // // Objects // // // ////////////////////////////////////////////////////////////////////// fc::variants database_api::get_objects(const vector& ids)const { return my->get_objects( ids ); } fc::variants database_api_impl::get_objects(const vector& ids)const { if( _subscribe_callback ) { for( auto id : ids ) { if( id.type() == operation_history_object_type && id.space() == protocol_ids ) continue; if( id.type() == impl_account_transaction_history_object_type && id.space() == implementation_ids ) continue; this->subscribe_to_item( id ); } } else { elog( "getObjects without subscribe callback??" ); } fc::variants result; result.reserve(ids.size()); std::transform(ids.begin(), ids.end(), std::back_inserter(result), [this](object_id_type id) -> fc::variant { if(auto obj = _db.find_object(id)) return obj->to_variant(); return {}; }); return result; } ////////////////////////////////////////////////////////////////////// // // // Subscriptions // // // ////////////////////////////////////////////////////////////////////// void database_api::set_subscribe_callback( std::function cb, bool notify_remove_create ) { my->set_subscribe_callback( cb, notify_remove_create ); } void database_api_impl::set_subscribe_callback( std::function cb, bool notify_remove_create ) { if( notify_remove_create ) { FC_ASSERT( _app_options && _app_options->enable_subscribe_to_all, "Subscribing to universal object creation and removal is disallowed in this server." ); } _subscribe_callback = cb; _notify_remove_create = notify_remove_create; _subscribed_accounts.clear(); static fc::bloom_parameters param; param.projected_element_count = 10000; param.false_positive_probability = 1.0/100; param.maximum_size = 1024*8*8*2; param.compute_optimal_parameters(); _subscribe_filter = fc::bloom_filter(param); } void database_api::set_pending_transaction_callback( std::function cb ) { my->set_pending_transaction_callback( cb ); } void database_api_impl::set_pending_transaction_callback( std::function cb ) { _pending_trx_callback = cb; } void database_api::set_block_applied_callback( std::function cb ) { my->set_block_applied_callback( cb ); } void database_api_impl::set_block_applied_callback( std::function cb ) { _block_applied_callback = cb; } void database_api::cancel_all_subscriptions() { my->cancel_all_subscriptions(); } void database_api_impl::cancel_all_subscriptions() { set_subscribe_callback( std::function(), true); _market_subscriptions.clear(); } ////////////////////////////////////////////////////////////////////// // // // Blocks and transactions // // // ////////////////////////////////////////////////////////////////////// optional database_api::get_block_header(uint32_t block_num)const { return my->get_block_header( block_num ); } optional database_api_impl::get_block_header(uint32_t block_num) const { auto result = _db.fetch_block_by_number(block_num); if(result) return *result; return {}; } map> database_api::get_block_header_batch(const vector block_nums)const { return my->get_block_header_batch( block_nums ); } map> database_api_impl::get_block_header_batch(const vector block_nums) const { map> results; for (const uint32_t block_num : block_nums) { results[block_num] = get_block_header(block_num); } return results; } optional database_api::get_block(uint32_t block_num)const { return my->get_block( block_num ); } optional database_api_impl::get_block(uint32_t block_num)const { return _db.fetch_block_by_number(block_num); } vector database_api::get_blocks(uint32_t start_block_num, uint32_t count) const { return my->get_blocks(start_block_num, count); } vector database_api_impl::get_blocks(uint32_t start_block_num, uint32_t count) const { return _dal.get_blocks(start_block_num, count); } vector database_api::get_blocks_with_virtual_operations(uint32_t start_block_num, uint32_t count, std::vector virtual_operation_ids) const { return my->get_blocks_with_virtual_operations(start_block_num, count, virtual_operation_ids); } vector database_api_impl::get_blocks_with_virtual_operations(uint32_t start_block_num, uint32_t count, std::vector& virtual_operation_ids) const { return _dal.get_blocks_with_virtual_operations(start_block_num, count, virtual_operation_ids); } processed_transaction database_api::get_transaction( uint32_t block_num, uint32_t trx_in_block )const { return my->get_transaction( block_num, trx_in_block ); } optional database_api::get_recent_transaction_by_id( const transaction_id_type& id )const { try { return my->_db.get_recent_transaction( id ); } catch ( ... ) { return optional(); } } processed_transaction database_api_impl::get_transaction(uint32_t block_num, uint32_t trx_num)const { auto opt_block = _db.fetch_block_by_number(block_num); FC_ASSERT( opt_block ); FC_ASSERT( opt_block->transactions.size() > trx_num ); return opt_block->transactions[trx_num]; } ////////////////////////////////////////////////////////////////////// // // // Globals // // // ////////////////////////////////////////////////////////////////////// chain_property_object database_api::get_chain_properties()const { return my->get_chain_properties(); } chain_property_object database_api_impl::get_chain_properties()const { return _db.get(chain_property_id_type()); } global_property_object database_api::get_global_properties()const { return my->get_global_properties(); } global_property_object database_api_impl::get_global_properties()const { return _dal.get_global_properties(); } fc::variant_object database_api::get_config()const { return my->get_config(); } fc::variant_object database_api_impl::get_config()const { return graphene::chain::get_config(); } chain_id_type database_api::get_chain_id()const { return my->get_chain_id(); } chain_id_type database_api_impl::get_chain_id()const { return _db.get_chain_id(); } dynamic_global_property_object database_api::get_dynamic_global_properties()const { return my->get_dynamic_global_properties(); } dynamic_global_property_object database_api_impl::get_dynamic_global_properties()const { return _db.get(dynamic_global_property_id_type()); } optional database_api::get_total_cycles() const { return my->get_total_cycles(); } optional database_api_impl::get_total_cycles() const { total_cycles_res result; const auto& accounts = _db.get_index_type().indices().get(); for (const account_object& acc : accounts) { if (acc.is_vault()) { optional vaultCycles = _dal.get_total_cycles(acc.get_id()); if (vaultCycles.valid()) { result.total_cycles += vaultCycles->total_cycles; result.total_dascoin += vaultCycles->total_dascoin; } } } return result; } optional database_api::get_queue_projection() const { return my->get_queue_projection(); } optional database_api_impl::get_queue_projection() const { queue_projection_res result; const auto& accounts = _db.get_index_type().indices().get(); for (const account_object& acc : accounts) { if (acc.is_vault()) { optional vaultQueue = _dal.get_queue_state_for_account(acc.get_id()); if (vaultQueue.valid()) { result = result + *vaultQueue; } } } return result; } ////////////////////////////////////////////////////////////////////// // // // Keys // // // ////////////////////////////////////////////////////////////////////// vector> database_api::get_key_references( vector key )const { return my->get_key_references( key ); } /** * @return all accounts that referr to the key or account id in their owner or active authorities. */ vector> database_api_impl::get_key_references( vector keys )const { wdump( (keys) ); vector< vector > final_result; final_result.reserve(keys.size()); for( auto& key : keys ) { address a1( pts_address(key, false, 56) ); address a2( pts_address(key, true, 56) ); address a3( pts_address(key, false, 0) ); address a4( pts_address(key, true, 0) ); address a5( key ); subscribe_to_item( key ); subscribe_to_item( a1 ); subscribe_to_item( a2 ); subscribe_to_item( a3 ); subscribe_to_item( a4 ); subscribe_to_item( a5 ); const auto& idx = _db.get_index_type(); const auto& aidx = dynamic_cast&>(idx); const auto& refs = aidx.get_secondary_index(); auto itr = refs.account_to_key_memberships.find(key); vector result; for( auto& a : {a1,a2,a3,a4,a5} ) { auto itr = refs.account_to_address_memberships.find(a); if( itr != refs.account_to_address_memberships.end() ) { result.reserve( itr->second.size() ); for( auto item : itr->second ) { wdump((a)(item)(item(_db).name)); result.push_back(item); } } } if( itr != refs.account_to_key_memberships.end() ) { result.reserve( itr->second.size() ); for( auto item : itr->second ) result.push_back(item); } final_result.emplace_back( std::move(result) ); } for( auto i : final_result ) subscribe_to_item(i); return final_result; } ////////////////////////////////////////////////////////////////////// // // // Accounts // // // ////////////////////////////////////////////////////////////////////// vector> database_api::get_accounts(const vector& account_ids)const { return my->get_accounts( account_ids ); } vector> database_api_impl::get_accounts(const vector& account_ids)const { vector> result; result.reserve(account_ids.size()); std::transform(account_ids.begin(), account_ids.end(), std::back_inserter(result), [this](account_id_type id) -> optional { if(auto o = _db.find(id)) { subscribe_to_item( id ); return *o; } return {}; }); return result; } std::map database_api::get_full_accounts( const vector& names_or_ids, bool subscribe ) { return my->get_full_accounts( names_or_ids, subscribe ); } std::map database_api_impl::get_full_accounts( const vector& names_or_ids, bool subscribe) { idump((names_or_ids)); std::map results; for (const std::string& account_name_or_id : names_or_ids) { const account_object* account = nullptr; if (std::isdigit(account_name_or_id[0])) account = _db.find(fc::variant(account_name_or_id, 1).as(1)); else { const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(account_name_or_id); if (itr != idx.end()) account = &*itr; } if (account == nullptr) continue; if( subscribe ) { if(_subscribed_accounts.size() < 100) { _subscribed_accounts.insert( account->get_id() ); subscribe_to_item( account->id ); } } // fc::mutable_variant_object full_account; full_account acnt; acnt.account = *account; acnt.statistics = account->statistics(_db); acnt.registrar_name = account->registrar(_db).name; acnt.referrer_name = account->referrer(_db).name; acnt.lifetime_referrer_name = account->lifetime_referrer(_db).name; acnt.votes.clear(); // Add the account itself, its statistics object, cashback balance, and referral account names /* full_account("account", *account)("statistics", account->statistics(_db)) ("registrar_name", account->registrar(_db).name)("referrer_name", account->referrer(_db).name) ("lifetime_referrer_name", account->lifetime_referrer(_db).name); */ if (account->cashback_vb) { acnt.cashback_balance = account->cashback_balance(_db); } // Add the account's proposals const auto& proposal_idx = _db.get_index_type(); const auto& pidx = dynamic_cast&>(proposal_idx); const auto& proposals_by_account = pidx.get_secondary_index(); auto required_approvals_itr = proposals_by_account._account_to_proposals.find( account->id ); if( required_approvals_itr != proposals_by_account._account_to_proposals.end() ) { acnt.proposals.reserve( required_approvals_itr->second.size() ); for( auto proposal_id : required_approvals_itr->second ) acnt.proposals.push_back( proposal_id(_db) ); } // Add the account's balances auto balance_range = _db.get_index_type().indices().get().equal_range(boost::make_tuple(account->id)); //vector balances; std::for_each(balance_range.first, balance_range.second, [&acnt](const account_balance_object& balance) { acnt.balances.emplace_back(balance); }); // Add the account's vesting balances auto vesting_range = _db.get_index_type().indices().get().equal_range(account->id); std::for_each(vesting_range.first, vesting_range.second, [&acnt](const vesting_balance_object& balance) { acnt.vesting_balances.emplace_back(balance); }); // Add the account's orders auto order_range = _db.get_index_type().indices().get().equal_range(account->id); std::for_each(order_range.first, order_range.second, [&acnt] (const limit_order_object& order) { acnt.limit_orders.emplace_back(order); }); auto call_range = _db.get_index_type().indices().get().equal_range(account->id); std::for_each(call_range.first, call_range.second, [&acnt] (const call_order_object& call) { acnt.call_orders.emplace_back(call); }); results[account_name_or_id] = acnt; } return results; } optional database_api::get_account_by_name( string name )const { return my->get_account_by_name( name ); } optional database_api_impl::get_account_by_name( string name )const { const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(name); if (itr != idx.end()) return *itr; return optional(); } vector database_api::get_account_references( account_id_type account_id )const { return my->get_account_references( account_id ); } vector database_api_impl::get_account_references( account_id_type account_id )const { const auto& idx = _db.get_index_type(); const auto& aidx = dynamic_cast&>(idx); const auto& refs = aidx.get_secondary_index(); auto itr = refs.account_to_account_memberships.find(account_id); vector result; if( itr != refs.account_to_account_memberships.end() ) { result.reserve( itr->second.size() ); for( auto item : itr->second ) result.push_back(item); } return result; } vector> database_api::lookup_account_names(const vector& account_names)const { return my->lookup_account_names( account_names ); } vector> database_api_impl::lookup_account_names(const vector& account_names)const { const auto& accounts_by_name = _db.get_index_type().indices().get(); vector > result; result.reserve(account_names.size()); std::transform(account_names.begin(), account_names.end(), std::back_inserter(result), [&accounts_by_name](const string& name) -> optional { auto itr = accounts_by_name.find(name); return itr == accounts_by_name.end()? optional() : *itr; }); return result; } map database_api::lookup_accounts(const string& lower_bound_name, uint32_t limit)const { return my->lookup_accounts( lower_bound_name, limit ); } map database_api_impl::lookup_accounts(const string& lower_bound_name, uint32_t limit)const { FC_ASSERT( limit <= 1000 ); const auto& accounts_by_name = _db.get_index_type().indices().get(); map result; for( auto itr = accounts_by_name.lower_bound(lower_bound_name); limit-- && itr != accounts_by_name.end(); ++itr ) { result.insert(make_pair(itr->name, itr->get_id())); if( limit == 1 ) subscribe_to_item( itr->get_id() ); } return result; } uint64_t database_api::get_account_count()const { return my->get_account_count(); } uint64_t database_api_impl::get_account_count()const { return _db.get_index_type().indices().size(); } ////////////////////////////////////////////////////////////////////// // // // Balances // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_account_balances(account_id_type id, const flat_set& assets) const { return my->get_account_balances( id, assets ); } vector database_api_impl::get_account_balances(account_id_type acnt, const flat_set& assets) const { vector result; if (assets.empty()) { // if the caller passes in an empty list of assets, return balances for all assets the account owns. const account_balance_index& balance_index = _db.get_index_type(); auto range = balance_index.indices().get().equal_range(boost::make_tuple(acnt)); for ( const account_balance_object& balance : boost::make_iterator_range(range.first, range.second) ) result.emplace_back(balance.get_asset_reserved_balance()); } else { result.reserve(assets.size()); std::transform(assets.begin(), assets.end(), std::back_inserter(result), [this, acnt](asset_id_type id) { return _db.get_balance_object(acnt, id).get_asset_reserved_balance(); }); } return result; } vector database_api::get_named_account_balances(const std::string& name, const flat_set& assets)const { return my->get_named_account_balances( name, assets ); } vector database_api_impl::get_named_account_balances(const std::string& name, const flat_set& assets) const { const auto& accounts_by_name = _db.get_index_type().indices().get(); auto itr = accounts_by_name.find(name); FC_ASSERT( itr != accounts_by_name.end() ); return get_account_balances(itr->get_id(), assets); } vector database_api::get_balance_objects( const vector
& addrs )const { return my->get_balance_objects( addrs ); } vector database_api_impl::get_balance_objects( const vector
& addrs )const { try { const auto& bal_idx = _db.get_index_type(); const auto& by_owner_idx = bal_idx.indices().get(); vector result; for( const auto& owner : addrs ) { subscribe_to_item( owner ); auto itr = by_owner_idx.lower_bound( boost::make_tuple( owner, asset_id_type(0) ) ); while( itr != by_owner_idx.end() && itr->owner == owner ) { result.push_back( *itr ); ++itr; } } return result; } FC_CAPTURE_AND_RETHROW( (addrs) ) } vector database_api::get_vested_balances( const vector& objs )const { return my->get_vested_balances( objs ); } vector database_api_impl::get_vested_balances( const vector& objs )const { try { vector result; result.reserve( objs.size() ); auto now = _db.head_block_time(); for( auto obj : objs ) result.push_back( obj(_db).available( now ) ); return result; } FC_CAPTURE_AND_RETHROW( (objs) ) } vector database_api::get_vesting_balances( account_id_type account_id )const { return my->get_vesting_balances( account_id ); } vector database_api_impl::get_vesting_balances( account_id_type account_id )const { try { vector result; auto vesting_range = _db.get_index_type().indices().get().equal_range(account_id); std::for_each(vesting_range.first, vesting_range.second, [&result](const vesting_balance_object& balance) { result.emplace_back(balance); }); return result; } FC_CAPTURE_AND_RETHROW( (account_id) ); } vector database_api::get_tethered_accounts_balances( account_id_type id, const flat_set& assets )const { return my->get_tethered_accounts_balances( id, assets ); } vector database_api_impl::get_tethered_accounts_balances( account_id_type account, const flat_set& assets )const { vector tmp; if (assets.empty()) { // if the caller passes in an empty list of assets, get all assets the account owns. const account_balance_index &balance_index = _db.get_index_type(); auto range = balance_index.indices().get().equal_range(boost::make_tuple(account)); for (const account_balance_object &balance : boost::make_iterator_range(range.first, range.second)) tmp.emplace_back(balance.asset_type); } else { tmp.reserve(assets.size()); std::copy(assets.begin(), assets.end(), std::back_inserter(tmp)); } vector result; std::transform(tmp.begin(), tmp.end(), std::back_inserter(result), [this, account](asset_id_type id) { return get_tethered_accounts_balances(account, id); }); return result; } tethered_accounts_balances_collection database_api_impl::get_tethered_accounts_balances( account_id_type id, asset_id_type asset )const { tethered_accounts_balances_collection ret; ret.total = 0; ret.asset_id = asset; const auto& idx = _db.get_index_type().indices().get(); const auto it = idx.find(id); flat_set> accounts; if (it != idx.end()) { const auto& account = *it; if (account.kind == account_kind::wallet) { accounts.insert(make_tuple(id, account.name, account.kind)); std::transform(account.vault.begin(), account.vault.end(), std::inserter(accounts, accounts.begin()), [&](account_id_type vault) { const auto& vault_acc = vault(_db); return make_tuple(vault, vault_acc.name, account_kind::vault); }); } else if (account.kind == account_kind::custodian || account.kind == account_kind::special) { accounts.insert(make_tuple(id, account.name, account.kind)); } else if (account.kind == account_kind::vault) { if (account.parents.empty()) accounts.insert(make_tuple(id, account.name, account.kind)); else return get_tethered_accounts_balances(*(account.parents.begin()), asset); } } for (const auto& i : accounts) { if (_db.check_if_balance_object_exists(get<0>(i), asset)) { const auto& balance_obj = _db.get_balance_object(get<0>(i), asset); ret.total += balance_obj.balance + balance_obj.reserved; ret.details.emplace_back(tethered_accounts_balance{get<0>(i), get<1>(i), get<2>(i), balance_obj.balance, balance_obj.reserved}); } } return ret; } ////////////////////////////////////////////////////////////////////// // // // Assets // // // ////////////////////////////////////////////////////////////////////// asset_id_type database_api_impl::get_web_asset_id() const { return _db.get_web_asset_id(); } vector> database_api::get_assets(const vector& asset_ids)const { return my->get_assets( asset_ids ); } vector> database_api_impl::get_assets(const vector& asset_ids)const { vector> result; result.reserve(asset_ids.size()); std::transform(asset_ids.begin(), asset_ids.end(), std::back_inserter(result), [this](asset_id_type id) -> optional { if(auto o = _db.find(id)) { subscribe_to_item( id ); return *o; } return {}; }); return result; } vector database_api::list_assets(const string& lower_bound_symbol, uint32_t limit)const { return my->list_assets( lower_bound_symbol, limit ); } vector database_api_impl::list_assets(const string& lower_bound_symbol, uint32_t limit)const { FC_ASSERT( limit <= 100 ); const auto& assets_by_symbol = _db.get_index_type().indices().get(); vector result; result.reserve(limit); auto itr = assets_by_symbol.lower_bound(lower_bound_symbol); if( lower_bound_symbol == "" ) itr = assets_by_symbol.begin(); while(limit-- && itr != assets_by_symbol.end()) result.emplace_back(*itr++); return result; } optional database_api::lookup_asset_symbol(const string& symbol_or_id) const { return my->lookup_asset_symbol( symbol_or_id ); } optional database_api_impl::lookup_asset_symbol(const string& symbol_or_id) const { return _dal.lookup_asset_symbol(symbol_or_id); } vector> database_api::lookup_asset_symbols(const vector& symbols_or_ids)const { return my->lookup_asset_symbols( symbols_or_ids ); } vector> database_api_impl::lookup_asset_symbols(const vector& symbols_or_ids)const { return _dal.lookup_asset_symbols( symbols_or_ids ); } ////////////////////////////////////////////////////////////////////// // // // Markets / feeds // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_limit_orders(asset_id_type a, asset_id_type b, uint32_t limit)const { return my->get_limit_orders( a, b, limit ); } /** * @return the limit orders for both sides of the book for the two assets specified up to limit number on each side. */ vector database_api_impl::get_limit_orders(asset_id_type a, asset_id_type b, uint32_t limit)const { const auto& limit_order_idx = _db.get_index_type(); const auto& limit_price_idx = limit_order_idx.indices().get(); vector result; uint32_t count = 0; auto limit_itr = limit_price_idx.lower_bound(price::max(a,b)); auto limit_end = limit_price_idx.upper_bound(price::min(a,b)); while(limit_itr != limit_end && count < limit) { result.push_back(*limit_itr); ++limit_itr; ++count; } count = 0; limit_itr = limit_price_idx.lower_bound(price::max(b,a)); limit_end = limit_price_idx.upper_bound(price::min(b,a)); while(limit_itr != limit_end && count < limit) { result.push_back(*limit_itr); ++limit_itr; ++count; } return result; } vector database_api::get_limit_orders_for_account(account_id_type id, asset_id_type a, asset_id_type b, uint32_t limit)const { return my->get_limit_orders_for_account( id, a, b, limit ); } /** * @return the limit orders for a given account, for both sides of the book for the two assets specified up to limit number on each side. */ vector database_api_impl::get_limit_orders_for_account(account_id_type id, asset_id_type a, asset_id_type b, uint32_t limit)const { FC_ASSERT( limit < 200, "Limit (${limit}) needs to be lower than 200", ("limit", limit) ); const auto& limit_order_idx = _db.get_index_type(); const auto& limit_account_idx = limit_order_idx.indices().get(); vector result; uint32_t count = 0; auto market = std::make_pair( a, b ); if( market.first > market.second ) std::swap( market.first, market.second ); auto limit_itr = limit_account_idx.lower_bound(id); auto limit_end = limit_account_idx.upper_bound(id); while(limit_itr != limit_end && count < limit) { if (limit_itr->get_market() == market) { result.push_back(*limit_itr); ++count; } ++limit_itr; } return result; } limit_orders_grouped_by_price database_api::get_limit_orders_grouped_by_price(asset_id_type a, asset_id_type b, uint32_t limit)const { return my->get_limit_orders_grouped_by_price( a, b, limit, ORDER_BOOK_QUERY_PRECISION, std::bind(&database_api::repack, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, limit) ); } limit_orders_grouped_by_price database_api::get_limit_orders_grouped_by_price_with_precision(asset_id_type a, asset_id_type b, uint32_t limit, uint32_t precision)const { return my->get_limit_orders_grouped_by_price( a, b, limit, asset::scaled_precision(precision).value, std::bind(&database_api::repack, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, limit) ); } template void database_api::repack(std::vector& ret, std::map &helper_map, bool ascending, uint32_t limit)const { uint32_t count = 0; if(ascending) { auto helper_itr = helper_map.begin(); while(helper_itr != helper_map.end() && count < limit) { ret.push_back(helper_itr->second); helper_itr++; count++; } } else { auto helper_itr = helper_map.rbegin(); while(helper_itr != helper_map.rend() && count < limit) { ret.push_back(helper_itr->second); helper_itr++; count++; } } } template T database_api_impl::get_limit_orders_grouped_by_price(asset_id_type base, asset_id_type quote, uint32_t limit, uint32_t precision, repack_function repack)const { const auto& limit_order_idx = _db.get_index_type(); const auto& limit_price_idx = limit_order_idx.indices().get(); T result; bool swap_buy_sell = false; if(base < quote) { std::swap(base, quote); swap_buy_sell = true; } auto func = [this, &limit_price_idx, limit, precision, repack](asset_id_type& a, asset_id_type& b, std::vector& ret, bool ascending){ std::map helper_map; auto limit_itr = limit_price_idx.lower_bound(price::max(a, b)); auto limit_end = limit_price_idx.upper_bound(price::min(a, b)); auto& asset_a = _db.get(a); auto& asset_b = _db.get(b); double coef = asset::scaled_precision(asset_a.precision).value * 1.0 / asset::scaled_precision(asset_b.precision).value; while(limit_itr != limit_end) { double price = ascending ? 1 / limit_itr->sell_price.to_real() : limit_itr->sell_price.to_real(); // adjust price precision and value accordingly so we can form a key auto p = round((ascending ? price * coef : price / coef) * precision); share_type price_key = static_cast(p); auto helper_itr = helper_map.find(price_key); auto quote = round(ascending ? limit_itr->for_sale.value * price : limit_itr->for_sale.value / price); // if we are adding limit order with new price if(helper_itr == helper_map.end()) { aggregated_limit_orders_with_same_price alo; alo.price = price_key; alo.base_volume = limit_itr->for_sale.value; alo.quote_volume = quote; alo.count = 1; helper_map[price_key] = alo; } else { helper_itr->second.base_volume += limit_itr->for_sale.value; helper_itr->second.quote_volume += quote; helper_itr->second.count++; } ++limit_itr; } // re-pack result in vector (from map) in desired order repack(ret, helper_map, ascending); }; if(swap_buy_sell) { func(base, quote, result.buy, false); func(quote, base, result.sell, true); } else { func(base, quote, result.sell, true); func(quote, base, result.buy, false); } return result; } limit_orders_collection_grouped_by_price database_api::get_limit_orders_collection_grouped_by_price(asset_id_type a, asset_id_type b, uint32_t limit_group, uint32_t limit_per_group) const { auto f = [this, limit_group, limit_per_group](std::vector& ret, std::map &helper_map, bool ascending) { // re-pack result in vector (from map) in desired order if(ascending) { my->func_re_pack(helper_map.begin(), helper_map.end(), ret, limit_group, limit_per_group); } else { my->func_re_pack(helper_map.rbegin(), helper_map.rend(), ret, limit_group, limit_per_group); } }; return my->get_limit_orders_grouped_by_price( a, b, 0, ORDER_BOOK_QUERY_PRECISION, f ); } template void database_api_impl::func_re_pack(Iter helper_itr, Iter end, std::vector& ret, uint32_t limit_group, uint32_t limit_per_group) const { uint32_t count = 0; while(helper_itr != end && count < limit_group) { auto& alo = helper_itr->second; share_type group_price_key = static_cast(alo.price / ORDER_BOOK_GROUP_QUERY_PRECISION_DIFF); aggregated_limit_orders_with_same_price_collection aloc; aloc.price = group_price_key; aloc.base_volume = alo.base_volume; aloc.quote_volume = alo.quote_volume; aloc.count = alo.count; aloc.limit_orders.push_back(alo); ret.push_back(aloc); helper_itr++; count++; // put all groups in same basket if price for group is same while(helper_itr != end) { alo = helper_itr->second; share_type group_price_key_temp = static_cast(alo.price / ORDER_BOOK_GROUP_QUERY_PRECISION_DIFF); if(group_price_key_temp != group_price_key) { break; } if(aloc.limit_orders.size() < limit_per_group) { ret.back().count += alo.count; ret.back().base_volume += alo.base_volume; ret.back().quote_volume += alo.quote_volume; ret.back().limit_orders.push_back(alo); } helper_itr++; } } } vector database_api::get_call_orders(asset_id_type a, uint32_t limit)const { return my->get_call_orders( a, limit ); } vector database_api_impl::get_call_orders(asset_id_type a, uint32_t limit)const { const auto& call_index = _db.get_index_type().indices().get(); const asset_object& mia = _db.get(a); price index_price = price::min(mia.bitasset_data(_db).options.short_backing_asset, mia.get_id()); vector< call_order_object> result; auto itr_min = call_index.lower_bound(index_price.min()); auto itr_max = call_index.lower_bound(index_price.max()); while( itr_min != itr_max && result.size() < limit ) { result.emplace_back(*itr_min); ++itr_min; } return result; } vector database_api::get_settle_orders(asset_id_type a, uint32_t limit)const { return my->get_settle_orders( a, limit ); } vector database_api_impl::get_settle_orders(asset_id_type a, uint32_t limit)const { const auto& settle_index = _db.get_index_type().indices().get(); const asset_object& mia = _db.get(a); vector result; auto itr_min = settle_index.lower_bound(mia.get_id()); auto itr_max = settle_index.upper_bound(mia.get_id()); while( itr_min != itr_max && result.size() < limit ) { result.emplace_back(*itr_min); ++itr_min; } return result; } vector database_api::get_margin_positions( const account_id_type& id )const { return my->get_margin_positions( id ); } vector database_api_impl::get_margin_positions( const account_id_type& id )const { try { const auto& idx = _db.get_index_type(); const auto& aidx = idx.indices().get(); auto start = aidx.lower_bound( boost::make_tuple( id, asset_id_type(0) ) ); auto end = aidx.lower_bound( boost::make_tuple( id+1, asset_id_type(0) ) ); vector result; while( start != end ) { result.push_back(*start); ++start; } return result; } FC_CAPTURE_AND_RETHROW( (id) ) } void database_api::subscribe_to_market(std::function callback, asset_id_type a, asset_id_type b) { my->subscribe_to_market( callback, a, b ); } void database_api_impl::subscribe_to_market(std::function callback, asset_id_type a, asset_id_type b) { if(a > b) std::swap(a,b); FC_ASSERT(a != b); _market_subscriptions[ std::make_pair(a,b) ] = callback; } void database_api::unsubscribe_from_market(asset_id_type a, asset_id_type b) { my->unsubscribe_from_market( a, b ); } void database_api_impl::unsubscribe_from_market(asset_id_type a, asset_id_type b) { if(a > b) std::swap(a,b); FC_ASSERT(a != b); _market_subscriptions.erase(std::make_pair(a,b)); } market_ticker database_api::get_ticker( const string& base, const string& quote )const { return my->get_ticker( base, quote ); } market_ticker database_api_impl::get_ticker( const string& base, const string& quote )const { FC_ASSERT( _app_options && _app_options->has_market_history_plugin, "Market history plugin is not enabled." ); const auto assets = lookup_asset_symbols( {base, quote} ); FC_ASSERT( assets[0], "Invalid base asset symbol: ${s}", ("s",base) ); FC_ASSERT( assets[1], "Invalid quote asset symbol: ${s}", ("s",quote) ); const fc::time_point_sec now = _db.head_block_time(); const fc::time_point_sec yesterday = fc::time_point_sec( now.sec_since_epoch() - 86400 ); market_ticker result; result.time = now; result.base = base; result.quote = quote; result.latest = 0; result.lowest_ask = 0; result.highest_bid = 0; result.percent_change = 0; result.base_volume = 0; result.quote_volume = 0; auto base_id = assets[0]->id; auto quote_id = assets[1]->id; if( base_id > quote_id ) std::swap( base_id, quote_id ); history_key hkey; hkey.base = base_id; hkey.quote = quote_id; hkey.sequence = std::numeric_limits::min(); // TODO: move following duplicate code out // TODO: using pow is a bit inefficient here, optimization is possible auto asset_to_real = [&]( const asset& a, int p ) { return double(a.amount.value)/pow( 10, p ); }; auto price_to_real = [&]( const price& p ) { if( p.base.asset_id == assets[0]->id ) return asset_to_real( p.base, assets[0]->precision ) / asset_to_real( p.quote, assets[1]->precision ); else return asset_to_real( p.quote, assets[0]->precision ) / asset_to_real( p.base, assets[1]->precision ); }; const auto& history_idx = _db.get_index_type().indices().get(); auto itr = history_idx.lower_bound( hkey ); bool is_latest = true; price latest_price; fc::uint128 base_volume; fc::uint128 quote_volume; while( itr != history_idx.end() && itr->key.base == base_id && itr->key.quote == quote_id ) { if( is_latest ) { is_latest = false; latest_price = itr->op.fill_price; result.latest = price_to_real( latest_price ); } if( itr->time < yesterday ) { if( itr->op.fill_price != latest_price ) result.percent_change = ( result.latest / price_to_real( itr->op.fill_price ) - 1 ) * 100; break; } if( itr->op.is_maker ) { if( assets[0]->id == itr->op.receives.asset_id ) { base_volume += itr->op.receives.amount.value; quote_volume += itr->op.pays.amount.value; } else { base_volume += itr->op.pays.amount.value; quote_volume += itr->op.receives.amount.value; } } ++itr; } auto uint128_to_double = []( const fc::uint128& n ) { if( n.hi == 0 ) return double( n.lo ); return double(n.hi) * (uint64_t(1)<<63) * 2 + n.lo; }; result.base_volume = uint128_to_double( base_volume ) / pow( 10, assets[0]->precision ); result.quote_volume = uint128_to_double( quote_volume ) / pow( 10, assets[1]->precision ); const auto orders = get_order_book( base, quote, 1 ); if( !orders.asks.empty() ) result.lowest_ask = orders.asks[0].price; if( !orders.bids.empty() ) result.highest_bid = orders.bids[0].price; return result; } market_hi_low_volume database_api::get_24_hi_low_volume( const string& base, const string& quote )const { return my->get_24_hi_low_volume( base, quote ); } market_hi_low_volume database_api_impl::get_24_hi_low_volume( const string& base, const string& quote )const { auto assets = lookup_asset_symbols( {base, quote} ); FC_ASSERT( assets[0], "Invalid base asset symbol: ${s}", ("s",base) ); FC_ASSERT( assets[1], "Invalid quote asset symbol: ${s}", ("s",quote) ); auto base_id = assets[0]->id; auto quote_id = assets[1]->id; market_hi_low_volume result; result.base = base; result.quote = quote; result.high = 0; result.low = 0; result.base_volume = 0; result.quote_volume = 0; try { if( base_id > quote_id ) std::swap(base_id, quote_id); auto now = fc::time_point_sec( fc::time_point::now() ); auto ts = now - fc::days(1).to_seconds(); auto trades = get_trade_history( base, quote, now, ts, 100 ); if( !trades.empty() ) { result.high = trades[0].price; result.low = trades[0].price; } for ( market_trade t: trades ) { if( result.high < t.price ) result.high = t.price; if( result.low > t.price ) result.low = t.price; result.base_volume += t.value; result.quote_volume += t.amount; } while (trades.size() == 100) { trades = get_trade_history_by_sequence( base, quote, trades[99].sequence, ts, 100 ); for ( market_trade t: trades ) { if( result.high < t.price ) result.high = t.price; if( result.low > t.price ) result.low = t.price; result.base_volume += t.value; result.quote_volume += t.amount; } } return result; } FC_CAPTURE_AND_RETHROW( (base)(quote) ) } optional database_api_impl::get_issued_asset_record(const string& unique_id, asset_id_type asset_id) const { return _dal.get_issued_asset_record(unique_id, asset_id); } bool database_api::check_issued_asset(const string& unique_id, const string& asset) const { return my->check_issued_asset(unique_id, asset); } bool database_api_impl::check_issued_asset(const string& unique_id, const string& asset) const { return _dal.check_issued_asset(unique_id, asset); } bool database_api::check_issued_webeur(const string& unique_id) const { return my->check_issued_webeur(unique_id); } bool database_api_impl::check_issued_webeur(const string& unique_id) const { return _dal.check_issued_webeur(unique_id); } order_book database_api::get_order_book( const string& base, const string& quote, unsigned limit )const { return my->get_order_book( base, quote, limit); } order_book database_api_impl::get_order_book( const string& base, const string& quote, unsigned limit )const { using boost::multiprecision::uint128_t; FC_ASSERT( limit <= 50 ); order_book result; result.base = base; result.quote = quote; auto assets = lookup_asset_symbols( {base, quote} ); FC_ASSERT( assets[0], "Invalid base asset symbol: ${s}", ("s",base) ); FC_ASSERT( assets[1], "Invalid quote asset symbol: ${s}", ("s",quote) ); auto base_id = assets[0]->id; auto quote_id = assets[1]->id; auto orders = get_limit_orders( base_id, quote_id, limit ); auto asset_to_real = [&]( const asset& a, int p ) { return double(a.amount.value)/pow( 10, p ); }; auto price_to_real = [&]( const price& p ) { if( p.base.asset_id == base_id ) return asset_to_real( p.base, assets[0]->precision ) / asset_to_real( p.quote, assets[1]->precision ); else return asset_to_real( p.quote, assets[0]->precision ) / asset_to_real( p.base, assets[1]->precision ); }; for( const auto& o : orders ) { if( o.sell_price.base.asset_id == base_id ) { order ord; ord.price = price_to_real( o.sell_price ); ord.quote = asset_to_real( share_type( ( uint128_t( o.for_sale.value ) * o.sell_price.quote.amount.value ) / o.sell_price.base.amount.value ), assets[1]->precision ); ord.base = asset_to_real( o.for_sale, assets[0]->precision ); result.bids.push_back( ord ); } else { order ord; ord.price = price_to_real( o.sell_price ); ord.quote = asset_to_real( o.for_sale, assets[1]->precision ); ord.base = asset_to_real( share_type( ( uint64_t( o.for_sale.value ) * o.sell_price.quote.amount.value ) / o.sell_price.base.amount.value ), assets[0]->precision ); result.asks.push_back( ord ); } } return result; } vector database_api::get_trade_history( const string& base, const string& quote, fc::time_point_sec start, fc::time_point_sec stop, unsigned limit )const { return my->get_trade_history( base, quote, start, stop, limit ); } vector database_api_impl::get_trade_history( const string& base, const string& quote, fc::time_point_sec start, fc::time_point_sec stop, unsigned limit )const { FC_ASSERT( _app_options && _app_options->has_market_history_plugin, "Market history plugin is not enabled." ); FC_ASSERT( limit <= 100 ); auto assets = lookup_asset_symbols( {base, quote} ); FC_ASSERT( assets[0], "Invalid base asset symbol: ${s}", ("s",base) ); FC_ASSERT( assets[1], "Invalid quote asset symbol: ${s}", ("s",quote) ); auto base_id = assets[0]->id; auto quote_id = assets[1]->id; if( base_id > quote_id ) std::swap( base_id, quote_id ); auto asset_to_real = [&]( const asset& a, int p ) { return double( a.amount.value ) / pow( 10, p ); }; auto price_to_real = [&]( const price& p ) { if( p.base.asset_id == assets[0]->id ) return asset_to_real( p.base, assets[0]->precision ) / asset_to_real( p.quote, assets[1]->precision ); else return asset_to_real( p.quote, assets[0]->precision ) / asset_to_real( p.base, assets[1]->precision ); }; if ( start.sec_since_epoch() == 0 ) start = fc::time_point_sec( fc::time_point::now() ); uint32_t count = 0; const auto& history_idx = _db.get_index_type().indices().get(); auto itr = history_idx.lower_bound( std::make_tuple( base_id, quote_id, start ) ); vector result; while( itr != history_idx.end() && count < limit && !( itr->key.base != base_id || itr->key.quote != quote_id || itr->time < stop ) ) { { market_trade trade; if( assets[0]->id == itr->op.receives.asset_id ) { trade.amount = asset_to_real( itr->op.pays, assets[1]->precision ); trade.value = asset_to_real( itr->op.receives, assets[0]->precision ); } else { trade.amount = asset_to_real( itr->op.receives, assets[1]->precision ); trade.value = asset_to_real( itr->op.pays, assets[0]->precision ); } trade.date = itr->time; trade.price = price_to_real( itr->op.fill_price ); if( itr->op.is_maker ) { trade.sequence = -itr->key.sequence; trade.side1_account_id = itr->op.account_id; } else trade.side2_account_id = itr->op.account_id; auto next_itr = std::next(itr); // Trades are usually tracked in each direction, exception: for global settlement only one side is recorded if( next_itr != history_idx.end() && next_itr->key.base == base_id && next_itr->key.quote == quote_id && next_itr->time == itr->time && next_itr->op.is_maker != itr->op.is_maker ) { // next_itr now could be the other direction // FIXME not 100% sure if( next_itr->op.is_maker ) { trade.sequence = -next_itr->key.sequence; trade.side1_account_id = next_itr->op.account_id; } else trade.side2_account_id = next_itr->op.account_id; // skip the other direction itr = next_itr; } result.push_back( trade ); ++count; } ++itr; } return result; } vector database_api::get_trade_history_by_sequence( const string& base, const string& quote, int64_t start, fc::time_point_sec stop, unsigned limit )const { return my->get_trade_history_by_sequence( base, quote, start, stop, limit ); } vector database_api_impl::get_trade_history_by_sequence( const string& base, const string& quote, int64_t start, fc::time_point_sec stop, unsigned limit )const { FC_ASSERT( _app_options && _app_options->has_market_history_plugin, "Market history plugin is not enabled." ); FC_ASSERT( limit <= 100 ); FC_ASSERT( start >= 0 ); int64_t start_seq = -start; auto assets = lookup_asset_symbols( {base, quote} ); FC_ASSERT( assets[0], "Invalid base asset symbol: ${s}", ("s",base) ); FC_ASSERT( assets[1], "Invalid quote asset symbol: ${s}", ("s",quote) ); auto base_id = assets[0]->id; auto quote_id = assets[1]->id; if( base_id > quote_id ) std::swap( base_id, quote_id ); const auto& history_idx = _db.get_index_type().indices().get(); history_key hkey; hkey.base = base_id; hkey.quote = quote_id; hkey.sequence = start_seq; auto asset_to_real = [&]( const asset& a, int p ) { return double( a.amount.value ) / pow( 10, p ); }; auto price_to_real = [&]( const price& p ) { if( p.base.asset_id == assets[0]->id ) return asset_to_real( p.base, assets[0]->precision ) / asset_to_real( p.quote, assets[1]->precision ); else return asset_to_real( p.quote, assets[0]->precision ) / asset_to_real( p.base, assets[1]->precision ); }; uint32_t count = 0; auto itr = history_idx.lower_bound( hkey ); vector result; while( itr != history_idx.end() && count < limit && !( itr->key.base != base_id || itr->key.quote != quote_id || itr->time < stop ) ) { if( itr->key.sequence == start_seq ) // found the key, should skip this and the other direction if found { auto next_itr = std::next(itr); if( next_itr != history_idx.end() && next_itr->key.base == base_id && next_itr->key.quote == quote_id && next_itr->time == itr->time && next_itr->op.is_maker != itr->op.is_maker ) { // next_itr now could be the other direction // FIXME not 100% sure // skip the other direction itr = next_itr; } } else { market_trade trade; if( assets[0]->id == itr->op.receives.asset_id ) { trade.amount = asset_to_real( itr->op.pays, assets[1]->precision ); trade.value = asset_to_real( itr->op.receives, assets[0]->precision ); } else { trade.amount = asset_to_real( itr->op.receives, assets[1]->precision ); trade.value = asset_to_real( itr->op.pays, assets[0]->precision ); } trade.date = itr->time; trade.price = price_to_real( itr->op.fill_price ); if( itr->op.is_maker ) { trade.sequence = -itr->key.sequence; trade.side1_account_id = itr->op.account_id; } else trade.side2_account_id = itr->op.account_id; auto next_itr = std::next(itr); // Trades are usually tracked in each direction, exception: for global settlement only one side is recorded if( next_itr != history_idx.end() && next_itr->key.base == base_id && next_itr->key.quote == quote_id && next_itr->time == itr->time && next_itr->op.is_maker != itr->op.is_maker ) { // next_itr now could be the other direction // FIXME not 100% sure if( next_itr->op.is_maker ) { trade.sequence = -next_itr->key.sequence; trade.side1_account_id = next_itr->op.account_id; } else trade.side2_account_id = next_itr->op.account_id; // skip the other direction itr = next_itr; } result.push_back( trade ); ++count; } ++itr; } return result; } ////////////////////////////////////////////////////////////////////// // // // Witnesses // // // ////////////////////////////////////////////////////////////////////// vector> database_api::get_witnesses(const vector& witness_ids)const { return my->get_witnesses( witness_ids ); } vector database_api::get_workers_by_account(account_id_type account)const { const auto& idx = my->_db.get_index_type().indices().get(); auto itr = idx.find(account); vector result; if( itr != idx.end() && itr->worker_account == account ) { result.emplace_back( *itr ); ++itr; } return result; } vector> database_api_impl::get_witnesses(const vector& witness_ids)const { vector> result; result.reserve(witness_ids.size()); std::transform(witness_ids.begin(), witness_ids.end(), std::back_inserter(result), [this](witness_id_type id) -> optional { if(auto o = _db.find(id)) return *o; return {}; }); return result; } fc::optional database_api::get_witness_by_account(account_id_type account)const { return my->get_witness_by_account( account ); } fc::optional database_api_impl::get_witness_by_account(account_id_type account) const { const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(account); if( itr != idx.end() ) return *itr; return {}; } map database_api::lookup_witness_accounts(const string& lower_bound_name, uint32_t limit)const { return my->lookup_witness_accounts( lower_bound_name, limit ); } map database_api_impl::lookup_witness_accounts(const string& lower_bound_name, uint32_t limit)const { FC_ASSERT( limit <= 1000 ); const auto& witnesses_by_id = _db.get_index_type().indices().get(); // we want to order witnesses by account name, but that name is in the account object // so the witness_index doesn't have a quick way to access it. // get all the names and look them all up, sort them, then figure out what // records to return. This could be optimized, but we expect the // number of witnesses to be few and the frequency of calls to be rare std::map witnesses_by_account_name; for (const witness_object& witness : witnesses_by_id) if (auto account_iter = _db.find(witness.witness_account)) if (account_iter->name >= lower_bound_name) // we can ignore anything below lower_bound_name witnesses_by_account_name.insert(std::make_pair(account_iter->name, witness.id)); auto end_iter = witnesses_by_account_name.begin(); while (end_iter != witnesses_by_account_name.end() && limit--) ++end_iter; witnesses_by_account_name.erase(end_iter, witnesses_by_account_name.end()); return witnesses_by_account_name; } uint64_t database_api::get_witness_count()const { return my->get_witness_count(); } uint64_t database_api_impl::get_witness_count()const { return _db.get_index_type().indices().size(); } ////////////////////////////////////////////////////////////////////// // // // Committee members // // // ////////////////////////////////////////////////////////////////////// vector> database_api::get_committee_members(const vector& committee_member_ids)const { return my->get_committee_members( committee_member_ids ); } vector> database_api_impl::get_committee_members(const vector& committee_member_ids)const { vector> result; result.reserve(committee_member_ids.size()); std::transform(committee_member_ids.begin(), committee_member_ids.end(), std::back_inserter(result), [this](committee_member_id_type id) -> optional { if(auto o = _db.find(id)) return *o; return {}; }); return result; } fc::optional database_api::get_committee_member_by_account(account_id_type account)const { return my->get_committee_member_by_account( account ); } fc::optional database_api_impl::get_committee_member_by_account(account_id_type account) const { const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(account); if( itr != idx.end() ) return *itr; return {}; } map database_api::lookup_committee_member_accounts(const string& lower_bound_name, uint32_t limit)const { return my->lookup_committee_member_accounts( lower_bound_name, limit ); } map database_api_impl::lookup_committee_member_accounts(const string& lower_bound_name, uint32_t limit)const { FC_ASSERT( limit <= 1000 ); const auto& committee_members_by_id = _db.get_index_type().indices().get(); // we want to order committee_members by account name, but that name is in the account object // so the committee_member_index doesn't have a quick way to access it. // get all the names and look them all up, sort them, then figure out what // records to return. This could be optimized, but we expect the // number of committee_members to be few and the frequency of calls to be rare std::map committee_members_by_account_name; for (const committee_member_object& committee_member : committee_members_by_id) if (auto account_iter = _db.find(committee_member.committee_member_account)) if (account_iter->name >= lower_bound_name) // we can ignore anything below lower_bound_name committee_members_by_account_name.insert(std::make_pair(account_iter->name, committee_member.id)); auto end_iter = committee_members_by_account_name.begin(); while (end_iter != committee_members_by_account_name.end() && limit--) ++end_iter; committee_members_by_account_name.erase(end_iter, committee_members_by_account_name.end()); return committee_members_by_account_name; } ////////////////////////////////////////////////////////////////////// // // // Authority / validation // // // ////////////////////////////////////////////////////////////////////// std::string database_api::get_transaction_hex(const signed_transaction& trx)const { return my->get_transaction_hex( trx ); } std::string database_api_impl::get_transaction_hex(const signed_transaction& trx)const { return fc::to_hex(fc::raw::pack(trx)); } set database_api::get_required_signatures( const signed_transaction& trx, const flat_set& available_keys )const { return my->get_required_signatures( trx, available_keys ); } set database_api_impl::get_required_signatures( const signed_transaction& trx, const flat_set& available_keys )const { wdump((trx)(available_keys)); auto result = trx.get_required_signatures( _db.get_chain_id(), available_keys, [&]( account_id_type id ){ return &id(_db).active; }, [&]( account_id_type id ){ return &id(_db).owner; }, _db.get_global_properties().parameters.max_authority_depth ); wdump((result)); return result; } set database_api::get_potential_signatures( const signed_transaction& trx )const { return my->get_potential_signatures( trx ); } set
database_api::get_potential_address_signatures( const signed_transaction& trx )const { return my->get_potential_address_signatures( trx ); } set database_api_impl::get_potential_signatures( const signed_transaction& trx )const { wdump((trx)); set result; trx.get_required_signatures( _db.get_chain_id(), flat_set(), [&]( account_id_type id ) { const auto& auth = id(_db).active; for( const auto& k : auth.get_keys() ) result.insert(k); return &auth; }, [&]( account_id_type id ) { const auto& auth = id(_db).owner; for( const auto& k : auth.get_keys() ) result.insert(k); return &auth; }, _db.get_global_properties().parameters.max_authority_depth ); wdump((result)); return result; } set
database_api_impl::get_potential_address_signatures( const signed_transaction& trx )const { set
result; trx.get_required_signatures( _db.get_chain_id(), flat_set(), [&]( account_id_type id ) { const auto& auth = id(_db).active; for( const auto& k : auth.get_addresses() ) result.insert(k); return &auth; }, [&]( account_id_type id ) { const auto& auth = id(_db).owner; for( const auto& k : auth.get_addresses() ) result.insert(k); return &auth; }, _db.get_global_properties().parameters.max_authority_depth ); return result; } bool database_api::verify_authority( const signed_transaction& trx )const { return my->verify_authority( trx ); } bool database_api_impl::verify_authority( const signed_transaction& trx )const { trx.verify_authority( _db.get_chain_id(), [&]( account_id_type id ){ return &id(_db).active; }, [&]( account_id_type id ){ return &id(_db).owner; }, _db.get_global_properties().parameters.max_authority_depth ); return true; } bool database_api::verify_account_authority( const string& name_or_id, const flat_set& signers )const { return my->verify_account_authority( name_or_id, signers ); } bool database_api_impl::verify_account_authority( const string& name_or_id, const flat_set& keys )const { FC_ASSERT( name_or_id.size() > 0); const account_object* account = nullptr; if (std::isdigit(name_or_id[0])) account = _db.find(fc::variant(name_or_id, 1).as(1)); else { const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(name_or_id); if (itr != idx.end()) account = &*itr; } FC_ASSERT( account, "no such account" ); /// reuse trx.verify_authority by creating a dummy transfer signed_transaction trx; transfer_operation op; op.from = account->id; trx.operations.emplace_back(op); return verify_authority( trx ); } processed_transaction database_api::validate_transaction( const signed_transaction& trx )const { return my->validate_transaction( trx ); } processed_transaction database_api_impl::validate_transaction( const signed_transaction& trx )const { return _db.validate_transaction(trx); } vector< fc::variant > database_api::get_required_fees( const vector& ops, asset_id_type id )const { return my->get_required_fees( ops, id ); } /** * Container method for mutually recursive functions used to * implement get_required_fees() with potentially nested proposals. */ struct get_required_fees_helper { get_required_fees_helper( const fee_schedule& _current_fee_schedule, const price& _core_exchange_rate, uint32_t _max_recursion ) : current_fee_schedule(_current_fee_schedule), core_exchange_rate(_core_exchange_rate), max_recursion(_max_recursion) {} fc::variant set_op_fees( operation& op ) { if( op.which() == operation::tag::value ) { return set_proposal_create_op_fees( op ); } else { asset fee = current_fee_schedule.set_fee( op, core_exchange_rate ); fc::variant result; fc::to_variant( fee, result, GRAPHENE_MAX_NESTED_OBJECTS ); return result; } } fc::variant set_proposal_create_op_fees( operation& proposal_create_op ) { proposal_create_operation& op = proposal_create_op.get(); std::pair< asset, fc::variants > result; for( op_wrapper& prop_op : op.proposed_ops ) { FC_ASSERT( current_recursion < max_recursion ); ++current_recursion; result.second.push_back( set_op_fees( prop_op.op ) ); --current_recursion; } // we need to do this on the boxed version, which is why we use // two mutually recursive functions instead of a visitor result.first = current_fee_schedule.set_fee( proposal_create_op, core_exchange_rate ); fc::variant vresult; fc::to_variant( result, vresult, GRAPHENE_MAX_NESTED_OBJECTS ); return vresult; } const fee_schedule& current_fee_schedule; const price& core_exchange_rate; uint32_t max_recursion; uint32_t current_recursion = 0; }; vector< fc::variant > database_api_impl::get_required_fees( const vector& ops, asset_id_type id )const { vector< operation > _ops = ops; // // we copy the ops because we need to mutate an operation to reliably // determine its fee, see #435 // vector< fc::variant > result; result.reserve(ops.size()); const asset_object& a = id(_db); get_required_fees_helper helper( _db.current_fee_schedule(), a.options.core_exchange_rate, GET_REQUIRED_FEES_MAX_RECURSION ); for( operation& op : _ops ) { result.push_back( helper.set_op_fees( op ) ); } return result; } ////////////////////////////////////////////////////////////////////// // // // Proposed transactions // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_proposed_transactions( account_id_type id )const { return my->get_proposed_transactions( id ); } /** TODO: add secondary index that will accelerate this process */ vector database_api_impl::get_proposed_transactions( account_id_type id )const { const auto& idx = _db.get_index_type(); vector result; idx.inspect_all_objects( [&](const object& obj){ const proposal_object& p = static_cast(obj); if( p.required_active_approvals.find( id ) != p.required_active_approvals.end() ) result.push_back(p); else if ( p.required_owner_approvals.find( id ) != p.required_owner_approvals.end() ) result.push_back(p); else if ( p.available_active_approvals.find( id ) != p.available_active_approvals.end() ) result.push_back(p); }); return result; } ////////////////////////////////////////////////////////////////////// // // // Blinded balances // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_blinded_balances( const flat_set& commitments )const { return my->get_blinded_balances( commitments ); } vector database_api_impl::get_blinded_balances( const flat_set& commitments )const { vector result; result.reserve(commitments.size()); const auto& bal_idx = _db.get_index_type(); const auto& by_commitment_idx = bal_idx.indices().get(); for( const auto& c : commitments ) { auto itr = by_commitment_idx.find( c ); if( itr != by_commitment_idx.end() ) result.push_back( *itr ); } return result; } ////////////////////////////////////////////////////////////////////// // // // Licenses: // // // ////////////////////////////////////////////////////////////////////// optional database_api::get_license_type(license_type_id_type license_id) const { return my->get_license_type(license_id); } optional database_api_impl::get_license_type(license_type_id_type license_id) const { return _dal.get_license_type(license_id); } vector database_api_impl::get_license_types() const { const auto& idx = _db.get_index_type().indices().get(); return vector(idx.begin(), idx.end()); } vector database_api::get_license_types() const { return my->get_license_types(); } vector> database_api::get_license_type_names_ids() const { return my->get_license_type_names_ids(); } vector> database_api_impl::get_license_type_names_ids() const { return _dal.get_license_type_names_ids(); } vector database_api::get_license_type_names_ids_grouped_by_kind() const { return my->get_license_type_names_ids_grouped_by_kind(); } vector database_api_impl::get_license_type_names_ids_grouped_by_kind() const { return _dal.get_license_type_names_ids_grouped_by_kind(); } vector database_api::get_license_objects_grouped_by_kind() const { return my->get_license_objects_grouped_by_kind(); } vector database_api_impl::get_license_objects_grouped_by_kind() const { return _dal.get_license_objects_grouped_by_kind(); } vector> database_api_impl::get_license_types(const vector& license_type_ids) const { vector> result; result.reserve(license_type_ids.size()); std::transform(license_type_ids.begin(), license_type_ids.end(), std::back_inserter(result), [this](license_type_id_type id) -> optional { if(auto o = _db.find(id)) { subscribe_to_item( id ); return *o; } return {}; }); return result; } vector database_api::list_license_types_by_name( const string& lower_bound_name, uint32_t limit ) const { FC_ASSERT( limit <= 100 ); return my->list_bounded_objects_indexed_by_string( lower_bound_name, limit ); } vector database_api::list_license_types_by_amount( const uint32_t lower_bound_amount, uint32_t limit ) const { FC_ASSERT( limit <= 100 ); return my->list_bounded_objects_indexed_by_num( lower_bound_amount, limit ); } vector> database_api::lookup_license_type_names(const vector& names_or_ids)const { return my->lookup_string_or_id( names_or_ids ); } vector> database_api::get_license_information(const vector& account_ids) const { return my->get_license_information(account_ids); } vector> database_api_impl::get_license_information(const vector& account_ids) const { vector> result; result.reserve(account_ids.size()); std::transform(account_ids.begin(), account_ids.end(), std::back_inserter(result), [this](account_id_type id) -> optional { auto acc = _db.find(id); if( acc && acc->license_information.valid() ) return {(*acc->license_information)(_db)}; return {}; }); return result; } vector database_api::get_upgrade_events() const { return my->get_upgrade_events(); } vector database_api_impl::get_upgrade_events() const { const auto& idx = _db.get_index_type().indices().get(); return vector(idx.begin(), idx.end()); } ////////////////////////////////////////////////////////////////////// // // // Cycles: // // // ////////////////////////////////////////////////////////////////////// acc_id_share_t_res database_api::get_free_cycle_balance(const account_id_type id)const { return my->get_free_cycle_balance(id); } acc_id_share_t_res database_api_impl::get_free_cycle_balance(const account_id_type id) const { return _dal.get_free_cycle_balance(id); } acc_id_vec_cycle_agreement_res database_api::get_all_cycle_balances(account_id_type id) const { return my->get_all_cycle_balances(id); } acc_id_vec_cycle_agreement_res database_api_impl::get_all_cycle_balances(account_id_type id) const { return _dal.get_all_cycle_balances(id); } acc_id_share_t_res database_api::get_dascoin_balance(account_id_type id) const { return my->get_dascoin_balance(id); } acc_id_share_t_res database_api_impl::get_dascoin_balance(account_id_type id) const { return _dal.get_dascoin_balance(id); } vector database_api::get_free_cycle_balances_for_accounts(vector ids) const { return my->get_free_cycle_balances_for_accounts(ids); } vector database_api_impl::get_free_cycle_balances_for_accounts(vector ids) const { return _dal.get_free_cycle_balances_for_accounts(ids); } vector database_api::get_all_cycle_balances_for_accounts(vector ids) const { return my->get_all_cycle_balances_for_accounts(ids); } vector database_api_impl::get_all_cycle_balances_for_accounts(vector ids) const { return _dal.get_all_cycle_balances_for_accounts(ids); } vector database_api::get_dascoin_balances_for_accounts(vector ids) const { return my->get_dascoin_balances_for_accounts(ids); } vector database_api_impl::get_dascoin_balances_for_accounts(vector ids) const { return _dal.get_dascoin_balances_for_accounts(ids); } vector database_api::get_reward_queue() const { return my->get_reward_queue(); } vector database_api_impl::get_reward_queue() const { return _dal.get_reward_queue(); } vector database_api::get_reward_queue_by_page(uint32_t from, uint32_t amount) const { return my->get_reward_queue_by_page(from, amount); } vector database_api_impl::get_reward_queue_by_page(uint32_t from, uint32_t amount) const { return _dal.get_reward_queue_by_page(from, amount); } uint32_t database_api::get_reward_queue_size() const { return my->get_reward_queue_size(); } uint32_t database_api_impl::get_reward_queue_size() const { return _dal.get_reward_queue_size(); } acc_id_queue_subs_w_pos_res database_api::get_queue_submissions_with_pos(account_id_type account_id) const { return my->get_queue_submissions_with_pos(account_id); } acc_id_queue_subs_w_pos_res database_api_impl::get_queue_submissions_with_pos(account_id_type account_id) const { return _dal.get_queue_submissions_with_pos(account_id); } vector database_api::get_queue_submissions_with_pos_for_accounts(vector ids) const { return my->get_queue_submissions_with_pos_for_accounts(ids); } vector database_api_impl::get_queue_submissions_with_pos_for_accounts(vector ids) const { return _dal.get_queue_submissions_with_pos_for_accounts(ids); } ////////////////////////////////////////////////////////////////////// // // // REQUESTS: // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_all_webasset_issue_requests() const { return my->list_all_objects(); } vector database_api::get_all_wire_out_holders() const { return my->list_all_objects(); } vector database_api::get_all_wire_out_with_fee_holders() const { return my->list_all_objects(); } ////////////////////////////////////////////////////////////////////// // // // VAULTS: // // // ////////////////////////////////////////////////////////////////////// optional database_api::get_vault_info(account_id_type vault_id) const { return my->get_vault_info(vault_id); } optional database_api_impl::get_vault_info(account_id_type vault_id) const { return _dal.get_vault_info(vault_id); } vector database_api::get_vaults_info(vector vault_ids) const { return my->get_vaults_info(vault_ids); } vector database_api_impl::get_vaults_info(vector vault_ids) const { return _dal.get_vaults_info(vault_ids); } optional database_api::calculate_cycle_price(share_type cycle_amount, asset_id_type asset_id) const { return my->calculate_cycle_price(cycle_amount, asset_id); } optional database_api_impl::calculate_cycle_price(share_type cycle_amount, asset_id_type asset_id) const { // For now we can only buy cycles with dascoin if (asset_id != _db.get_dascoin_asset_id()) return {}; const dynamic_global_property_object dgpo = get_dynamic_global_properties(); const auto& asset_obj = asset_id(_db); double price = static_cast(cycle_amount.value) / (static_cast(dgpo.frequency.value) / DASCOIN_FREQUENCY_PRECISION); price = std::ceil(price * std::pow(10, asset_obj.precision)) / std::pow(10, asset_obj.precision); return cycle_price{cycle_amount, asset(price * std::pow(10, asset_obj.precision), asset_obj.id), dgpo.frequency}; } vector database_api::get_top_dasc_holders() const { return my->get_top_dasc_holders(); } vector database_api_impl::get_top_dasc_holders() const { static const uint32_t max_holders = 100; vector tmp; const auto& dasc_id = _db.get_dascoin_asset_id(); const auto& idx = _db.get_index_type().indices().get(); for ( auto it = idx.cbegin(); it != idx.cend(); ++it ) { const auto& account = *it; dasc_holder holder; holder.holder = account.id; if (account.kind == account_kind::wallet) { holder.vaults = account.vault.size(); const auto& balance_obj = _db.get_balance_object(account.id, dasc_id); holder.amount = balance_obj.balance + balance_obj.reserved; std::for_each(account.vault.begin(), account.vault.end(), [this, &holder, &dasc_id](const account_id_type& vault_id) { const auto& balance_obj = _db.get_balance_object(vault_id, dasc_id); holder.amount += balance_obj.balance; }); tmp.emplace_back(holder); } else if (account.kind == account_kind::custodian || (account.kind == account_kind::vault && account.parents.empty())) { holder.vaults = 0; const auto& balance_obj = _db.get_balance_object(account.id, dasc_id); holder.amount = balance_obj.balance; tmp.emplace_back(holder); } } std::partial_sort(tmp.begin(), tmp.begin() + max_holders, tmp.end(), [](dasc_holder& a, dasc_holder& b) { return a.amount > b.amount; }); vector ret(tmp.begin(), tmp.begin() + max_holders); return ret; } optional database_api::get_withdrawal_limit(account_id_type account, asset_id_type asset_id) const { return my->get_withdrawal_limit(account, asset_id); } optional database_api_impl::get_withdrawal_limit(account_id_type account, asset_id_type asset_id) const { // Do we have a price for this asset? auto p = _db.get_price_in_web_eur(asset_id); if (!p.valid()) return {}; const auto& global_parameters_ext = _db.get_global_properties().parameters.extensions; auto withdrawal_limit_it = std::find_if(global_parameters_ext.begin(), global_parameters_ext.end(), [](const chain_parameters::chain_parameters_extension& ext){ return ext.which() == chain_parameters::chain_parameters_extension::tag< withdrawal_limit_type >::value; }); // Is withdrawal limit set? if (withdrawal_limit_it == global_parameters_ext.end()) return {}; auto& limit = (*withdrawal_limit_it).get(); // Is asset limited? if (limit.limited_assets.find(asset_id) == limit.limited_assets.end()) return {}; const auto& idx = _db.get_index_type().indices().get(); auto itr = idx.find(account); if (itr == idx.end() || itr->kind != account_kind::wallet) return {}; const auto& idx2 = _db.get_index_type().indices().get(); auto itr2 = idx2.find(account); if (itr2 == idx2.end()) return withdrawal_limit{limit.limit * *p, asset{0, asset_id}, _db.head_block_time(), {}}; bool reset_limit = (_db.head_block_time() - itr2->beginning_of_withdrawal_interval > fc::microseconds(static_cast(limit.duration) * 1000000)); asset spent; fc::time_point_sec when; if (reset_limit) { spent = asset{0, asset_id}; when = _db.head_block_time(); } else { spent = itr2->spent * *p; when = itr2->beginning_of_withdrawal_interval; } return withdrawal_limit{itr2->limit * *p, spent, when, itr2->last_withdrawal}; } ////////////////////////////////////////////////////////////////////// // // // DASPAY: // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_payment_service_providers() const { return my->list_all_objects(); } optional> database_api::get_daspay_authority_for_account(account_id_type account) const { return my->get_daspay_authority_for_account(account); } optional> database_api_impl::get_daspay_authority_for_account(account_id_type account) const { const auto& idx = _db.get_index_type().indices().get(); auto it = idx.lower_bound(account); const auto& it_end = idx.upper_bound(account); if (it == idx.end()) { return {}; } vector ret; std::transform(it, it_end, std::back_inserter(ret), [](const daspay_authority_object& dao) -> daspay_authority { return daspay_authority{dao.payment_provider, dao.daspay_public_key, dao.memo}; }); return ret; } vector database_api::get_delayed_operations_for_account(account_id_type account) const { return my->get_delayed_operations_for_account(account); } vector database_api_impl::get_delayed_operations_for_account(account_id_type account) const { const auto& delayed_operations = _db.get_index_type().indices().get(); vector result; for (const delayed_operation_object& operation: delayed_operations) { if (operation.account == account) result.emplace_back(operation); } return result; } ////////////////////////////////////////////////////////////////////// // // // DAS33: // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_das33_pledges(das33_pledge_holder_id_type from, uint32_t limit, optional phase) const { return my->get_das33_pledges(from, limit, phase); } das33_pledges_by_account_result database_api::get_das33_pledges_by_account(account_id_type account) const { return my->get_das33_pledges_by_account(account); } vector database_api::get_das33_pledges_by_project(das33_project_id_type project, das33_pledge_holder_id_type from, uint32_t limit, optional phase) const { return my->get_das33_pledges_by_project(project, from, limit, phase); } vector database_api_impl::get_das33_pledges(das33_pledge_holder_id_type from, uint32_t limit, optional phase) const { FC_ASSERT( limit <= 100 ); vector result; auto default_pledge_id = das33_pledge_holder_id_type(); const auto& pledges = _db.get_index_type().indices().get(); for( auto itr = pledges.lower_bound(from); limit && itr != pledges.end(); ++itr ) { if (itr->id != default_pledge_id) { if (phase && *phase != itr->phase_number) continue; result.emplace_back(*itr); limit--; } } return result; } das33_pledges_by_account_result database_api_impl::get_das33_pledges_by_account(account_id_type account) const { vector pledges; map total; map last_round; const auto& idx = _db.get_index_type().indices().get().equal_range(account); std::copy(idx.first, idx.second, std::back_inserter(pledges)); map last_round_number; for (u_int i = 0; i < pledges.size(); i++) { das33_project_id_type project_id = pledges[i].project_id; share_type round_number = pledges[i].phase_number; if (total.find(project_id) != total.end()) { total[project_id] = total[project_id] + pledges[i].base_expected.amount + pledges[i].bonus_expected.amount; } else { total[project_id] = pledges[i].base_expected.amount + pledges[i].bonus_expected.amount; } if (last_round_number.find(project_id) != last_round_number.end()) { if (last_round_number[project_id] < round_number) last_round_number[project_id] = round_number; } else { last_round_number[project_id] = round_number; } } for (u_int j = 0; j < pledges.size(); j++) { das33_project_id_type project_id = pledges[j].project_id; share_type round_number = pledges[j].phase_number; if (round_number == last_round_number[project_id]) { if (last_round.find(project_id) != last_round.end()) last_round[project_id] = last_round[project_id] + pledges[j].base_expected.amount; else last_round[project_id] = pledges[j].base_expected.amount; } } das33_pledges_by_account_result result; result.pledges = pledges; result.total_expected = total; result.base_expected_in_last_round = last_round; return result; } vector database_api_impl::get_das33_pledges_by_project(das33_project_id_type project, das33_pledge_holder_id_type from, uint32_t limit, optional phase) const { FC_ASSERT( limit <= 100 ); vector result; auto default_pledge_id = das33_pledge_holder_id_type(); const auto& pledges = _db.get_index_type().indices().get(); for( auto itr = pledges.lower_bound(make_tuple(project, from)); limit && itr->project_id == project && itr != pledges.end(); ++itr ) { if (itr->id != default_pledge_id) { if (phase && *phase != itr->phase_number) continue; result.emplace_back(*itr); limit--; } } return result; } vector database_api::get_das33_projects(const string& lower_bound_name, uint32_t limit) const { return my->get_das33_projects(lower_bound_name, limit); } vector database_api_impl::get_das33_projects(const string& lower_bound_name, uint32_t limit) const { FC_ASSERT( limit <= 100 ); const auto& projects_by_name = _db.get_index_type().indices().get(); vector result; auto default_project_id = das33_project_id_type(); for( auto itr = projects_by_name.lower_bound(lower_bound_name); limit-- && itr != projects_by_name.end(); ++itr ) { if (itr->id != default_project_id) result.emplace_back(*itr); } return result; } vector database_api::get_amount_of_assets_pledged_to_project(das33_project_id_type project) const { return my->get_amount_of_assets_pledged_to_project(project); } vector database_api_impl::get_amount_of_assets_pledged_to_project(das33_project_id_type project) const { vector result; map index_map; auto default_pledge_id = das33_pledge_holder_id_type(); const auto& pledges = _db.get_index_type().indices().get(); for( auto itr = pledges.lower_bound(project); itr != pledges.upper_bound(project); ++itr ) { if (itr->id != default_pledge_id) { if (index_map.find(itr->pledged.asset_id) != index_map.end()) { result[index_map[itr->pledged.asset_id]] += itr->pledged; } else { index_map[itr->pledged.asset_id] = result.size(); result.emplace_back(itr->pledged); } } } return result; } vector database_api::get_amount_of_assets_pledged_to_project_in_phase(das33_project_id_type project, uint32_t phase) const { return my->get_amount_of_assets_pledged_to_project_in_phase(project, phase); } vector database_api_impl::get_amount_of_assets_pledged_to_project_in_phase(das33_project_id_type project, uint32_t phase) const { vector result; map index_map; // Get project const auto& idx = _db.get_index_type().indices().get(); auto project_iterator = idx.find(project); auto project_object = &(*project_iterator); result.emplace_back(asset{0, project_object->token_id}); result.emplace_back(asset{0, project_object->token_id}); index_map[project_object->token_id] = 0; auto default_pledge_id = das33_pledge_holder_id_type(); const auto& pledges = _db.get_index_type().indices().get(); for( auto itr = pledges.lower_bound(project); itr != pledges.upper_bound(project); ++itr ) { if (itr->id != default_pledge_id && itr->phase_number == phase) { if (index_map.find(itr->pledged.asset_id) != index_map.end()) { result[index_map[itr->pledged.asset_id]] += itr->pledged; } else { index_map[itr->pledged.asset_id] = result.size(); result.emplace_back(itr->pledged); } result[index_map[project_object->token_id]] += (itr->base_expected + itr->bonus_expected); result[1] += itr->base_expected;// * project_object->token_price; } } result[1] = result[1] * project_object->token_price; return result; } das33_project_tokens_amount database_api::get_amount_of_project_tokens_received_for_asset(das33_project_id_type project, asset to_pledge) const { return my->get_amount_of_project_tokens_received_for_asset(project, to_pledge); } das33_project_tokens_amount database_api_impl::get_amount_of_project_tokens_received_for_asset(das33_project_id_type project, asset to_pledge) const { const auto& project_obj = project(_db); share_type precision = graphene::chain::precision_modifier(to_pledge.asset_id(_db), _db.get_web_asset_id()(_db)); const auto& asset_price = graphene::chain::calculate_price(to_pledge.asset_id, project, _db); FC_ASSERT(asset_price.valid(), "There is no proper price for ${asset}", ("asset", to_pledge.asset_id)); asset base_asset = graphene::chain::asset_price_multiply(to_pledge, precision.value, *asset_price, project_obj.token_price); asset bonus; auto discount_iterator = project_obj.discounts.find(to_pledge.asset_id); if ( discount_iterator != project_obj.discounts.end()) { bonus.amount = (base_asset.amount * 100 / discount_iterator->second) - base_asset.amount; bonus.asset_id = base_asset.asset_id; } das33_project_tokens_amount result = das33_project_tokens_amount(to_pledge, base_asset, bonus); return result; } das33_project_tokens_amount database_api::get_amount_of_asset_needed_for_project_token(das33_project_id_type project, asset_id_type asset_id, asset tokens) const { return my->get_amount_of_asset_needed_for_project_token(project, asset_id, tokens); } das33_project_tokens_amount database_api_impl::get_amount_of_asset_needed_for_project_token(das33_project_id_type project, asset_id_type asset_id, asset tokens) const { const auto& project_obj = project(_db); share_type precision = graphene::chain::precision_modifier(tokens.asset_id(_db), _db.get_web_asset_id()(_db)); const auto& asset_price = graphene::chain::calculate_price(asset_id, project, _db); FC_ASSERT(asset_price.valid(), "There is no proper price for ${asset}", ("asset", asset_id)); asset to_pledge = graphene::chain::asset_price_multiply(tokens, precision.value, project_obj.token_price, *asset_price); asset bonus; auto discount_iterator = project_obj.discounts.find(asset_id); if ( discount_iterator != project_obj.discounts.end()) { bonus.amount = (tokens.amount * 100 / discount_iterator->second) - tokens.amount; bonus.asset_id = tokens.asset_id; } das33_project_tokens_amount result = das33_project_tokens_amount(to_pledge, tokens, bonus); return result; } ////////////////////////////////////////////////////////////////////// // // // Prices: // // // ////////////////////////////////////////////////////////////////////// vector database_api::get_last_prices() const { return my->get_last_prices(); } vector database_api_impl::get_last_prices() const { vector result; const auto& idx = _db.get_index_type().indices().get(); for (auto itr = idx.begin(); itr != idx.end(); itr++) result.emplace_back(*itr); return result; } vector database_api::get_external_prices() const { return my->get_external_prices(); } vector database_api_impl::get_external_prices() const { vector result; const auto& idx = _db.get_index_type().indices().get(); for (auto itr = idx.begin(); itr != idx.end(); itr++) result.emplace_back(*itr); return result; } ////////////////////////////////////////////////////////////////////// // // // Private methods // // // ////////////////////////////////////////////////////////////////////// void database_api_impl::broadcast_updates( const vector& updates ) { if( updates.size() && _subscribe_callback ) { auto capture_this = shared_from_this(); fc::async([capture_this,updates](){ if(capture_this->_subscribe_callback) capture_this->_subscribe_callback( fc::variant(updates) ); }); } } void database_api_impl::broadcast_market_updates( const market_queue_type& queue) { if( queue.size() ) { auto capture_this = shared_from_this(); fc::async([capture_this, this, queue]() { for (const auto &item : queue) { auto sub = _market_subscriptions.find(item.first); if (sub != _market_subscriptions.end()) sub->second(fc::variant(item.second)); } }); } } void database_api_impl::on_objects_removed( const vector& ids, const vector& objs, const flat_set& impacted_accounts ) { handle_object_changed(_notify_remove_create, false, ids, impacted_accounts, [objs](object_id_type id) -> const object* { auto it = std::find_if(objs.begin(), objs.end(), [id](const object* o) {return o != nullptr && o->id == id;}); if (it != objs.end()) { return *it; } return nullptr; }); } void database_api_impl::on_objects_new(const vector& ids, const flat_set& impacted_accounts) { handle_object_changed(_notify_remove_create, true, ids, impacted_accounts, std::bind(&object_database::find_object, &_db, std::placeholders::_1) ); } void database_api_impl::on_objects_changed(const vector& ids, const flat_set& impacted_accounts) { handle_object_changed(false, true, ids, impacted_accounts, std::bind(&object_database::find_object, &_db, std::placeholders::_1) ); } void database_api_impl::handle_object_changed(bool force_notify, bool full_object, const vector& ids, const flat_set& impacted_accounts, std::function find_object) { if( _subscribe_callback ) { vector updates; for(auto id : ids) { const object* obj = nullptr; if( force_notify || is_subscribed_to_item(id) || is_impacted_account(impacted_accounts) ) { if ( full_object ) { obj = find_object(id); if( obj ) { updates.emplace_back( obj->to_variant() ); } } else { updates.emplace_back( fc::variant( id, 1 ) ); } } } if( updates.size() ) broadcast_updates(updates); } if( _market_subscriptions.size() ) { market_queue_type broadcast_queue; for(auto id : ids) { if( id.is() ) { enqueue_if_subscribed_to_market( find_object(id), broadcast_queue, full_object ); } else if( id.is() ) { enqueue_if_subscribed_to_market( find_object(id), broadcast_queue, full_object ); } } if( broadcast_queue.size() ) broadcast_market_updates(broadcast_queue); } } /** note: this method cannot yield because it is called in the middle of * apply a block. */ void database_api_impl::on_applied_block() { if (_block_applied_callback) { auto capture_this = shared_from_this(); block_id_type block_id = _db.head_block_id(); fc::async([this,capture_this,block_id](){ _block_applied_callback(fc::variant(block_id, 1)); }); } if(_market_subscriptions.size() == 0) return; const auto& ops = _db.get_applied_operations(); map< std::pair, vector> > subscribed_markets_ops; for(const optional< operation_history_object >& o_op : ops) { if( !o_op.valid() ) continue; const operation_history_object& op = *o_op; std::pair market; switch(op.op.which()) { /* This is sent via the object_changed callback case operation::tag::value: market = op.op.get().get_market(); break; */ case operation::tag::value: market = op.op.get().get_market(); break; /* case operation::tag::value: */ default: break; } if(_market_subscriptions.count(market)) subscribed_markets_ops[market].push_back(std::make_pair(op.op, op.result)); } /// we need to ensure the database_api is not deleted for the life of the async operation auto capture_this = shared_from_this(); fc::async([this,capture_this,subscribed_markets_ops](){ for(auto item : subscribed_markets_ops) { auto itr = _market_subscriptions.find(item.first); if(itr != _market_subscriptions.end()) itr->second(fc::variant(item.second, GRAPHENE_NET_MAX_NESTED_OBJECTS)); } }); } } } // graphene::app namespace Platform::Singletons::Tests { TEST_CLASS(SingletonTests) { public: TEST_METHOD(TwoValuesAreTheSameTest) { auto value1 = Singleton.Get([&]()-> auto { return 1; }); auto value2 = Singleton.Get([&]()-> auto { return 1; }); Assert::AreEqual(value1, value2); } }; } 1-10 //========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "ASN1OctetString.h" #include "CASN1OctetString.h" #include "core/CArrayOf.h" #include "core/CByte.h" #include "utility/Arrays.h" using Elastos::Core::IArrayOf; using Elastos::Core::CArrayOf; using Elastos::Core::IByte; using Elastos::Core::EIID_IByte; using Elastos::Core::CByte; using Elastos::Utility::Arrays; namespace Org { namespace Apache { namespace Harmony { namespace Security { namespace Asn1 { INIT_PROI_3 const AutoPtr ASN1OctetString::ASN1 = InitASN1(); CAR_INTERFACE_IMPL(ASN1OctetString, ASN1StringType, IASN1OctetString) AutoPtr ASN1OctetString::InitASN1() { AutoPtr asn1Obj; CASN1OctetString::New((IASN1OctetString**)&asn1Obj); return asn1Obj; } ECode ASN1OctetString::constructor() { return ASN1StringType::constructor(IASN1Constants::TAG_OCTETSTRING); } ECode ASN1OctetString::GetInstance( /* [out] */ IASN1OctetString** instance) { VALIDATE_NOT_NULL(instance) *instance = ASN1; REFCOUNT_ADD(*instance) return NOERROR; } ECode ASN1OctetString::Decode( /* [in] */ IBerInputStream* bis, /* [out] */ IInterface** object) { VALIDATE_NOT_NULL(object); *object = NULL; FAIL_RETURN(bis->ReadOctetString()); Boolean isVerify; if (bis->GetVerify(&isVerify), isVerify) { return NOERROR; } return GetDecodedObject(bis, object); } ECode ASN1OctetString::GetDecodedObject( /* [in] */ IBerInputStream* bis, /* [out] */ IInterface** object) { AutoPtr< ArrayOf > buffer; bis->GetBuffer((ArrayOf**)&buffer); Int32 offset; bis->GetContentOffset(&offset); Int32 length; bis->GetLength(&length); AutoPtr< ArrayOf > result; Arrays::CopyOfRange(buffer, offset, offset + length, (ArrayOf**)&result); Int32 size = result->GetLength(); AutoPtr arrays; CArrayOf::New(EIID_IByte, size, (IArrayOf**)&arrays); for (Int32 i = 0; i < size; i++) { AutoPtr byteObj; CByte::New((*result)[i], (IByte**)&byteObj); arrays->Set(i, byteObj); } *object = arrays; REFCOUNT_ADD(*object); return NOERROR; } ECode ASN1OctetString::EncodeContent( /* [in] */ IBerOutputStream* bos) { return bos->EncodeOctetString(); } ECode ASN1OctetString::SetEncodingContent( /* [in] */ IBerOutputStream* bos) { AutoPtr content; bos->GetContent((IInterface**)&content); Int32 length; IArrayOf::Probe(content)->GetLength(&length); return bos->SetLength(length); } } // namespace Asn1 } // namespace Security } // namespace Harmony } // namespace Apache } // namespace Org nalinbhardwaj/olympiad #include #include #include #include #include #include #include using namespace std; typedef long long int lli; typedef long double dbl; const lli maxn = lli(1e5)+5; lli A[maxn], B[maxn]; int main(void) { ifstream fin("tallbarn.in"); ofstream fout("tallbarn.out"); lli n, k; set> S; fin >> n >> k; for(lli i = 0;i < n;i++) fin >> A[i]; if(n == 1) { fout << round(A[0]/k) << "\n"; return 0; } for(lli i = 0;i < n;i++, k--) { B[i] = 1; S.insert({dbl(A[i])/(B[i]*B[i]+B[i]), i}); } while(k) { pair top = *S.rbegin(); S.erase(top); pair topp = *S.rbegin(); while(top.first >= topp.first) { //cout << top.first << " " << topp.first << "\n"; if(!k) break; B[top.second]++; k--; top = {dbl(A[top.second])/(B[top.second]*B[top.second]+B[top.second]), top.second}; } S.insert(top); } dbl res = 0.00; for(lli i = 0;i < n;i++) res += dbl(A[i])/B[i]; fout << lli(round(res)) << "\n"; }Fernthedev/BeatSaber-Quest-Codegen // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Net.Http.Headers.HttpHeaderKind #include "System/Net/Http/Headers/HttpHeaderKind.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Net::Http::Headers namespace System::Net::Http::Headers { // Forward declaring type: TryParseDelegate`1 template class TryParseDelegate_1; // Forward declaring type: TryParseListDelegate`1 template class TryParseListDelegate_1; // Forward declaring type: HttpHeaders class HttpHeaders; } // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2 template class Func_2; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1 template class List_1; } // Completed forward declares // Type namespace: System.Net.Http.Headers namespace System::Net::Http::Headers { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Net.Http.Headers.HeaderInfo // [TokenAttribute] Offset: FFFFFFFF class HeaderInfo : public ::Il2CppObject { public: // Nested type: System::Net::Http::Headers::HeaderInfo::HeaderTypeInfo_2 template class HeaderTypeInfo_2; // Nested type: System::Net::Http::Headers::HeaderInfo::CollectionHeaderTypeInfo_2 template class CollectionHeaderTypeInfo_2; // public System.Boolean AllowsMany // Size: 0x1 // Offset: 0x10 bool AllowsMany; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: AllowsMany and: HeaderKind char __padding0[0x3] = {}; // public readonly System.Net.Http.Headers.HttpHeaderKind HeaderKind // Size: 0x4 // Offset: 0x14 System::Net::Http::Headers::HttpHeaderKind HeaderKind; // Field size check static_assert(sizeof(System::Net::Http::Headers::HttpHeaderKind) == 0x4); // public readonly System.String Name // Size: 0x8 // Offset: 0x18 ::Il2CppString* Name; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Func`2 k__BackingField // Size: 0x8 // Offset: 0x20 System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString; // Field size check static_assert(sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*) == 0x8); // Creating value type constructor for type: HeaderInfo HeaderInfo(bool AllowsMany_ = {}, System::Net::Http::Headers::HttpHeaderKind HeaderKind_ = {}, ::Il2CppString* Name_ = {}, System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString_ = {}) noexcept : AllowsMany{AllowsMany_}, HeaderKind{HeaderKind_}, Name{Name_}, CustomToString{CustomToString_} {} // Get instance field reference: public System.Boolean AllowsMany bool& dyn_AllowsMany(); // Get instance field reference: public readonly System.Net.Http.Headers.HttpHeaderKind HeaderKind System::Net::Http::Headers::HttpHeaderKind& dyn_HeaderKind(); // Get instance field reference: public readonly System.String Name ::Il2CppString*& dyn_Name(); // Get instance field reference: private System.Func`2 k__BackingField System::Func_2<::Il2CppObject*, ::Il2CppString*>*& dyn_$CustomToString$k__BackingField(); // public System.Func`2 get_CustomToString() // Offset: 0x15AA4A0 System::Func_2<::Il2CppObject*, ::Il2CppString*>* get_CustomToString(); // private System.Void set_CustomToString(System.Func`2 value) // Offset: 0x15AA4A8 void set_CustomToString(System::Func_2<::Il2CppObject*, ::Il2CppString*>* value); // public System.String get_Separator() // Offset: 0x15AA4B0 ::Il2CppString* get_Separator(); // protected System.Void .ctor(System.String name, System.Net.Http.Headers.HttpHeaderKind headerKind) // Offset: 0x15AA454 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HeaderInfo* New_ctor(::Il2CppString* name, System::Net::Http::Headers::HttpHeaderKind headerKind) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HeaderInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New (name, headerKind))); } // static public System.Net.Http.Headers.HeaderInfo CreateSingle(System.String name, System.Net.Http.Headers.TryParseDelegate`1 parser, System.Net.Http.Headers.HttpHeaderKind headerKind, System.Func`2 toString) // Offset: 0xFFFFFFFF template static System::Net::Http::Headers::HeaderInfo* CreateSingle(::Il2CppString* name, System::Net::Http::Headers::TryParseDelegate_1* parser, System::Net::Http::Headers::HttpHeaderKind headerKind, System::Func_2<::Il2CppObject*, ::Il2CppString*>* toString) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HeaderInfo::CreateSingle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Net.Http.Headers", "HeaderInfo", "CreateSingle", std::vector{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class::get()}, ::std::vector{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(parser), ::il2cpp_utils::ExtractType(headerKind), ::il2cpp_utils::ExtractType(toString)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class::get()})); return ::il2cpp_utils::RunMethodThrow(static_cast(nullptr), ___generic__method, name, parser, headerKind, toString); } // static public System.Net.Http.Headers.HeaderInfo CreateMulti(System.String name, System.Net.Http.Headers.TryParseListDelegate`1 elementParser, System.Net.Http.Headers.HttpHeaderKind headerKind, System.Int32 minimalCount, System.String separator) // Offset: 0xFFFFFFFF template static System::Net::Http::Headers::HeaderInfo* CreateMulti(::Il2CppString* name, System::Net::Http::Headers::TryParseListDelegate_1* elementParser, System::Net::Http::Headers::HttpHeaderKind headerKind, int minimalCount, ::Il2CppString* separator) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HeaderInfo::CreateMulti"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Net.Http.Headers", "HeaderInfo", "CreateMulti", std::vector{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class::get()}, ::std::vector{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(elementParser), ::il2cpp_utils::ExtractType(headerKind), ::il2cpp_utils::ExtractType(minimalCount), ::il2cpp_utils::ExtractType(separator)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class::get()})); return ::il2cpp_utils::RunMethodThrow(static_cast(nullptr), ___generic__method, name, elementParser, headerKind, minimalCount, separator); } // public System.Object CreateCollection(System.Net.Http.Headers.HttpHeaders headers) // Offset: 0x15AA490 ::Il2CppObject* CreateCollection(System::Net::Http::Headers::HttpHeaders* headers); // public System.Void AddToCollection(System.Object collection, System.Object value) // Offset: 0xFFFFFFFF void AddToCollection(::Il2CppObject* collection, ::Il2CppObject* value); // protected System.Object CreateCollection(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HeaderInfo headerInfo) // Offset: 0xFFFFFFFF ::Il2CppObject* CreateCollection(System::Net::Http::Headers::HttpHeaders* headers, System::Net::Http::Headers::HeaderInfo* headerInfo); // public System.Collections.Generic.List`1 ToStringCollection(System.Object collection) // Offset: 0xFFFFFFFF System::Collections::Generic::List_1<::Il2CppString*>* ToStringCollection(::Il2CppObject* collection); // public System.Boolean TryParse(System.String value, out System.Object result) // Offset: 0xFFFFFFFF bool TryParse(::Il2CppString* value, ByRef<::Il2CppObject*> result); }; // System.Net.Http.Headers.HeaderInfo #pragma pack(pop) static check_size*)> __System_Net_Http_Headers_HeaderInfoSizeCheck; static_assert(sizeof(HeaderInfo) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(System::Net::Http::Headers::HeaderInfo*, "System.Net.Http.Headers", "HeaderInfo"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::get_CustomToString // Il2CppName: get_CustomToString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter* (System::Net::Http::Headers::HeaderInfo::*)()>(&System::Net::Http::Headers::HeaderInfo::get_CustomToString)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "get_CustomToString", std::vector(), ::std::vector{}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::set_CustomToString // Il2CppName: set_CustomToString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter*)>(&System::Net::Http::Headers::HeaderInfo::set_CustomToString)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Func`2"), ::std::vector{::il2cpp_utils::GetClassFromName("System", "Object"), ::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "set_CustomToString", std::vector(), ::std::vector{value}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::get_Separator // Il2CppName: get_Separator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&System::Net::Http::Headers::HeaderInfo::get_Separator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "get_Separator", std::vector(), ::std::vector{}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::CreateSingle // Il2CppName: CreateSingle // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::CreateMulti // Il2CppName: CreateMulti // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::CreateCollection // Il2CppName: CreateCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&System::Net::Http::Headers::HeaderInfo::CreateCollection)> { static const MethodInfo* get() { static auto* headers = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "HttpHeaders")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "CreateCollection", std::vector(), ::std::vector{headers}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::AddToCollection // Il2CppName: AddToCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&System::Net::Http::Headers::HeaderInfo::AddToCollection)> { static const MethodInfo* get() { static auto* collection = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "AddToCollection", std::vector(), ::std::vector{collection, value}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::CreateCollection // Il2CppName: CreateCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&System::Net::Http::Headers::HeaderInfo::CreateCollection)> { static const MethodInfo* get() { static auto* headers = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "HttpHeaders")->byval_arg; static auto* headerInfo = &::il2cpp_utils::GetClassFromName("System.Net.Http.Headers", "HeaderInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "CreateCollection", std::vector(), ::std::vector{headers, headerInfo}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::ToStringCollection // Il2CppName: ToStringCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter* (System::Net::Http::Headers::HeaderInfo::*)(::Il2CppObject*)>(&System::Net::Http::Headers::HeaderInfo::ToStringCollection)> { static const MethodInfo* get() { static auto* collection = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "ToStringCollection", std::vector(), ::std::vector{collection}); } }; // Writing MetadataGetter for method: System::Net::Http::Headers::HeaderInfo::TryParse // Il2CppName: TryParse template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&System::Net::Http::Headers::HeaderInfo::TryParse)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "Object")->this_arg; return ::il2cpp_utils::FindMethod(classof(System::Net::Http::Headers::HeaderInfo*), "TryParse", std::vector(), ::std::vector{value, result}); } }; #include "EntityResource.h" #include namespace df3d { static void PreloadEntityData(const Json::Value &root, std::vector &outDeps) { if (root.isMember("components")) { for (const auto &compJson : root["components"]) { auto type = Id(compJson["type"].asCString()); DF3D_ASSERT(compJson.isMember("data")); const auto &data = compJson["data"]; if (type == Id("mesh")) outDeps.push_back(data["path"].asString()); else if (type == Id("vfx")) outDeps.push_back(data["path"].asString()); } } if (root.isMember("children")) { for (const auto &child : root["children"]) PreloadEntityData(child, outDeps); } } void EntityHolder::listDependencies(ResourceDataSource &dataSource, std::vector &outDeps) { auto root = JsonUtils::fromFile(dataSource); if (root.isNull()) return; PreloadEntityData(root, outDeps); } bool EntityHolder::decodeStartup(ResourceDataSource &dataSource, Allocator &allocator) { auto root = JsonUtils::fromFile(dataSource); if (root.isNull()) return false; m_resource = MAKE_NEW(allocator, EntityResource)(); m_resource->root = std::move(root); m_resource->isWorld = m_isWorldResource; return true; } void EntityHolder::decodeCleanup(Allocator &allocator) { } bool EntityHolder::createResource(Allocator &allocator) { return true; } void EntityHolder::destroyResource(Allocator &allocator) { MAKE_DELETE(allocator, m_resource); m_resource = nullptr; } } 10-100 //-------------------------------------------------------------------------- // // Environment: // This software is part of the EvtGen package developed jointly // for the BaBar and CLEO collaborations. If you use all or part // of it, please give an appropriate acknowledgement. // // Module: EvtBtoXsll.cc // // Description: Routine to generate non-resonant B -> Xs l+ l- decays. // It generates a dilepton mass spectrum according to Kruger and Sehgal // and then generates the two lepton momenta accoring to Ali et al. // The resultant X_s particles may be decayed by JETSET. // // Modification history: // // Jan 17, 2001 Module created // Jul 15, 2003 Input model parameters // //------------------------------------------------------------------------ // #include "EvtGenBase/EvtPatches.hh" #include #include "EvtGenBase/EvtRandom.hh" #include "EvtGenBase/EvtParticle.hh" #include "EvtGenBase/EvtGenKine.hh" #include "EvtGenBase/EvtPDL.hh" #include "EvtGenBase/EvtReport.hh" #include "EvtGenModels/EvtbTosllAmp.hh" #include "EvtGenModels/EvtBtoXsll.hh" #include "EvtGenModels/EvtBtoXsllUtil.hh" #include "EvtGenBase/EvtConst.hh" #include "EvtGenBase/EvtId.hh" using std::endl; EvtBtoXsll::~EvtBtoXsll() { delete _calcprob; } std::string EvtBtoXsll::getName(){ return "BTOXSLL"; } EvtDecayBase* EvtBtoXsll::clone(){ return new EvtBtoXsll; } void EvtBtoXsll::init(){ // check that there are no arguments checkNArg(0,4,5); checkNDaug(3); // Check that the two leptons are the same type EvtId lepton1type = getDaug(1); EvtId lepton2type = getDaug(2); int etyp = 0; int mutyp = 0; int tautyp = 0; if ( lepton1type == EvtPDL::getId("e+") || lepton1type == EvtPDL::getId("e-") ) { etyp++;} if ( lepton2type == EvtPDL::getId("e+") || lepton2type == EvtPDL::getId("e-") ) { etyp++;} if ( lepton1type == EvtPDL::getId("mu+") || lepton1type == EvtPDL::getId("mu-") ) { mutyp++;} if ( lepton2type == EvtPDL::getId("mu+") || lepton2type == EvtPDL::getId("mu-") ) { mutyp++;} if ( lepton1type == EvtPDL::getId("tau+") || lepton1type == EvtPDL::getId("tau-") ) { tautyp++;} if ( lepton2type == EvtPDL::getId("tau+") || lepton2type == EvtPDL::getId("tau-") ) { tautyp++;} if ( etyp != 2 && mutyp != 2 && tautyp != 2 ) { report(Severity::Error,"EvtGen") << "Expect two leptons of the same type in EvtBtoXsll.cc\n"; ::abort(); } // Check that the second and third entries are leptons with positive // and negative charge, respectively int lpos = 0; int lneg = 0; if ( lepton1type == EvtPDL::getId("e+") || lepton1type == EvtPDL::getId("mu+") || lepton1type == EvtPDL::getId("tau+") ) { lpos++;} if ( lepton2type == EvtPDL::getId("e-") || lepton2type == EvtPDL::getId("mu-") || lepton2type == EvtPDL::getId("tau-") ) { lneg++;} if ( lpos != 1 || lneg != 1 ) { report(Severity::Error,"EvtGen") << "Expect 2nd and 3rd particles to be positive and negative leptons in EvtBtoXsll.cc\n"; ::abort(); } _mb=4.8; _ms=0.2; _mq=0.; _pf=0.41; _mxmin=1.1; if ( getNArg()==4) { // b-quark mass _mb = getArg(0); // s-quark mass _ms = getArg(1); // spectator quark mass _mq = getArg(2); // Fermi motion parameter _pf = getArg(3); } if ( getNArg()==5) { _mxmin = getArg(4); } _calcprob = new EvtBtoXsllUtil; double ml = EvtPDL::getMeanMass(getDaug(1)); // determine the maximum probability density from dGdsProb int i, j; int nsteps = 100; double s = 0.0; double smin = 4.0 * ml * ml; double smax = (_mb - _ms)*(_mb - _ms); double probMax = -10000.0; double sProbMax = -10.0; double uProbMax = -10.0; for (i=0;idGdsProb(_mb, _ms, ml, s); if (prob > probMax) { sProbMax = s; probMax = prob; } } _dGdsProbMax = probMax; if ( verbose() ) { report(Severity::Info,"EvtGen") << "dGdsProbMax = " << probMax << " for s = " << sProbMax << endl; } // determine the maximum probability density from dGdsdupProb probMax = -10000.0; sProbMax = -10.0; for (i=0;idGdsdupProb(_mb, _ms, ml, s, u); if (prob > probMax) { sProbMax = s; uProbMax = u; probMax = prob; } } } _dGdsdupProbMax = 2.0*probMax; if ( verbose() ) { report(Severity::Info,"EvtGen") << "dGdsdupProbMax = " << probMax << " for s = " << sProbMax << " and u = " << uProbMax << endl; } } void EvtBtoXsll::initProbMax(){ noProbMax(); } void EvtBtoXsll::decay( EvtParticle *p ){ p->makeDaughters(getNDaug(),getDaugs()); EvtParticle* xhadron = p->getDaug(0); EvtParticle* leptonp = p->getDaug(1); EvtParticle* leptonn = p->getDaug(2); double mass[3]; findMasses( p, getNDaug(), getDaugs(), mass ); double mB = p->mass(); double ml = mass[1]; double pb; int im = 0; static int nmsg = 0; double xhadronMass = -999.0; EvtVector4R p4xhadron; EvtVector4R p4leptonp; EvtVector4R p4leptonn; // require the hadronic system has mass greater than that of a Kaon pion pair // while (xhadronMass < 0.6333) // the above minimum value of K+pi mass appears to be too close // to threshold as far as JETSET is concerned // (JETSET gets caught in an infinite loop) // so we choose a lightly larger value for the threshold while (xhadronMass < _mxmin) { im++; // Apply Fermi motion and determine effective b-quark mass // Old BaBar MC parameters // double pf = 0.25; // double ms = 0.2; // double mq = 0.3; double mb = 0.0; double xbox, ybox; while (mb <= 0.0) { pb = _calcprob->FermiMomentum(_pf); // effective b-quark mass mb = mB*mB + _mq*_mq - 2.0*mB*sqrt(pb*pb + _mq*_mq); if ( mb>0. && sqrt(mb)-_ms < 2.0*ml ) mb= -10.; } mb = sqrt(mb); // cout << "b-quark momentum = " << pb << " mass = " << mb << endl; // generate a dilepton invariant mass double s = 0.0; double smin = 4.0 * ml * ml; double smax = (mb - _ms)*(mb - _ms); while (s == 0.0) { xbox = EvtRandom::Flat(smin, smax); ybox = EvtRandom::Flat(_dGdsProbMax); double prob= _calcprob->dGdsProb(mb, _ms, ml, xbox); if ( !(prob>=0.0) && !(prob<=0.0)) { // report(Severity::Info,"EvtGen") << "nan from dGdsProb " << prob << " " << mb << " " << _ms << " " << ml << " " << xbox << std::endl; } if ( ybox < prob ) s=xbox; } // cout << "dGdsProb(s) = " << _calcprob->dGdsProb(mb, _ms, ml, s) // << " for s = " << s << endl; // two-body decay of b quark at rest into s quark and dilepton pair: // b -> s (ll) EvtVector4R p4sdilep[2]; double msdilep[2]; msdilep[0] = _ms; msdilep[1] = sqrt(s); EvtGenKine::PhaseSpace(2, msdilep, p4sdilep, mb); // generate dilepton decay with the expected asymmetry: (ll) -> l+ l- EvtVector4R p4ll[2]; double mll[2]; mll[0] = ml; mll[1] = ml; double tmp = 0.0; while (tmp == 0.0) { // (ll) -> l+ l- decay in dilepton rest frame EvtGenKine::PhaseSpace(2, mll, p4ll, msdilep[1]); // boost to b-quark rest frame p4ll[0] = boostTo(p4ll[0], p4sdilep[1]); p4ll[1] = boostTo(p4ll[1], p4sdilep[1]); // compute kinematical variable u EvtVector4R p4slp = p4sdilep[0] + p4ll[0]; EvtVector4R p4sln = p4sdilep[0] + p4ll[1]; double u = p4slp.mass2() - p4sln.mass2(); ybox = EvtRandom::Flat(_dGdsdupProbMax); double prob = _calcprob->dGdsdupProb(mb, _ms, ml, s, u); if ( !(prob>=0.0) && !(prob<=0.0)) { report(Severity::Info,"EvtGen") << "nan from dGdsProb " << prob << " " << mb << " " << _ms << " " << ml << " " << s << " " << u << std::endl; } if (prob > _dGdsdupProbMax && nmsg < 20) { report(Severity::Info,"EvtGen") << "d2gdsdup GT d2gdsdup_max:" << prob << " " << _dGdsdupProbMax << " for s = " << s << " u = " << u << " mb = " << mb << endl; nmsg++; } if (ybox < prob) { tmp = 1.0; // cout << "dGdsdupProb(s) = " << prob // << " for u = " << u << endl; } } // assign 4-momenta to valence quarks inside B meson in B rest frame double phi = EvtRandom::Flat( EvtConst::twoPi ); double costh = EvtRandom::Flat( -1.0, 1.0 ); double sinth = sqrt(1.0 - costh*costh); // b-quark four-momentum in B meson rest frame EvtVector4R p4b(sqrt(mb*mb + pb*pb), pb*sinth*sin(phi), pb*sinth*cos(phi), pb*costh); // B meson in its rest frame // // EvtVector4R p4B(mB, 0.0, 0.0, 0.0); // // boost B meson to b-quark rest frame // // p4B = boostTo(p4B, p4b); // // cout << " B meson mass in b-quark rest frame = " << p4B.mass() << endl; // boost s, l+ and l- to B meson rest frame // EvtVector4R p4s = boostTo(p4sdilep[0], p4B); // p4leptonp = boostTo(p4ll[0], p4B); // p4leptonn = boostTo(p4ll[1], p4B); EvtVector4R p4s = boostTo(p4sdilep[0], p4b); p4leptonp = boostTo(p4ll[0], p4b); p4leptonn = boostTo(p4ll[1], p4b); // spectator quark in B meson rest frame EvtVector4R p4q( sqrt(pb*pb + _mq*_mq), -p4b.get(1), -p4b.get(2), -p4b.get(3) ); // hadron system in B meson rest frame p4xhadron = p4s + p4q; xhadronMass = p4xhadron.mass(); // cout << "Xs mass = " << xhadronMass << " trial " << im << endl; } // initialize the decay products xhadron->init(getDaug(0), p4xhadron); // For B-bar mesons (i.e. containing a b quark) we have the normal // order of leptons if ( p->getId() == EvtPDL::getId("anti-B0") || p->getId() == EvtPDL::getId("B-") ) { leptonp->init(getDaug(1), p4leptonp); leptonn->init(getDaug(2), p4leptonn); } // For B mesons (i.e. containing a b-bar quark) we need to flip the // role of the positive and negative leptons in order to produce the // correct forward-backward asymmetry between the two leptons else { leptonp->init(getDaug(1), p4leptonn); leptonn->init(getDaug(2), p4leptonp); } return ; } #include "Sphere.h" namespace Millipede { bool Sphere::hit(const Ray& ray, double t_min, double t_max, std::shared_ptr& hit_record) const { Vector oc = ray.origin() - centre; double a = dot(ray.direction(), ray.direction()); double b = dot(oc, ray.direction()); double c = dot(oc, oc) - radius * radius; double discriminant = b * b - a * c; if (discriminant > 0) { double t = (-b - sqrt(b * b - a * c)) / a; if (t < t_max && t > t_min) { hit_record->t = t; hit_record->p = ray.point(t); hit_record->normal = (hit_record->p - centre) / radius; hit_record->material = sphere_material; return true; } t = (-b + sqrt(b * b - a * c)) / a; if (t < t_max && t > t_min) { hit_record->t = t; hit_record->p = ray.point(t); hit_record->normal = (hit_record->p - centre) / radius; hit_record->material = sphere_material; return true; } } return false; } }BetaScatt/BetaScatt.cc #include "G4RunManager.hh" #include "G4UImanager.hh" #include "G4UIterminal.hh" #include "G4UItcsh.hh" #include "G4PhysListFactory.hh" #include "G4VModularPhysicsList.hh" #include "G4ios.hh" #ifdef G4ANALYSIS_USE #include #include #endif #include "PadAnalysisManager.hh" #include "PadDetectorConstruction.hh" #include "PadPrimaryGeneratorAction.hh" #include "PadRunAction.hh" #include "PadEventAction.hh" #include "PadSteppingAction.hh" #include "PadCentralData.hh" #include "globals.hh" #include "Randomize.hh" // You can activate GEOMETRY_DEBUG by changing the comments on the last lines of the CMakeLists.txt file. #ifdef GEOMETRY_DEBUG #include "G4VisExecutive.hh" #endif void WriteHelp() { G4cout << "Usage: BetaScat " << G4endl << G4endl; G4cout << "This program simulates the scattering of electrons in" << G4endl; G4cout << "the emission channeling setups of IKS and ITN." << G4endl << G4endl; G4cout << "If command-line arguments are passed to the program (not" << G4endl; G4cout << "mandatory), the FIRST argument should be the INPUT FILE" << G4endl; G4cout << "(give full path). The SECOND optional argument should" << G4endl; G4cout << "contain the PATH where the other in- and output files" << G4endl; G4cout << "can be found/written to. Caution: if set, this path" << G4endl; G4cout << "argument will override the FilePath entry in the input" << G4endl; G4cout << "file." << G4endl << G4endl; G4cout << "More information on how to run the program can be found" << G4endl; G4cout << "in manual.pdf." << G4endl << G4endl; G4cout << "(c) - 2006" << G4endl; } int main(int argc, char* argv[]) { #ifdef GDEBUG std::cout << " begin program! " << std::endl; #endif // First test if the short help text should be printed if ( (argc == 2) && (argv[1][0] == '-') ) { WriteHelp(); return 0; } #ifdef GDEBUG std::cout << " help text. " << std::endl; #endif // Construct default run manager G4RunManager* runManager = new G4RunManager; // Construct object to hold data to be shared among classes // The constructor will read the default input file, or the // one given on the command line PadCentralData *dataObject = new PadCentralData(argc,argv); // Before reading the input file, check if there are command // line arguments, which contain alternative files and paths // If arguments are given, pass them on to *dataObject. // First argument should be the input filename (full path!!), // the second one the path of the output files. // Set the Random number generator engine and // read previously saved seed file G4String SeedFileName = dataObject->GetSeedFileName(); CLHEP::HepRandom::createInstance(); CLHEP::RanluxEngine* theRanluxEngine = new CLHEP::RanluxEngine(); theRanluxEngine->restoreStatus(SeedFileName); CLHEP::HepRandom::setTheEngine(theRanluxEngine); #ifdef GDEBUG std::cout << " CLHEP intitialization " << std::endl; #endif // Construct analysis object if variable is set #ifdef G4ANALYSIS_USE TFile * file = new TFile (dataObject->GetHistogramFileName(),"RECREATE"); PadAnalysisManager* analysisManager = new PadAnalysisManager(dataObject,file); #endif #ifdef GDEBUG std::cout << " Created file and analysisManager " << std::endl; #endif // Mandatory initialization classes // Detector Construction runManager->SetUserInitialization(new PadDetectorConstruction); // Physics List G4int verbose = 1; G4PhysListFactory factory; G4VModularPhysicsList* physlist = factory.GetReferencePhysList("QBBC"); //QBBC_EMZ G4double ParticleCut = dataObject->GetDefaultCutValue(); physlist->SetVerboseLevel(verbose); physlist->SetDefaultCutValue(ParticleCut); runManager->SetUserInitialization(physlist); #ifdef GDEBUG std::cout << " Set user initialization " << std::endl; #endif #ifdef G4ANALYSIS_USE // Mandatory user action class runManager->SetUserAction(new PadPrimaryGeneratorAction(dataObject, analysisManager)); #endif // Analysis routines to make histograms #ifdef G4ANALYSIS_USE runManager->SetUserAction(new PadRunAction(analysisManager)); runManager->SetUserAction(new PadEventAction(analysisManager)); runManager->SetUserAction(new PadSteppingAction(analysisManager)); #else runManager->SetUserAction(new PadRunAction()); runManager->SetUserAction(new PadEventAction()); runManager->SetUserAction(new PadSteppingAction()); #endif #ifdef GDEBUG std::cout << " runManager setting user action " << std::endl; #endif // Initialize G4 kernel runManager->Initialize(); #ifdef GDEBUG std::cout << " runManager initialize " << std::endl; #endif #ifdef GEOMETRY_DEBUG // Suggestion: // run /control/execute vis.mac for a fast visualization setup. G4UIsession* session = new G4UIterminal(new G4UItcsh); #else // get the pointer to UI manager and set verbosities G4UImanager* UI = G4UImanager::GetUIpointer(); UI->ApplyCommand("/run/verbose "+dataObject->GetVerboseRun()); UI->ApplyCommand("/event/verbose "+dataObject->GetVerboseEvent()); UI->ApplyCommand("/tracking/verbose "+dataObject->GetVerboseTrack()); std::cout << " G4UI verbosity " << std::endl; #endif #ifdef GEOMETRY_DEBUG G4VisManager* visManager = new G4VisExecutive; visManager->Initialize(); #endif // start a run #ifdef GEOMETRY_DEBUG session->SessionStart(); delete session; #else runManager->BeamOn(dataObject->GetNumberOfEvents()); std::cout << " runManager Beam on. " << std::endl; #endif //job termination if(dataObject->GetWriteSeed() == 1) { theRanluxEngine->saveStatus(SeedFileName); } delete theRanluxEngine; //#ifdef GDEBUG std::cout << " Ending job. " << std::endl; //#endif #ifdef G4ANALYSIS_USE delete analysisManager; // delete analysisFactory; file->Write(0, TObject::kOverwrite); file->Close(); delete file; #endif std::cout << " Ending job. " << std::endl; #ifdef GEOMETRY_DEBUG delete visManager; #endif delete dataObject; delete runManager; return 0; } modules/core/euler/unit/simd/erfc.cpp //============================================================================== // Copyright 2003 - 2013 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include NT2_TEST_CASE_TPL ( erfc_real, NT2_SIMD_REAL_TYPES) { using nt2::erfc; using nt2::tag::erfc_; using boost::simd::native; typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t; typedef native vT; typedef typename nt2::meta::call::type r_t; typedef vT wished_r_t; // return type conformity test NT2_TEST_TYPE_IS(r_t, wished_r_t); // specific values tests #ifndef BOOST_SIMD_NO_INVALIDS NT2_TEST_ULP_EQUAL(erfc(nt2::Inf()), nt2::Zero(), 200); NT2_TEST_ULP_EQUAL(erfc(nt2::Nan()), nt2::Nan(), 200); #endif NT2_TEST_ULP_EQUAL(erfc(nt2::Mzero()), nt2::One(), 200); NT2_TEST_ULP_EQUAL(erfc(nt2::One()), nt2::splat(0.157299207050285), 200); NT2_TEST_ULP_EQUAL(erfc(nt2::Half()), nt2::splat(0.479500122186953), 200); NT2_TEST_ULP_EQUAL(erfc(nt2::Two()), nt2::splat(0.004677734981047), 200); NT2_TEST_ULP_EQUAL(erfc(nt2::Zero()), nt2::One(), 200); NT2_TEST(nt2::all(nt2::is_less(erfc((nt2::Ten())- nt2::splat(2.088487583762545e-45)), nt2::Eps()))); NT2_TEST(nt2::all(nt2::is_less(erfc(nt2::splat(15))- nt2::splat(7.212994172451206e-100), nt2::Eps()))); NT2_TEST_ULP_EQUAL(erfc(nt2::splat(-6)), nt2::Two(), 4); } YUNEEC/openvino_contribmodules/cuda_plugin/src/ops/less.cpp // Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "less.hpp" #include namespace CUDAPlugin { LessOp::LessOp(const CreationContext& context, const ngraph::Node& node, IndexCollection&& inputIds, IndexCollection&& outputIds) : Comparison(context, node, std::move(inputIds), std::move(outputIds), kernel::Comparison::Op_t::LESS) {} OPERATION_REGISTER(LessOp, Less); } // namespace CUDAPlugin //===---- Reduction.cpp - OpenMP device reduction implementation - C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the implementation of reduction with KMPC interface. // //===----------------------------------------------------------------------===// #include "Debug.h" #include "Interface.h" #include "Mapping.h" #include "State.h" #include "Synchronization.h" #include "Types.h" #include "Utils.h" using namespace _OMP; namespace { #pragma omp declare target void gpu_regular_warp_reduce(void *reduce_data, ShuffleReductFnTy shflFct) { for (uint32_t mask = mapping::getWarpSize() / 2; mask > 0; mask /= 2) { shflFct(reduce_data, /*LaneId - not used= */ 0, /*Offset = */ mask, /*AlgoVersion=*/0); } } void gpu_irregular_warp_reduce(void *reduce_data, ShuffleReductFnTy shflFct, uint32_t size, uint32_t tid) { uint32_t curr_size; uint32_t mask; curr_size = size; mask = curr_size / 2; while (mask > 0) { shflFct(reduce_data, /*LaneId = */ tid, /*Offset=*/mask, /*AlgoVersion=*/1); curr_size = (curr_size + 1) / 2; mask = curr_size / 2; } } #if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 static uint32_t gpu_irregular_simd_reduce(void *reduce_data, ShuffleReductFnTy shflFct) { uint32_t size, remote_id, physical_lane_id; physical_lane_id = mapping::getThreadIdInBlock() % mapping::getWarpSize(); __kmpc_impl_lanemask_t lanemask_lt = mapping::lanemaskLT(); __kmpc_impl_lanemask_t Liveness = mapping::activemask(); uint32_t logical_lane_id = utils::popc(Liveness & lanemask_lt) * 2; __kmpc_impl_lanemask_t lanemask_gt = mapping::lanemaskGT(); do { Liveness = mapping::activemask(); remote_id = utils::ffs(Liveness & lanemask_gt); size = utils::popc(Liveness); logical_lane_id /= 2; shflFct(reduce_data, /*LaneId =*/logical_lane_id, /*Offset=*/remote_id - 1 - physical_lane_id, /*AlgoVersion=*/2); } while (logical_lane_id % 2 == 0 && size > 1); return (logical_lane_id == 0); } #endif static int32_t nvptx_parallel_reduce_nowait(int32_t TId, int32_t num_vars, uint64_t reduce_size, void *reduce_data, ShuffleReductFnTy shflFct, InterWarpCopyFnTy cpyFct, bool isSPMDExecutionMode, bool) { uint32_t BlockThreadId = mapping::getThreadIdInBlock(); if (mapping::isMainThreadInGenericMode()) BlockThreadId = 0; uint32_t NumThreads = omp_get_num_threads(); if (NumThreads == 1) return 1; /* * This reduce function handles reduction within a team. It handles * parallel regions in both L1 and L2 parallelism levels. It also * supports Generic, SPMD, and NoOMP modes. * * 1. Reduce within a warp. * 2. Warp master copies value to warp 0 via shared memory. * 3. Warp 0 reduces to a single value. * 4. The reduced value is available in the thread that returns 1. */ #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 uint32_t WarpsNeeded = (NumThreads + mapping::getWarpSize() - 1) / mapping::getWarpSize(); uint32_t WarpId = mapping::getWarpId(); // Volta execution model: // For the Generic execution mode a parallel region either has 1 thread and // beyond that, always a multiple of 32. For the SPMD execution mode we may // have any number of threads. if ((NumThreads % mapping::getWarpSize() == 0) || (WarpId < WarpsNeeded - 1)) gpu_regular_warp_reduce(reduce_data, shflFct); else if (NumThreads > 1) // Only SPMD execution mode comes thru this case. gpu_irregular_warp_reduce(reduce_data, shflFct, /*LaneCount=*/NumThreads % mapping::getWarpSize(), /*LaneId=*/mapping::getThreadIdInBlock() % mapping::getWarpSize()); // When we have more than [mapping::getWarpSize()] number of threads // a block reduction is performed here. // // Only L1 parallel region can enter this if condition. if (NumThreads > mapping::getWarpSize()) { // Gather all the reduced values from each warp // to the first warp. cpyFct(reduce_data, WarpsNeeded); if (WarpId == 0) gpu_irregular_warp_reduce(reduce_data, shflFct, WarpsNeeded, BlockThreadId); } return BlockThreadId == 0; #else __kmpc_impl_lanemask_t Liveness = mapping::activemask(); if (Liveness == lanes::All) // Full warp gpu_regular_warp_reduce(reduce_data, shflFct); else if (!(Liveness & (Liveness + 1))) // Partial warp but contiguous lanes gpu_irregular_warp_reduce(reduce_data, shflFct, /*LaneCount=*/utils::popc(Liveness), /*LaneId=*/mapping::getThreadIdInBlock() % mapping::getWarpSize()); else { // Dispersed lanes. Only threads in L2 // parallel region may enter here; return // early. return gpu_irregular_simd_reduce(reduce_data, shflFct); } // When we have more than [mapping::getWarpSize()] number of threads // a block reduction is performed here. // // Only L1 parallel region can enter this if condition. if (NumThreads > mapping::getWarpSize()) { uint32_t WarpsNeeded = (NumThreads + mapping::getWarpSize() - 1) / mapping::getWarpSize(); // Gather all the reduced values from each warp // to the first warp. cpyFct(reduce_data, WarpsNeeded); uint32_t WarpId = BlockThreadId / mapping::getWarpSize(); if (WarpId == 0) gpu_irregular_warp_reduce(reduce_data, shflFct, WarpsNeeded, BlockThreadId); return BlockThreadId == 0; } // Get the OMP thread Id. This is different from BlockThreadId in the case of // an L2 parallel region. return TId == 0; #endif // __CUDA_ARCH__ >= 700 } uint32_t roundToWarpsize(uint32_t s) { if (s < mapping::getWarpSize()) return 1; return (s & ~(unsigned)(mapping::getWarpSize() - 1)); } uint32_t kmpcMin(uint32_t x, uint32_t y) { return x < y ? x : y; } static volatile uint32_t IterCnt = 0; static volatile uint32_t Cnt = 0; } // namespace extern "C" { int32_t __kmpc_nvptx_parallel_reduce_nowait_v2( IdentTy *Loc, int32_t TId, int32_t num_vars, uint64_t reduce_size, void *reduce_data, ShuffleReductFnTy shflFct, InterWarpCopyFnTy cpyFct) { return nvptx_parallel_reduce_nowait(TId, num_vars, reduce_size, reduce_data, shflFct, cpyFct, mapping::isSPMDMode(), false); } int32_t __kmpc_nvptx_teams_reduce_nowait_v2( IdentTy *Loc, int32_t TId, void *GlobalBuffer, uint32_t num_of_records, void *reduce_data, ShuffleReductFnTy shflFct, InterWarpCopyFnTy cpyFct, ListGlobalFnTy lgcpyFct, ListGlobalFnTy lgredFct, ListGlobalFnTy glcpyFct, ListGlobalFnTy glredFct) { // Terminate all threads in non-SPMD mode except for the master thread. uint32_t ThreadId = mapping::getThreadIdInBlock(); if (mapping::isGenericMode()) { if (!mapping::isMainThreadInGenericMode()) return 0; ThreadId = 0; } // In non-generic mode all workers participate in the teams reduction. // In generic mode only the team master participates in the teams // reduction because the workers are waiting for parallel work. uint32_t NumThreads = omp_get_num_threads(); uint32_t TeamId = omp_get_team_num(); uint32_t NumTeams = omp_get_num_teams(); static unsigned SHARED(Bound); static unsigned SHARED(ChunkTeamCount); // Block progress for teams greater than the current upper // limit. We always only allow a number of teams less or equal // to the number of slots in the buffer. bool IsMaster = (ThreadId == 0); while (IsMaster) { Bound = atomic::read((uint32_t *)&IterCnt, __ATOMIC_SEQ_CST); if (TeamId < Bound + num_of_records) break; } if (IsMaster) { int ModBockId = TeamId % num_of_records; if (TeamId < num_of_records) { lgcpyFct(GlobalBuffer, ModBockId, reduce_data); } else lgredFct(GlobalBuffer, ModBockId, reduce_data); fence::system(__ATOMIC_SEQ_CST); // Increment team counter. // This counter is incremented by all teams in the current // BUFFER_SIZE chunk. ChunkTeamCount = atomic::inc((uint32_t *)&Cnt, num_of_records - 1u, __ATOMIC_SEQ_CST); } // Synchronize if (mapping::isSPMDMode()) __kmpc_barrier(Loc, TId); // reduce_data is global or shared so before being reduced within the // warp we need to bring it in local memory: // local_reduce_data = reduce_data[i] // // Example for 3 reduction variables a, b, c (of potentially different // types): // // buffer layout (struct of arrays): // a, a, ..., a, b, b, ... b, c, c, ... c // |__________| // num_of_records // // local_data_reduce layout (struct): // a, b, c // // Each thread will have a local struct containing the values to be // reduced: // 1. do reduction within each warp. // 2. do reduction across warps. // 3. write the final result to the main reduction variable // by returning 1 in the thread holding the reduction result. // Check if this is the very last team. unsigned NumRecs = kmpcMin(NumTeams, uint32_t(num_of_records)); if (ChunkTeamCount == NumTeams - Bound - 1) { // // Last team processing. // if (ThreadId >= NumRecs) return 0; NumThreads = roundToWarpsize(kmpcMin(NumThreads, NumRecs)); if (ThreadId >= NumThreads) return 0; // Load from buffer and reduce. glcpyFct(GlobalBuffer, ThreadId, reduce_data); for (uint32_t i = NumThreads + ThreadId; i < NumRecs; i += NumThreads) glredFct(GlobalBuffer, i, reduce_data); // Reduce across warps to the warp master. if (NumThreads > 1) { gpu_regular_warp_reduce(reduce_data, shflFct); // When we have more than [mapping::getWarpSize()] number of threads // a block reduction is performed here. uint32_t ActiveThreads = kmpcMin(NumRecs, NumThreads); if (ActiveThreads > mapping::getWarpSize()) { uint32_t WarpsNeeded = (ActiveThreads + mapping::getWarpSize() - 1) / mapping::getWarpSize(); // Gather all the reduced values from each warp // to the first warp. cpyFct(reduce_data, WarpsNeeded); uint32_t WarpId = ThreadId / mapping::getWarpSize(); if (WarpId == 0) gpu_irregular_warp_reduce(reduce_data, shflFct, WarpsNeeded, ThreadId); } } if (IsMaster) { Cnt = 0; IterCnt = 0; return 1; } return 0; } if (IsMaster && ChunkTeamCount == num_of_records - 1) { // Allow SIZE number of teams to proceed writing their // intermediate results to the global buffer. atomic::add((uint32_t *)&IterCnt, uint32_t(num_of_records), __ATOMIC_SEQ_CST); } return 0; } void __kmpc_nvptx_end_reduce(int32_t TId) {} void __kmpc_nvptx_end_reduce_nowait(int32_t TId) {} } #pragma omp end declare target #include #include #include #include const int MAX_N = 150000; struct Node { int lc; // 左儿子 int rc; // 右儿子 int s; // 节点数 int v; // 数值 int p; // 权重 } tree[MAX_N]; int tot, cnt; int crt, qx, qy, qqx, qqy; std::string s[MAX_N]; #pragma region initial void update(int x); int create(int x); void spilt(int l, int r, int &x, int &y); int merge(int x, int y); void insert(int x, int y); void query(int x); int read(); #pragma endregion initial int main() { // std::ios::sync_with_stdio(false); srand(20210711); int n = read(); for (int i = 1; i <= n; i++) { std::cin >> s[++cnt]; insert(i - 1, cnt); } int m = read(); for (int i = 1; i <= m; i++) { std::cin >> s[++cnt]; insert(read(), cnt); } int q = read(); for (int i = 1; i <= q; i++) { query(read()); } return 0; } void update(int x) { tree[x].s = tree[tree[x].lc].s + tree[tree[x].rc].s + 1; } int create(int x) { tree[++tot].s = 1; tree[tot].v = x; tree[tot].p = rand(); return tot; } void spilt(int l, int r, int &x, int &y) { if (!l) { x = y = 0; } else { if (r <= tree[tree[l].lc].s) { y = l; spilt(tree[l].lc, r, x, tree[l].lc); } else { x = l; spilt(tree[l].rc, r - tree[tree[l].lc].s - 1, tree[l].rc, y); } update(l); } } int merge(int x, int y) { if (!x or !y) { return x + y; } if (tree[x].p < tree[y].p) { tree[x].rc = merge(tree[x].rc, y); update(x); return x; } else { tree[y].lc = merge(x, tree[y].lc); update(y); return y; } } void insert(int x, int y) { spilt(crt, x, qx, qy); crt = merge(qx, merge(create(y), qy)); } void query(int x) { spilt(crt, x, qx, qy); spilt(qy, 1, qqx, qqy); std::cout << s[tree[qqx].v] << '\n'; crt = merge(qx, merge(qqx, qqy)); } int read() { int x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - 48; ch = getchar(); } return x * f; }10-100 /* Copyright (c) <2015> Verisign, Inc. 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 "smg_pgp_association.h" #include "smg_defs.h" using namespace std; SmgPgpAssociation::SmgPgpAssociation() : SmgAssociation() { } SmgPgpAssociation::SmgPgpAssociation(const SmgPgpAssociation &p_oRHS) : SmgAssociation() { (*this) = p_oRHS; } SmgPgpAssociation::~SmgPgpAssociation() { clear(); } bool SmgPgpAssociation::init(SmgPgpKey &p_oKey) { return isInitialized(); } bool SmgPgpAssociation::initLocal(std::string &p_sID, const char *p_szHomeDir /*= NULL*/) { return isInitialized(); } bool SmgPgpAssociation::toWire(SmgBytesVector_t &p_oOutput) { bool bRet = false; return bRet; } bool SmgPgpAssociation::fromWire(uint8_t *p_pBuffer, size_t p_uLen) { bool bRet = false; return bRet; } bool SmgPgpAssociation::toText(std::string &p_sOutput) { bool bRet = false; return bRet; } bool SmgPgpAssociation::fromText(std::string &p_sTxt) { bool bRet = false; return bRet; } SmgPgpKey &SmgPgpAssociation::getKey() { return m_oKey; } void SmgPgpAssociation::setKey(SmgPgpKey &p_oKey) { m_oKey = p_oKey; } bool SmgPgpAssociation::verify(SmgBytesVector_t &p_oBytes) { bool bRet = false; return bRet; } bool SmgPgpAssociation::encrypt(SmgBytesVector_t &p_oBytes, SmgBytesVector_t &p_oEncryptedBytes) { bool bRet = false; return bRet; } bool SmgPgpAssociation::encrypt(SmgBytesVector_t &p_oBytes, std::string &p_sEncrypted) { bool bRet = false; return bRet; } bool SmgPgpAssociation::encrypt(std::string &p_oClear, std::string &p_sEncrypted) { bool bRet = false; return bRet; } bool SmgPgpAssociation::decrypt(SmgBytesVector_t &p_oEncryptedBytes, SmgBytesVector_t &p_oBytes) { bool bRet = false; return bRet; } bool SmgPgpAssociation::decrypt(std::string &p_sEncrypted, SmgBytesVector_t &p_oBytes) { bool bRet = false; return bRet; } bool SmgPgpAssociation::sign(SmgBytesVector_t &p_oBytes, SmgBytesVector_t &p_oSignature) { bool bRet = false; return bRet; } bool SmgPgpAssociation::sign(SmgBytesVector_t &p_oBytes, std::string &p_sSignature) { bool bRet = false; return bRet; } SmgAssociation &SmgPgpAssociation::operator=(const SmgPgpAssociation &p_oRHS) { SmgAssociation::operator=(p_oRHS); return *this; } bool SmgPgpAssociation::clear() { return false; } /* |INCLUDES: QT| */ #include #include #include #include /* |INCLUDES: SQUARE| */ /* |INCLUDES: PROJECT| */ #include "square-DraglistWidget.h" #include "square-DragItem.h" /* ------------------------------------------------------------------ [PUBLIC] */ DragListWidget::DragListWidget(QSize _size, QWidget *_parent) : QListWidget(_parent), size_(_size), mimeString_("square/x-d2node-data") { setDragEnabled(true); setViewMode(QListView::IconMode); setDropIndicatorShown(true); setMinimumHeight(_size.height() + 10); setMaximumHeight(_size.height() + 10); setIconSize(_size); setWrapping(false); } /* ------------------------------------------------------------------ [PROTECTED] */ void DragListWidget::startDrag(Qt::DropActions) { QByteArray itemData; QDataStream dataStream(&itemData, QIODevice::WriteOnly); QListWidgetItem *item = currentItem(); QPixmap pixmap = qvariant_cast(item->data(Qt::UserRole)); int itemID = item->data(Qt::UserRole + 1).toInt(); dataStream << pixmap << itemID; QMimeData *mimeData = new QMimeData; { mimeData->setData(mimeString_, itemData); } QDrag *drag = new QDrag(this); { drag->setPixmap(pixmap); drag->setMimeData(mimeData); drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)); } if (drag->exec(Qt::MoveAction) == Qt::MoveAction){/* ? */}; } // Copyright 2014 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 "device/hid/hid_service_linux.h" #include #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/thread_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "device/hid/hid_connection_linux.h" #include "device/hid/hid_device_info.h" #include "device/hid/hid_report_descriptor.h" #include "device/udev_linux/scoped_udev.h" #if defined(OS_CHROMEOS) #include "base/sys_info.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/permission_broker_client.h" #endif // defined(OS_CHROMEOS) namespace device { namespace { const char kHidrawSubsystem[] = "hidraw"; const char kHIDID[] = "HID_ID"; const char kHIDName[] = "HID_NAME"; const char kHIDUnique[] = "HID_UNIQ"; const char kSysfsReportDescriptorKey[] = "report_descriptor"; #if defined(OS_CHROMEOS) void OnRequestAccessComplete( scoped_refptr reply_task_runner, const base::Callback& callback, bool success) { reply_task_runner->PostTask(FROM_HERE, base::Bind(callback, success)); } void RequestAccess( const std::string& device_node, scoped_refptr reply_task_runner, const base::Callback& callback) { bool success = false; if (base::SysInfo::IsRunningOnChromeOS()) { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; if (client) { client->RequestPathAccess( device_node, -1, base::Bind(OnRequestAccessComplete, reply_task_runner, callback)); return; } } else { // Not really running on Chrome OS, declare success. success = true; } reply_task_runner->PostTask(FROM_HERE, base::Bind(callback, success)); } #endif } // namespace HidServiceLinux::HidServiceLinux( scoped_refptr ui_task_runner) : ui_task_runner_(ui_task_runner), weak_factory_(this) { base::ThreadRestrictions::AssertIOAllowed(); task_runner_ = base::ThreadTaskRunnerHandle::Get(); DeviceMonitorLinux* monitor = DeviceMonitorLinux::GetInstance(); monitor->AddObserver(this); monitor->Enumerate( base::Bind(&HidServiceLinux::OnDeviceAdded, weak_factory_.GetWeakPtr())); } void HidServiceLinux::Connect(const HidDeviceId& device_id, const ConnectCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); ScopedUdevDevicePtr device = DeviceMonitorLinux::GetInstance()->GetDeviceFromPath( device_id); if (!device) { task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr)); return; } const char* device_node = udev_device_get_devnode(device.get()); if (!device_node) { task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr)); return; } base::Callback finish_connect = base::Bind(&HidServiceLinux::FinishConnect, weak_factory_.GetWeakPtr(), device_id, std::string(device_node), callback); #if defined(OS_CHROMEOS) ui_task_runner_->PostTask(FROM_HERE, base::Bind(RequestAccess, std::string(device_node), task_runner_, finish_connect)); #else // Use the task runner to preserve the asynchronous behavior of this call on // non-Chrome OS platforms. task_runner_->PostTask(FROM_HERE, base::Bind(finish_connect, true)); #endif } HidServiceLinux::~HidServiceLinux() { if (DeviceMonitorLinux::HasInstance()) DeviceMonitorLinux::GetInstance()->RemoveObserver(this); } void HidServiceLinux::OnDeviceAdded(udev_device* device) { if (!device) return; const char* device_path = udev_device_get_syspath(device); if (!device_path) return; const char* subsystem = udev_device_get_subsystem(device); if (!subsystem || strcmp(subsystem, kHidrawSubsystem) != 0) return; HidDeviceInfo device_info; device_info.device_id = device_path; uint32_t int_property = 0; const char* str_property = NULL; udev_device* parent = udev_device_get_parent(device); if (!parent) { return; } const char* hid_id = udev_device_get_property_value(parent, kHIDID); if (!hid_id) { return; } std::vector parts; base::SplitString(hid_id, ':', &parts); if (parts.size() != 3) { return; } if (HexStringToUInt(base::StringPiece(parts[1]), &int_property)) { device_info.vendor_id = int_property; } if (HexStringToUInt(base::StringPiece(parts[2]), &int_property)) { device_info.product_id = int_property; } str_property = udev_device_get_property_value(parent, kHIDUnique); if (str_property != NULL) { device_info.serial_number = str_property; } str_property = udev_device_get_property_value(parent, kHIDName); if (str_property != NULL) { device_info.product_name = str_property; } const char* parent_sysfs_path = udev_device_get_syspath(parent); if (!parent_sysfs_path) { return; } base::FilePath report_descriptor_path = base::FilePath(parent_sysfs_path).Append(kSysfsReportDescriptorKey); std::string report_descriptor_str; if (!base::ReadFileToString(report_descriptor_path, &report_descriptor_str)) { return; } HidReportDescriptor report_descriptor( reinterpret_cast(&report_descriptor_str[0]), report_descriptor_str.length()); report_descriptor.GetDetails(&device_info.collections, &device_info.has_report_id, &device_info.max_input_report_size, &device_info.max_output_report_size, &device_info.max_feature_report_size); AddDevice(device_info); } void HidServiceLinux::OnDeviceRemoved(udev_device* device) { const char* device_path = udev_device_get_syspath(device);; if (device_path) { RemoveDevice(device_path); } } void HidServiceLinux::FinishConnect( const HidDeviceId& device_id, const std::string device_node, const base::Callback)>& callback, bool success) { DCHECK(thread_checker_.CalledOnValidThread()); if (!success) { callback.Run(nullptr); } const auto& map_entry = devices().find(device_id); if (map_entry == devices().end()) { callback.Run(nullptr); } callback.Run(new HidConnectionLinux(map_entry->second, device_node)); } } // namespace device /*************************************************************************** * * rw_iso2022.cpp * * $Id: //stdlib/dev/source/stdlib/iso2022.cpp#41 $ * *************************************************************************** * * Copyright (c) 1994-2005 Quovadx, Inc., acting through its Rogue Wave * Software division. 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. * **************************************************************************/ #define _RWSTD_LIB_SRC #include #ifndef _RWSTD_NO_V3_LOCALE #include // for strxxx() #include // for mbstate_t #include #include #include "iso2022.h" #include "locale_body.h" #define CHSET_ANSI_X_3_4_1968 6 #define CHSET_JIS_X_0201_KANA 13 #define CHSET_JIS_X_0201_ROMAN 14 #define CHSET_JIS_X_0208_1978 42 #define CHSET_JIS_X_0208_1983 87 #define CHSET_JIS_X_0212_1990 159 #define CHSET_GB2312_1980 58 #define CHSET_KSC_5601_1987 149 #define CHSET_ISO_8859_1 100 #define CHSET_ISO_8859_7 126 #define DBIDX_ANSI_X_3_4_1968 1 #define DBIDX_ISO_8859_1 2 #define DBIDX_ISO_8859_2 3 #define DBIDX_ISO_8859_3 4 #define DBIDX_ISO_8859_4 5 #define DBIDX_ISO_8859_5 6 #define DBIDX_ISO_8859_6 7 #define DBIDX_ISO_8859_7 8 #define DBIDX_ISO_8859_8 9 #define DBIDX_EUC_JP 10 #define DBIDX_EUC_KR 11 #define DBIDX_GB2312 12 #define ISO_2022_JP_SET_ASCII "\x1B(B" #define ISO_2022_JP_SET_JIS201_ROMAN "\x1B(J" #define ISO_2022_JP_SET_JIS201_KANA "\x1B(I" #define ISO_2022_JP_SET_JIS208_78 "\x1B$@" #define ISO_2022_JP_SET_JIS208_83 "\x1B$B" #define ISO_2022_JP_SET_GB2312_80 "\x1B$A" #define ISO_2022_JP_SET_KSC5601_87 "\x1B$(C" #define ISO_2022_JP_SET_JIS212_90 "\x1B$(D" #define ISO_2022_JP_SET_ISO_8859_1 "\x1B.A" #define ISO_2022_JP_SET_ISO_8859_7 "\x1B.F" #define ISO_2022_JP_SET_SS2 "\x1BN" #define ASCII_CHAR_LEN 1 #define EUCJP_ASCII_CHAR_LEN 1 #define EUCJP_JISX0201_ROMAN_CHAR_LEN 1 #define EUCJP_JISX0201_KANA_CHAR_LEN 2 #define EUCJP_JISX0208_CHAR_LEN 2 #define EUCJP_JISX0212_CHAR_LEN 3 #define GB2312_CHAR_LEN 2 #define KSC5601_CHAR_LEN 2 #define ISO_8859_1_CHAR_LEN 1 #define ISO_8859_7_CHAR_LEN 1 #define ISO_2022_SET_SB94_G0 0x28 #define ISO_2022_SET_SB94_G1 0x29 #define ISO_2022_SET_SB94_G2 0x2A #define ISO_2022_SET_SB94_G3 0x2B #define ISO_2022_SET_SB96_G1 0x2D #define ISO_2022_SET_SB96_G2 0x2E #define ISO_2022_SET_SB96_G3 0x2F #define ISO_2022_SET_MB 0x24 #define ISO_2022_SET_MB94_G0 0x28 #define ISO_2022_SET_MB94_G1 0x29 #define ISO_2022_SET_MB94_G2 0x2A #define ISO_2022_SET_MB94_G3 0x2B #define ISO_2022_SET_MB96_G1 0x2D #define ISO_2022_SET_MB96_G2 0x2E #define ISO_2022_SET_MB96_G3 0x2F #define ISO_2022_SET_SS2 0x4E #define ESCAPE_CHAR 0x1B #if !defined (_UTF8_MB_CUR_MAX) # define _UTF8_MB_CUR_MAX 6 #endif #define CODECVT_ERROR _V3_LOCALE::codecvt_base::error #define CODECVT_OK _V3_LOCALE::codecvt_base::ok #define CODECVT_PARTIAL _V3_LOCALE::codecvt_base::partial _RWSTD_NAMESPACE (__rw) { enum __rw_codeset_type_t { sb94 = 0, sb96, mb94, mb96 }; // State of the ISO-2022 conversions struct __rw_iso2022_state_t { // 0 - unused, 1 - used, default 0 unsigned used:1; // invoked code elements: valid values 1-4, invalid 0, default 0 unsigned gl_map:3; unsigned gr_map:3; // shift state: 0 - one character, 1 - two characters, default 0 unsigned shift_state:1; // single-shift 2 and 3 functions unsigned sshift2:1; unsigned sshift3:1; // equivalent of G0-G3 code elements unsigned char g_map [4]; // default 0 }; // Mapping between the code of the character set and the name struct __rw_chset_map_t { const char* name; // codeset canonical name unsigned char index; // database index unsigned char width; // encoding width const char* seq; // designating sequence unsigned int seqlen; // designating sequence length }; // Database file mappings struct __rw_db_map_t { const void* pv; // pointer to mapping _RWSTD_SIZE_T size; // size of mapping const char* name; // canonical name }; // make sure there is just one copy of the empty string used // in the table below (space optimization in case the compiler // doesn't collapse them automatically static const char __rw_empty[] = ""; // Array of mappings: code registration number to name static const __rw_chset_map_t __rw_chset_map [256] = { #define EMPTY __rw_empty, 0, 0, 0, 0 {/* 0x00 */ EMPTY }, {/* 0x01 */ EMPTY }, {/* 0x02 */ EMPTY }, {/* 0x03 */ EMPTY }, {/* 0x04 */ EMPTY }, {/* 0x05 */ EMPTY }, { /* 0x06 */ "ANSI_X3.4-1968", DBIDX_ANSI_X_3_4_1968, 0, ISO_2022_JP_SET_ASCII, sizeof (ISO_2022_JP_SET_ASCII) - 1U }, {/* 0x07 */ EMPTY }, {/* 0x08 */ EMPTY }, {/* 0x09 */ EMPTY }, {/* 0x0a */ EMPTY }, {/* 0x0b */ EMPTY }, {/* 0x0c */ EMPTY }, { /* 0x0d */ "EUC-JP", DBIDX_EUC_JP, 0, ISO_2022_JP_SET_JIS201_KANA, sizeof (ISO_2022_JP_SET_JIS201_KANA) - 1U }, { /* 0x0e */ "EUC-JP", DBIDX_EUC_JP, 0, ISO_2022_JP_SET_JIS201_ROMAN, sizeof (ISO_2022_JP_SET_JIS201_ROMAN) - 1U }, {/* 0x0f */ EMPTY }, {/* 0x10 */ EMPTY }, {/* 0x11 */ EMPTY }, {/* 0x12 */ EMPTY }, {/* 0x13 */ EMPTY }, {/* 0x14 */ EMPTY }, {/* 0x15 */ EMPTY }, {/* 0x16 */ EMPTY }, {/* 0x17 */ EMPTY }, {/* 0x18 */ EMPTY }, {/* 0x19 */ EMPTY }, {/* 0x1a */ EMPTY }, {/* 0x1b */ EMPTY }, {/* 0x1c */ EMPTY }, {/* 0x1d */ EMPTY }, {/* 0x1e */ EMPTY }, {/* 0x1f */ EMPTY }, {/* 0x20 */ EMPTY }, {/* 0x21 */ EMPTY }, {/* 0x22 */ EMPTY }, {/* 0x23 */ EMPTY }, {/* 0x24 */ EMPTY }, {/* 0x25 */ EMPTY }, {/* 0x26 */ EMPTY }, {/* 0x27 */ EMPTY }, {/* 0x28 */ EMPTY }, {/* 0x29 */ EMPTY }, { /* 0x2a */ "EUC-JP", DBIDX_EUC_JP, 1, ISO_2022_JP_SET_JIS208_78, sizeof (ISO_2022_JP_SET_JIS208_78) - 1U }, {/* 0x2b */ EMPTY }, {/* 0x2c */ EMPTY }, {/* 0x2d */ EMPTY }, {/* 0x2e */ EMPTY }, {/* 0x2f */ EMPTY }, {/* 0x30 */ EMPTY }, {/* 0x31 */ EMPTY }, {/* 0x32 */ EMPTY }, {/* 0x33 */ EMPTY }, {/* 0x34 */ EMPTY }, {/* 0x35 */ EMPTY }, {/* 0x36 */ EMPTY }, {/* 0x37 */ EMPTY }, {/* 0x38 */ EMPTY }, {/* 0x39 */ EMPTY }, { /* 0x3a */ "GB2312", DBIDX_GB2312, 1, ISO_2022_JP_SET_GB2312_80, sizeof (ISO_2022_JP_SET_GB2312_80) - 1U }, {/* 0x3b */ EMPTY }, {/* 0x3c */ EMPTY }, {/* 0x3d */ EMPTY }, {/* 0x3e */ EMPTY }, {/* 0x3f */ EMPTY }, {/* 0x40 */ EMPTY }, {/* 0x41 */ EMPTY }, {/* 0x42 */ EMPTY }, {/* 0x43 */ EMPTY }, {/* 0x44 */ EMPTY }, {/* 0x45 */ EMPTY }, {/* 0x46 */ EMPTY }, {/* 0x47 */ EMPTY }, {/* 0x48 */ EMPTY }, {/* 0x49 */ EMPTY }, {/* 0x4a */ EMPTY }, {/* 0x4b */ EMPTY }, {/* 0x4c */ EMPTY }, {/* 0x4d */ EMPTY }, {/* 0x4e */ EMPTY }, {/* 0x4f */ EMPTY }, {/* 0x50 */ EMPTY }, {/* 0x51 */ EMPTY }, {/* 0x52 */ EMPTY }, {/* 0x53 */ EMPTY }, {/* 0x54 */ EMPTY }, {/* 0x55 */ EMPTY }, {/* 0x56 */ EMPTY }, { /* 0x57 */ "EUC-JP", DBIDX_EUC_JP, 1, ISO_2022_JP_SET_JIS208_83, sizeof (ISO_2022_JP_SET_JIS208_83) - 1U }, {/* 0x58 */ EMPTY }, {/* 0x59 */ EMPTY }, {/* 0x5a */ EMPTY }, {/* 0x5b */ EMPTY }, {/* 0x5c */ EMPTY }, {/* 0x5d */ EMPTY }, {/* 0x5e */ EMPTY }, {/* 0x5f */ EMPTY }, {/* 0x60 */ EMPTY }, {/* 0x61 */ EMPTY }, {/* 0x62 */ EMPTY }, {/* 0x63 */ EMPTY }, { /* 0x64 */ "ISO-8859-1", DBIDX_ISO_8859_1, 0, ISO_2022_JP_SET_ISO_8859_1, sizeof (ISO_2022_JP_SET_ISO_8859_1) - 1U }, {/* 0x65 */ EMPTY }, {/* 0x66 */ EMPTY }, {/* 0x67 */ EMPTY }, {/* 0x68 */ EMPTY }, {/* 0x69 */ EMPTY }, {/* 0x6a */ EMPTY }, {/* 0x6b */ EMPTY }, {/* 0x6c */ EMPTY }, {/* 0x6d */ EMPTY }, {/* 0x6e */ EMPTY }, {/* 0x6f */ EMPTY }, {/* 0x70 */ EMPTY }, {/* 0x71 */ EMPTY }, {/* 0x72 */ EMPTY }, {/* 0x73 */ EMPTY }, {/* 0x74 */ EMPTY }, {/* 0x75 */ EMPTY }, {/* 0x76 */ EMPTY }, {/* 0x77 */ EMPTY }, {/* 0x78 */ EMPTY }, {/* 0x79 */ EMPTY }, {/* 0x7a */ EMPTY }, {/* 0x7b */ EMPTY }, {/* 0x7c */ EMPTY }, {/* 0x7d */ EMPTY }, { /* 0x7e */ "ISO-8859-7", DBIDX_ISO_8859_7, 0, ISO_2022_JP_SET_ISO_8859_7, sizeof (ISO_2022_JP_SET_ISO_8859_7) - 1U }, {/* 0x7f */ EMPTY }, {/* 0x80 */ EMPTY }, {/* 0x81 */ EMPTY }, {/* 0x82 */ EMPTY }, {/* 0x83 */ EMPTY }, {/* 0x84 */ EMPTY }, {/* 0x85 */ EMPTY }, {/* 0x86 */ EMPTY }, {/* 0x87 */ EMPTY }, {/* 0x88 */ EMPTY }, {/* 0x89 */ EMPTY }, {/* 0x8a */ EMPTY }, {/* 0x8b */ EMPTY }, {/* 0x8c */ EMPTY }, {/* 0x8d */ EMPTY }, {/* 0x8e */ EMPTY }, {/* 0x8f */ EMPTY }, {/* 0x90 */ EMPTY }, {/* 0x91 */ EMPTY }, {/* 0x92 */ EMPTY }, {/* 0x93 */ EMPTY }, {/* 0x94 */ EMPTY }, { /* 0x95 */ "EUC-KR", DBIDX_EUC_KR, 1, ISO_2022_JP_SET_KSC5601_87, sizeof (ISO_2022_JP_SET_KSC5601_87) - 1U }, {/* 0x96 */ EMPTY }, {/* 0x97 */ EMPTY }, {/* 0x98 */ EMPTY }, {/* 0x99 */ EMPTY }, {/* 0x9a */ EMPTY }, {/* 0x9b */ EMPTY }, {/* 0x9c */ EMPTY }, {/* 0x9d */ EMPTY }, {/* 0x9e */ EMPTY }, { /* 0x9f */ "EUC-JP", DBIDX_EUC_JP, 1, ISO_2022_JP_SET_JIS212_90, sizeof (ISO_2022_JP_SET_JIS212_90) - 1U }, {/* 0xa0 */ EMPTY }, {/* 0xa1 */ EMPTY }, {/* 0xa2 */ EMPTY }, {/* 0xa3 */ EMPTY }, {/* 0xa4 */ EMPTY }, {/* 0xa5 */ EMPTY }, {/* 0xa6 */ EMPTY }, {/* 0xa7 */ EMPTY }, {/* 0xa8 */ EMPTY }, {/* 0xa9 */ EMPTY }, {/* 0xaa */ EMPTY }, {/* 0xab */ EMPTY }, {/* 0xac */ EMPTY }, {/* 0xad */ EMPTY }, {/* 0xae */ EMPTY }, {/* 0xaf */ EMPTY }, {/* 0xb0 */ EMPTY }, {/* 0xb1 */ EMPTY }, {/* 0xb2 */ EMPTY }, {/* 0xb3 */ EMPTY }, {/* 0xb4 */ EMPTY }, {/* 0xb5 */ EMPTY }, {/* 0xb6 */ EMPTY }, {/* 0xb7 */ EMPTY }, {/* 0xb8 */ EMPTY }, {/* 0xb9 */ EMPTY }, {/* 0xba */ EMPTY }, {/* 0xbb */ EMPTY }, {/* 0xbc */ EMPTY }, {/* 0xbd */ EMPTY }, {/* 0xbe */ EMPTY }, {/* 0xbf */ EMPTY }, {/* 0xc0 */ EMPTY }, {/* 0xc1 */ EMPTY }, {/* 0xc2 */ EMPTY }, {/* 0xc3 */ EMPTY }, {/* 0xc4 */ EMPTY }, {/* 0xc5 */ EMPTY }, {/* 0xc6 */ EMPTY }, {/* 0xc7 */ EMPTY }, {/* 0xc8 */ EMPTY }, {/* 0xc9 */ EMPTY }, {/* 0xca */ EMPTY }, {/* 0xcb */ EMPTY }, {/* 0xcc */ EMPTY }, {/* 0xcd */ EMPTY }, {/* 0xce */ EMPTY }, {/* 0xcf */ EMPTY }, {/* 0xd0 */ EMPTY }, {/* 0xd1 */ EMPTY }, {/* 0xd2 */ EMPTY }, {/* 0xd3 */ EMPTY }, {/* 0xd4 */ EMPTY }, {/* 0xd5 */ EMPTY }, {/* 0xd6 */ EMPTY }, {/* 0xd7 */ EMPTY }, {/* 0xd8 */ EMPTY }, {/* 0xd9 */ EMPTY }, {/* 0xda */ EMPTY }, {/* 0xdb */ EMPTY }, {/* 0xdc */ EMPTY }, {/* 0xdd */ EMPTY }, {/* 0xde */ EMPTY }, {/* 0xdf */ EMPTY }, {/* 0xe0 */ EMPTY }, {/* 0xe1 */ EMPTY }, {/* 0xe2 */ EMPTY }, {/* 0xe3 */ EMPTY }, {/* 0xe4 */ EMPTY }, {/* 0xe5 */ EMPTY }, {/* 0xe6 */ EMPTY }, {/* 0xe7 */ EMPTY }, {/* 0xe8 */ EMPTY }, {/* 0xe9 */ EMPTY }, {/* 0xea */ EMPTY }, {/* 0xeb */ EMPTY }, {/* 0xec */ EMPTY }, {/* 0xed */ EMPTY }, {/* 0xee */ EMPTY }, {/* 0xef */ EMPTY }, {/* 0xf0 */ EMPTY }, {/* 0xf1 */ EMPTY }, {/* 0xf2 */ EMPTY }, {/* 0xf3 */ EMPTY }, {/* 0xf4 */ EMPTY }, {/* 0xf5 */ EMPTY }, {/* 0xf6 */ EMPTY }, {/* 0xf7 */ EMPTY }, {/* 0xf8 */ EMPTY }, {/* 0xf9 */ EMPTY }, {/* 0xfa */ EMPTY }, {/* 0xfb */ EMPTY }, {/* 0xfc */ EMPTY }, {/* 0xfd */ EMPTY }, {/* 0xfe */ EMPTY }, {/* 0xff */ EMPTY } }; // Mapping pointer - size of mapping - canonical name static __rw_db_map_t __rw_db_map [32] = { { 0, 0, __rw_empty }, { 0, 0, "ANSI_X3.4-1968" }, { 0, 0, "ISO-8859-1" }, { 0, 0, "ISO-8859-2" }, { 0, 0, "ISO-8859-3" }, { 0, 0, "ISO-8859-4" }, { 0, 0, "ISO-8859-5" }, { 0, 0, "ISO-8859-6" }, { 0, 0, "ISO-8859-7" }, { 0, 0, "ISO-8859-8" }, { 0, 0, "EUC-JP" }, { 0, 0, "EUC-KR" }, { 0, 0, "GB2312" }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty }, { 0, 0, __rw_empty } }; // Retrieves the type of the encoding as indicated by the name int __rw_encoding_from_name (const char* name) { _RWSTD_ASSERT (0 != name); static const char pfx [] = "ISO-2022-"; if (0 != strncmp (pfx, name, sizeof pfx - 1U)) return stateless; name += sizeof pfx - 1U; if (0 == strcmp (name, "JP-2")) { return iso2022_jp2; } if (0 == strcmp (name, "JP")) { return iso2022_jp; } if (0 == strcmp (name, "KR")) { return iso2022_kr; } if (0 == strcmp (name, "CN")) { return iso2022_cn; } return stateless; } // Array of ISO-2022 encoding states; the array has a default size of 256 // entries; the declaration of the array is guarded for size // // The usage of the structs in the array: // - the struct "allocated" are marked as used; // - the index of the struct in the array is stored in the std::mbstate_t // struct used in codecvt facet; // - the std::mbstate_t values are shifted from the real iso2022_state // struct index by one so that a value of zero in an std::mbstate_t // variable indicates a new conversion for which a state has to be // allocated #if _RWSTD_MBSTATE_T_SIZE == 1 # define ISO_2022_ARRAY_SIZE 255 # define ISO_2022_STATE_INDEX_T unsigned char #else # define ISO_2022_ARRAY_SIZE 511 # define ISO_2022_STATE_INDEX_T unsigned short #endif // array of available states (limits the number of distinct mbstate_t // objects with unique value that may be simultaneously valid) static __rw_iso2022_state_t __rw_iso2022_states [ISO_2022_ARRAY_SIZE]; // returns an index in the array of state structures or -1 if none // is available; ISO-2022-JP and ISO-2022-JP-2 assume different // initializations static inline int __rw_allocate_state () { _RWSTD_MT_CLASS_GUARD (__rw_iso2022_state_t); for (int i = 0; i < ISO_2022_ARRAY_SIZE; i++) if (__rw_iso2022_states [i].used == 0) { __rw_iso2022_states [i].used = 1; return i; } return -1; } // deallocates state and makes it available for future conversions // if `initial_only' is non-zero suceeds only if the `iso_state' // argument represents an initial shift state static inline void __rw_deallocate_state (__rw_iso2022_state_t &iso_state, _RWSTD_C::mbstate_t &state, bool initial_only) { _RWSTD_MT_CLASS_GUARD (__rw_iso2022_state_t); if (initial_only) { // test the state object for return to initial shift state const int i = iso_state.gl_map - 1; _RWSTD_ASSERT (i >= 0 && i < 4); if ( iso_state.g_map [i] != CHSET_ANSI_X_3_4_1968 || iso_state.sshift2 || iso_state.sshift3) return; // proceed only if `iostate' is in an initial shift state } // zero out both structures memset (&state, 0, sizeof state); memset (&iso_state, 0, sizeof iso_state); } static __rw_iso2022_state_t* __rw_get_iso2022_state (_RWSTD_C::mbstate_t& state, int enc) { __rw_iso2022_state_t* pstate = 0; // retrieve the array index ISO_2022_STATE_INDEX_T* pc = _RWSTD_REINTERPRET_CAST (ISO_2022_STATE_INDEX_T*, &state); int n = *pc; _RWSTD_ASSERT(n >= 0 && n <= ISO_2022_ARRAY_SIZE); // a value of zero in std::mbstate_t indicates conversion anew, // calling for a state allocation if (n == 0) { n = __rw_allocate_state (); // the case when the allocation was not possible if (n == -1) return pstate; // store the state index *pc = _RWSTD_STATIC_CAST (ISO_2022_STATE_INDEX_T, n + 1); } else n--; // store the pointer to the state object pstate = &__rw_iso2022_states [n]; // initialize the state according to the encoding type switch (enc) { case iso2022_jp: case iso2022_jp2: pstate->g_map [0] = CHSET_ANSI_X_3_4_1968; pstate->gl_map = 1; break; default: break; } return pstate; } // Retrieval of the character set's registration number; the code // designator values overlap (they are, however, distinct in each category) static inline unsigned char __rw_sb94_encoding_reg (unsigned char c) { unsigned char reg = 0; switch (c) { case 0x42: reg = CHSET_ANSI_X_3_4_1968; /* ANSI X-3.4/1968 */ break; case 0x49: reg = CHSET_JIS_X_0201_KANA; /* JIS X 0201 Katakana */ break; case 0x4a: reg = CHSET_JIS_X_0201_ROMAN; /* JIS X 0201 Roman */ break; } return reg; } static inline unsigned char __rw_sb96_encoding_reg (unsigned char c) { unsigned char reg = 0; switch (c) { case 0x41: reg = CHSET_ISO_8859_1; /* ISO-8859-1 */ break; case 0x46: reg = CHSET_ISO_8859_7; /* ISO-8859-7 */ break; } return reg; } static inline unsigned char __rw_mb94_encoding_reg (unsigned char c) { unsigned char reg = 0; switch (c) { case 0x40: reg = CHSET_JIS_X_0208_1978; /* JIS X 0208-1978 */ break; case 0x41: reg = CHSET_GB2312_1980; /* GB 2312-80 */ break; case 0x42: reg = CHSET_JIS_X_0208_1983; /* JIS X 0208-1983 */ break; case 0x43: reg = CHSET_KSC_5601_1987; /* KSC 5601 Korean */ break; case 0x44: reg = CHSET_JIS_X_0212_1990; /* JIS X 0212-1990 */ break; } return reg; } static inline unsigned char __rw_mb96_encoding_reg (unsigned char) { return 0; } // Retrieves the code registration associated with a particular encoding class // and a particular character set designator in that class static inline unsigned char __rw_get_encoding_reg (__rw_codeset_type_t type, unsigned char code) { switch (type) { case sb94: return __rw_sb94_encoding_reg (code); case sb96: return __rw_sb96_encoding_reg (code); case mb94: return __rw_mb94_encoding_reg (code); case mb96: return __rw_mb96_encoding_reg (code); } return 0; } #if 0 // unused // Retrieval of the character set's registration name static inline const char* __rw_get_encoding_name (unsigned char n) { return (__rw_chset_map [n].name [0] == 0)?0:__rw_chset_map [n].name; } // A way of mapping a combination type-code to an index in the array of // codecvt databases mappings. The databases mappings are installed in // the array of mappings like this: // 1 - ANSI.X-3.4-1968 // 2-9 - ISO-8859-1, 2, 3, 4, 5, 6, 7, 8 // 10 - EUC-JP // 11 - EUC-KR // 12 - GB2312-1980 static inline unsigned char __rw_get_encoding_dbindex (__rw_codeset_type_t t, unsigned char code) { unsigned char reg = __rw_get_encoding_reg (t, code); if (reg == 0) return 0; return __rw_chset_map [reg].index; } #endif // 0/1 static inline const void* __rw_get_encoding_database (unsigned char n) { // if already mapped return it if (__rw_db_map [n].pv) return __rw_db_map [n].pv; // a wrong index would point to a struct bearing no name if (__rw_db_map [n].name [0] == 0) return 0; // if not, obtain it from __rw_get_facet_data int cat = __rw_get_cat ((__rw_facet::_C_wcodecvt_byname + 1) / 2); __rw_db_map [n].pv = __rw_get_facet_data (cat, __rw_db_map[n].size, 0, __rw_db_map [n].name); return __rw_db_map [n].pv; } // Insert designating sequence in the destination buffer; the encoding is // given by the last parameter and is currently one of the following: // - ISO_2022-JP // - ISO_2022-JP2 static _V3_LOCALE::codecvt_base::result __rw_iso2022jp_designate (__rw_iso2022_state_t& state, char*& to, char* to_end, unsigned char reg, int enc) { // length of a designating sequence in ISO-2022-JP and // ISO-2022-JP-2 is 3 or 4 elements _RWSTD_SIZE_T len = sizeof (ISO_2022_JP_SET_ASCII) - 1U; _RWSTD_SIZE_T sslen = 0; // register designation bool g2 = false; const char* esc = 0; const char* ss = 0; switch (reg) { case CHSET_ANSI_X_3_4_1968: esc = ISO_2022_JP_SET_ASCII; break; case CHSET_JIS_X_0201_ROMAN: esc = ISO_2022_JP_SET_JIS201_ROMAN; break; case CHSET_JIS_X_0208_1978: esc = ISO_2022_JP_SET_JIS208_78; break; case CHSET_JIS_X_0208_1983: esc = ISO_2022_JP_SET_JIS208_83; break; case CHSET_GB2312_1980: esc = (enc == iso2022_jp)?0:ISO_2022_JP_SET_GB2312_80; break; case CHSET_ISO_8859_1: esc = (enc == iso2022_jp)?0:ISO_2022_JP_SET_ISO_8859_1; ss = ISO_2022_JP_SET_SS2; sslen = sizeof (ISO_2022_JP_SET_SS2) - 1U; g2 = true; break; case CHSET_ISO_8859_7: esc = (enc == iso2022_jp)?0:ISO_2022_JP_SET_ISO_8859_7; ss = ISO_2022_JP_SET_SS2; sslen = sizeof (ISO_2022_JP_SET_SS2) - 1U; g2 = true; break; // only JIS X 0212-1990 and KSC5601-1987 are 4 elements long case CHSET_JIS_X_0212_1990: if (enc != iso2022_jp) { esc = ISO_2022_JP_SET_JIS212_90; len = sizeof (ISO_2022_JP_SET_JIS212_90) - 1U; } break; case CHSET_KSC_5601_1987: if (enc != iso2022_jp) { esc = ISO_2022_JP_SET_KSC5601_87; len = sizeof (ISO_2022_JP_SET_KSC5601_87) - 1U; } break; default: return CODECVT_ERROR; } if (g2) { if (state.sshift2 == 1) { // there is already a correct designation and a single // shift function inserted in the destination buffer return CODECVT_OK; } // insert the designation if (reg != state.g_map [2]) { // FIXME - check correctness if (_RWSTD_STATIC_CAST (_RWSTD_SIZE_T, to_end - to) < len) return CODECVT_PARTIAL; memcpy (to, esc, len); to += len; // adjust the state state.g_map [2] = reg; } // insert the single shift function // FIXME - check correctness if (_RWSTD_STATIC_CAST (_RWSTD_SIZE_T, to_end - to) < len) return CODECVT_PARTIAL; memcpy (to, ss, sslen); to += sslen; // adjust the single shift indicator state.sshift2 = 1; } else { // FIXME - check correctness if (_RWSTD_STATIC_CAST (_RWSTD_SIZE_T, to_end - to) < len) return CODECVT_PARTIAL; memcpy (to, esc, len); to += len; // adjust the state state.g_map [0] = reg; state.gl_map = 1; state.shift_state = __rw_chset_map [reg].width; } return CODECVT_OK; } // Process one escape sequence in an ISO-2022 stream; // // Upon entry: // - from - points to the first byte after the ESCAPE_CHAR indicator; // - enc - encoding type. static _V3_LOCALE::codecvt_base::result __rw_iso2022_escape (__rw_iso2022_state_t& state, const char*& from, const char* from_end, int enc) { // copy of source pointer const char* ps = from + 1; // test for end of sequence if (from_end == ps) return CODECVT_OK; __rw_codeset_type_t type = sb94; switch (*ps) { case ISO_2022_SET_SS2: // Single-Shift 2 invokes G2 in GL for one character; // adjust the source pointer... from = ++ps; // ...and set the single-shift 2 flag in the state structure state.sshift2 = 1; return CODECVT_OK; case ISO_2022_SET_SB94_G0: type = sb94; break; case ISO_2022_SET_SB96_G2: type = sb96; break; case ISO_2022_SET_MB: type = mb94; // test for end of sequence if (from_end == ps + 1) return CODECVT_OK; // advance one more; this designation is 4 bytes long if (*(ps + 1) == ISO_2022_SET_MB94_G0) ps++; break; default: return CODECVT_ERROR; } if (from_end == ++ps) return CODECVT_OK; // retrieve the registration code and store the state const unsigned char reg = __rw_get_encoding_reg (type, *ps++); if (!reg) return CODECVT_ERROR; // check the registration code returned by the function above if (enc == iso2022_jp && (reg == CHSET_JIS_X_0212_1990 || reg == CHSET_GB2312_1980 || reg == CHSET_KSC_5601_1987 || reg == CHSET_ISO_8859_1 || reg == CHSET_ISO_8859_7)) { return CODECVT_ERROR; } // designation is always in G0 unless the type is sb96 state.g_map [type == sb96 ? 2 : 0] = reg; // however, the invocation is always in GL for ISO-2022-xxx!! state.gl_map = 1; state.shift_state = __rw_chset_map [reg].width; // adjust the source pointer from = ps; return CODECVT_OK; } /****************************************************************************/ // ISO-2022-JP conversion from ANSI_X3.4-1968 // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_ascii_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { // the registration unsigned char reg = CHSET_ANSI_X_3_4_1968; unsigned int width = __rw_chset_map [reg].width + 1; _RWSTD_ASSERT (from_end-from >= int(width)); _RWSTD_UNUSED (from_end); _V3_LOCALE::codecvt_base::result ret; // check the designation sequence if (state.g_map [0] != reg) { char* pd = to; // insert a designation sequence in this place ret = __rw_iso2022jp_designate (state, pd, to_end, reg, enc); if (ret != CODECVT_OK) return ret; state.gl_map = 1; state.g_map [0] = reg; state.shift_state = __rw_chset_map [reg].width; // adjust destination pointer to = pd; if (to == to_end) return ret; } // FIXME - check the validity of this test if (to_end - to < int (width)) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width > 1) *to++ = char (*from++ & 0x7f); return CODECVT_OK; } // ISO-2022-JP conversion from KSC5601-1987 // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_ksc5601_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { // the registration unsigned char reg = CHSET_KSC_5601_1987; unsigned int width = __rw_chset_map [reg].width + 1; _RWSTD_ASSERT(from_end-from >= int(width)); _RWSTD_UNUSED(from_end); _V3_LOCALE::codecvt_base::result ret; // check the designation sequence if (state.g_map [0] != reg) { char* pd = to; // insert a designation sequence in this place ret = __rw_iso2022jp_designate (state, pd, to_end, reg, enc); if (ret != CODECVT_OK) return ret; state.gl_map = 1; state.g_map [0] = reg; state.shift_state = __rw_chset_map [reg].width; // adjust destination pointer to = pd; if (to == to_end) return ret; } // FIXME - check the validity of this test if (to_end - to < int (width)) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width > 1) *to++ = char (*from++ & 0x7f); return CODECVT_OK; } // ISO-2022-JP conversion from GB2312-1980 // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_gb2312_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { // the registration unsigned char reg = CHSET_GB2312_1980; unsigned int width = __rw_chset_map [reg].width + 1; _RWSTD_ASSERT(from_end-from >= int(width)); _RWSTD_UNUSED(from_end); _V3_LOCALE::codecvt_base::result ret; // check the designation sequence if (state.g_map [0] != reg) { char* pd = to; // insert a designation sequence in this place ret = __rw_iso2022jp_designate (state, pd, to_end, reg, enc); if (ret != CODECVT_OK) return ret; state.gl_map = 1; state.g_map [0] = reg; state.shift_state = __rw_chset_map [reg].width; // adjust destination pointer to = pd; if (to == to_end) return ret; } // FIXME - check the validity of this test if (to_end - to < int(width)) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width > 1) *to++ = char (*from++ & 0x7f); return CODECVT_OK; } // ISO-2022-JP conversion from ISO-8859-7 // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_iso88597_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { // the registration unsigned char reg2 = CHSET_ISO_8859_7; unsigned int width2 = __rw_chset_map [reg2].width + 1; _RWSTD_ASSERT(from_end-from >= int(width2)); _RWSTD_UNUSED(from_end); _V3_LOCALE::codecvt_base::result ret; // always call designate for this one; designation will at least insert a // single shift function in the destination buffer ret = __rw_iso2022jp_designate (state, to, to_end, reg2, enc); if (ret != CODECVT_OK) return ret; // adjust the G2 designation state.g_map [2] = reg2; // FIXME - check the validity of this test if (to_end - to < int (width2)) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width2 > 1) *to++ = char (*from++ & 0x7f); // clear the single shift functions state.sshift2 = state.sshift3 = 0; return CODECVT_OK; } // ISO-2022-JP conversion from ISO-8859-1 // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_iso88591_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { // the registration unsigned char reg2 = CHSET_ISO_8859_1; unsigned int width2 = __rw_chset_map [reg2].width + 1; _RWSTD_ASSERT(from_end-from >= int(width2)); _RWSTD_UNUSED(from_end); _V3_LOCALE::codecvt_base::result ret; // always call designate for this one; designation will at least insert a // single shift function in the destination buffer ret = __rw_iso2022jp_designate (state, to, to_end, reg2, enc); if (ret != CODECVT_OK) return ret; // adjust the G2 designation state.g_map [2] = reg2; // FIXME - check the validity of this test if (to_end - to < int (width2)) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width2 > 1) *to++ = char (*from++ & 0x7f); // clear the single shift functions state.sshift2 = state.sshift3 = 0; return CODECVT_OK; } // ISO-2022-JP conversion from packed EUC-JP // Convert one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_eucjp_to_iso2022 (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, char* to_end, int enc) { int width = 0; unsigned char reg = 0; _V3_LOCALE::codecvt_base::result ret; // convert and store the encoding unsigned char c = *_RWSTD_REINTERPRET_CAST(const unsigned char*, from); switch (c) { case 0x8e: // JIS X 0201 Katakana reg = CHSET_JIS_X_0201_KANA; from++; break; case 0x8f: // JIS X 0212 1990 reg = CHSET_JIS_X_0212_1990; from++; break; default: if (c > 0x80) { // JIS X 0208-1978 reg = CHSET_JIS_X_0208_1978; } else { // JIS X 0201 Roman/ANSI_X3.4-1968 reg = CHSET_ANSI_X_3_4_1968; } break; } // width in elements of the ISO-2022 output width = __rw_chset_map [reg].width + 1; // check the designation sequence if (state.g_map [0] != reg) { char* pd = to; // insert a designation sequence in this place ret = __rw_iso2022jp_designate (state, pd, to_end, reg, enc); if (ret != CODECVT_OK) return ret; // adjust destination pointer to = pd; state.gl_map = 1; state.g_map [0] = reg; state.shift_state = __rw_chset_map [reg].width; if (to == to_end) return ret; } // insert the character in the destination buffer if (width > from_end - from) return CODECVT_OK; // FIXME - check the validity of this test if (to_end - to < __rw_chset_map[reg].width) return CODECVT_PARTIAL; *to++ = char (*from++ & 0x7f); if (width > 1) *to++ = char (*from++ & 0x7f); return CODECVT_OK; } // ISO-2022-JP conversion to GB2312-1980 // Converts one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static inline _V3_LOCALE::codecvt_base::result __rw_iso2022_to_gb2312 (const char*& from, const char* from_end, char*& to, int /* reg */, int /* enc */) { _V3_LOCALE::codecvt_base::result res = CODECVT_OK; if (from_end - from < GB2312_CHAR_LEN) return res; // store the destination bytes after setting the highest bit *to++ = char (*from++ | 0x80); *to++ = char (*from++ | 0x80); return res; } // ISO-2022-JP conversion to KSC2312 // Converts one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static inline _V3_LOCALE::codecvt_base::result __rw_iso2022_to_ksc5601 (const char*& from, const char* from_end, char*& to, int /* reg */, int /* enc */) { _V3_LOCALE::codecvt_base::result res = CODECVT_OK; if (from_end - from < KSC5601_CHAR_LEN) return res; // store the destination bytes after setting the highest bit *to++ = char (*from++ | 0x80); *to++ = char (*from++ | 0x80); return res; } // ISO-2022-JP conversion to ISO-8859-1 // Converts one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static inline _V3_LOCALE::codecvt_base::result __rw_iso2022_to_iso88591 (const char*& from, const char* from_end, char*& to, int /* reg */, int /* enc */) { _V3_LOCALE::codecvt_base::result res = CODECVT_OK; if (from_end - from < ISO_8859_1_CHAR_LEN) return res; // store the destination bytes after setting the highest bit *to++ = char (*from++ | 0x80); return res; } // ISO-2022-JP conversion to ISO-8859-7 // Converts one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static inline _V3_LOCALE::codecvt_base::result __rw_iso2022_to_iso88597 (const char*& from, const char* from_end, char*& to, int /* reg */, int /* enc */) { _V3_LOCALE::codecvt_base::result res = CODECVT_OK; if (from_end - from < ISO_8859_7_CHAR_LEN) return res; // store the destination bytes after setting the highest bit *to++ = char (*from++ | 0x80); return res; } // ISO-2022-JP conversion to packed EUC-JP // Converts one character. // Returns: // _V3_LOCALE::codecvt_base::ok in case the conversion succeeded // _V3_LOCALE::codecvt_base::partial for partial conversions // _V3_LOCALE::codecvt_base::error erroneous sequence static _V3_LOCALE::codecvt_base::result __rw_iso2022_to_eucjp (const char*& from, const char* from_end, char*& to, int reg, int enc) { // encoding registration number int width = __rw_chset_map [reg].width + 1; // test the length of the input if (from_end - from < width) return CODECVT_OK; _V3_LOCALE::codecvt_base::result res = CODECVT_OK; // from either the ANSI_X3.4-1968 or JIS X 0201 Roman or JIS X 0201 Kana switch (reg) { case CHSET_ANSI_X_3_4_1968: case CHSET_JIS_X_0201_ROMAN: // these character sets encode on one byte in EUC-JP *to++ = *from++; break; case CHSET_JIS_X_0208_1978: case CHSET_JIS_X_0208_1983: *to++ = char (*from++ | 0x80); *to++ = char (*from++ | 0x80); break; // The following belong to ISO-2022-JP-2 case CHSET_JIS_X_0201_KANA: if (enc == iso2022_jp) { res = CODECVT_ERROR; break; } // this character set encode on two bytes in EUC-JP *to++ = '\x8e'; *to++ = char (*from++ | 0x80); break; case CHSET_JIS_X_0212_1990: if (enc == iso2022_jp) { res = CODECVT_ERROR; break; } *to++ = '\x8f'; *to++ = char (*from++ | 0x80); *to++ = char (*from++ | 0x80); break; default: res = CODECVT_ERROR; break; } return res; } // Converts one character from the external representation to the // intermediary encoding that is later used in retrieving the internal // representation of that character static _V3_LOCALE::codecvt_base::result __rw_iso2022_to_interm (__rw_iso2022_state_t& state, const char*& from, const char* from_end, char*& to, unsigned char& reg, int enc) { _V3_LOCALE::codecvt_base::result res = CODECVT_OK; bool first = true; for (; *from == ESCAPE_CHAR; first = false) { // clear up the single shift functions set before if (first == false) state.sshift2 = state.sshift3 = 0; const char* tmp = from; res = __rw_iso2022_escape (state, from, from_end, enc); // the detected escape sequence has not been consumed because it // was incomplete or an error has been returned if (res != CODECVT_OK || tmp == from) return res; } if (*from <= 0x20) { ;// FIXME - process control characters } // if any single shift sequence has been selected, then clear up the // flag and adjust the registration code accordingly if (state.sshift2 == 1) { state.sshift2 = 0; // registration code switches to whatever code has been selected // in G2 (one of ISO-8859-1 and ISO-8859-7) reg = state.g_map [2]; } else { // refresh the reg value reg = state.g_map [0]; } // ISO-2022-JP and ISO-2022-JP-2 use G0 exclusively switch (reg) { case CHSET_ANSI_X_3_4_1968: case CHSET_JIS_X_0201_KANA: case CHSET_JIS_X_0201_ROMAN: case CHSET_JIS_X_0208_1978: case CHSET_JIS_X_0208_1983: case CHSET_JIS_X_0212_1990: res = __rw_iso2022_to_eucjp (from, from_end, to, reg, enc); break; case CHSET_GB2312_1980: res = __rw_iso2022_to_gb2312 (from, from_end, to, reg, enc); break; case CHSET_KSC_5601_1987: res = __rw_iso2022_to_ksc5601 (from, from_end, to, reg, enc); break; case CHSET_ISO_8859_1: res = __rw_iso2022_to_iso88591 (from, from_end, to, reg, enc); break; case CHSET_ISO_8859_7: res = __rw_iso2022_to_iso88597 (from, from_end, to, reg, enc); break; } // clear any single shift functions, if any state.sshift2 = state.sshift3 = 0; return CODECVT_OK; } static _V3_LOCALE::codecvt_base::result __rw_ucs4_to_eucjp (const wchar_t*& from, const wchar_t* from_end, char*& to, char* to_end, const _RW::__rw_codecvt_t* impl) { typedef unsigned char UChar; // "impl" as raw pointer to unsigned ints const char* impl_raw = _RWSTD_REINTERPRET_CAST(const char*,impl); // utf8 temporary buffer char tmp [_UTF8_MB_CUR_MAX]; char* ptmp = tmp; // tbls will point to the first lookup table const unsigned int* tbls = impl->utf8_to_ext_tab ();; const unsigned int* tbl = tbls; _RWSTD_ASSERT(tbls); if (from == from_end || to == to_end) return CODECVT_OK; _RWSTD_SIZE_T ret = __rw_itoutf8 (*from, ptmp); unsigned int wc = tbl [UChar (*ptmp)]; while (wc & 0x80000000) { if (wc == _RWSTD_UINT_MAX) // FIXME - this is an error condition return CODECVT_ERROR; if (ret-- == 0) // FIXME - this is an error condition return CODECVT_ERROR; // get next table wc &= 0x7fffffff; tbl = tbls + 256 * wc; wc = tbl [UChar (*++ptmp)]; } // store the encoding sequence at destination _RWSTD_SIZE_T offset = wc + sizeof (_RW::__rw_codecvt_t); while (impl_raw [offset]) { if (to == to_end) return CODECVT_PARTIAL; else *to++ = impl_raw [offset++]; } from++; return CODECVT_OK; } static unsigned char /* registration code */ __rw_ucs4_to_interm ( const wchar_t*& from, char*& to) { typedef unsigned char UChar; static const struct { UChar db; UChar reg; } db_array [] = { { DBIDX_ANSI_X_3_4_1968, CHSET_ANSI_X_3_4_1968 }, { DBIDX_EUC_JP , CHSET_JIS_X_0212_1990 }, { DBIDX_EUC_KR , CHSET_KSC_5601_1987 }, { DBIDX_GB2312 , CHSET_GB2312_1980 }, { DBIDX_ISO_8859_7 , CHSET_ISO_8859_7 }, { DBIDX_ISO_8859_1 , CHSET_ISO_8859_1 } }; // utf8 temporary buffer char tmp [_UTF8_MB_CUR_MAX]; for (int i = 0; i < int(sizeof (db_array)/sizeof (unsigned char)); i++) { char* ptmp = tmp; // obtain the database mapping const void* pdb = __rw_get_encoding_database (db_array [i].db); if (pdb == 0) continue; // cast the database map pointer to the correct type const _RW::__rw_codecvt_t* impl = _RWSTD_STATIC_CAST(const _RW::__rw_codecvt_t*, pdb); // the "raw access" pointer used in finding the external repr. const char* impl_raw = _RWSTD_REINTERPRET_CAST(const char*,impl); // tbls will point to the first lookup table const unsigned int* tbls = impl->utf8_to_ext_tab (); const unsigned int* tbl = tbls; _RWSTD_ASSERT(tbls); _RWSTD_SIZE_T ret = __rw_itoutf8 (*from, ptmp); bool success = true; unsigned int wc = tbl [UChar (*ptmp)]; while (wc & 0x80000000) { if (wc == _RWSTD_UINT_MAX || ret-- == 0) { success = false; break; } // get next table wc &= 0x7fffffff; tbl = tbls + 256 * wc; wc = tbl [UChar (*++ptmp)]; } // continue on the next lookup if (!success) continue; // store the encoding sequence at destination _RWSTD_SIZE_T offset = wc + sizeof (_RW::__rw_codecvt_t); while (impl_raw [offset]) *to++ = impl_raw [offset++]; // advance source pointer to next position from++; // Find the registration code of the encoding and return it return db_array [i].reg; } // invalid registration code return 0; } // does the conversion of one character to internal representation static _V3_LOCALE::codecvt_base::result __rw_iso2022_to_ucs4 (_RWSTD_C::mbstate_t& state, __rw_iso2022_state_t* iso_state, const char*& from, const char* from_end, wchar_t*& to, wchar_t* /* to_end */, int enc) { _V3_LOCALE::codecvt_base::result res; // the registration code of the character set unsigned char reg = iso_state->g_map [0]; int width = iso_state->shift_state + 1; // test input width if (from_end - from < width) { // test and deallocate state if (iso_state->g_map [0] == CHSET_ANSI_X_3_4_1968) __rw_deallocate_state (*iso_state, state, false); return CODECVT_OK; } // temporary buffer to accomodate the intermediary encoding char tmp_buffer [8]; char* tmp_to = tmp_buffer; char* tmp_to_end; const char* from_next = from; // convert one character at a time and note that the registration // code is actually modified by the following call in the case // of single shift functions res = __rw_iso2022_to_interm (*iso_state, from_next, from_end, tmp_to, reg, enc); if (res != CODECVT_OK || (from_next == from && tmp_to == tmp_buffer)) { __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return res; } // the input sequence started with an escape sequence if (tmp_to == tmp_buffer) { from = from_next; return res; } tmp_to_end = tmp_to; tmp_to = tmp_buffer; // get the proper database for decoding input const void* pdb = __rw_get_encoding_database (__rw_chset_map [reg].index); if (pdb == 0) { __rw_deallocate_state (*iso_state, state, false); return CODECVT_ERROR; } const _RW::__rw_codecvt_t* pimpl = _RWSTD_STATIC_CAST(const _RW::__rw_codecvt_t*, pdb); // retrieve the lookup table start const unsigned int* tbls = pimpl->n_to_w_tab (); const unsigned int* tbl = tbls; _RWSTD_ASSERT(tbls); // wider character representations will be looked upon in the // database tables unsigned int wc = tbl [*(unsigned char*)tmp_to]; while (wc & 0x80000000) { if (wc == _RWSTD_UINT_MAX) { __rw_deallocate_state (*iso_state, state, false); return CODECVT_ERROR; } // wc is table index tbl = tbls + 256*(wc & 0x7fffffff); tmp_to++; // we have reached end of EUC-JP temporary buffer and we found // here an incomplete sequence; the incomplete sequence here // is an error if (tmp_to == tmp_to_end) { __rw_deallocate_state (*iso_state, state, false); return CODECVT_ERROR; } wc = tbl [*(unsigned char*)tmp_to]; } // update source pointer and store the value at destination from = from_next; *to++ = pimpl->get_ucs4_at_offset(wc); return CODECVT_OK; } /****************************************************************************/ // Conversion from ISO-2022-JP to UCS-4 _V3_LOCALE::codecvt_base::result __rw_iso2022jp_do_in (_RWSTD_C::mbstate_t& state, const char*& from, const char* from_end, wchar_t*& to, wchar_t* to_end) { // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; // Loop until the source buffer is consumed, an error occurs, or // the destination buffer reaches capacity const char* from_next = from; wchar_t* to_next = to; while (from_end - from && to_end - to) { // operation result _V3_LOCALE::codecvt_base::result res; res = __rw_iso2022_to_ucs4 (state, iso_state, from_next, from_end, to_next, to_end, iso2022_jp); if (res != CODECVT_OK) return res; // an ok result with no conversion if (res == CODECVT_OK && from_next == from && to_next == to) return res; from = from_next; to = to_next; } // deallocate state if the conversion has gone back to initial state __rw_deallocate_state (*iso_state, state, true); return CODECVT_OK; } // Conversion from UCS-4 to ISO-2022-JP _V3_LOCALE::codecvt_base::result __rw_iso2022jp_do_out (_RWSTD_C::mbstate_t& state, const wchar_t*& from, const wchar_t* from_end, char*& to, char* to_end) { // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; // destination buffer to accomodate the EUC-JP encoding char euc_buffer [8]; // use the EUC-JP database for a full lookup const void* pdb = __rw_get_encoding_database (DBIDX_EUC_JP); if (pdb == 0){ __rw_deallocate_state (*iso_state, state, false); return CODECVT_ERROR; } const _RW::__rw_codecvt_t* pimpl = _RWSTD_STATIC_CAST(const _RW::__rw_codecvt_t*, pdb); _RWSTD_ASSERT(pimpl); // Loop until the source buffer is consumed, an error occurs, or // the destination buffer reaches capacity while (from_end - from && to_end - to) { _V3_LOCALE::codecvt_base::result res; // convert the UCS-4 value to EUC-JP const wchar_t* ps = from; const wchar_t* pse = from_end; char* euc = euc_buffer; char* euce = euc_buffer + 8; res = __rw_ucs4_to_eucjp (ps, pse, euc, euce, pimpl); if (res != CODECVT_OK || (ps == from && euc == euc_buffer)) { __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return res; } char* pd = to; // convert the EUC-JP value to ISO-2022 euce = euc; const char* ceuc = euc_buffer; res = __rw_eucjp_to_iso2022 (*iso_state, ceuc, euce, pd, to_end, iso2022_jp); if (res != CODECVT_OK || (ceuc == euc_buffer && pd == to)) { __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return res; } //adjust source pointer from = ps; to = pd; } // deallocate state if the conversion has gone back to // initial state __rw_deallocate_state (*iso_state, state, true); return CODECVT_OK; } _V3_LOCALE::codecvt_base::result __rw_iso2022jp_do_unshift (_RWSTD_C::mbstate_t& state, char*& to, char* to_end) { _V3_LOCALE::codecvt_base::result res = CODECVT_ERROR; // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return res; if (iso_state->g_map [iso_state->gl_map - 1] != CHSET_ANSI_X_3_4_1968) res = __rw_iso2022jp_designate (*iso_state, to, to_end, CHSET_ANSI_X_3_4_1968, iso2022_jp); else res = CODECVT_OK; // deallocate a state if the conversion has gone back to // initial shift state and operation succeeded, OR, if // the result is error __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return res; } _RWSTD_SIZE_T __rw_iso2022jp_do_length (_RWSTD_C::mbstate_t& state, const char* from, const char* from_end, _RWSTD_SIZE_T max) { _RWSTD_ASSERT(from <= from_end); // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; int ret = 0; _V3_LOCALE::codecvt_base::result res = CODECVT_OK; while (max && from_end - from) { while (*from == ESCAPE_CHAR) if (*from == ESCAPE_CHAR) { const char* tmp = from; res = __rw_iso2022_escape (*iso_state, from, from_end, iso2022_jp); if (res != CODECVT_OK || from == tmp) break; continue; } if (from_end - from < int(iso_state->shift_state) + 1) break; ret++, max--; from += iso_state->shift_state + 1; } // deallocate a state if the conversion has gone back to initial shift // state __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return ret; } _RWSTD_SIZE_T __rw_iso2022jp_do_max_length () { return 2; } int __rw_iso2022jp_do_encoding () { return -1; } bool __rw_iso2022jp_do_always_noconv () { return false; } /****************************************************************************/ // Conversion from ISO-2022-JP to UCS-4 _V3_LOCALE::codecvt_base::result __rw_iso2022jp2_do_in (_RWSTD_C::mbstate_t& state, const char*& from, const char* from_end, wchar_t*& to, wchar_t* to_end) { // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; // Loop until the source buffer is consumed, an error occurs, or // the destination buffer reaches capacity while (from_end - from && to_end - to) { const char* from_next = from; wchar_t* to_next = to; // operation result _V3_LOCALE::codecvt_base::result res; res = __rw_iso2022_to_ucs4 (state, iso_state, from_next, from_end, to_next, to_end, iso2022_jp2); if (res != CODECVT_OK) return res; // an ok result with no conversion if (res == CODECVT_OK && from_next == from && to_next == to) return res; from = from_next; to = to_next; } // deallocate state if the conversion has gone back to initial state __rw_deallocate_state (*iso_state, state, true); return CODECVT_OK; } // Conversion from UCS-4 to ISO-2022-JP-2 _V3_LOCALE::codecvt_base::result __rw_iso2022jp2_do_out (_RWSTD_C::mbstate_t& state, const wchar_t*& from, const wchar_t* from_end, char*& to, char* to_end) { // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; // destination buffer to accomodate the intermediate encoding char tmp [8]; // Loop until the source buffer is consumed, an error occurs, or // the destination buffer reaches capacity while (from_end - from && to_end - to) { _V3_LOCALE::codecvt_base::result res; // convert the UCS-4 value to intermediary encoding const wchar_t* ps = from; char* tmps = tmp; char* tmpe = tmp + 8; unsigned char reg = __rw_ucs4_to_interm (ps, tmps); if (reg == 0) { // deallocate state __rw_deallocate_state (*iso_state, state, false); // error condition - none of the databases contained a mapping // of the character return CODECVT_ERROR; } char* pd = to; // convert the intermediary value to ISO-2022 tmpe = tmps; const char* ctmps = tmp; // the registration of the encoding dictates how the conversion is // to be performed further switch (reg) { case CHSET_ANSI_X_3_4_1968: res = __rw_ascii_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; case CHSET_JIS_X_0212_1990: res = __rw_eucjp_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; case CHSET_KSC_5601_1987: res = __rw_ksc5601_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; case CHSET_GB2312_1980: res = __rw_gb2312_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; case CHSET_ISO_8859_7: res = __rw_iso88597_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; case CHSET_ISO_8859_1: res = __rw_iso88591_to_iso2022 (*iso_state, ctmps, tmpe, pd, to_end, iso2022_jp2); break; default: return CODECVT_ERROR; } if (res != CODECVT_OK || (ctmps==tmp && pd==to)) { __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return res; } //adjust source pointer from = ps; to = pd; // after a successful insertion the single shift functions // must be cleared iso_state->sshift2 = iso_state->sshift3 = 0; } // deallocate state if the conversion has gone back to // initial state __rw_deallocate_state (*iso_state, state, true); return CODECVT_OK; } _V3_LOCALE::codecvt_base::result __rw_iso2022jp2_do_unshift (_RWSTD_C::mbstate_t& state, char*& to, char* to_end) { return __rw_iso2022jp_do_unshift (state, to, to_end); } _RWSTD_SIZE_T __rw_iso2022jp2_do_length (_RWSTD_C::mbstate_t& state, const char* from, const char* from_end, _RWSTD_SIZE_T max) { _RWSTD_ASSERT(from <= from_end); // the iso2022 state __rw_iso2022_state_t* iso_state = __rw_get_iso2022_state (state, iso2022_jp); if (iso_state == 0) return CODECVT_ERROR; int ret = 0; _V3_LOCALE::codecvt_base::result res = CODECVT_OK; while (max && from_end - from) { bool first = true; for (; *from == ESCAPE_CHAR; first = false) { // clear up the single shift functions set before if (first == false) iso_state->sshift2 = iso_state->sshift3 = 0; const char* tmp = from; res = __rw_iso2022_escape (*iso_state, from, from_end, iso2022_jp2); // the detected escape sequence has not been consumed because it // was incomplete if (res != CODECVT_OK || tmp == from) return ret; } if (*from <= 0x20) { ;// FIXME - process control characters } // the registration for all character sets other than the ISO's // is stored in the first register, G0. unsigned char reg = iso_state->g_map [0]; unsigned int width; if (iso_state->sshift2 == 1) { width = 1; } else { width = __rw_chset_map [reg].width + 1; } if (from_end - from < int (width)) break; ret++, max--; from += width; // clean up the single shift function iso_state->sshift2 = iso_state->sshift3 = 0; } // deallocate a state if the conversion has gone back to initial shift // state __rw_deallocate_state (*iso_state, state, CODECVT_ERROR != res); return ret; } _RWSTD_SIZE_T __rw_iso2022jp2_do_max_length () { return 2; } int __rw_iso2022jp2_do_encoding () { return -1; } bool __rw_iso2022jp2_do_always_noconv () { return false; } } // namespace __rw #endif // _RWSTD_NO_V3_LOCALE src/module.cc #include "module.h" #include "murmur3.h" using namespace Nan; using v8::Local; using v8::Object; using v8::FunctionTemplate; NAN_METHOD(murmur3) { uint8_t* buffer = nullptr; uint32_t size = 0; uint32_t bits = 32; if (info.Length() == 0) { info.GetReturnValue().Set(NewBuffer((char*) buffer, size) .ToLocalChecked()); return; } if (info.Length() == 2 && info[1]->IsNumber()) { bits = Nan::To(info[1]).FromJust(); if (bits != 32 && bits != 128) { ThrowError("Must be either 32 or 128 bits"); } } Local bufferObj = Nan::To(info[0]).ToLocalChecked(); buffer = (uint8_t*) node::Buffer::Data(bufferObj); size = node::Buffer::Length(bufferObj); const int hashbytes = bits / 8; uint8_t* output = new uint8_t[hashbytes]; memset(output, 0, hashbytes); switch (bits) { case 32: murmurHash3_x86_32(buffer, size, 0xcafebabe, output); break; case 128: murmurHash3_x64_128(buffer, size, 0xcafebabe, output); break; } info.GetReturnValue().Set( NewBuffer((char*) output, hashbytes).ToLocalChecked()); } NAN_MODULE_INIT(InitAll) { Set(target, New("murmur3").ToLocalChecked(), GetFunction(New(murmur3)).ToLocalChecked()); } NODE_MODULE(NativeExtension, InitAll) /*********************************************************************/ /* */ /* Nagoya Institute of Technology, Aichi, Japan, */ /* Nara Institute of Science and Technology, Nara, Japan */ /* and */ /* Carnegie Mellon University, Pittsburgh, PA */ /* Copyright (c) 2003-2004 */ /* All Rights Reserved. */ /* */ /* Permission is hereby granted, free of charge, to use and */ /* distribute this software and its documentation without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of this work, and to permit persons to whom this */ /* work is furnished to do so, subject to the following conditions: */ /* */ /* 1. The code must retain the above copyright notice, this list */ /* of conditions and the following disclaimer. */ /* 2. Any modifications must be clearly marked as such. */ /* 3. Original authors' names are not deleted. */ /* */ /* NAGOYA INSTITUTE OF TECHNOLOGY, NARA INSTITUTE OF SCIENCE AND */ /* TECHNOLOGY, CARNEGIE MELLON UNIVERSITY, AND THE CONTRIBUTORS TO */ /* THIS WORK DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, */ /* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, */ /* IN NO EVENT SHALL NAGOYA INSTITUTE OF TECHNOLOGY, NARA */ /* INSTITUTE OF SCIENCE AND TECHNOLOGY, CARNEGIE MELLON UNIVERSITY, */ /* NOR THE CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR */ /* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM */ /* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, */ /* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN */ /* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* */ /*********************************************************************/ /* */ /* Author : () */ /* Date : June 2004 */ /* */ /*-------------------------------------------------------------------*/ /* */ /* VQ with LBG Algorithm */ /* */ /*-------------------------------------------------------------------*/ #include #include #include #include #include "../include/fileio.h" #include "../include/option.h" #include "../include/voperate.h" #include "./vq_sub.h" typedef struct CONDITION_STRUCT { long dim; long sd; long cls; XBOOL float_flag; XBOOL msg_flag; XBOOL help_flag; } CONDITION; CONDITION cond = {25, 0, 1, XFALSE, XTRUE, XFALSE}; #define NUM_ARGFILE 2 ARGFILE argfile_struct[] = { {"[infile]", NULL}, {"[outlabel]", NULL}, }; #define NUM_OPTION 6 OPTION option_struct[] ={ {"-dim", NULL, "dimension of vector", "dim", NULL, TYPE_LONG, &cond.dim, XFALSE}, {"-sd", NULL, "start dim", "sd", NULL, TYPE_LONG, &cond.sd, XFALSE}, {"-cls", NULL, "codebook size", "cls", NULL, TYPE_LONG, &cond.cls, XFALSE}, {"-float", NULL, "float format", NULL, NULL, TYPE_BOOLEAN, &cond.float_flag, XFALSE}, {"-nmsg", NULL, "no message", NULL, NULL, TYPE_BOOLEAN, &cond.msg_flag, XFALSE}, {"-help", "-h", "display this message", NULL, NULL, TYPE_BOOLEAN, &cond.help_flag, XFALSE}, }; OPTIONS options_struct = { NULL, 1, NUM_OPTION, option_struct, NUM_ARGFILE, argfile_struct, }; // main int main(int argc, char *argv[]) { int i, fc = 0; int j, u, nts, ni, tmp; double data[1]; float fdata[1]; float *tmpfdata = NULL; char outf[MAX_MESSAGE] = ""; FILE *fpi, *fpo; struct codebook *cbook; struct sample smpl; struct analysis condana; // get program name options_struct.progname = xgetbasicname(argv[0]); // get option for (i = 1, fc = 0; i < argc; i++) if (getoption(argc, argv, &i, &options_struct) == UNKNOWN) getargfile(argv[i], &fc, &options_struct); // display message if (cond.help_flag == XTRUE) printhelp(options_struct, "VQ with LBG Algorithm"); if (fc != options_struct.num_file) printerr(options_struct, "not enough files"); cbook = (struct codebook *)malloc( 1 * sizeof(struct codebook) ); cbook->dim_s = (int)cond.sd; cbook->vecorder = (int)cond.dim; nts = cbook->vecorder; cbook->vecsize = (int)cond.cls; sprintf(outf, "%s%d.mat", options_struct.file[1].name, cbook->vecsize); condana.nts = nts; if (cond.msg_flag == XTRUE) { fprintf(stderr, "Input File: %s\n", options_struct.file[0].name); fprintf(stderr, "Output File: %s\n", outf); } if ((fpi = fopen(options_struct.file[0].name, "rb")) == NULL) { fprintf(stderr, "Can't open file: %s\n", options_struct.file[0].name); exit(1); } tmp = 0; if (cond.float_flag == XFALSE) { while (1 == fread(data, sizeof(double), 1, fpi)) tmp++; } else { while (1 == fread(fdata, sizeof(float), 1, fpi)) tmp++; } fseek(fpi, 0, SEEK_SET); ni = tmp / nts; if (tmp != ni * nts) { fprintf(stderr, "Error dimension [%d][%d]\n", ni, nts); exit(1); } if (cond.msg_flag == XTRUE) fprintf(stderr, "all vector[%d][%d]\n", ni, nts); if (cond.float_flag == XFALSE) { if (ni > MAXMEM / (int)sizeof(double) / nts) ni = MAXMEM / (int)sizeof(double) / nts; } else { if (ni > MAXMEM / (int)sizeof(float) / nts) ni = MAXMEM / (int)sizeof(float) / nts; } smpl.buff = dalloc(ni*nts); if (cond.float_flag == XFALSE) { for(i=0;ivpara, sizeof(double), cbook->vecsize * cbook->vecorder, fpo); fclose(fpo); } else { tmpfdata = falloc(cbook->vecsize * cbook->vecorder); tmp = cbook->vecsize * cbook->vecorder; lbg(&condana, cbook, &smpl, options_struct.file[1].name, cond.float_flag, cond.msg_flag); for (j = 0; j < tmp; j++) tmpfdata[j] = (float)cbook->vpara[j]; if ((fpo = fopen(outf, "wb")) == NULL) { fprintf(stderr, "Can't open file: %s\n", outf); exit(1); } fwrite(tmpfdata, sizeof(float), cbook->vecsize * cbook->vecorder, fpo); fclose(fpo); free(tmpfdata); tmpfdata = NULL; } if (cond.msg_flag == XTRUE) fprintf(stderr, "wrote %s\n", outf); // for(i=0; i < smpl.nfrms ; i++) // printf("lab[%d] = %d\n",i,cbook->vlab[i]); // memory free free_vqlabel(cbook); free(cbook); free(smpl.buff); if (cond.msg_flag == XTRUE) fprintf(stderr, "done\n"); return 0; } gzwz/weChatWeChat/widget.cpp #include "widget.h" #include "ui_widget.h" #include #include #include #include #include #include #include #include #include Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { setWindowTitle("微聊"); ui->setupUi(this); ui->password->setEchoMode(QLineEdit::Password); ui->errwidget->hide(); QSystemTrayIcon *s = new QSystemTrayIcon(this); s->setIcon(QIcon(":/images/img/2.ico")); s->show(); s->setToolTip("微聊"); //托盘图标激活 connect(s,QSystemTrayIcon::activated,this,activated); } Widget::~Widget() { delete ui; } void Widget::on_closeButton_clicked() { this->close(); this->destroy(); } void Widget::on_loginButton_clicked() { mw = new MainWindow(); mw->setWindowTitle("微聊"); mw->show(); this->close(); } void Widget::on_errBackButton_clicked() { ui->contentwidget->show(); ui->errwidget->hide(); } void Widget::activated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: setWindowState(Qt::WindowActive); activateWindow(); break; default: break; } } JonathanGuthrie/wodinasynchronousaction.hpp1-10 /* * Copyright 2013 * * 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. */ #if !defined(_DELTAQUEUEASYNCHRONOUSACTION_HPP_INCLUDED_) #define _DELTAQUEUEASYNCHRONOUSACTION_HPP_INCLUDED_ #include #include "mailstore.hpp" // When the timer expires, execute the check for mailbox changes method in the selected // mail store. class DeltaQueueAsynchronousAction : public DeltaQueueAction { public: DeltaQueueAsynchronousAction(int delta, InternetSession *session); virtual void handleTimeout(bool isPurge); }; #endif // _DELTAQUEUEASYNCHRONOUSACTION_HPP_INCLUDED_ #include using namespace std; int main() { int t; cin >> t; string s; while (t--) { cin >> s; int size = s.size(), count = 0; for (int i = 0; i < size; i++) if (s[i] == '1') { count++; } if (count & 1) { cout << "WIN"; } else { cout << "LOSE"; } cout << endl; } return 0; }/* * Copyright 2020 Bloomberg Finance LP * * 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 #include #include #include #include #include #include #include #include #include #include #include #include namespace buildboxcommon { ReloadTokenAuthenticator::ReloadTokenAuthenticator( const grpc::string &token_path, const char *refresh_time) : d_token_path(token_path) { if (refresh_time == nullptr) { d_skip_refresh = true; } else { d_refresh_duration = ParseTime(refresh_time); } TrimAndSetToken(); } grpc::Status ReloadTokenAuthenticator::GetMetadata( grpc::string_ref service_url, grpc::string_ref method_name, const grpc::AuthContext &, std::multimap *metadata) { if (!d_skip_refresh) { RefreshTokenIfNeeded(); } const std::string tmp_token_string = GetTokenString(); BUILDBOX_LOG_TRACE("Calling GetMetadata with args: [" << service_url << " " << method_name << "] and access token from path: [" << d_token_path << "]"); metadata->emplace("authorization", tmp_token_string); return grpc::Status::OK; } void ReloadTokenAuthenticator::RefreshTokenIfNeeded() { const auto current_time = std::chrono::steady_clock::now(); const auto next_refresh_time = GetNextRefreshTime(); if (current_time >= next_refresh_time) { if (d_reload_lock.try_lock()) { std::lock_guard reload_lock_guard(d_reload_lock, std::adopt_lock); TrimAndSetToken(); } } } void ReloadTokenAuthenticator::TrimAndSetToken() { std::string new_token_string = FileUtils::getFileContents(d_token_path.c_str()); // Trim the acccess token of any trailing // whitespace StringUtils::trim(&new_token_string); std::unique_lock lock(d_token_string_lock); d_token_string = "Bearer " + new_token_string; BUILDBOX_LOG_INFO("Read and set access token from disk"); // Set next reload time SetNextRefreshTimeFromNow(); } std::chrono::seconds ReloadTokenAuthenticator::ParseTime(const char *refresh_time_char) const { const std::string refresh_time = std::string(refresh_time_char); if (refresh_time.empty()) { const std::string error_string = "Empty string cannot be specified for reload token interval"; BUILDBOX_LOG_ERROR(error_string); BUILDBOXCOMMON_THROW_EXCEPTION(std::invalid_argument, error_string); } static const std::unordered_map prefix_to_mult = { {'M', 60}, {'H', 60 * 60}}; // toupper returns an int, so cast it to a char const char back = (char)toupper(refresh_time.back()); int suffix = 0; int multiplier = 60; if (prefix_to_mult.find(back) != prefix_to_mult.end()) { multiplier = prefix_to_mult.at(back); suffix = 1; } std::size_t pos; int refresh_duration; const std::string error_string = "Invalid value specified for reload access time"; try { refresh_duration = std::stoi(refresh_time, &pos) * multiplier; if (refresh_time.size() - suffix != pos) { BUILDBOXCOMMON_THROW_EXCEPTION(std::invalid_argument, error_string); } } catch (const std::invalid_argument &ia) { BUILDBOX_LOG_ERROR(error_string); throw ia; } return std::chrono::seconds(refresh_duration); } std::string ReloadTokenAuthenticator::GetTokenString() { std::shared_lock lock(d_token_string_lock); return d_token_string; } std::chrono::steady_clock::time_point ReloadTokenAuthenticator::GetNextRefreshTime() { std::shared_lock lock(d_next_refresh_time_lock); return d_next_refresh_time; } void ReloadTokenAuthenticator::SetNextRefreshTimeFromNow() { std::unique_lock lock(d_next_refresh_time_lock); const auto now = std::chrono::steady_clock::now(); d_next_refresh_time = now + d_refresh_duration; } } // namespace buildboxcommon yukienomiya/competitive-programmingUVa/637_Booklet_Printing/main.cpp #include #include #include using namespace std; int main() { int no_pages; while (cin >> no_pages) { if (no_pages == 0) break; if (no_pages == 1) { cout << "Printing order for 1 pages:" << endl; cout << "Sheet 1, front: Blank, 1" << endl; continue; } int blank_pages = (no_pages % 4 != 0) ? (4 - (no_pages % 4)) : 0; int total_pages = no_pages + blank_pages; vector pages; pages.reserve(total_pages); for (int i = 0; i < no_pages; i++) { pages.push_back(to_string(i + 1)); } for (int i = 0; i < blank_pages; i++) { pages.push_back("Blank"); } cout << "Printing order for " << no_pages << " pages:" << endl; int sheet = 1, i = 0, j = total_pages - 1; int no_sheets = total_pages / 4; for (int idx = 0; idx < no_sheets; idx++) { string to_print[4] = {pages[j], pages[i], pages[i + 1], pages[j - 1]}; i += 2; j -= 2; cout << "Sheet " << idx + 1 << ", front: " << to_print[0] << ", " << to_print[1] << endl; cout << "Sheet " << idx + 1 << ", back : " << to_print[2] << ", " << to_print[3] << endl; } } return 0; }// // test_catch2_WaitingTaskChain.cpp // CMSSW // // Created by on 7/8/21. // #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "tbb/global_control.h" #include "FWCore/Concurrency/interface/chain_first.h" TEST_CASE("Test chain::first", "[chain::first]") { tbb::global_control control(tbb::global_control::max_allowed_parallelism, 1); SECTION("no explicit exception handling") { SECTION("first | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | runLast") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(false); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 0); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } SECTION("first(exception) | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); throw std::exception(); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } SECTION("first(exception) | then | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); throw std::exception(); }) | then([&count](auto h) { ++count; REQUIRE(false); }) | then([&count](auto h) { ++count; REQUIRE(false); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } } SECTION("then with exception handler testing") { SECTION("first | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 2); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 3); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | then | lastTask") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 1); h.doneWaiting(*iPtr); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } } SECTION("ifException.else testing") { SECTION("first | lastTask") { std::atomic count{0}; std::atomic exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic count{0}; std::atomic exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 1); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 2); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic count{0}; std::atomic exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 1); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 2); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 3); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | then | then | lastTask") { std::atomic count{0}; std::atomic exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 1); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 2); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 3); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(exceptCount.load() == 3); REQUIRE(count.load() == 0); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } } SECTION("ifThen testing") { SECTION("first | ifThen(true) | then | runLast") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | ifThen(true, [&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | ifThen(false) | then | runLast") { std::atomic count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | ifThen(false, [&count](auto h) { ++count; REQUIRE(false); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } } } 1-10 // Deciphering the Mayan Writing #include #include #include #include using namespace std; const int maxl = 200; int cnt[maxl], realcnt[maxl]; int main(void) { int res = 0, n, m; string g, s; cin >> n >> m >> g >> s; for(auto it: g) cnt[int(it)]++; set cur; for(int i = 0;i < maxl;i++) { if(cnt[i] != realcnt[i]) cur.insert(i); } for(int i = 0;i < n;i++) { int idx = int(s[i]); if(cnt[idx] != realcnt[idx]) cur.erase(idx); realcnt[idx]++; if(cnt[idx] != realcnt[idx]) cur.insert(idx); } res += cur.empty(); for(int i = n;i < m;i++) { int idx = int(s[i]); if(cnt[idx] != realcnt[idx]) cur.erase(idx); realcnt[idx]++; if(cnt[idx] != realcnt[idx]) cur.insert(idx); idx = int(s[i-n]); if(cnt[idx] != realcnt[idx]) cur.erase(idx); realcnt[idx]--; if(cnt[idx] != realcnt[idx]) cur.insert(idx); res += cur.empty(); } printf("%d\n", res); }// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #include "exec/vectorized/schema_scanner/schema_helper.h" #include #include #include "gen_cpp/FrontendService.h" #include "gen_cpp/FrontendService_types.h" #include "gen_cpp/PlanNodes_types.h" #include "runtime/client_cache.h" #include "runtime/exec_env.h" #include "runtime/runtime_state.h" #include "runtime/string_value.h" #include "util/debug_util.h" #include "util/network_util.h" #include "util/runtime_profile.h" #include "util/thrift_rpc_helper.h" #include "util/thrift_util.h" namespace starrocks::vectorized { Status SchemaHelper::get_db_names(const std::string& ip, const int32_t port, const TGetDbsParams& request, TGetDbsResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->getDbNames(*result, request); }); } Status SchemaHelper::get_table_names(const std::string& ip, const int32_t port, const TGetTablesParams& request, TGetTablesResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->getTableNames(*result, request); }); } Status SchemaHelper::list_table_status(const std::string& ip, const int32_t port, const TGetTablesParams& request, TListTableStatusResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->listTableStatus(*result, request); }); } Status SchemaHelper::describe_table(const std::string& ip, const int32_t port, const TDescribeTableParams& request, TDescribeTableResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->describeTable(*result, request); }); } Status SchemaHelper::show_varialbes(const std::string& ip, const int32_t port, const TShowVariableRequest& request, TShowVariableResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->showVariables(*result, request); }); } std::string SchemaHelper::extract_db_name(const std::string& full_name) { auto found = full_name.find(':'); if (found == std::string::npos) { return full_name; } found++; return std::string(full_name.c_str() + found, full_name.size() - found); } Status SchemaHelper::get_user_privs(const std::string& ip, const int32_t port, const TGetUserPrivsParams& request, TGetUserPrivsResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->getUserPrivs(*result, request); }); } Status SchemaHelper::get_db_privs(const std::string& ip, const int32_t port, const TGetDBPrivsParams& request, TGetDBPrivsResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->getDBPrivs(*result, request); }); } Status SchemaHelper::get_table_privs(const std::string& ip, const int32_t port, const TGetTablePrivsParams& request, TGetTablePrivsResult* result) { return ThriftRpcHelper::rpc( ip, port, [&request, &result](FrontendServiceConnection& client) { client->getTablePrivs(*result, request); }); } void fill_data_column_with_null(vectorized::Column* data_column) { vectorized::NullableColumn* nullable_column = down_cast(data_column); nullable_column->append_nulls(1); } } // namespace starrocks::vectorized #include "netlink.hpp" #include "util.hpp" #include #include #include #include #include #include #include #include namespace phosphor { namespace network { namespace netlink { namespace detail { void processMsg(std::string_view& msgs, bool& done, const ReceiveCallback& cb) { // Parse and update the message buffer auto hdr = stdplus::raw::copyFrom(msgs); if (hdr.nlmsg_len < sizeof(hdr)) { throw std::runtime_error("Invalid nlmsg length"); } if (msgs.size() < hdr.nlmsg_len) { throw std::runtime_error("Bad nlmsg payload"); } auto msg = msgs.substr(NLMSG_HDRLEN, hdr.nlmsg_len - NLMSG_HDRLEN); msgs.remove_prefix(NLMSG_ALIGN(hdr.nlmsg_len)); // Figure out how to handle the individual message bool doCallback = true; if (hdr.nlmsg_flags & NLM_F_MULTI) { done = false; } if (hdr.nlmsg_type == NLMSG_NOOP) { doCallback = false; } else if (hdr.nlmsg_type == NLMSG_DONE) { if (done) { throw std::runtime_error("Got done for non-multi msg"); } done = true; doCallback = false; } else if (hdr.nlmsg_type == NLMSG_ERROR) { auto err = stdplus::raw::copyFrom(msg); // This is just an ACK so don't do the callback if (err.error <= 0) { doCallback = false; } } // All multi-msg headers must have the multi flag if (!done && !(hdr.nlmsg_flags & NLM_F_MULTI)) { throw std::runtime_error("Got non-multi msg before done"); } if (doCallback) { cb(hdr, msg); } } static void receive(int sock, const ReceiveCallback& cb) { // We need to make sure we have enough room for an entire packet otherwise // it gets truncated. The netlink docs guarantee packets will not exceed 8K std::array buf; iovec iov{}; iov.iov_base = buf.data(); iov.iov_len = buf.size(); sockaddr_nl from{}; from.nl_family = AF_NETLINK; msghdr hdr{}; hdr.msg_name = &from; hdr.msg_namelen = sizeof(from); hdr.msg_iov = &iov; hdr.msg_iovlen = 1; // We only do multiple recvs if we have a MULTI type message bool done = true; do { ssize_t recvd = recvmsg(sock, &hdr, 0); if (recvd < 0) { throw std::system_error(errno, std::generic_category(), "netlink recvmsg"); } if (recvd == 0) { throw std::runtime_error("netlink recvmsg: Got empty payload"); } std::string_view msgs(buf.data(), recvd); do { processMsg(msgs, done, cb); } while (!done && !msgs.empty()); if (done && !msgs.empty()) { throw std::runtime_error("Extra unprocessed netlink messages"); } } while (!done); } static void requestSend(int sock, void* data, size_t size) { sockaddr_nl dst{}; dst.nl_family = AF_NETLINK; iovec iov{}; iov.iov_base = data; iov.iov_len = size; msghdr hdr{}; hdr.msg_name = reinterpret_cast(&dst); hdr.msg_namelen = sizeof(dst); hdr.msg_iov = &iov; hdr.msg_iovlen = 1; if (sendmsg(sock, &hdr, 0) < 0) { throw std::system_error(errno, std::generic_category(), "netlink sendmsg"); } } static int newRequestSocket(int protocol) { int sock = socket(AF_NETLINK, SOCK_RAW, protocol); if (sock < 0) { throw std::system_error(errno, std::generic_category(), "netlink open"); } sockaddr_nl local{}; local.nl_family = AF_NETLINK; int r = bind(sock, reinterpret_cast(&local), sizeof(local)); if (r < 0) { close(sock); throw std::system_error(errno, std::generic_category(), "netlink bind"); } return sock; } void performRequest(int protocol, void* data, size_t size, const ReceiveCallback& cb) { Descriptor sock(newRequestSocket(protocol)); requestSend(sock(), data, size); receive(sock(), cb); } } // namespace detail std::tuple extractRtAttr(std::string_view& data) { auto hdr = stdplus::raw::copyFrom(data); if (hdr.rta_len < RTA_LENGTH(0)) { throw std::runtime_error("Invalid rtattr length"); } if (data.size() < hdr.rta_len) { throw std::runtime_error("Not enough data for rtattr"); } auto attr = data.substr(RTA_LENGTH(0), hdr.rta_len - RTA_LENGTH(0)); data.remove_prefix(RTA_ALIGN(hdr.rta_len)); return {hdr, attr}; } } // namespace netlink } // namespace network } // namespace phosphor /*! \file pcg_engine-inl.hpp \author \brief No brief description \details No detailed description. \copyright Copyright (c) 2015-2021 This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef ZISC_PCG_ENGINE_INL_HPP #define ZISC_PCG_ENGINE_INL_HPP #include "pcg_engine.hpp" // Standard C++ library #include #include #include // Zisc #include "zisc/concepts.hpp" #include "zisc/utility.hpp" #include "zisc/zisc_config.hpp" namespace zisc { /*! \details No detailed description */ template inline PcgEngine::PcgEngine() noexcept { setSeed(BaseEngine::defaultSeed()); } /*! \details No detailed description \param [in] seed No description. */ template inline PcgEngine::PcgEngine(const ValueType seed) noexcept { setSeed(seed); } /*! \details No detailed description \return No description */ template inline auto PcgEngine::generate() noexcept -> ValueType { const ValueType base = generateBase(); const ValueType result = output(base); return result; } /*! \details No detailed description \return No description */ template inline constexpr std::size_t PcgEngine::getPeriodPow2() noexcept { constexpr bool is_mcg = kBase == PcgBase::Mcg; constexpr std::size_t period_pow2 = 8 * sizeof(ValueType) - (is_mcg ? 2 : 0); return period_pow2; } /*! \details No detailed description \tparam Integer No description. \param [in] sample No description. \return No description */ template template inline constexpr bool PcgEngine::isEndOfPeriod( const Integer sample) noexcept { constexpr std::size_t sample_bit_size = sizeof(Integer) * 8; constexpr std::size_t period_pow2 = getPeriodPow2(); if constexpr (sample_bit_size <= period_pow2) { // Workaround constexpr Integer end_of_period = std::numeric_limits::max(); return sample == end_of_period; } else { constexpr Integer end_of_period = (cast(1u) << period_pow2) - 1; return sample == end_of_period; } } /*! \details No detailed description \param [in] seed No description. */ template inline void PcgEngine::setSeed(const ValueType seed) noexcept { constexpr bool is_mcg = (kBase == PcgBase::Mcg); state_ = is_mcg ? (seed | cast(3)) : bump(seed + increment()); } /*! \details No detailed description \param [in] state No description. \return No description */ template inline auto PcgEngine::bump(const ValueType state) const noexcept -> ValueType { const ValueType result = state * multiplier() + increment(); return result; } /*! \details No detailed description \return No description */ template inline auto PcgEngine::generateBase() noexcept -> ValueType { if constexpr (kOutputPrevious) { const ValueType old_state = state_; state_ = bump(state_); return old_state; } else { state_ = bump(state_); return state_; } } /*! \details No detailed description \return No description */ template inline constexpr auto PcgEngine::increment() noexcept -> ValueType { ValueType i = 0; constexpr bool is_mcg = kBase == PcgBase::Mcg; if constexpr (!is_mcg) { if constexpr (sizeof(ValueType) == 1) i = 77u; else if constexpr (sizeof(ValueType) == 2) i = 47989u; else if constexpr (sizeof(ValueType) == 4) i = 2891336453u; else if constexpr (sizeof(ValueType) == 8) i = 1442695040888963407ull; } return i; } /*! \details No detailed description \return No description */ template inline constexpr auto PcgEngine::mcgMultiplier() noexcept -> ValueType { ValueType m = 0; if constexpr (sizeof(ValueType) == 1) m = 217u; else if constexpr (sizeof(ValueType) == 2) m = 62169u; else if constexpr (sizeof(ValueType) == 4) m = 277803737u; else if constexpr (sizeof(ValueType) == 8) m = 12605985483714917081ull; return m; } /*! \details No detailed description \return No description */ template inline constexpr auto PcgEngine::multiplier() noexcept -> ValueType { ValueType m = 0; if constexpr (sizeof(ValueType) == 1) m = 141u; else if constexpr (sizeof(ValueType) == 2) m = 12829u; else if constexpr (sizeof(ValueType) == 4) m = 747796405u; else if constexpr (sizeof(ValueType) == 8) m = 6364136223846793005ull; return m; } /*! \details No detailed description \param [in] internal No description. \return No description */ template inline auto PcgEngine::output(ValueType internal) noexcept -> ValueType { // Constant values constexpr BitCountType xtypebits = cast(8 * sizeof(ValueType)); constexpr BitCountType bits = cast(8 * sizeof(ValueType)); constexpr BitCountType opbits = (128 <= xtypebits) ? 6 : ( 64 <= xtypebits) ? 5 : ( 32 <= xtypebits) ? 4 : ( 16 <= xtypebits) ? 3 : 2; constexpr BitCountType shift = bits - xtypebits; constexpr BitCountType mask = (1 << opbits) - 1; constexpr BitCountType xshift = (2u * xtypebits + 2u) / 3u; const BitCountType rshift = opbits ? cast(internal >> (bits - opbits)) & mask : 0; internal ^= internal >> (opbits + rshift); internal *= mcgMultiplier(); ValueType result = internal >> shift; result ^= result >> xshift; return result; } } // namespace zisc #endif // ZISC_PCG_ENGINE_INL_HPP class Solution { public: int f[1000000]; int numDecodings(string s) { memset(f, 0, sizeof(f)); if (s == "") return 0; if (s[0] == '0') return 0; f[0] = 1; if (s[1] == '0'){ if (s[0] == '2' || s[0] == '1') f[1] = 1; else return 0; }else{ if (((s[0]-'0')*10+s[1]-'0') <= 26) f[1] = 2; else f[1] = 1; } for (int i = 2; i < s.length(); i++){ if (s[i] == '0'){ if (s[i-1] == '2' || s[i-1] == '1') f[i] = f[i-2]; else return 0; }else{ if (s[i-1] == '0') f[i] = f[i-1]; else if (((s[i-1]-'0')*10+s[i]-'0') <= 26) f[i] = f[i-1] + f[i-2]; else f[i] = f[i-1]; } } return f[s.length()-1]; } };#ifndef nomad__src__scalar__functions__smooth_functions__asin_hpp #define nomad__src__scalar__functions__smooth_functions__asin_hpp #include #include #include #include namespace nomad { inline double asin(double x) { return std::asin(x); } template inline var asin(const var& input) { if (ValidateIO) { double val = input.first_val(); validate_input(val, "asin"); validate_lower_bound(val, -1, "asin"); validate_upper_bound(val, 1, "asin"); } const short partials_order = 3; const unsigned int n_inputs = 1; create_node>(n_inputs); const double x = input.first_val(); try { push_dual_numbers(std::asin(x)); } catch (nomad_error) { throw nomad_output_value_error("asin"); } push_inputs(input.dual_numbers()); const double d1 = 1.0 / (1 - x * x); const double d2 = std::sqrt(d1); try { if (AutodiffOrder >= 1) push_partials(d2); if (AutodiffOrder >= 2) push_partials(x * d1 * d2); if (AutodiffOrder >= 3) push_partials((1 + 2 * x * x) * d1 * d1 * d2); } catch (nomad_error) { throw nomad_output_partial_error("asin"); } return var(next_node_idx_ - 1); } } #endif //Language: GNU C++ #include #include #include #include using namespace std; const int N=2011; vector cld[N]; int level[N]; int n; int in[N]; void sol() { queue Q; while(!Q.empty()) Q.pop(); for(int i=1;i<=n;i++) if(!in[i]){ Q.push(i); level[i]=1; } int res=1; while(!Q.empty()) { int fth=Q.front();Q.pop(); int lmt=cld[fth].size(); for(int i=0;ires) res=level[v]; } } printf("%d\n",res); } int main() { while(scanf("%d",&n)!=-1) { for(int i=1;i<=n;i++){ cld[i].clear(); in[i]=0; } for(int i=1;i<=n;i++) { int fth; scanf("%d",&fth); if(fth+1){ cld[fth].push_back(i); in[i]++; } } sol(); } return 0; }1-10 #include using namespace std; int main(){ string A; string B; cin>>A>>B; int a = A.length(); int b = B.length(); int t[a+1][b+1]; for(int i = 0;i < a+1;i++) t[i][0] = 0; for(int i = 0;i < b+1;i++) t[0][i] = 0; for(int i = 1;i < a+1;i++) for(int j = 1;j < b+1; j++) if(A[i-1] == B[j-1]) t[i][j] = 1 + t[i-1][j-1]; else t[i][j] = max(t[i-1][j], t[i][j-1]); cout << t[a][b]; }1-10 #pragma once #include #include #include namespace CreateCoin { namespace schema { namespace detail { ////////////////////////////////////////////// // account_name_type // ////////////////////////////////////////////// struct schema_account_name_type_impl : public abstract_schema { CreateCoin_SCHEMA_CLASS_BODY( schema_account_name_type_impl ) }; } template<> struct schema_reflect< CreateCoin::protocol::account_name_type > { typedef detail::schema_account_name_type_impl schema_impl_type; }; } } namespace fc { template<> struct get_typename< CreateCoin::protocol::account_name_type > { static const char* name() { return "CreateCoin::protocol::account_name_type"; } }; } tiling.cpp #include "wm.h" using namespace UW; void WindowManager::tile(Desktop *d, Monitor *m) { if (d->clients.size() == 0) { return; } (*this.*layout[d->clients.size() > 0 ? d->mode : MONOCLE])(m->x + (d->isBar ? config->PANEL_HEIGHT_VERTICAL_LEFT : 0), m->y + (config->SHOW_PANEL && d->isBar ? config->PANEL_HEIGHT_HORIZONTAL_UP : 0), m->w - (d->isBar ? (config->PANEL_HEIGHT_VERTICAL_LEFT+config->PANEL_HEIGHT_VERTICAL_RIGHT) : 0), m->h - (d->isBar ? (config->PANEL_HEIGHT_HORIZONTAL_UP+config->PANEL_HEIGHT_HORIZONTAL_DOWN) : 0), d); } void WindowManager::gridMode(int x, int y, int w, int h, Desktop *d) { int n = 0; int cols = 0; int cn = 0; int rn = 0; int i = -1; for (auto& c : d->clients) { if (!isFloatOrFullscreen(c.get())) { ++n; } } for (cols = 0; cols <= n / 2; cols++) { if (cols * cols >= n) { break; } } if (n == 0) { return; } else if (n == 5) { cols = 2; } int rows = n/cols; int ch = h - config->BORDER_WIDTH - config->USELESSGAP; int cw = (w - config->BORDER_WIDTH - config->USELESSGAP)/(cols ? cols:1); for (auto& c : d->clients) { if (isFloatOrFullscreen(c.get())) { continue; } else { ++i; } if (i/rows + 1 > cols - n % cols) { rows = n/cols + 1; } auto win = config->SHOW_DECORATE ? c.get()->decorate : c.get()->win; if (!c.get()->isHide){ XMoveResizeWindow(display, win, x + cn*cw + config->USELESSGAP, y + rn*ch/rows + config->USELESSGAP, cw - 2*config->BORDER_WIDTH-config->USELESSGAP, ch/rows - 2*config->BORDER_WIDTH-config->USELESSGAP); if (config->SHOW_DECORATE && c.get()->isDecorated) { c->moveResizeLocal(x + cn*cw + config->USELESSGAP, y + rn*ch/rows + config->USELESSGAP, cw - 2*config->BORDER_WIDTH-config->USELESSGAP, ch/rows - 2*config->BORDER_WIDTH-config->USELESSGAP, *config, display); } } if (++rn >= rows) { rn = 0; cn++; } } } void WindowManager::monocleMode(int x, int y, int w, int h, Desktop *d) { for (auto& c : d->clients) { if (!isFloatOrFullscreen(c.get())) { if (!c->isHide) { if (config->SHOW_DECORATE) { XMoveResizeWindow(display, c->decorate, x + config->USELESSGAP, y + config->USELESSGAP, w - 2*config->USELESSGAP, h - 2*config->USELESSGAP); } XMoveResizeWindow(display, c->win, x + config->USELESSGAP, y + config->USELESSGAP, w - 2*config->USELESSGAP, h - 2*config->USELESSGAP); } } } } void WindowManager::floatMode(int x, int y, int w, int h, Desktop *d) { for (auto& c : d->clients) { c->isFloat = true; } } void WindowManager::fullscreenMode(Client *c, Desktop *d, Monitor *m, bool fullscrn) { if (fullscrn != c->isFull) { XChangeProperty(display, c->win, netatoms[NET_WM_STATE], XA_ATOM, 32, PropModeReplace, (unsigned char*) ((c->isFull = fullscrn) ? &netatoms[NET_FULLSCREEN]:0), fullscrn); if (config->SHOW_DECORATE) { XChangeProperty(display, c->decorate, netatoms[NET_WM_STATE], XA_ATOM, 32, PropModeReplace, (unsigned char*) ((c->isFull = fullscrn) ? &netatoms[NET_FULLSCREEN]:0), fullscrn); } } if (fullscrn) { if (config->SHOW_DECORATE) { XMoveResizeWindow(display, c->decorate, m->x, m->y, m->w, m->h); } XMoveResizeWindow(display, c->win, m->x, m->y, m->w, m->h); } else { tile(d, m); } auto win = config->SHOW_DECORATE ? c->decorate : c->win; XSetWindowBorderWidth(display, win, (c->isFull || d->clients.size() <= 1 ? 0 : config->BORDER_WIDTH)); } void WindowManager::stackMode(int x, int y, int w, int h, Desktop *d) { Client *c = nullptr; Client *t = nullptr; int stackType = (int)d->mode; int p = 0; int z = (stackType == H_STACK_UP || stackType == H_STACK_DOWN ? w : h); //clientSize int ma = (stackType == H_STACK_UP || stackType == H_STACK_DOWN ? h : w) * config->MASTER_SIZE + d->masterSize; int nm = d->nm; int stackSize = 0; //get master int cid = 0; for (auto& _c : d->clients) { if (!isFloatOrFullscreen(_c.get())) { if (c) { stackSize++; //stack size } else { c = _c.get(); //master win cid = c->id; } } } if (c && !stackSize && !c->isHide) { auto win = config->SHOW_DECORATE ? c->decorate : c->win; if (!c->isHide) { XMoveResizeWindow(display, win, x + config->USELESSGAP, y + config->USELESSGAP, w - 2*(config->BORDER_WIDTH+config->USELESSGAP), h - 2*(config->BORDER_WIDTH+config->USELESSGAP)); if (config->SHOW_DECORATE && c->decorate) { c->moveResizeLocal(x + config->USELESSGAP, y + config->USELESSGAP, w - 2*(config->BORDER_WIDTH+config->USELESSGAP), h - 2*(config->BORDER_WIDTH+config->USELESSGAP), *config, display); } } } if (!c || !stackSize) { return; } else if (stackSize - nm <= 0) { nm = stackSize; } else { stackSize -= nm-1; p = (z - d->firstStackSize)%stackSize + d->firstStackSize; z = (z - d->firstStackSize)/stackSize; } for (int i = 0; i < nm; i++) { if (c->isHide) { for (auto i = cid+1; i < d->clients.size(); i++) { if (!isFloatOrFullscreen(d->clients[i].get())) { c = d->clients[i].get(); cid = c->id; break; } } continue; } auto win = config->SHOW_DECORATE ? c->decorate : c->win; if (stackType == H_STACK_DOWN) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x+config->USELESSGAP + i * (w-config->USELESSGAP)/nm, y+config->USELESSGAP, (w-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), *config, display); } XMoveResizeWindow(display, win, x+config->USELESSGAP + i * (w-config->USELESSGAP)/nm, y+config->USELESSGAP, (w-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP)); } else if (stackType == V_STACK_LEFT) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal((w-ma+(d->isBar && config->SHOW_PANEL ? config->PANEL_HEIGHT_VERTICAL_LEFT : 0))+config->USELESSGAP, y+config->USELESSGAP + i * (h-config->USELESSGAP)/nm, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), (h-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, *config, display); } XMoveResizeWindow(display, win, (w-ma+(d->isBar && config->SHOW_PANEL ? config->PANEL_HEIGHT_VERTICAL_LEFT : 0))+config->USELESSGAP, y+config->USELESSGAP + i * (h-config->USELESSGAP)/nm, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), (h-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP); } else if (stackType == V_STACK_RIGHT) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x+config->USELESSGAP, y+config->USELESSGAP + i * (h-config->USELESSGAP)/nm, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), (h-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, *config, display); } XMoveResizeWindow(display, win, x+config->USELESSGAP, y+config->USELESSGAP + i * (h-config->USELESSGAP)/nm, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), (h-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP); } else if (stackType == H_STACK_UP) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x+config->USELESSGAP + i * (w-config->USELESSGAP)/nm, (h-ma+(d->isBar && config->SHOW_PANEL ? config->PANEL_HEIGHT_HORIZONTAL_UP : 0))+config->USELESSGAP, (w-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP), *config, display); } XMoveResizeWindow(display, win, x+config->USELESSGAP + i * (w-config->USELESSGAP)/nm, (h-ma+(d->isBar && config->SHOW_PANEL ? config->PANEL_HEIGHT_HORIZONTAL_UP : 0))+config->USELESSGAP, (w-config->USELESSGAP)/nm - 2*config->BORDER_WIDTH-config->USELESSGAP, ma - 2*(config->BORDER_WIDTH+config->USELESSGAP)); } for (auto i = cid+1; i < d->clients.size(); i++) { if (!isFloatOrFullscreen(d->clients[i].get())) { c = d->clients[i].get(); cid = c->id; break; } } } /* for (auto i = cid+1; i < d->clients.size(); i++) { if (!IsFloatOrFullscreen(d->clients[i])) { c = d->clients[i]; cid = c->id; break; } }*/ int cw = (stackType == V_STACK_LEFT || stackType == V_STACK_RIGHT ? w : h) - 2*config->BORDER_WIDTH - config->USELESSGAP - ma; int ch = z - 2*config->BORDER_WIDTH - config->USELESSGAP; auto win = config->SHOW_DECORATE ? c->decorate : c->win; if (stackType == V_STACK_RIGHT) { x += ma; y += config->USELESSGAP; if (!c->isHide) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x, y, cw, ch - config->USELESSGAP + p, *config, display); } XMoveResizeWindow(display, win, x, y, cw, ch - config->USELESSGAP + p); } } else if (stackType == V_STACK_LEFT) { y += config->USELESSGAP; x += config->USELESSGAP; if (!c->isHide) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x, y, cw, ch - config->USELESSGAP + p, *config, display); } XMoveResizeWindow(display, win, x, y, cw, ch - config->USELESSGAP + p); } } else if (stackType == H_STACK_UP) { x += config->USELESSGAP; y += config->USELESSGAP; if (!c->isHide) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x, y, ch - config->USELESSGAP + p, cw, *config, display); } XMoveResizeWindow(display, win, x, y, ch - config->USELESSGAP + p, cw); } } else { y += ma; x += config->USELESSGAP; if (!c->isHide) { if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x, y, ch - config->USELESSGAP + p, cw, *config, display); } XMoveResizeWindow(display, win, x, y, ch - config->USELESSGAP + p, cw); } } stackType == V_STACK_LEFT || stackType == V_STACK_RIGHT ? (y += z+p - config->USELESSGAP) : (x += z+p - config->USELESSGAP); for (auto i = cid+1; i < d->clients.size(); i++) { if (isFloatOrFullscreen(d->clients[i].get())) { continue; } auto _win = config->SHOW_DECORATE ? (d->clients[i])->decorate : (d->clients[i])->win; if (stackType == V_STACK_LEFT || stackType == V_STACK_RIGHT) { if (!d->clients[i]->isHide){ if (config->SHOW_DECORATE && (d->clients[i])->isDecorated) { d->clients[i]->moveResizeLocal(x, y, cw, ch, *config, display); } XMoveResizeWindow(display, _win, x, y, cw, ch); } y += z; } else { if (!d->clients[i]->isHide){ if (config->SHOW_DECORATE && (d->clients[i])->isDecorated) { d->clients[i]->moveResizeLocal(x, y, ch, cw, *config, display); } XMoveResizeWindow(display, _win, x, y, ch, cw); } x += z; } } } void WindowManager::fibonacciMode(int x, int y, int w, int h, Desktop *d) { int j = -1; int cw = w - config->BORDER_WIDTH - config->USELESSGAP*2; int ch = h - config->BORDER_WIDTH - config->USELESSGAP*2; Client *n = nullptr; Client *c = nullptr; auto winCount = 0; for (auto i = 0; i < d->clients.size(); ++i) { if (!isFloatOrFullscreen(d->clients[i].get())) { winCount++; } } x += config->USELESSGAP; y += config->USELESSGAP; for (auto i = 0; i < d->clients.size(); ++i) { c = d->clients[i].get(); if (isFloatOrFullscreen(c)) { continue; } else { j++; } for (auto ii = i+1; ii < d->clients.size(); ++ii) { n = d->clients[ii].get(); if (!isFloatOrFullscreen(n)) { break; } } if (n && winCount!=1) (j&1) ? ((ch /= 2)) : ((cw /= 2)); if (j) (j&1) ? (x += cw + config->USELESSGAP) : (y += ch + config->USELESSGAP); auto win = config->SHOW_DECORATE ? c->decorate : c->win; if (!c->isHide){ if (config->SHOW_DECORATE && c->isDecorated) { c->moveResizeLocal(x, y, cw - config->BORDER_WIDTH, ch - config->BORDER_WIDTH, *config, display); } XMoveResizeWindow(display, win, x, y, cw - config->BORDER_WIDTH, ch - config->BORDER_WIDTH); } if (n && winCount!=1) if (j&1) { ch-=config->USELESSGAP; y += config->USELESSGAP; } else { cw-=config->USELESSGAP; x += config->USELESSGAP; } winCount--; } } void WindowManager::doubleStackVerticalMode(int x, int y, int w, int h, Desktop *d) { int cw = w - config->BORDER_WIDTH*2 - config->USELESSGAP*2; int ch = h - config->BORDER_WIDTH*2 - config->USELESSGAP*2; std::vector avalibleClients; for (auto i = 0; i < d->clients.size(); ++i) { if (!isFloatOrFullscreen(d->clients[i].get())) { avalibleClients.push_back(d->clients[i].get()); } } if (!avalibleClients.size()) { return; } x += config->USELESSGAP; y += config->USELESSGAP; if (avalibleClients.size() == 1) { auto win = config->SHOW_DECORATE ? avalibleClients[0]->decorate : avalibleClients[0]->win; if (config->SHOW_DECORATE && avalibleClients[0]->isDecorated) { avalibleClients[0]->moveResizeLocal(x, y, cw - config->BORDER_WIDTH, ch - config->USELESSGAP, *config, display); } XMoveResizeWindow(display, win, x, y, cw - config->BORDER_WIDTH, ch - config->USELESSGAP); return; } if (avalibleClients.size() == 2) { auto win1 = config->SHOW_DECORATE ? avalibleClients[0]->decorate : avalibleClients[0]->win; auto win2 = config->SHOW_DECORATE ? avalibleClients[1]->decorate : avalibleClients[1]->win; if (config->SHOW_DECORATE && avalibleClients[0]->isDecorated) { avalibleClients[0]->moveResizeLocal(x, y, (cw - config->BORDER_WIDTH - config->USELESSGAP) / 2, (ch - config->USELESSGAP), *config, display); } XMoveResizeWindow(display, win1, x, y, (cw - config->BORDER_WIDTH - config->USELESSGAP) / 2, (ch - config->USELESSGAP)); if (config->SHOW_DECORATE && avalibleClients[1]->isDecorated) { avalibleClients[1]->moveResizeLocal(x+(cw - config->BORDER_WIDTH) / 2 + config->USELESSGAP, y, (cw - config->BORDER_WIDTH - 2*config->USELESSGAP) / 2, (ch - config->USELESSGAP), *config, display); } XMoveResizeWindow(display, win2, x+(cw - config->BORDER_WIDTH) / 2 + config->USELESSGAP, y, (cw - config->BORDER_WIDTH - 2*config->USELESSGAP) / 2, (ch - config->USELESSGAP)); return; } int masterSize = d->masterSize + cw / 3 - 2 * config->BORDER_WIDTH; auto clientsSize = avalibleClients.size() - 1; int clientsRSize = 0; int clientsLSize = 0; if (clientsSize % 2 == 0) { clientsRSize = clientsLSize = clientsSize / 2; } else { clientsRSize = clientsSize / 2 + 1; clientsLSize = clientsSize / 2; } auto rStackCount = 0; auto lStackCount = 0; for (auto i = 0; i < avalibleClients.size(); ++i) { auto win = config->SHOW_DECORATE ? avalibleClients[i]->decorate : avalibleClients[i]->win; if (i == 0) { if (config->SHOW_DECORATE && avalibleClients[i]->isDecorated) { avalibleClients[i]->moveResizeLocal((cw - masterSize) / 2 + 2*config->USELESSGAP, y, masterSize - config->USELESSGAP*2, (ch - config->BORDER_WIDTH), *config, display); } XMoveResizeWindow(display, win, (cw - masterSize) / 2 + 2*config->USELESSGAP, y, masterSize - config->USELESSGAP*2, (ch - config->BORDER_WIDTH)); continue; } auto leftOrRight = static_cast(i % 2); if (leftOrRight) { // right if (config->SHOW_DECORATE && avalibleClients[i]->isDecorated) { avalibleClients[i]->moveResizeLocal(masterSize + ((cw - masterSize) / 2) + config->USELESSGAP, y+ (((ch - config->BORDER_WIDTH) / clientsRSize)) * rStackCount, ((cw - masterSize) / 2) - config->BORDER_WIDTH, ((ch - config->BORDER_WIDTH*(clientsRSize-1) - config->USELESSGAP*(clientsRSize-1)) / clientsRSize) - config->BORDER_WIDTH, *config, display); } XMoveResizeWindow(display, win, masterSize + ((cw - masterSize) / 2) + config->USELESSGAP, y + (((ch - config->BORDER_WIDTH) / clientsRSize)) * rStackCount, ((cw - masterSize) / 2) - config->BORDER_WIDTH, ((ch - config->BORDER_WIDTH * (clientsRSize-1) - config->USELESSGAP * (clientsRSize-1)) / clientsRSize) - config->BORDER_WIDTH); rStackCount++; } else { // left if (config->SHOW_DECORATE && avalibleClients[i]->isDecorated) { avalibleClients[i]->moveResizeLocal(x, y + (((ch - config->BORDER_WIDTH) / clientsLSize)) * lStackCount, ((cw - masterSize) / 2) - config->BORDER_WIDTH, ((ch - config->BORDER_WIDTH*(clientsLSize-1) - config->USELESSGAP*(clientsLSize-1)) / clientsLSize) - config->BORDER_WIDTH, *config, display); } XMoveResizeWindow(display, win, x, y + (((ch - config->BORDER_WIDTH) / clientsLSize)) * lStackCount, ((cw - masterSize) / 2) - config->BORDER_WIDTH, ((ch - config->BORDER_WIDTH*(clientsLSize-1) - config->USELESSGAP*(clientsLSize-1)) / clientsLSize) - config->BORDER_WIDTH); lStackCount++; } } } Zilanlann/cp-code #include #include #include typedef long long ll; using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector ve(n); for (auto& v : ve) cin >> v; int a = 0, b = 0; sort(ve.begin(), ve.end()); for (int i = 1; i <= n; i++) { auto iter = lower_bound(ve.begin(), ve.end(), abs(a - b)); if (a < b) a += *iter; else b += *iter; *iter = -1; } cout << abs(a - b) << "\n"; return 0; }/** * @file Scene.cpp * @brief Scene class implementation. * @author zer0 * @date 2019-05-29 */ #include #include #include #include // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace scene { Scene::Scene() { // EMPTY. } Scene::Scene(Scene const & obj) : Scene() { (*this) = obj; } Scene::Scene(Scene && obj) TBAG_NOEXCEPT : Scene() { (*this) = std::move(obj); } Scene::~Scene() { // EMPTY. } Scene & Scene::operator =(Scene const & obj) { copy(obj); return *this; } Scene & Scene::operator =(Scene && obj) TBAG_NOEXCEPT { swap(obj); return *this; } void Scene::copy(Scene const & obj) { if (this != &obj) { // TODO: Copy object. } } void Scene::swap(Scene & obj) TBAG_NOEXCEPT { if (this != &obj) { // TODO: Swap object. } } } // namespace scene // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- src/routines/level3/xher2k.cpp // ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // // // This file implements the Xher2k class (see the header for information about the class). // // ================================================================================================= #include "routines/level3/xher2k.hpp" #include #include namespace clblast { // ================================================================================================= // Constructor: forwards to base class constructor template Xher2k::Xher2k(Queue &queue, EventPointer event, const std::string &name): Xherk(queue, event, name) { } // ================================================================================================= // The main routine template void Xher2k::DoHer2k(const Layout layout, const Triangle triangle, const Transpose ab_transpose, const size_t n, const size_t k, const T alpha, const Buffer &a_buffer, const size_t a_offset, const size_t a_ld, const Buffer &b_buffer, const size_t b_offset, const size_t b_ld, const U beta, const Buffer &c_buffer, const size_t c_offset, const size_t c_ld) { // Runs the first matrix multiplication auto first_herk_event = Event(); auto complex_beta = T{beta, static_cast(0.0)}; const auto negated_ab_transpose = (ab_transpose != Transpose::kNo) ? Transpose::kNo : Transpose::kYes; HerkAB(layout, triangle, ab_transpose, negated_ab_transpose, n, k, alpha, a_buffer, a_offset, a_ld, b_buffer, b_offset, b_ld, complex_beta, c_buffer, c_offset, c_ld, first_herk_event.pointer(), false); ; first_herk_event.WaitForCompletion(); // Swaps the arguments for matrices A and B, sets 'beta' to 1, and conjugate alpha auto conjugate_alpha = T{alpha.real(), -alpha.imag()}; auto complex_one = T{static_cast(1.0), static_cast(0.0)}; HerkAB(layout, triangle, ab_transpose, negated_ab_transpose, n, k, conjugate_alpha, b_buffer, b_offset, b_ld, a_buffer, a_offset, a_ld, complex_one, c_buffer, c_offset, c_ld, event_, true); } // ================================================================================================= // Compiles the templated class template class Xher2k; template class Xher2k; // ================================================================================================= } // namespace clblast searchsummary/src/vespa/searchsummary/docsummary/attribute_combiner_dfw.cpp // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_combiner_dfw.h" #include "array_attribute_combiner_dfw.h" #include "struct_map_attribute_combiner_dfw.h" #include "docsum_field_writer_state.h" #include "docsumstate.h" #include #include #include #include #include LOG_SETUP(".searchsummary.docsummary.attribute_combiner_dfw"); using search::AttributeGuard; using search::AttributeVector; using search::attribute::CollectionType; namespace search::docsummary { namespace { class StructFields { std::vector _mapFields; std::vector _arrayFields; bool _hasMapKey; bool _error; public: StructFields(const vespalib::string &fieldName, const IAttributeManager &attrMgr); ~StructFields(); const std::vector &getMapFields() const { return _mapFields; } const std::vector &getArrayFields() const { return _arrayFields; } bool hasMapKey() const { return _hasMapKey; } bool getError() const { return _error; } }; StructFields::StructFields(const vespalib::string &fieldName, const IAttributeManager &attrMgr) : _mapFields(), _arrayFields(), _hasMapKey(false), _error(false) { std::vector attrs; auto attrCtx = attrMgr.createContext(); attrCtx->getAttributeList(attrs); vespalib::string prefix = fieldName + "."; vespalib::string keyName = prefix + "key"; vespalib::string valuePrefix = prefix + "value."; for (const auto attr : attrs) { vespalib::string name = attr->getName(); if (name.substr(0, prefix.size()) != prefix) { continue; } auto collType = attr->getCollectionType(); if (collType != CollectionType::Type::ARRAY) { LOG(warning, "Attribute %s is not an array attribute", name.c_str()); _error = true; break; } if (name.substr(0, valuePrefix.size()) == valuePrefix) { _mapFields.emplace_back(name.substr(valuePrefix.size())); } else { _arrayFields.emplace_back(name.substr(prefix.size())); if (name == keyName) { _hasMapKey = true; } } } if (!_error) { std::sort(_arrayFields.begin(), _arrayFields.end()); std::sort(_mapFields.begin(), _mapFields.end()); if (!_mapFields.empty()) { if (!_hasMapKey) { LOG(warning, "Missing key attribute '%s', have value attributes for map", keyName.c_str()); _error = true; } else if (_arrayFields.size() != 1u) { LOG(warning, "Could not determine if field '%s' is array or map of struct", fieldName.c_str()); _error = true; } } } } StructFields::~StructFields() = default; } AttributeCombinerDFW::AttributeCombinerDFW(const vespalib::string &fieldName) : ISimpleDFW(), _stateIndex(0), _fieldName(fieldName) { } AttributeCombinerDFW::~AttributeCombinerDFW() = default; bool AttributeCombinerDFW::IsGenerated() const { return true; } bool AttributeCombinerDFW::setFieldWriterStateIndex(uint32_t fieldWriterStateIndex) { _stateIndex = fieldWriterStateIndex; return true; } std::unique_ptr AttributeCombinerDFW::create(const vespalib::string &fieldName, IAttributeManager &attrMgr) { StructFields structFields(fieldName, attrMgr); if (structFields.getError()) { return std::unique_ptr(); } else if (!structFields.getMapFields().empty()) { return std::make_unique(fieldName, structFields.getMapFields()); } return std::make_unique(fieldName, structFields.getArrayFields()); } void AttributeCombinerDFW::insertField(uint32_t docid, GetDocsumsState *state, ResType, vespalib::slime::Inserter &target) { auto &fieldWriterState = state->_fieldWriterStates[_stateIndex]; if (!fieldWriterState) { fieldWriterState = allocFieldWriterState(*state->_attrCtx); } fieldWriterState->insertField(docid, target); } } 1-10 /* * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2009 Red Hat, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "ci/ciMethod.hpp" #include "shark/llvmHeaders.hpp" #include "shark/sharkIntrinsics.hpp" #include "shark/sharkState.hpp" #include "shark/sharkValue.hpp" #include "shark/shark_globals.hpp" using namespace llvm; bool SharkIntrinsics::is_intrinsic(ciMethod *target) { switch (target->intrinsic_id()) { case vmIntrinsics::_none: return false; // java.lang.Math case vmIntrinsics::_min: case vmIntrinsics::_max: case vmIntrinsics::_dabs: case vmIntrinsics::_dsin: case vmIntrinsics::_dcos: case vmIntrinsics::_dtan: case vmIntrinsics::_datan2: case vmIntrinsics::_dsqrt: case vmIntrinsics::_dlog: case vmIntrinsics::_dlog10: case vmIntrinsics::_dpow: case vmIntrinsics::_dexp: return true; // java.lang.Object case vmIntrinsics::_getClass: return true; // java.lang.System case vmIntrinsics::_currentTimeMillis: return true; // java.lang.Thread case vmIntrinsics::_currentThread: return true; // sun.misc.Unsafe case vmIntrinsics::_compareAndSwapInt: return true; default: if (SharkPerformanceWarnings) { warning( "unhandled intrinsic vmIntrinsic::%s", vmIntrinsics::name_at(target->intrinsic_id())); } } return false; } void SharkIntrinsics::inline_intrinsic(ciMethod *target, SharkState *state) { SharkIntrinsics intrinsic(state, target); intrinsic.do_intrinsic(); } void SharkIntrinsics::do_intrinsic() { switch (target()->intrinsic_id()) { // java.lang.Math case vmIntrinsics::_min: do_Math_minmax(llvm::ICmpInst::ICMP_SLE); break; case vmIntrinsics::_max: do_Math_minmax(llvm::ICmpInst::ICMP_SGE); break; case vmIntrinsics::_dabs: do_Math_1to1(builder()->fabs()); break; case vmIntrinsics::_dsin: do_Math_1to1(builder()->sin()); break; case vmIntrinsics::_dcos: do_Math_1to1(builder()->cos()); break; case vmIntrinsics::_dtan: do_Math_1to1(builder()->tan()); break; case vmIntrinsics::_datan2: do_Math_2to1(builder()->atan2()); break; case vmIntrinsics::_dsqrt: do_Math_1to1(builder()->sqrt()); break; case vmIntrinsics::_dlog: do_Math_1to1(builder()->log()); break; case vmIntrinsics::_dlog10: do_Math_1to1(builder()->log10()); break; case vmIntrinsics::_dpow: do_Math_2to1(builder()->pow()); break; case vmIntrinsics::_dexp: do_Math_1to1(builder()->exp()); break; // java.lang.Object case vmIntrinsics::_getClass: do_Object_getClass(); break; // java.lang.System case vmIntrinsics::_currentTimeMillis: do_System_currentTimeMillis(); break; // java.lang.Thread case vmIntrinsics::_currentThread: do_Thread_currentThread(); break; // sun.misc.Unsafe case vmIntrinsics::_compareAndSwapInt: do_Unsafe_compareAndSwapInt(); break; default: ShouldNotReachHere(); } } void SharkIntrinsics::do_Math_minmax(ICmpInst::Predicate p) { // Pop the arguments SharkValue *sb = state()->pop(); SharkValue *sa = state()->pop(); Value *a = sa->jint_value(); Value *b = sb->jint_value(); // Perform the test BasicBlock *ip = builder()->GetBlockInsertionPoint(); BasicBlock *return_a = builder()->CreateBlock(ip, "return_a"); BasicBlock *return_b = builder()->CreateBlock(ip, "return_b"); BasicBlock *done = builder()->CreateBlock(ip, "done"); builder()->CreateCondBr(builder()->CreateICmp(p, a, b), return_a, return_b); builder()->SetInsertPoint(return_a); builder()->CreateBr(done); builder()->SetInsertPoint(return_b); builder()->CreateBr(done); builder()->SetInsertPoint(done); PHINode *phi = builder()->CreatePHI(a->getType(), 0, "result"); phi->addIncoming(a, return_a); phi->addIncoming(b, return_b); // Push the result state()->push( SharkValue::create_jint( phi, sa->zero_checked() && sb->zero_checked())); } void SharkIntrinsics::do_Math_1to1(Value *function) { SharkValue *empty = state()->pop(); assert(empty == NULL, "should be"); state()->push( SharkValue::create_jdouble( builder()->CreateCall( function, state()->pop()->jdouble_value()))); state()->push(NULL); } void SharkIntrinsics::do_Math_2to1(Value *function) { SharkValue *empty = state()->pop(); assert(empty == NULL, "should be"); Value *y = state()->pop()->jdouble_value(); empty = state()->pop(); assert(empty == NULL, "should be"); Value *x = state()->pop()->jdouble_value(); state()->push( SharkValue::create_jdouble( builder()->CreateCall2(function, x, y))); state()->push(NULL); } void SharkIntrinsics::do_Object_getClass() { Value *klass = builder()->CreateValueOfStructEntry( state()->pop()->jobject_value(), in_ByteSize(oopDesc::klass_offset_in_bytes()), SharkType::klass_type(), "klass"); state()->push( SharkValue::create_jobject( builder()->CreateValueOfStructEntry( klass, Klass::java_mirror_offset(), SharkType::oop_type(), "java_mirror"), true)); } void SharkIntrinsics::do_System_currentTimeMillis() { state()->push( SharkValue::create_jlong( builder()->CreateCall(builder()->current_time_millis()), false)); state()->push(NULL); } void SharkIntrinsics::do_Thread_currentThread() { state()->push( SharkValue::create_jobject( builder()->CreateValueOfStructEntry( thread(), JavaThread::threadObj_offset(), SharkType::oop_type(), "threadObj"), true)); } void SharkIntrinsics::do_Unsafe_compareAndSwapInt() { // Pop the arguments Value *x = state()->pop()->jint_value(); Value *e = state()->pop()->jint_value(); SharkValue *empty = state()->pop(); assert(empty == NULL, "should be"); Value *offset = state()->pop()->jlong_value(); Value *object = state()->pop()->jobject_value(); Value *unsafe = state()->pop()->jobject_value(); // Convert the offset offset = builder()->CreateCall( builder()->unsafe_field_offset_to_byte_offset(), offset); // Locate the field Value *addr = builder()->CreateIntToPtr( builder()->CreateAdd( builder()->CreatePtrToInt(object, SharkType::intptr_type()), builder()->CreateIntCast(offset, SharkType::intptr_type(), true)), PointerType::getUnqual(SharkType::jint_type()), "addr"); // Perform the operation Value *result = builder()->CreateAtomicCmpXchg(addr, e, x, llvm::SequentiallyConsistent); // Push the result state()->push( SharkValue::create_jint( builder()->CreateIntCast( builder()->CreateICmpEQ(result, e), SharkType::jint_type(), true), false)); } #include #include #include #include "../audio.h" #include "../context.h" #include "../holders/audio_holder.h" void ImportMusic(Context& context, const std::string& path, const std::string& name) { context.Get()->RegisterMusic(path, name); } void ImportSFX(Context& context, const std::string& path, const std::string& name) { context.Get()->RegisterSFX(path, name); } void PlayMusic(const Context& context, const std::string& name, i32 loops) { context.Get()->GetMusic(name)->Play(loops); } void PlaySFX(const Context& context, const std::string& name, i32 loops, i32 ticks) { context.Get()->GetSFX(name)->Play(loops, ticks, -1); } void StopMusic(const Context& context, const std::string& name) { context.Get()->GetMusic(name)->Stop(); } void StopSFX(const Context& context, const std::string& name) { context.Get()->GetSFX(name)->Stop(); } glovecompress.hpp #pragma once #include #include #include #include #include "utils.hpp" namespace { /* Gets name of compression method */ static std::string getCompressionMethodStr(std::string& accepted, std::vector& compatible) { auto _accepted = tokenize(accepted, ",", defaultTrim); for (auto m: compatible) { auto el = std::find(_accepted.begin(), _accepted.end(), m); if (el != _accepted.end()) return *el; } return ""; } }; namespace GloveCompress { /* This errors are far from deflate/inflate errors, will indicate our destination buffer is not big enough to store the whole compressed or uncompressed data. */ const short ERR_UNDERSIZED = -100; const short ERR_DEFLATE_PARTIAL = -101; const short ERR_DEFLATE_PARTIAL_STREAM = -102; const short ERR_INVALID_METHOD = -103; const long CHUNK = 16384; static short getCompressionMethodCode(std::string name) { if (name == "gzip") return 1; else if (name =="deflate") return 0; return -1; } static std::string getCompressionMethodName(short code) { switch (code) { case 0: return "deflate"; case 1: return "gzip"; default: return ""; } } /* Will select one accepted method if compatible. After that, will get the code of the compression method*/ static short getCompressionMethod(std::string& accepted, std::vector& compatible) { auto cmet = getCompressionMethodStr(accepted, compatible); return getCompressionMethodCode(cmet); } /** *********************************** * Compress source data from memory to memory. * * @param source Source data * @param source_size Size of source data (if compressing a string, it can be strlen(source)+1) * @param dest Where to store compressed data * @param destination_size Max. size of compressed data * @param method 0 (deflate), 1 (gzip) * @param level Compession level * * @return If <0, error, Z_MEM_ERROR if could not allocate memory. * Z_VERSION_ERROR if version of zlib.h and linked library * Z_STREAM_ERROR if invalid compression level supplied. * ERR_UNDERSIZED if dest is not big enough to store all data * ERR_DEFLATE_PARTIAL if there was a problem running deflate * and it was not fully deflated * ERR_DEFLATE_PARTIAL_STREAM there was a problem and the compressed * stream does not ends right. * ERR_INVALID_METHOD if method number is not valid * If >0, size of compressed data */ static int dodeflate(char* source, size_t source_size, char* dest, size_t& destination_size, short method, int level) { int ret, flush; size_t have; z_stream strm; unsigned char *in = (unsigned char*)source; unsigned char *out = (unsigned char*)dest; size_t original_dest_size = destination_size; if ( (method<0) || (method>1) ) return ERR_INVALID_METHOD; /* Initialize deflate */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in; ret = (method==0)?deflateInit(&strm, level):deflateInit2(&strm, level, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY); if (ret != Z_OK) return ret; /* compress !! */ do { if (source_size>CHUNK) { strm.avail_in = CHUNK; source_size-=CHUNK; } else { strm.avail_in = source_size; source_size = 0; } flush = (source_size == 0) ? Z_FINISH : Z_NO_FLUSH; strm.next_in = in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = deflate(&strm, flush); /* no bad return value */ if (ret == Z_STREAM_ERROR) /* error check */ return ret; have = CHUNK - strm.avail_out; out+=have; /* Move out pointer */ destination_size-=have; /* calculate destination size left */ } while (strm.avail_out == 0); if (strm.avail_in != 0) return ERR_DEFLATE_PARTIAL; in+=CHUNK; /* Move in to the next chunk */ /* done when last data in file processed */ } while (flush != Z_FINISH); if (ret != Z_STREAM_END) return ERR_DEFLATE_PARTIAL_STREAM; /* clean up and return */ (void)deflateEnd(&strm); destination_size = original_dest_size-destination_size; return 0; } static int dodeflate(const std::string& in, std::string& out, short method, int level) { auto size = in.length(); out.clear(); out.resize(size); auto result = GloveCompress::dodeflate((char*)in.c_str(), size+1, &out[0], size, method, level); out.shrink_to_fit(); return result; } /* THIS FUNCTION WILL BE CHANGED SOON */ /** *********************************** * Uncompress source data from memory to memory. * * @param source Source data (compressed data) * @param source_size Size of source data * @param dest Where to store uncompressed data * @param destination_size Max. size of compressed data * * @return If <0, error, Z_DATA_ERROR if deflated data is invalid or incomplete * Z_VERSION_ERROR if version of zlib.h and linked library * Z_STREAM_ERROR if there was a problem deflating. * Z_MEM_ERROR problem allocating memory * ERR_UNDERSIZED if dest is not big enough to store all data * If >0, size of uncompressed data */ static int doinflate(char* source, size_t source_size, char* dest, size_t destination_size) { int ret; size_t have; z_stream strm; unsigned char* in = (unsigned char*)source; unsigned char* out = (unsigned char*)dest; size_t original_dest_size = destination_size; /* initialize z_stream */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) return ret; /* decompress until source is completelly read */ do { if (source_size>CHUNK) { strm.avail_in = CHUNK; source_size-=CHUNK; } else { strm.avail_in = source_size; source_size = 0; } strm.next_in = in; /* run inflate() on input until output buffer */ do { if (destination_size { argtype type() const override { return argtype::enum_value; } std::optional string() const override { return "locale"; } std::string_view description() const override { return "set the current locale"; } void operator()(app_settings&, std::string_view val) override { set_locale_all(std::string(val)); } }; android-opencv/opencv/modules/video/src/blobtrackingcc.cpp /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" static float CalcAverageMask(CvBlob* pBlob, IplImage* pImgFG) { /* Calculate sum of mask: */ double Area, Aver = 0; CvRect r; CvMat mat; if (pImgFG == NULL) { return 0; } r.x = cvRound(pBlob->x - pBlob->w * 0.5); r.y = cvRound(pBlob->y - pBlob->h * 0.5); r.width = cvRound(pBlob->w); r.height = cvRound(pBlob->h); Area = r.width * r.height; if (r.x < 0) {r.width += r.x; r.x = 0;} if (r.y < 0) {r.height += r.y; r.y = 0;} if ((r.x + r.width) >= pImgFG->width) {r.width = pImgFG->width - r.x - 1;} if ((r.y + r.height) >= pImgFG->height) {r.height = pImgFG->height - r.y - 1;} if (r.width > 0 && r.height > 0) { double Sum = cvSum(cvGetSubRect(pImgFG, &mat, r)).val[0] / 255.0; assert(Area > 0); Aver = Sum / Area; } return (float)Aver; } /* Calculate sum of mask. */ /*============== BLOB TRACKERCC CLASS DECLARATION =============== */ typedef struct DefBlobTracker { CvBlob blob; CvBlobTrackPredictor* pPredictor; CvBlob BlobPredict; int Collision; CvBlobSeq* pBlobHyp; float AverFG; } DefBlobTracker; void cvFindBlobsByCCClasters(IplImage* pFG, CvBlobSeq* pBlobs, CvMemStorage* storage); class CvBlobTrackerCC : public CvBlobTracker { private: float m_AlphaSize; float m_AlphaPos; float m_Alpha; int m_Collision; int m_ConfidenceType; const char* m_ConfidenceTypeStr; CvBlobSeq m_BlobList; CvBlobSeq m_BlobListNew; // int m_LastID; CvMemStorage* m_pMem; int m_ClearHyp; IplImage* m_pImg; IplImage* m_pImgFG; public: CvBlobTrackerCC(): m_BlobList(sizeof(DefBlobTracker)) { // m_LastID = 0; m_ClearHyp = 0; m_pMem = cvCreateMemStorage(); m_Collision = 1; /* if 1 then collistion will be detected and processed */ AddParam("Collision", &m_Collision); CommentParam("Collision", "If 1 then collision cases are processed in special way"); m_AlphaSize = 0.02f; AddParam("AlphaSize", &m_AlphaSize); CommentParam("AlphaSize", "Size update speed (0..1)"); m_AlphaPos = 1.0f; AddParam("AlphaPos", &m_AlphaPos); CommentParam("AlphaPos", "Position update speed (0..1)"); m_Alpha = 0.001f; AddParam("Alpha", &m_Alpha); CommentParam("Alpha", "Coefficient for model histogram updating (0 - hist is not updated)"); m_ConfidenceType = 0; m_ConfidenceTypeStr = "NearestBlob"; AddParam("ConfidenceType", &m_ConfidenceTypeStr); CommentParam("ConfidenceType", "Type of calculated Confidence (NearestBlob, AverFG, BC)"); SetModuleName("CC"); }; ~CvBlobTrackerCC() { if (m_pMem) { cvReleaseMemStorage(&m_pMem); } }; /* Blob functions: */ virtual int GetBlobNum() {return m_BlobList.GetBlobNum();}; virtual CvBlob* GetBlob(int BlobIndex) {return m_BlobList.GetBlob(BlobIndex);}; virtual void SetBlob(int BlobIndex, CvBlob* pBlob) { CvBlob* pB = m_BlobList.GetBlob(BlobIndex); if (pB) { pB[0] = pBlob[0]; } }; virtual CvBlob* GetBlobByID(int BlobID) {return m_BlobList.GetBlobByID(BlobID);}; virtual void DelBlob(int BlobIndex) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIndex); if (pBT == NULL) { return; } if (pBT->pPredictor) { pBT->pPredictor->Release(); } else { printf("WARNING!!! Invalid Predictor in CC tracker"); } delete pBT->pBlobHyp; m_BlobList.DelBlob(BlobIndex); }; #if 0 virtual void DelBlobByID(int BlobID) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlobByID(BlobID); pBT->pPredictor->Release(); delete pBT->pBlobHyp; m_BlobList.DelBlobByID(BlobID); }; #endif virtual void Release() {delete this;}; /* Add new blob to track it and assign to this blob personal ID */ /* pBlob - pinter to structure with blob parameters (ID is ignored)*/ /* pImg - current image */ /* pImgFG - current foreground mask */ /* return pointer to new added blob */ virtual CvBlob* AddBlob(CvBlob* pB, IplImage* /*pImg*/, IplImage* pImgFG = NULL) { assert(pImgFG); /* This tracker uses only foreground mask. */ DefBlobTracker NewB; NewB.blob = pB[0]; // CV_BLOB_ID(&NewB) = m_LastID; NewB.pBlobHyp = new CvBlobSeq; NewB.pPredictor = cvCreateModuleBlobTrackPredictKalman(); /* Module for position prediction. */ NewB.pPredictor->Update(pB); NewB.AverFG = pImgFG ? CalcAverageMask(pB, pImgFG) : 0; m_BlobList.AddBlob((CvBlob*)&NewB); return m_BlobList.GetBlob(m_BlobList.GetBlobNum() - 1); }; virtual void Process(IplImage* pImg, IplImage* pImgFG = NULL) { CvSeq* cnts; CvSeq* cnt; int i; m_pImg = pImg; m_pImgFG = pImgFG; if (m_BlobList.GetBlobNum() <= 0) { return; } /* Clear bloblist for new blobs: */ m_BlobListNew.Clear(); assert(m_pMem); cvClearMemStorage(m_pMem); assert(pImgFG); /* Find CC: */ #if 0 { // By contour clustering: cvFindBlobsByCCClasters(pImgFG, &m_BlobListNew, m_pMem); } #else { /* One contour - one blob: */ IplImage* pBin = cvCloneImage(pImgFG); assert(pBin); cvThreshold(pBin, pBin, 128, 255, CV_THRESH_BINARY); cvFindContours(pBin, m_pMem, &cnts, sizeof(CvContour), CV_RETR_EXTERNAL); /* Process each contour: */ for (cnt = cnts; cnt; cnt = cnt->h_next) { CvBlob NewBlob; /* Image moments: */ double M00, X, Y, XX, YY; CvMoments m; CvRect r = ((CvContour*)cnt)->rect; CvMat mat; if (r.height < 3 || r.width < 3) { continue; } cvMoments(cvGetSubRect(pImgFG, &mat, r), &m, 0); M00 = cvGetSpatialMoment(&m, 0, 0); if (M00 <= 0) { continue; } X = cvGetSpatialMoment(&m, 1, 0) / M00; Y = cvGetSpatialMoment(&m, 0, 1) / M00; XX = (cvGetSpatialMoment(&m, 2, 0) / M00) - X * X; YY = (cvGetSpatialMoment(&m, 0, 2) / M00) - Y * Y; NewBlob = cvBlob(r.x + (float)X, r.y + (float)Y, (float)(4 * sqrt(XX)), (float)(4 * sqrt(YY))); m_BlobListNew.AddBlob(&NewBlob); } /* Next contour. */ cvReleaseImage(&pBin); } #endif for (i = m_BlobList.GetBlobNum(); i > 0; --i) { /* Predict new blob position: */ CvBlob* pB = NULL; DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(i - 1); /* Update predictor by previous value of blob: */ pBT->pPredictor->Update(&(pBT->blob)); /* Predict current position: */ pB = pBT->pPredictor->Predict(); if (pB) { pBT->BlobPredict = pB[0]; } else { pBT->BlobPredict = pBT->blob; } } /* Predict new blob position. */ if (m_Collision) for (i = m_BlobList.GetBlobNum(); i > 0; --i) { /* Predict collision. */ int Collision = 0; int j; DefBlobTracker* pF = (DefBlobTracker*)m_BlobList.GetBlob(i - 1); for (j = m_BlobList.GetBlobNum(); j > 0; --j) { /* Predict collision: */ CvBlob* pB1; CvBlob* pB2; DefBlobTracker* pF2 = (DefBlobTracker*)m_BlobList.GetBlob(j - 1); if (i == j) { continue; } pB1 = &pF->BlobPredict; pB2 = &pF2->BlobPredict; if (fabs(pB1->x - pB2->x) < 0.6 *(pB1->w + pB2->w) && fabs(pB1->y - pB2->y) < 0.6 *(pB1->h + pB2->h)) { Collision = 1; } pB1 = &pF->blob; pB2 = &pF2->blob; if (fabs(pB1->x - pB2->x) < 0.6 *(pB1->w + pB2->w) && fabs(pB1->y - pB2->y) < 0.6 *(pB1->h + pB2->h)) { Collision = 1; } if (Collision) { break; } } /* Check next blob to cross current. */ pF->Collision = Collision; } /* Predict collision. */ for (i = m_BlobList.GetBlobNum(); i > 0; --i) { /* Find a neighbour on current frame * for each blob from previous frame: */ CvBlob* pB = m_BlobList.GetBlob(i - 1); DefBlobTracker* pBT = (DefBlobTracker*)pB; //int BlobID = CV_BLOB_ID(pB); //CvBlob* pBBest = NULL; //double DistBest = -1; //int j; if (pBT->pBlobHyp->GetBlobNum() > 0) { /* Track all hypotheses: */ int h, hN = pBT->pBlobHyp->GetBlobNum(); for (h = 0; h < hN; ++h) { int j, jN = m_BlobListNew.GetBlobNum(); CvBlob* pB = pBT->pBlobHyp->GetBlob(h); int BlobID = CV_BLOB_ID(pB); CvBlob* pBBest = NULL; double DistBest = -1; for (j = 0; j < jN; j++) { /* Find best CC: */ double Dist = -1; CvBlob* pBNew = m_BlobListNew.GetBlob(j); double dx = fabs(CV_BLOB_X(pB) - CV_BLOB_X(pBNew)); double dy = fabs(CV_BLOB_Y(pB) - CV_BLOB_Y(pBNew)); if (dx > 2 * CV_BLOB_WX(pB) || dy > 2 * CV_BLOB_WY(pB)) { continue; } Dist = sqrt(dx * dx + dy * dy); if (Dist < DistBest || pBBest == NULL) { DistBest = Dist; pBBest = pBNew; } } /* Find best CC. */ if (pBBest) { pB[0] = pBBest[0]; CV_BLOB_ID(pB) = BlobID; } else { /* Delete this hypothesis. */ pBT->pBlobHyp->DelBlob(h); h--; hN--; } } /* Next hypothysis. */ } /* Track all hypotheses. */ } /* Track next blob. */ m_ClearHyp = 1; } /* Process. */ virtual void ProcessBlob(int BlobIndex, CvBlob* pBlob, IplImage* /*pImg*/, IplImage* /*pImgFG*/ = NULL) { int ID = pBlob->ID; CvBlob* pB = m_BlobList.GetBlob(BlobIndex); DefBlobTracker* pBT = (DefBlobTracker*)pB; //CvBlob* pBBest = NULL; //double DistBest = -1; int BlobID; if (pB == NULL) { return; } BlobID = pB->ID; if (m_Collision && pBT->Collision) { /* Tracking in collision: */ pB[0] = pBT->BlobPredict; CV_BLOB_ID(pB) = BlobID; } /* Tracking in collision. */ else { /* Non-collision tracking: */ CvBlob* pBBest = GetNearestBlob(pB); if (pBBest) { float w = pBlob->w * (1 - m_AlphaSize) + m_AlphaSize * pBBest->w; float h = pBlob->h * (1 - m_AlphaSize) + m_AlphaSize * pBBest->h; float x = pBlob->x * (1 - m_AlphaPos) + m_AlphaPos * pBBest->x; float y = pBlob->y * (1 - m_AlphaPos) + m_AlphaPos * pBBest->y; pB->w = w; pB->h = h; pB->x = x; pB->y = y; CV_BLOB_ID(pB) = BlobID; } } /* Non-collision tracking. */ pBlob[0] = pB[0]; pBlob->ID = ID; }; virtual double GetConfidence(int BlobIndex, CvBlob* pBlob, IplImage* /*pImg*/, IplImage* pImgFG = NULL) { /* Define coefficients in exp by exp(-XT*K)=VT: */ static double _KS = -log(0.1) / pow(0.5, 2); /* XT = 1, VT = 0.1 - when size is Larger in 2 times Confidence is smoller in 10 times */ static double _KP = -log(0.1) / pow(m_pImg->width * 0.02, 2); /* XT = 0.02*ImgWidth, VT = 0.1*/ DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIndex); float dx, dy, dw, dh; float dp2, ds2; double W = 1; CvBlob* pBC = GetNearestBlob(pBlob); if (pBC == NULL) { return 0; } dx = pBC->x - pBlob->x; dy = pBC->y - pBlob->y; dw = (pBC->w - pBlob->w) / pBC->w; dh = (pBC->h - pBlob->h) / pBC->h; dp2 = dx * dx + dy * dy; ds2 = dw * dw + dh * dh; if (!pBT->Collision) { /* Confidence for size by nearest blob: */ W *= exp(-_KS * ds2); } if (m_ConfidenceType == 0 && !pBT->Collision) { /* Confidence by nearest blob: */ W *= exp(-_KP * dp2); } if (m_ConfidenceType == 1 && pBT->AverFG > 0) { /* Calculate sum of mask: */ float Aver = CalcAverageMask(pBlob, pImgFG); if (Aver < pBT->AverFG) { float diff = 1 + 0.9f * (Aver - pBT->AverFG) / pBT->AverFG; if (diff < 0.1f) { diff = 0.1f; } W *= diff; } } /* Calculate sum of mask. */ if (m_ConfidenceType == 2) { /* Calculate BCoeff: */ float S = 0.2f; float Aver = CalcAverageMask(pBlob, pImgFG); double B = sqrt(Aver * pBT->AverFG) + sqrt((1 - Aver) * (1 - pBT->AverFG)); W *= exp((B - 1) / (2 * S)); } /* Calculate sum of mask. */ return W; }; virtual void UpdateBlob(int BlobIndex, CvBlob* /*pBlob*/, IplImage* /*pImg*/, IplImage* pImgFG = NULL) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIndex); if (pImgFG == NULL || pBT == NULL) { return; } if (!pBT->Collision) { //pBT->AverFG = pBT->AverFG * (1-m_Alpha) + m_Alpha * CalcAverageMask(pBlob,pImgFG); } }; virtual void ParamUpdate() { const char* pCT[3] = {"NearestBlob", "AverFG", "BC"}; int i; CvBlobTracker::ParamUpdate(); for (i = 0; i < 3; ++i) { if (cv_stricmp(m_ConfidenceTypeStr, pCT[i]) == 0) { m_ConfidenceType = i; } } SetParamStr("ConfidenceType", pCT[m_ConfidenceType]); } /* =============== MULTI HYPOTHESIS INTERFACE ================== */ /* Return number of position hypotheses of currently tracked blob: */ virtual int GetBlobHypNum(int BlobIdx) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIdx); assert(pBT->pBlobHyp); return pBT->pBlobHyp->GetBlobNum(); }; /* CvBlobtrackerList::GetBlobHypNum() */ /* Return pointer to specified blob hypothesis by index blob: */ virtual CvBlob* GetBlobHyp(int BlobIndex, int hypothesis) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIndex); assert(pBT->pBlobHyp); return pBT->pBlobHyp->GetBlob(hypothesis); }; /* CvBlobtrackerList::GetBlobHyp() */ /* Set new parameters for specified (by index) blob hypothesis * (can be called several times for each hypothesis): */ virtual void SetBlobHyp(int BlobIndex, CvBlob* pBlob) { if (m_ClearHyp) { /* Clear all hypotheses: */ int b, bN = m_BlobList.GetBlobNum(); for (b = 0; b < bN; ++b) { DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(b); assert(pBT->pBlobHyp); pBT->pBlobHyp->Clear(); } m_ClearHyp = 0; } { /* Add hypothesis: */ DefBlobTracker* pBT = (DefBlobTracker*)m_BlobList.GetBlob(BlobIndex); assert(pBT->pBlobHyp); pBT->pBlobHyp->AddBlob(pBlob); } }; private: CvBlob* GetNearestBlob(CvBlob* pB) { //DefBlobTracker* pBT = (DefBlobTracker*)pB; CvBlob* pBBest = NULL; double DistBest = -1; int j, BlobID; if (pB == NULL) { return NULL; } BlobID = pB->ID; for (j = m_BlobListNew.GetBlobNum(); j > 0; --j) { /* Find best CC: */ double Dist = -1; CvBlob* pBNew = m_BlobListNew.GetBlob(j - 1); double dx = fabs(CV_BLOB_X(pB) - CV_BLOB_X(pBNew)); double dy = fabs(CV_BLOB_Y(pB) - CV_BLOB_Y(pBNew)); if (dx > 2 * CV_BLOB_WX(pB) || dy > 2 * CV_BLOB_WY(pB)) { continue; } Dist = sqrt(dx * dx + dy * dy); if (Dist < DistBest || pBBest == NULL) { DistBest = Dist; pBBest = pBNew; } } /* Find best CC. */ return pBBest; }; /* GetNearestBlob */ }; CvBlobTracker* cvCreateBlobTrackerCC() { return (CvBlobTracker*) new CvBlobTrackerCC; } /*============== BLOB TRACKERCC CLASS DECLARATION =============== */ /* * Copyright 2019 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 * * 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. */ /** * Note: this file has a self-contained implementation of `GeoPoint` that can * be used by the Android library. The resulting Android binary doesn't include * symbols from Firestore in third_party, so this implementation has to fill in. */ // TODO(b/138615769): remove this file. #include #include #include #include "app/src/assert.h" #include "firebase/firestore/geo_point.h" namespace firebase { namespace firestore { GeoPoint::GeoPoint(double latitude, double longitude) : latitude_(latitude), longitude_(longitude) { FIREBASE_ASSERT_MESSAGE( !std::isnan(latitude) && -90 <= latitude && latitude <= 90, "Latitude must be in the range of [-90, 90]"); FIREBASE_ASSERT_MESSAGE( !std::isnan(longitude) && -180 <= longitude && longitude <= 180, "Latitude must be in the range of [-180, 180]"); } std::string GeoPoint::ToString() const { std::ostringstream stream; stream << *this; return stream.str(); } std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point) { return out << "GeoPoint(latitude=" << geo_point.latitude() << ", longitude=" << geo_point.longitude() << ")"; } bool operator<(const GeoPoint& lhs, const GeoPoint& rhs) { if (lhs.latitude() == rhs.latitude()) { return lhs.longitude() < rhs.longitude(); } else { return lhs.latitude() < rhs.latitude(); } } } // namespace firestore } // namespace firebase #include "stdafx.h" #include "SnapStorage.h" #include "../../core_dispatcher.h" #include "../../main_window/history_control/complex_message/FileSharingUtils.h" #include "../../main_window/contact_list/ContactListModel.h" #include "../../main_window/contact_list/SnapItemDelegate.h" #include "../../my_info.h" #include "../../gui_settings.h" #include "../../utils/utils.h" #include "../../utils/gui_coll_helper.h" #include "../../../common.shared/loader_errors.h" namespace { const int snap_border_radius = 8; } namespace Logic { SnapStorage::SnapStorage() : expiredId_(-1) { expiredTimer_ = new QTimer(this); expiredTimer_->setSingleShot(true); connect(expiredTimer_, SIGNAL(timeout()), this, SLOT(expired()), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(userSnaps(Logic::UserSnapsInfo, bool)), this, SLOT(userSnaps(Logic::UserSnapsInfo, bool)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(userSnapsStorage(QList, bool)), this, SLOT(userSnapsStorage(QList, bool)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(userSnapsState(Logic::SnapState)), this, SLOT(userSnapsState(Logic::SnapState)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(snapPreviewInfoDownloaded(qint64, QString, QString, bool)), this, SLOT(snapPreviewInfoDownloaded(qint64, QString, QString, bool)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(imageDownloaded(qint64, QString, QPixmap, QString)), this, SLOT(imageDownloaded(qint64, QString, QPixmap, QString)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(fileSharingFileDownloaded(qint64, QString, QString)), this, SLOT(fileDownloaded(qint64, QString, QString)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(fileSharingFileDownloading(qint64, QString, qint64, qint64)), this, SLOT(fileDownloading(qint64, QString, qint64, qint64)), Qt::QueuedConnection); connect(Ui::GetDispatcher(), SIGNAL(fileSharingError(qint64, QString, qint32)), this, SLOT(fileSharingError(qint64, QString, qint32)), Qt::QueuedConnection); } SnapStorage::~SnapStorage() { } QVariant SnapStorage::data(const QModelIndex& _index, int _role) const { if (!_index.isValid()) return QVariant(); return QVariant::fromValue(getData(_index.row(), _index.column())); } Qt::ItemFlags SnapStorage::flags(const QModelIndex& _index) const { if (!_index.isValid()) return Qt::ItemIsEnabled; unsigned flags = QAbstractItemModel::flags(_index) | Qt::ItemIsEnabled; flags |= ~Qt::ItemIsEditable; return (Qt::ItemFlags)flags; } void SnapStorage::startTv(int row, int col) { PlayList_.clear(); auto& index = Index_; if (row == getFeaturedRow()) index = FeaturedIndex_; else if (row != getFriendsRow()) return; if (col > index.size()) return; QList result; for (auto i = col; i < index.size(); ++i) { auto u = index[i]; { for (auto s : u.Snaps_) { if (s.getId() > u.State_.LastViewedSnapId_ || u.State_.LastViewedSnapId_ == -1) { PlayItem snap; snap.AimId_ = u.AimId_; snap.OriginalAimId_ = s.OriginalAimId_; snap.Url_ = s.Url_; snap.Id_ = s.SnapId_; snap.Preview_ = s.FullPreview_; snap.LocalPath_ = s.LocalPath_; snap.First_ = PlayList_.isEmpty(); PlayList_.push_back(snap); PreviewItem item; item.AimId_ = u.AimId_; item.Id_ = s.SnapId_; if (!result.contains(item)) result.push_back(item); } } } } if (PlayList_.isEmpty()) { for (auto i = col; i < index.size(); ++i) { auto u = index[i]; { for (auto s : u.Snaps_) { PlayItem snap; snap.AimId_ = u.AimId_; snap.OriginalAimId_ = s.OriginalAimId_; snap.Url_ = s.Url_; snap.Id_ = s.SnapId_; snap.Preview_ = s.FullPreview_; snap.LocalPath_ = s.LocalPath_; snap.First_ = PlayList_.isEmpty(); PlayList_.push_back(snap); PreviewItem item; item.AimId_ = u.AimId_; item.Id_ = s.SnapId_; if (!result.contains(item)) result.push_back(item); } } } } if (!PlayList_.isEmpty()) emit tvStarted(result, PlayList_.front().LocalPath_.isEmpty()); processPlaylist(); } void SnapStorage::startUserSnaps(const QString& _aimId) { auto aimId = _aimId.isEmpty() ? Ui::MyInfo()->aimId() : _aimId; if (!Snaps_.contains(aimId)) return; auto u = Snaps_[aimId]; if (u.Snaps_.isEmpty()) return; for (auto s : u.Snaps_) { PlayItem snap; snap.AimId_ = u.AimId_; snap.OriginalAimId_ = s.OriginalAimId_; snap.Url_ = s.Url_; snap.Id_ = s.SnapId_; snap.Preview_ = s.FullPreview_; snap.LocalPath_ = s.LocalPath_; snap.User_ = true; snap.First_ = PlayList_.isEmpty(); PlayList_.push_back(snap); } processPlaylist(); } QPixmap SnapStorage::getFirstUserPreview(const QString& _aimId) { QPixmap result; auto aimId = _aimId.isEmpty() ? Ui::MyInfo()->aimId() : _aimId; if (!Snaps_.contains(aimId)) return result; auto u = Snaps_[aimId]; if (u.Snaps_.isEmpty()) return result; return u.Snaps_.first().SourcePreview_; } QPixmap SnapStorage::getSnapPreviewFull(qint64 _id) { for (auto u : Snaps_) { for (auto s : u.Snaps_) { if (s.SnapId_ == _id) return s.FullPreview_; } } return QPixmap(); } QString SnapStorage::getSnapUrl(qint64 _id) { for (auto u : Snaps_) { for (auto s : u.Snaps_) { if (s.SnapId_ == _id) return s.Url_; } } return QString(); } int SnapStorage::getSnapsCount(const QString& _aimId) const { auto u = Snaps_.find(_aimId); if (u == Snaps_.end()) return 0; return u->Snaps_.size(); } int SnapStorage::loadingSnapsCount(const QString& _aimId) const { int result = 0; for (auto p : PlayList_) { if (p.AimId_ == _aimId) ++result; } return result; } QString SnapStorage::getFriednly(const QString& _aimId) const { QString result = Logic::getContactListModel()->getDisplayName(_aimId); if (Snaps_.find(_aimId) == Snaps_.end()) { for (auto u : Snaps_) { for (auto s : u.Snaps_) { if (s.OriginalAimId_ == _aimId) { return s.OriginalFriendly_.isEmpty() ? result : s.OriginalFriendly_; } } } return result; } else if (Snaps_[_aimId].Friendly_.isEmpty()) { return result; } if (result != _aimId) return result; return Snaps_[_aimId].Friendly_; } bool SnapStorage::isOfficial(const QString& _aimId) const { if (!Snaps_.contains(_aimId)) return false; return Snaps_[_aimId].IsOfficial_; } int SnapStorage::getViews(qint64 id) const { for (auto u : Snaps_) { for (auto s : u.Snaps_) { if (s.SnapId_ == id) return s.Views_; } } return 0; } int32_t SnapStorage::getTimestamp(qint64 id) const { for (auto u : Snaps_) { for (auto s : u.Snaps_) { if (s.SnapId_ == id) return s.Timestamp_; } } return 0; } PlayItem SnapStorage::getLoadingSnap() const { if (PlayList_.isEmpty()) return PlayItem(); return PlayList_.front(); } bool SnapStorage::haveLoading() const { return !PlayList_.empty(); } int SnapStorage::getFriendsSnapsCount() const { return Index_.size(); } int SnapStorage::getFeaturedSnapsCount() const { return FeaturedIndex_.size(); } void SnapStorage::readSnap(const QString& aimId, qint64 id) { for (QMap::iterator i = Snaps_.begin(); i != Snaps_.end(); ++i) { if (i->AimId_ == aimId) { if (i->State_.LastViewedSnapId_ < id) { i->State_.LastViewedSnapId_ = id; calcUserLastSnaps(aimId); } } } rebuildIndex(false); Ui::GetDispatcher()->read_snap(aimId, id, true); } void SnapStorage::clearPlaylist() { PlayList_.clear(); } void SnapStorage::refresh() { Ui::gui_coll_helper collection(Ui::GetDispatcher()->create_collection(), true); Ui::GetDispatcher()->post_message_to_core("snaps/refresh", collection.get()); } void SnapStorage::fileDownloaded(qint64 _seq, QString _url, QString _localPath) { if (!Seq_.contains(_seq)) return; Seq_.removeAll(_seq); updateSnapLocalPath(_url, _localPath); for (QMap::iterator i = Snaps_.begin(); i != Snaps_.end(); ++i) { for (QList::iterator is = i->Snaps_.begin(); is != i->Snaps_.end(); ++is) { if (is->Url_ == _url) { is->LocalPath_ = _localPath; for (QList::iterator iter = PlayList_.begin(); iter != PlayList_.end(); ++iter) { if (iter->Url_ == _url) { iter->LocalPath_ = _localPath; processPlaylist(); return; } } } } } } void SnapStorage::fileDownloading(qint64 _seq, QString _url, qint64 _downloaded, qint64 _total) { if (!Seq_.contains(_seq)) return; for (auto i : PlayList_) { if (i.Url_ == _url) { int percents = ((float)_downloaded / _total) * 100; emit snapProgress(_url, percents); return; } } } void SnapStorage::fileSharingError(qint64 _seq, QString _url, qint32 _err) { if (!Seq_.contains(_seq)) return; Seq_.removeAll(_seq); if ((loader_errors)_err == loader_errors::metainfo_not_found) { if (PlayList_.begin()->Url_ == _url) PlayList_.pop_front(); } processPlaylist(); } void SnapStorage::userSnapsState(Logic::SnapState _state) { for (QMap::iterator i = Snaps_.begin(); i != Snaps_.end(); ++i) { if (i->AimId_ == _state.AimId_) { i->State_ = _state; calcUserLastSnaps(_state.AimId_); } } rebuildIndex(false); } void SnapStorage::expired() { if (expiredId_ != -1) { bool found = false; for (QMap::iterator u = Snaps_.begin(); u != Snaps_.end();) { for (QList::iterator iter = u->Snaps_.begin(); iter != u->Snaps_.end();) { if (iter->SnapId_ == expiredId_) { found = true; iter = u->Snaps_.erase(iter); } else { ++iter; } } if (u->Snaps_.isEmpty()) { Ui::gui_coll_helper collection(Ui::GetDispatcher()->create_collection(), true); collection.set_value_as_qstring("aimid", u->AimId_); Ui::GetDispatcher()->post_message_to_core("snaps/remove_from_cache", collection.get()); u = Snaps_.erase(u); } else { ++u; } if (found) break; } } rebuildIndex(false); } void SnapStorage::clearStorage() { DownloadingUrls_.clear(); Seq_.clear(); Snaps_.clear(); rebuildIndex(false); } void SnapStorage::userSnaps(Logic::UserSnapsInfo _info, bool _fromRefresh) { if (!updateSnaps(_info) && !_fromRefresh) return; rebuildIndex(false); } void SnapStorage::userSnapsStorage(QList _snaps, bool _fromCache) { for (auto s : _snaps) { updateSnaps(s); } rebuildIndex(_fromCache); if (_fromCache) refresh(); } void SnapStorage::snapPreviewInfoDownloaded(qint64 _snapId, QString _preview, QString _ttl_id, bool _found) { for (QMap::iterator i = Snaps_.begin(); i != Snaps_.end(); ) { for (QList::iterator is = i->Snaps_.begin(); is != i->Snaps_.end();) { if (is->getId() == _snapId || is->TtlId_ == _ttl_id) { if (!_found) { DownloadingUrls_.removeAll(is->Url_); is = i->Snaps_.erase(is); continue; } is->PreviewUri_ = _preview; if (!_preview.isEmpty()) { auto raise = Ui::get_gui_settings()->get_value(settings_show_snaps, false); is->PreviewSeq_ = Ui::GetDispatcher()->downloadImage(_preview, i->AimId_, QString(), false, 0, 0, raise); Seq_.push_back(is->PreviewSeq_); } } ++is; } if (!_found && i->Snaps_.isEmpty()) { i = Snaps_.erase(i); continue; } ++i; } if (!_found) rebuildIndex(false); } void SnapStorage::imageDownloaded(qint64 _seq, QString _rawUri, QPixmap _image, QString _localPath) { if (!Seq_.contains(_seq)) return; for (QMap::iterator i = Snaps_.begin(); i != Snaps_.end(); ++i) { for (QList::iterator is = i->Snaps_.begin(); is != i->Snaps_.end(); ++is) { if (is->PreviewSeq_ == _seq) { is->SourcePreview_ = _image; is->MiniPreview_ = preparePreview(_image); is->FullPreview_ = prepareFull(_image); is->PreviewSeq_ = -1; Seq_.removeAll(_seq); updateSnapImage(is->getId(), _image); return; } } } } bool SnapStorage::updateSnaps(Logic::UserSnapsInfo _info) { auto cur = QDateTime::currentDateTimeUtc(); for (QList::iterator iter = _info.Snaps_.begin(); iter != _info.Snaps_.end();) { auto ts = QDateTime::fromTime_t(iter->Timestamp_); if (ts.secsTo(cur) > iter->Ttl_) iter = _info.Snaps_.erase(iter); else ++iter; } const auto haveSnaps = !_info.Snaps_.empty(); QStringList snapsUrls; if (!haveSnaps) { Snaps_.remove(_info.AimId_); emit removed(_info.AimId_); return true; } else { if (Snaps_.contains(_info.AimId_)) { if (Snaps_[_info.AimId_].Snaps_.size() == _info.Snaps_.size()) { for (int i = 0; i < _info.Snaps_.size(); ++i) { if (Snaps_[_info.AimId_].Snaps_[i].getId() != _info.Snaps_[i].getId()) { snapsUrls << _info.Snaps_[i].Url_; } } } else { for (int i = 0; i < Snaps_[_info.AimId_].Snaps_.size(); ++i) { auto s = Snaps_[_info.AimId_].Snaps_[i]; if (!_info.Snaps_.contains(s)) { emit snapRemoved(_info.AimId_, s.SnapId_, s.LocalPath_); } } for (auto s : _info.Snaps_) { snapsUrls << s.Url_; } } for (QList::iterator is = _info.Snaps_.begin(); is != _info.Snaps_.end(); ++is) { for (auto us : Snaps_[_info.AimId_].Snaps_) { if (is->getId() == us.getId()) { is->PreviewSeq_ = us.PreviewSeq_; is->PreviewUri_ = us.PreviewUri_; is->FullPreview_ = us.FullPreview_; is->MiniPreview_ = us.MiniPreview_; } } } Snaps_[_info.AimId_] = _info; } else { for (auto s : _info.Snaps_) { snapsUrls << s.Url_; } Snaps_[_info.AimId_] = _info; } } if (haveSnaps) { qSort(Snaps_[_info.AimId_].Snaps_.begin(), Snaps_[_info.AimId_].Snaps_.end(), [](const SnapInfo& first, const SnapInfo& second) { return first.Timestamp_ < second.Timestamp_; }); calcUserLastSnaps(_info.AimId_); } return !snapsUrls.isEmpty(); } QPixmap SnapStorage::preparePreview(const QPixmap& _preview) { auto previewSize = Logic::SnapItemDelegate::getSnapPreviewItemSize(); QPixmap p; auto originalFactor = (double)_preview.height() / (double)_preview.width(); auto previewFactor = (double)previewSize.height() / (double)previewSize.width(); if (_preview.height() > _preview.width() && (originalFactor >= previewFactor)) { p = _preview.scaledToWidth(previewSize.width(), Qt::SmoothTransformation); } else { p = _preview.scaledToHeight(previewSize.height(), Qt::SmoothTransformation); } auto r = QRect(p.width() / 2 - previewSize.width() / 2, p.height() / 2 - previewSize.height() / 2, previewSize.width(), previewSize.height()); QPixmap result = p.copy(r); QImage resultImg(result.size(), QImage::Format_ARGB32); QPainter painter(&resultImg); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::SmoothPixmapTransform); QColor color1(Qt::black); color1.setAlpha(0.3 * 255); QColor color2(Qt::black); color2.setAlpha(0.1 * 255); QColor color3(Qt::black); color3.setAlpha(0); auto gHeight = Logic::SnapItemDelegate::getGradientHeight(); auto gRect = QRect(0, resultImg.height() - gHeight, resultImg.width(), gHeight); QLinearGradient g(gRect.topLeft(), gRect.bottomLeft()); g.setColorAt(0, color3); g.setColorAt(0.7, color2); g.setColorAt(1, color1); QPainter gPainter(&result); gPainter.setRenderHint(QPainter::Antialiasing); gPainter.setRenderHint(QPainter::SmoothPixmapTransform); gPainter.fillRect(gRect, g); painter.fillRect(resultImg.rect(), Qt::white); auto b = QBrush(result); painter.setBrush(b); painter.setPen(QPen(Qt::transparent, 0)); painter.drawRoundedRect(resultImg.rect(), Utils::scale_value(snap_border_radius), Utils::scale_value(snap_border_radius)); return QPixmap::fromImage(resultImg); } QPixmap SnapStorage::prepareFull(const QPixmap& _preview) { return _preview; } void SnapStorage::rebuildIndex(bool fromCache) { Index_.clear(); FeaturedIndex_.clear(); auto myAimId = Ui::MyInfo()->aimId(); for (auto s : Snaps_) { if (s.IsFriend_ || s.AimId_ == myAimId) Index_.push_back(s); else FeaturedIndex_.push_back(s); } std::sort(FeaturedIndex_.begin(), FeaturedIndex_.end(), [](const Logic::UserSnapsInfo& first, Logic::UserSnapsInfo& second) { if (first.LastNewSnapTimestamp_ != 0 && second.LastNewSnapTimestamp_ != 0) return first.LastNewSnapTimestamp_ > second.LastNewSnapTimestamp_; if (first.LastNewSnapTimestamp_ != 0) return true; if (second.LastNewSnapTimestamp_ != 0) return false; return first.LastSnapTimestamp_ > second.LastSnapTimestamp_; }); std::sort(Index_.begin(), Index_.end(), [myAimId](const Logic::UserSnapsInfo& first, Logic::UserSnapsInfo& second) { if (first.LastNewSnapTimestamp_ != 0 && second.LastNewSnapTimestamp_ != 0) return first.LastNewSnapTimestamp_ > second.LastNewSnapTimestamp_; if (first.LastNewSnapTimestamp_ != 0) return true; if (second.LastNewSnapTimestamp_ != 0) return false; return first.LastSnapTimestamp_ > second.LastSnapTimestamp_; }); int32_t firstExpiredTime = -1; int32_t firstExpiredTtl = -1; qint64 firstExpiredId = -1; for (auto u : Snaps_) { int32_t timestamp = -1; for (auto s : u.Snaps_) { if (firstExpiredTime == -1 || (s.Timestamp_ + s.Ttl_) < (firstExpiredTime + firstExpiredTtl)) { firstExpiredTime = s.Timestamp_; firstExpiredTtl = s.Ttl_; firstExpiredId = s.SnapId_; } if (s.Timestamp_ > timestamp) { timestamp = s.Timestamp_; } if (!s.Url_.isEmpty() && !DownloadingUrls_.contains(s.Url_)) { auto raise = Ui::get_gui_settings()->get_value(settings_show_snaps, false); Ui::GetDispatcher()->download_snap_metainfo(u.AimId_, Ui::ComplexMessage::extractIdFromFileSharingUri(s.Url_), raise); DownloadingUrls_ << s.Url_; } } } expiredTimer_->stop(); expiredId_ = -1; if (firstExpiredTime != -1) { expiredId_ = firstExpiredId; auto expired = QDateTime::fromTime_t(firstExpiredTime + firstExpiredTtl); auto cur = QDateTime::currentDateTimeUtc(); auto interval = cur.msecsTo(expired); expiredTimer_->setInterval(interval); expiredTimer_->start(); } else { int i = 1; } emit dataChanged(index(0, 0), index(rowCount(), columnCount())); int rows = 0; if (!Index_.empty()) ++rows; if (!FeaturedIndex_.empty()) ++rows; setRowCount(rows); setColumnCount(std::max(Index_.size(), FeaturedIndex_.size())); emit indexChanged(); } Logic::SnapItem SnapStorage::getData(int row, int col) const { Logic::SnapItem item; if (row != getFriendsRow() && row != getFeaturedRow()) return item; const auto& index = row == getFeaturedRow() ? FeaturedIndex_ : Index_; if (col >= index.size()) return item; UserSnapsInfo u = index[col]; item.AimId_ = u.AimId_; item.Friendly_ = u.Friendly_; item.Views_ = u.State_.Views_; item.IsOfficial_ = u.IsOfficial_; int timestamp = 0; for (auto s : u.Snaps_) { if (s.getId() > u.State_.LastViewedSnapId_ || u.State_.LastViewedSnapId_ == -1) item.HaveNewSnap_ = true; if (s.Timestamp_ > timestamp) { timestamp = s.Timestamp_; item.Snap_ = s.MiniPreview_; } } return item; } void SnapStorage::calcUserLastSnaps(const QString& _aimid) { int32_t lastSnapTimestamp = 0; int32_t lastNewSnapTimestamp = 0; for (auto s : Snaps_[_aimid].Snaps_) { if (s.Timestamp_ > lastSnapTimestamp) lastSnapTimestamp = s.Timestamp_; if ((s.getId() > Snaps_[_aimid].State_.LastViewedSnapId_ || Snaps_[_aimid].State_.LastViewedSnapId_ == -1) && s.Timestamp_ > lastNewSnapTimestamp) lastNewSnapTimestamp = s.Timestamp_; } Snaps_[_aimid].LastSnapTimestamp_ = lastSnapTimestamp; Snaps_[_aimid].LastNewSnapTimestamp_ = lastNewSnapTimestamp; } void SnapStorage::updateSnapImage(qint64 _snapId, QPixmap _image) { for (unsigned i = 0; i < Index_.size(); ++i) { for (QList::iterator is = Index_[i].Snaps_.begin(); is != Index_[i].Snaps_.end(); ++is) { if (is->getId() == _snapId) { is->SourcePreview_ = _image; is->MiniPreview_ = preparePreview(_image); is->FullPreview_ = prepareFull(_image); emit dataChanged(index(0, 0), index(rowCount(), columnCount())); emit previewChanged(Index_[i].AimId_); } } } for (unsigned i = 0; i < FeaturedIndex_.size(); ++i) { for (QList::iterator is = FeaturedIndex_[i].Snaps_.begin(); is != FeaturedIndex_[i].Snaps_.end(); ++is) { if (is->getId() == _snapId) { is->SourcePreview_ = _image; is->MiniPreview_ = preparePreview(_image); is->FullPreview_ = prepareFull(_image); emit dataChanged(index(0, 0), index(rowCount(), columnCount())); emit previewChanged(FeaturedIndex_[i].AimId_); } } } } void SnapStorage::updateSnapLocalPath(const QString& _url, const QString& _local) { for (unsigned i = 0; i < Index_.size(); ++i) { for (QList::iterator is = Index_[i].Snaps_.begin(); is != Index_[i].Snaps_.end(); ++is) { if (is->Url_ == _url) { is->LocalPath_ = _local; } } } for (unsigned i = 0; i < FeaturedIndex_.size(); ++i) { for (QList::iterator is = FeaturedIndex_[i].Snaps_.begin(); is != FeaturedIndex_[i].Snaps_.end(); ++is) { if (is->Url_ == _url) { is->LocalPath_ = _local; } } } } void SnapStorage::downloadSnap(const QString& _aimId, const QString& _url) { Seq_.push_back(Ui::GetDispatcher()->downloadSharedFile(_aimId, _url, false, QString(), true)); } void SnapStorage::processPlaylist() { QList::iterator iter = PlayList_.begin(); while (iter != PlayList_.end() && !iter->LocalPath_.isEmpty()) { if (iter->User_) emit playUserSnap(iter->LocalPath_, iter->AimId_, iter->OriginalAimId_, iter->Url_, iter->Id_, iter->First_); else emit playSnap(iter->LocalPath_, iter->AimId_, iter->OriginalAimId_, iter->Url_, iter->Id_, iter->First_); iter = PlayList_.erase(iter); } if (!PlayList_.isEmpty()) { auto item = PlayList_.begin(); downloadSnap(item->AimId_, item->Url_); } } SnapStorage* GetSnapStorage() { static std::unique_ptr storage(new SnapStorage()); return storage.get(); } } 100-1000 #define SIZE 128 void prefixsum(int in[SIZE], int out[SIZE]) { out[0]=in[0]; for(int i = 1; i < SIZE; i++) { #pragma HLS PIPELINE out[i] = out[i-1] + in[i]; } } Eigenbaukombinat/ebk_co2ampel #include #include "MHZ19.h" #include "SSD1306Wire.h" #include // Maximum CO² levels for green and yellow, everything above is considered red. #define GREEN_CO2 800 #define YELLOW_CO2 1500 // Measurement interval in miliseconds #define INTERVAL 10000 // Pins for MH-Z19 #define RX_PIN 16 #define TX_PIN 17 // Pins for SD1306 #define SDA_PIN 21 #define SCL_PIN 22 // Pin for LED #define LED_PIN 4 MHZ19 myMHZ19; HardwareSerial mySerial(1); SSD1306Wire display(0x3c, SDA_PIN, SCL_PIN); Adafruit_NeoPixel pixels = Adafruit_NeoPixel(1, LED_PIN, NEO_RGB + NEO_KHZ400); unsigned long getDataTimer = 0; int lastvals[120]; int dheight; void setup() { Serial.begin(9600); mySerial.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN); myMHZ19.begin(mySerial); display.init(); display.setContrast(255); delay(1000); display.clear(); dheight = display.getHeight(); myMHZ19.autoCalibration(); // Fill array of last measurements with -1 for (int x = 0; x <= 119; x = x + 1) { lastvals[x] = -1; } pixels.begin(); pixels.setPixelColor(0, 30,0,0); pixels.show(); } int calc_vpos_for_co2(int co2val, int display_height) { return display_height - int((float(display_height) / 3000) * co2val); } void set_led_color(int co2) { if (co2 < GREEN_CO2) { // Green pixels.setPixelColor(0, 30,0,0); } else if (co2 < YELLOW_CO2) { // Yellow pixels.setPixelColor(0, 40,40, 0); } else { // Red pixels.setPixelColor(0, 0,90,0); } pixels.show(); } void loop() { if (millis() - getDataTimer >= INTERVAL) { // Get new CO² value. int CO2 = myMHZ19.getCO2(); // Shift entries in array back one position. for (int x = 1; x <= 119; x = x + 1) { lastvals[x - 1] = lastvals[x]; } // Add new measurement at the end. lastvals[119] = CO2; // Clear display and redraw whole graph. display.clear(); for (int h = 1; h < 120; h = h + 1) { int curval = lastvals[h]; if (curval > 0) { int vpos = calc_vpos_for_co2(lastvals[h], dheight); int vpos_last = calc_vpos_for_co2(lastvals[h - 1], dheight); display.drawLine(h - 1, vpos_last, h, vpos); } } // Set LED color and print value on display set_led_color(CO2); display.setLogBuffer(1, 30); display.println(CO2); display.drawLogBuffer(0, 0); display.display(); // Debug output Serial.print("CO2 (ppm): "); Serial.println(CO2); getDataTimer = millis(); } }jpokornyiii/allwpilibhal/src/main/native/sim/mockdata/SimDeviceData.cpp // Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "hal/simulation/SimDeviceData.h" // NOLINT(build/include_order) #include #include "SimDeviceDataInternal.h" using namespace hal; namespace hal::init { void InitializeSimDeviceData() { static SimDeviceData sdd; ::hal::SimSimDeviceData = &sdd; } } // namespace hal::init SimDeviceData* hal::SimSimDeviceData; SimDeviceData::Device* SimDeviceData::LookupDevice(HAL_SimDeviceHandle handle) { if (handle <= 0) { return nullptr; } --handle; if (static_cast(handle) >= m_devices.size() || !m_devices[handle]) { return nullptr; } return m_devices[handle].get(); } SimDeviceData::Value* SimDeviceData::LookupValue(HAL_SimValueHandle handle) { if (handle <= 0) { return nullptr; } // look up device Device* deviceImpl = LookupDevice(handle >> 16); if (!deviceImpl) { return nullptr; } // look up value handle &= 0xffff; --handle; if (static_cast(handle) >= deviceImpl->values.size() || !deviceImpl->values[handle]) { return nullptr; } return deviceImpl->values[handle].get(); } void SimDeviceData::SetDeviceEnabled(const char* prefix, bool enabled) { std::scoped_lock lock(m_mutex); auto it = std::find_if(m_prefixEnabled.begin(), m_prefixEnabled.end(), [=](const auto& elem) { return elem.first == prefix; }); if (it != m_prefixEnabled.end()) { it->second = enabled; return; } m_prefixEnabled.emplace_back(prefix, enabled); // keep it sorted by name // string comparison sorts shorter before longer, so reverse the sort std::sort(m_prefixEnabled.begin(), m_prefixEnabled.end(), [](const auto& l, const auto& r) { return l.first >= r.first; }); } bool SimDeviceData::IsDeviceEnabled(const char* name) { std::scoped_lock lock(m_mutex); for (const auto& elem : m_prefixEnabled) { if (wpi::StringRef{name}.startswith(elem.first)) { return elem.second; } } return true; } HAL_SimDeviceHandle SimDeviceData::CreateDevice(const char* name) { std::scoped_lock lock(m_mutex); // don't create if disabled for (const auto& elem : m_prefixEnabled) { if (wpi::StringRef{name}.startswith(elem.first)) { if (elem.second) { break; // enabled } return 0; // disabled } } // check for duplicates and don't overwrite them if (m_deviceMap.count(name) > 0) { return 0; } // don't allow more than 4096 devices (limit driven by 12-bit allocation in // value changed callback uid) if (m_devices.size() >= 4095) { return 0; } // create and save auto deviceImpl = std::make_shared(name); HAL_SimDeviceHandle deviceHandle = m_devices.emplace_back(deviceImpl) + 1; deviceImpl->handle = deviceHandle; m_deviceMap[name] = deviceImpl; // notify callbacks m_deviceCreated(name, deviceHandle); return deviceHandle; } void SimDeviceData::FreeDevice(HAL_SimDeviceHandle handle) { std::scoped_lock lock(m_mutex); --handle; // see if it exists if (handle < 0 || static_cast(handle) >= m_devices.size()) { return; } auto deviceImpl = std::move(m_devices[handle]); if (!deviceImpl) { return; } // remove from map m_deviceMap.erase(deviceImpl->name); // remove from vector m_devices.erase(handle); // notify callbacks m_deviceFreed(deviceImpl->name.c_str(), handle + 1); } HAL_SimValueHandle SimDeviceData::CreateValue( HAL_SimDeviceHandle device, const char* name, int32_t direction, int32_t numOptions, const char** options, const double* optionValues, const HAL_Value& initialValue) { std::scoped_lock lock(m_mutex); // look up device Device* deviceImpl = LookupDevice(device); if (!deviceImpl) { return 0; } // check for duplicates and don't overwrite them auto it = deviceImpl->valueMap.find(name); if (it != deviceImpl->valueMap.end()) { return 0; } // don't allow more than 4096 values per device (limit driven by 12-bit // allocation in value changed callback uid) if (deviceImpl->values.size() >= 4095) { return 0; } // create and save; encode device into handle auto valueImplPtr = std::make_unique(name, direction, initialValue); Value* valueImpl = valueImplPtr.get(); HAL_SimValueHandle valueHandle = (device << 16) | (deviceImpl->values.emplace_back(std::move(valueImplPtr)) + 1); valueImpl->handle = valueHandle; // copy options (if any provided) if (numOptions > 0 && options) { valueImpl->enumOptions.reserve(numOptions); valueImpl->cstrEnumOptions.reserve(numOptions); for (int32_t i = 0; i < numOptions; ++i) { valueImpl->enumOptions.emplace_back(options[i]); // point to our copy of the string, not the passed-in one valueImpl->cstrEnumOptions.emplace_back( valueImpl->enumOptions.back().c_str()); } } // copy option values (if any provided) if (numOptions > 0 && optionValues) { valueImpl->enumOptionValues.assign(optionValues, optionValues + numOptions); } deviceImpl->valueMap[name] = valueImpl; // notify callbacks deviceImpl->valueCreated(name, valueHandle, direction, &initialValue); return valueHandle; } HAL_Value SimDeviceData::GetValue(HAL_SimValueHandle handle) { std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); if (!valueImpl) { HAL_Value value; value.data.v_int = 0; value.type = HAL_UNASSIGNED; return value; } return valueImpl->value; } void SimDeviceData::SetValue(HAL_SimValueHandle handle, const HAL_Value& value) { std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); if (!valueImpl) { return; } valueImpl->value = value; // notify callbacks valueImpl->changed(valueImpl->name.c_str(), valueImpl->handle, valueImpl->direction, &value); } int32_t SimDeviceData::RegisterDeviceCreatedCallback( const char* prefix, void* param, HALSIM_SimDeviceCallback callback, bool initialNotify) { std::scoped_lock lock(m_mutex); // register callback int32_t index = m_deviceCreated.Register(prefix, param, callback); // initial notifications if (initialNotify) { for (auto&& device : m_devices) { if (wpi::StringRef{device->name}.startswith(prefix)) { callback(device->name.c_str(), param, device->handle); } } } return index; } void SimDeviceData::CancelDeviceCreatedCallback(int32_t uid) { if (uid <= 0) { return; } std::scoped_lock lock(m_mutex); m_deviceCreated.Cancel(uid); } int32_t SimDeviceData::RegisterDeviceFreedCallback( const char* prefix, void* param, HALSIM_SimDeviceCallback callback) { std::scoped_lock lock(m_mutex); return m_deviceFreed.Register(prefix, param, callback); } void SimDeviceData::CancelDeviceFreedCallback(int32_t uid) { if (uid <= 0) { return; } std::scoped_lock lock(m_mutex); m_deviceFreed.Cancel(uid); } HAL_SimDeviceHandle SimDeviceData::GetDeviceHandle(const char* name) { std::scoped_lock lock(m_mutex); auto it = m_deviceMap.find(name); if (it == m_deviceMap.end()) { return 0; } if (auto deviceImpl = it->getValue().lock()) { return deviceImpl->handle; } else { return 0; } } const char* SimDeviceData::GetDeviceName(HAL_SimDeviceHandle handle) { std::scoped_lock lock(m_mutex); // look up device Device* deviceImpl = LookupDevice(handle); if (!deviceImpl) { return nullptr; } return deviceImpl->name.c_str(); } void SimDeviceData::EnumerateDevices(const char* prefix, void* param, HALSIM_SimDeviceCallback callback) { std::scoped_lock lock(m_mutex); for (auto&& device : m_devices) { if (wpi::StringRef{device->name}.startswith(prefix)) { callback(device->name.c_str(), param, device->handle); } } } int32_t SimDeviceData::RegisterValueCreatedCallback( HAL_SimDeviceHandle device, void* param, HALSIM_SimValueCallback callback, bool initialNotify) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); if (!deviceImpl) { return -1; } // register callback int32_t index = deviceImpl->valueCreated.Register(callback, param); // initial notifications if (initialNotify) { for (auto&& value : deviceImpl->values) { callback(value->name.c_str(), param, value->handle, value->direction, &value->value); } } // encode device into uid return (device << 16) | (index & 0xffff); } void SimDeviceData::CancelValueCreatedCallback(int32_t uid) { if (uid <= 0) { return; } std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(uid >> 16); if (!deviceImpl) { return; } deviceImpl->valueCreated.Cancel(uid & 0xffff); } int32_t SimDeviceData::RegisterValueChangedCallback( HAL_SimValueHandle handle, void* param, HALSIM_SimValueCallback callback, bool initialNotify) { std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); if (!valueImpl) { return -1; } // register callback int32_t index = valueImpl->changed.Register(callback, param); // initial notification if (initialNotify) { callback(valueImpl->name.c_str(), param, valueImpl->handle, valueImpl->direction, &valueImpl->value); } // encode device and value into uid return (((handle >> 16) & 0xfff) << 19) | ((handle & 0xfff) << 7) | (index & 0x7f); } void SimDeviceData::CancelValueChangedCallback(int32_t uid) { if (uid <= 0) { return; } std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(((uid >> 19) << 16) | ((uid >> 7) & 0xfff)); if (!valueImpl) { return; } valueImpl->changed.Cancel(uid & 0x7f); } HAL_SimValueHandle SimDeviceData::GetValueHandle(HAL_SimDeviceHandle device, const char* name) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); if (!deviceImpl) { return 0; } // lookup value auto it = deviceImpl->valueMap.find(name); if (it == deviceImpl->valueMap.end()) { return 0; } if (!it->getValue()) { return 0; } return it->getValue()->handle; } void SimDeviceData::EnumerateValues(HAL_SimDeviceHandle device, void* param, HALSIM_SimValueCallback callback) { std::scoped_lock lock(m_mutex); Device* deviceImpl = LookupDevice(device); if (!deviceImpl) { return; } for (auto&& value : deviceImpl->values) { callback(value->name.c_str(), param, value->handle, value->direction, &value->value); } } const char** SimDeviceData::GetValueEnumOptions(HAL_SimValueHandle handle, int32_t* numOptions) { *numOptions = 0; std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); if (!valueImpl) { return nullptr; } // get list of options (safe to return as they never change) auto& options = valueImpl->cstrEnumOptions; *numOptions = options.size(); return options.data(); } const double* SimDeviceData::GetValueEnumDoubleValues(HAL_SimValueHandle handle, int32_t* numOptions) { *numOptions = 0; std::scoped_lock lock(m_mutex); Value* valueImpl = LookupValue(handle); if (!valueImpl) { return nullptr; } // get list of option values (safe to return as they never change) auto& optionValues = valueImpl->enumOptionValues; *numOptions = optionValues.size(); return optionValues.data(); } void SimDeviceData::ResetData() { std::scoped_lock lock(m_mutex); m_devices.clear(); m_deviceMap.clear(); m_prefixEnabled.clear(); m_deviceCreated.Reset(); m_deviceFreed.Reset(); } extern "C" { void HALSIM_SetSimDeviceEnabled(const char* prefix, HAL_Bool enabled) { SimSimDeviceData->SetDeviceEnabled(prefix, enabled); } HAL_Bool HALSIM_IsSimDeviceEnabled(const char* name) { return SimSimDeviceData->IsDeviceEnabled(name); } int32_t HALSIM_RegisterSimDeviceCreatedCallback( const char* prefix, void* param, HALSIM_SimDeviceCallback callback, HAL_Bool initialNotify) { return SimSimDeviceData->RegisterDeviceCreatedCallback( prefix, param, callback, initialNotify); } void HALSIM_CancelSimDeviceCreatedCallback(int32_t uid) { SimSimDeviceData->CancelDeviceCreatedCallback(uid); } int32_t HALSIM_RegisterSimDeviceFreedCallback(const char* prefix, void* param, HALSIM_SimDeviceCallback callback, HAL_Bool initialNotify) { return SimSimDeviceData->RegisterDeviceFreedCallback(prefix, param, callback); } void HALSIM_CancelSimDeviceFreedCallback(int32_t uid) { SimSimDeviceData->CancelDeviceFreedCallback(uid); } HAL_SimDeviceHandle HALSIM_GetSimDeviceHandle(const char* name) { return SimSimDeviceData->GetDeviceHandle(name); } const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) { return SimSimDeviceData->GetDeviceName(handle); } HAL_SimDeviceHandle HALSIM_GetSimValueDeviceHandle(HAL_SimValueHandle handle) { if (handle <= 0) { return 0; } return handle >> 16; } void HALSIM_EnumerateSimDevices(const char* prefix, void* param, HALSIM_SimDeviceCallback callback) { SimSimDeviceData->EnumerateDevices(prefix, param, callback); } int32_t HALSIM_RegisterSimValueCreatedCallback(HAL_SimDeviceHandle device, void* param, HALSIM_SimValueCallback callback, HAL_Bool initialNotify) { return SimSimDeviceData->RegisterValueCreatedCallback(device, param, callback, initialNotify); } void HALSIM_CancelSimValueCreatedCallback(int32_t uid) { SimSimDeviceData->CancelValueCreatedCallback(uid); } int32_t HALSIM_RegisterSimValueChangedCallback(HAL_SimValueHandle handle, void* param, HALSIM_SimValueCallback callback, HAL_Bool initialNotify) { return SimSimDeviceData->RegisterValueChangedCallback(handle, param, callback, initialNotify); } void HALSIM_CancelSimValueChangedCallback(int32_t uid) { SimSimDeviceData->CancelValueChangedCallback(uid); } HAL_SimValueHandle HALSIM_GetSimValueHandle(HAL_SimDeviceHandle device, const char* name) { return SimSimDeviceData->GetValueHandle(device, name); } void HALSIM_EnumerateSimValues(HAL_SimDeviceHandle device, void* param, HALSIM_SimValueCallback callback) { SimSimDeviceData->EnumerateValues(device, param, callback); } const char** HALSIM_GetSimValueEnumOptions(HAL_SimValueHandle handle, int32_t* numOptions) { return SimSimDeviceData->GetValueEnumOptions(handle, numOptions); } const double* HALSIM_GetSimValueEnumDoubleValues(HAL_SimValueHandle handle, int32_t* numOptions) { return SimSimDeviceData->GetValueEnumDoubleValues(handle, numOptions); } void HALSIM_ResetSimDeviceData(void) { SimSimDeviceData->ResetData(); } } // extern "C" 10-100 //+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1998 - 1999 // // File: ci64.hxx // // Contents: Content index specific 32 <-> 64 bit portability definitions // // History: 22-Apr-98 vikasman Created // //-------------------------------------------------------------------------- #pragma once #include #include #include "cidebnot.h" inline LONG CiPtrToLong( LONG_PTR p ) { Win4Assert( p <= LONG_MAX && p >= LONG_MIN ); return PtrToLong( (PVOID)p ); } #define CiPtrToInt( p ) CiPtrToLong( p ) inline ULONG CiPtrToUlong( ULONG_PTR p ) { Win4Assert( p <= ULONG_MAX ); return PtrToUlong( (PVOID)p ); } #define CiPtrToUint( p ) CiPtrToUlong( p ) // // On Win64 a PROPVARIANT is 24 bytes // 2 for vartype // 6 for packing // 4 for ULONG count // 4 for alignment // 8 for pointer // // On Win32 a PROPVARIANT is 16 bytes // 2 for vartype // 6 for packing // 4 for ULONG count // 4 for pointer // #define SizeOfWin32PROPVARIANT 16 #ifdef _WIN64 #define PTR32 DWORD #else #define PTR32 LPVOID #endif typedef struct tagBLOB32 { ULONG cbSize; // number of bytes PTR32 pBlob; // 32 pointer } BLOB32; typedef struct tagPROPVARIANT32 { VARTYPE vt; WORD wReserved1; WORD wReserved2; WORD wReserved3; union { PTR32 p; // 32 bit pointer BLOB32 blob; // blob data ULONGLONG uhVal; // 64 bit data }; }PROPVARIANT32; typedef struct tagSAFEARRAY32 { USHORT cDims; USHORT fFeatures; ULONG cbElements; ULONG cLocks; PTR32 pvData; // 32-bit pointer SAFEARRAYBOUND rgsabound[ 1 ]; } SAFEARRAY32; typedef struct tagCLIPDATA32 { ULONG cbSize; long ulClipFmt; /* [size_is] */ PTR32 pClipData; } CLIPDATA32; // protocol/binary/binarysession.hpp // // Copyright (c) 2013 () // // This file is part of SolidFrame framework. // // 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. // #ifndef SOLID_PROTOCOL_BINARY_SESSION_HPP #define SOLID_PROTOCOL_BINARY_SESSION_HPP #include #include #include "system/debug.hpp" #include "utility/dynamicpointer.hpp" #include "utility/queue.hpp" #include "utility/stack.hpp" namespace solid{ namespace protocol{ namespace binary{ struct PacketHeader{ enum{ SizeOf = 4, DataType = 1, CompressedFlag = 1 }; PacketHeader( const uint8 _type = 0, const uint8 _flags = 0, const uint16 _size = 0 ): type(_type), flags(_flags), size(_size){} void reset( const uint8 _type = 0, const uint8 _flags = 0, const uint16 _size = 0 ){ type = _type; flags = _flags; size = _size; } bool isDataType()const{ return type == DataType; } bool isCompressed()const{ return flags & CompressedFlag; } template char* store(S &_rs, char * _pc)const{ _pc = _rs.storeValue(_pc, type); _pc = _rs.storeValue(_pc, flags); _pc = _rs.storeValue(_pc, size); return _pc; } template const char* load(D &_rd, const char *_pc){ _pc = _rd.loadValue(_pc, type); _pc = _rd.loadValue(_pc, flags); _pc = _rd.loadValue(_pc, size); return _pc; } uint8 type; uint8 flags; uint16 size; }; struct DummyCompressor{ const size_t reservedSize()const{ return 0; } bool shouldCompress(const size_t _sz)const{ return false; } bool compress(char *_pdest, size_t &_destsz, const char *_psrc, const size_t _srcsz){ return false; } bool decompress(char *_pdest, size_t &_destsz, const char *_psrc, const size_t _srcsz){ return false; } }; struct BasicController{ template void onDoneSend(Ctx &_rctx, const size_t _msgidx){} template void onSend(Ctx &_rctx, const size_t _sz){} template void onRecv(Ctx &_rctx, const size_t _sz){} }; template class Session{ struct MessageStub{ MessageStub():sndflgs(0), onsendq(false){} void sendClear(){ sndmsgptr.clear(); sndflgs = 0; onsendq = false; } void recvClear(){ rcvmsgptr.clear(); } MsgCtx ctx; DynamicPointer sndmsgptr; DynamicPointer rcvmsgptr; uint32 sndflgs; bool onsendq; }; enum{ RecvPacketHeaderState = 1, RecvPacketDataState }; public: Session():rcvbufoff(0), cnsbufoff(0), rcvstate(RecvPacketHeaderState), rcvmsgidx(-1){} template Session(T &_rt):ctl(_rt), rcvbufoff(0), cnsbufoff(0), rcvstate(RecvPacketHeaderState), rcvmsgidx(-1){ } size_t send(size_t _idx, DynamicPointer &_rmsgptr, uint32 _flags = 0){ if(_idx == static_cast(-1)){ _idx = msgvec.size(); } if(_idx >= msgvec.size()){ msgvec.resize(_idx + 1); } MessageStub &rms = msgvec[_idx]; cassert(!rms.onsendq); rms.sndflgs = _flags; rms.sndmsgptr = _rmsgptr; rms.onsendq = true; sndq.push(_idx); return _idx; } size_t send(const size_t _idx, DynamicPointer &_rmsgptr, MsgCtx &_rmsgctx, uint32 _flags = 0){ if(_idx >= msgvec.size()){ msgvec.resize(_idx + 1); } MessageStub &rms = msgvec[_idx]; cassert(!rms.onsendq); rms.sndflgs = _flags; rms.ctx = _rmsgctx; rms.sndmsgptr = _rmsgptr; rms.onsendq = true; sndq.push(_idx); return _idx; } DynamicPointer& sendMessage(const size_t _idx){ cassert(_idx < msgvec.size()); return msgvec[_idx].sndmsgptr; } DynamicPointer const& sendMessage(const size_t _idx)const{ cassert(_idx < msgvec.size()); return msgvec[_idx].sndmsgptr; } DynamicPointer& recvMessage(const size_t _idx){ cassert(_idx < msgvec.size()); return msgvec[_idx].rcvmsgptr; } DynamicPointer const& recvMessage(const size_t _idx)const{ cassert(_idx < msgvec.size()); return msgvec[_idx].rcvmsgptr; } MsgCtx& messageContext(const size_t _idx){ cassert(_idx < msgvec.size()); return msgvec[_idx].ctx; } const MsgCtx& messageContext(const size_t _idx)const{ cassert(_idx < msgvec.size()); return msgvec[_idx].ctx; } bool isSendQueueEmpty()const{ return sndq.empty(); } bool isFreeSend(const size_t _idx){ if(_idx < msgvec.size()){ MessageStub &rms = msgvec[_idx]; return !rms.onsendq; }else return true; } //protected: char * recvBufferOffset(char *_pbuf)const{ return _pbuf + rcvbufoff; } const size_t recvBufferCapacity(const size_t _cp)const{ return _cp - rcvbufoff; } template bool consume( Des &_rd, Ctx &_rctx, char *_pb, size_t _bl, C &_rc, char *_tmpbuf, const size_t _tmpbufcp ){ typedef C CompressorT; typedef Des DeserializerT; if(!_bl) return true; rcvbufoff += _bl; const char *cnspos = _pb + cnsbufoff; size_t cnslen = rcvbufoff - cnsbufoff; while(cnslen){ if(rcvstate == RecvPacketHeaderState){ if(cnslen < PacketHeader::SizeOf){ optimizeRecvBuffer(_pb); return true; } rcvstate = RecvPacketDataState; } PacketHeader pkthdr; pkthdr.load(_rd, cnspos); if((pkthdr.size + PacketHeader::SizeOf) > cnslen){ optimizeRecvBuffer(_pb); return true;//wait for more data } //we have the entire packet size_t destsz = _tmpbufcp; const char *crttmppos = _tmpbuf; size_t crttmplen; if(pkthdr.isCompressed()){ if(!_rc.decompress(_tmpbuf, destsz, cnspos + PacketHeader::SizeOf, pkthdr.size)){ return false; } crttmplen = destsz; }else{ crttmppos = cnspos + PacketHeader::SizeOf; crttmplen = pkthdr.size; } while(crttmplen){ if(_rd.empty()){ crttmppos = _rd.loadValue(crttmppos, rcvmsgidx); crttmplen -= sizeof(uint32); if(rcvmsgidx >= msgvec.size()){ msgvec.resize(rcvmsgidx + 1); } idbgx(Debug::proto_bin, "receive message on pos "< int fill( Ser &_rs, Ctx &_rctx, char *_pb, size_t _bl, C &_rc, char *_tmpbuf, const size_t _tmpbufcp ){ typedef C CompressorT; typedef Ser SerializerT; if(sndq.empty()) return 0; char *crtpos = _pb; size_t crtlen = _bl; while(crtlen >= _tmpbufcp && sndq.size()){ char *crttmppos = _tmpbuf; size_t crttmplen = _tmpbufcp; size_t crttmpsz = 0; crttmplen -= PacketHeader::SizeOf; crttmplen -= _rc.reservedSize(); while(crttmplen > 8 && sndq.size()){ const size_t msgidx = sndq.front(); MessageStub &rms = msgvec[msgidx]; if(_rs.empty()){ crttmppos = _rs.storeValue(crttmppos, static_cast(msgidx)); crttmplen -= sizeof(uint32); crttmpsz += sizeof(uint32); idbgx(Debug::proto_bin, "send message on pos "< int fill( Ser &_rs, Ctx &_rctx, char *_pb, size_t _bl ){ typedef Ser SerializerT; if(sndq.empty()) return 0; char *crtpos = _pb; size_t crtlen = _bl; char *crttmppos = crtpos + PacketHeader::SizeOf; size_t crttmplen = crtlen - PacketHeader::SizeOf; size_t crttmpsz = 0; while(crttmplen > 8 && sndq.size()){ MessageStub &rms = msgvec[sndq.front()]; if(_rs.empty()){ crttmppos = _rs.storeValue(crttmppos, static_cast(sndq.front())); crttmplen -= sizeof(uint32); crttmpsz += sizeof(uint32); _rs.push(rms.sndmsgptr.get(), "message"); } _rctx.sendMessageIndex(sndq.front()); int rv = _rs.run(crttmppos, crttmplen, _rctx); if(rv < 0){ rms.sendClear(); sndq.pop(); ctl.onDoneSend(_rctx); return -1; }else if(_rs.empty()){ rms.sendClear(); sndq.pop(); ctl.onDoneSend(_rctx); } crttmppos += rv; crttmplen -= rv; crttmpsz += rv; } size_t destsz = crttmpsz; uint8 pkgflags = 0; PacketHeader pkthdr(PacketHeader::DataType, pkgflags, destsz); crtpos = pkthdr.store(_rs, crtpos); //crtlen -= (destsz + PacketHeader::SizeOf); crtpos += destsz; return crtpos - _pb; } private: void optimizeRecvBuffer(char *_pb){ const size_t cnssz = rcvbufoff - cnsbufoff; if(cnssz <= cnsbufoff){ idbgx(Debug::proto_bin, "memcopy "< #endif #include "TableConnectionData.hxx" namespace dbaui { class IRelationControlInterface { public: virtual ~IRelationControlInterface(){} /** getConnectionData returns the current connection data @return the current connectiondata */ virtual TTableConnectionData::value_type getConnectionData() const = 0; /** setValid set the valid inside, can be used for OK buttons @param _bValid true when the using control allows an update */ virtual void setValid(sal_Bool _bValid) = 0; virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getConnection() = 0; /** notifyConnectionChange is callback which is called when the table selection has changed and a new connection exists @param _pConnectionData the connection which exists between the new tables */ virtual void notifyConnectionChange() = 0; }; } #endif // DBAUI_RELCONTROLIFACE_HXX AlesMaver/ExpansionHunter // // Expansion Hunter // Copyright 2016-2019 Illumina, Inc. // All rights reserved. // // Author: <> // // 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 #include #include #include #include #include #include "graphalign/GraphAlignment.hh" #include "graphcore/Graph.hh" #include "common/Common.hh" #include "common/GenomicRegion.hh" #include "common/Reference.hh" namespace ehunter { class LocusStats { public: LocusStats(AlleleCount alleleCount, int meanReadLength, double depth) : alleleCount_(alleleCount) , meanReadLength_(meanReadLength) , depth_(depth) { } AlleleCount alleleCount() const { return alleleCount_; } int meanReadLength() const { return meanReadLength_; } double depth() const { return depth_; } bool operator==(const LocusStats& other) const; private: AlleleCount alleleCount_; int meanReadLength_; double depth_; }; std::ostream& operator<<(std::ostream& out, const LocusStats& stats); } /* The MIT License (MIT) (http://opensource.org/licenses/MIT) Copyright (c) 2015 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 "RKFWSensorManagerInternals.h" #include #include #include "RKFWCriticalSectionEnterer.h" namespace RKFW { SensorManagerInternals::SensorManagerInternals( SensorManager* parentSensorManager ) : mParentSensorManager(parentSensorManager), mCriticalSection(), mSensors(), mRecentlyAttachedSensorIds(), mRecentlyDetachedSensorIds(), mCreateSensorsFromIndices(true), mListeners() { InitializeCriticalSection( &mCriticalSection ); } SensorManagerInternals::~SensorManagerInternals() { Sensors sensors = mSensors; // The copy is on purpose here for ( std::size_t i=0; igetConnectionId() ); assert( mSensors.empty() ); // http://social.msdn.microsoft.com/Forums/en-US/kinectsdknuiapi/thread/ee5b3708-a279-48cf-bd1e-8dbc72dc2e23 // Note I suppose this removes all the registered callbacks including the ones that may have been registered // outside the scope of this library :( NuiSetDeviceStatusCallback( NULL, NULL ); DeleteCriticalSection( &mCriticalSection ); } void SensorManagerInternals::update() { if ( mCreateSensorsFromIndices ) { NuiSetDeviceStatusCallback( &sensorStatusProc, this ); // Enumerate and create sensors. After this initially enumeration, // the device status callback will take over to update the list of sensors createSensorsFromIndices(); mCreateSensorsFromIndices = false; } updateSensorList(); for ( Sensors::iterator itr=mSensors.begin(); itr!=mSensors.end(); ++itr ) (*itr)->update(); } bool SensorManagerInternals::createSensorsFromIndices() { int numSensors = 0; HRESULT hr = NuiGetSensorCount( &numSensors ); if ( FAILED(hr) ) return false; for ( int i=0; iisValid() ) return false; // Check for sensor id collision std::wstring sensorId = sensor->getConnectionId(); for ( std::size_t i=0; igetConnectionId()==sensorId ) return false; // Notify for ( Listeners::const_iterator itr=mListeners.begin(); itr!=mListeners.end(); ++itr ) (*itr)->onSensorAdding( mParentSensorManager ); mSensors.push_back( sensor ); // Notify for ( Listeners::const_iterator itr=mListeners.begin(); itr!=mListeners.end(); ++itr ) (*itr)->onSensorAdded( mParentSensorManager, sensor ); return true; } bool SensorManagerInternals::createSensorFromIndex( int index ) { if ( index<0 ) return false; Sensor* sensor = new Sensor( index ); if ( !addSensor( sensor ) ) { delete sensor; return false; } return true; } bool SensorManagerInternals::createSensorFromId( const std::wstring& sensorId ) { // Pre-check that we're not trying to create a Sensor with the same id as an existing one for ( std::size_t i=0; igetConnectionId()==sensorId ) return false; Sensor* sensor = new Sensor( sensorId ); if ( !addSensor( sensor ) ) { delete sensor; return false; } return true; } bool SensorManagerInternals::deleteSensor( const std::wstring& sensorId ) { Sensors::iterator itr = mSensors.begin(); while ( itr!=mSensors.end() ) { if ( (*itr)->getConnectionId()==sensorId ) break; else *itr++; } if ( itr==mSensors.end() ) return false; Sensor* sensor = *itr; // Notify for ( Listeners::const_iterator itr=mListeners.begin(); itr!=mListeners.end(); ++itr ) (*itr)->onSensorRemoving( mParentSensorManager, sensor ); mSensors.erase( itr ); delete sensor; // Notify for ( Listeners::const_iterator itr=mListeners.begin(); itr!=mListeners.end(); ++itr ) (*itr)->onSensorRemoved( mParentSensorManager, sensor ); return true; } void SensorManagerInternals::updateSensorList() { std::vector recentlyAttachedSensorIds; std::vector recentlyDetachedSensorIds; { CriticalSectionEnterer criticalSectionRAII( mCriticalSection ); recentlyAttachedSensorIds = mRecentlyAttachedSensorIds; mRecentlyAttachedSensorIds.clear(); recentlyDetachedSensorIds = mRecentlyDetachedSensorIds; mRecentlyDetachedSensorIds.clear(); } for ( std::size_t i=0; i( pUserData ); assert( internals ); CriticalSectionEnterer criticalSectionRAII( internals->mCriticalSection ); // After investigation, the status passed by the system to the callback works as follow: // - when the sensor is plugged-in, there's a call with S_NUI_INITIALIZING then another one // with the status indicating success (S_OK) or the nature of the problem (E_NUI_INSUFFICIENTBANDWIDTH, etc...) // - when the sensor is disconnected, the call is done with a status set to E_NUI_NOTPOWERED (under Parallels Desktop) // or E_NUI_DISCONNECTED (under Boot Camp) // The following implementation only notifies the manager of a new sensor when it fully works. That means the // manager can't tell the client code if a problematic sensor is plugged in and what's the problem. if ( hrStatus==S_OK ) { std::wstring attachedSensorId = instanceName; std::vector& attachedSensorIds = internals->mRecentlyAttachedSensorIds; if ( std::find( attachedSensorIds.begin(), attachedSensorIds.end(), attachedSensorId )==attachedSensorIds.end() ) attachedSensorIds.push_back( attachedSensorId ); } else if ( hrStatus==E_NUI_NOTPOWERED || hrStatus==E_NUI_NOTCONNECTED ) { std::wstring detachedSensorId = instanceName; std::vector & detachedSensorIds = internals->mRecentlyDetachedSensorIds; if ( std::find( detachedSensorIds.begin(), detachedSensorIds.end(), detachedSensorId )==detachedSensorIds.end() ) detachedSensorIds.push_back( detachedSensorId ); } } /* void SensorManagerInternals::wideCharStringToMultiByteString( const wchar_t* wideCharString, std::string& multiByteString ) { assert( wideCharString ); size_t size = wcslen(wideCharString)+1; char* buffer = new char[size]; size_t numCharConverted = 0; int ret = wcstombs_s( &numCharConverted, buffer, size, wideCharString, size ); if ( ret==0 ) multiByteString = buffer; delete[] buffer; }*/ void SensorManagerInternals::addListener( SensorManager::Listener* listener ) { assert(listener); mListeners.push_back(listener); } bool SensorManagerInternals::removeListener( SensorManager::Listener* listener ) { Listeners::iterator itr = std::find( mListeners.begin(), mListeners.end(), listener ); if ( itr==mListeners.end() ) return false; mListeners.erase( itr ); return true; } }tests/tlrCoreTest/StringFormatTest.cpp0 // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2021 // All rights reserved. #include #include #include using namespace tlr::string; namespace tlr { namespace CoreTest { StringFormatTest::StringFormatTest(const std::shared_ptr& context) : ITest("CoreTest::StringFormatTest", context) {} std::shared_ptr StringFormatTest::create(const std::shared_ptr& context) { return std::shared_ptr(new StringFormatTest(context)); } void StringFormatTest::run() { { const std::string s = Format(""); TLR_ASSERT(s.empty()); } { const std::string s = Format("abc"); TLR_ASSERT("abc" == s); } { const std::string s = Format("{0}{1}{2}").arg("a").arg("b").arg("c"); TLR_ASSERT("abc" == s); } { const std::string s = Format("{0}{1}{2}").arg(1).arg(2).arg(3); TLR_ASSERT("123" == s); } { const std::string s = Format("{0}").arg(1.0F, 2); TLR_ASSERT("1.00" == s); } { const std::string s = Format("{0}").arg(1.0, 2); TLR_ASSERT("1.00" == s); } { const auto f = Format("").arg(1); TLR_ASSERT(f.hasError()); std::stringstream ss; ss << "String format error: " << f.getError(); _print(ss.str()); } { const auto f = Format("{0}{0}").arg(0).arg(1); TLR_ASSERT(f.hasError()); std::stringstream ss; ss << "String format error: " << f.getError(); _print(ss.str()); } } } } Samples/Unmanaged/NativeSystem/NetworkEngine.cpp #include #include "NetworkEngine.h" NetworkEngine::NetworkEngine() { } NetworkEngine::~NetworkEngine() { } void NetworkEngine::send(int idx, Log* log) { std::cout << "NetworkEngine is sending ..." << std::endl; } 0 #include "benchmark/benchmark.h" // The following lines pull in the real gbenchmark *.cc files. #include "src/benchmark.cc" #include "src/benchmark_register.cc" #include "src/colorprint.cc" #include "src/commandlineflags.cc" #include "src/complexity.cc" #include "src/console_reporter.cc" #include "src/counter.cc" #include "src/csv_reporter.cc" #include "src/json_reporter.cc" #include "src/reporter.cc" #include "src/sleep.cc" #include "src/statistics.cc" #include "src/string_util.cc" #include "src/sysinfo.cc" #include "src/timers.cc" // Copyright 2021 // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following // conditions: The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS // IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #ifndef GG_MATH_VEC_HPP #define GG_MATH_VEC_HPP #include #include #include #include #include #include #include #include #include #include "types.hpp" #include "util.hpp" #ifndef GGMATH_ALLOW_SIZE_MISMATCH // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) # define GGMATH_ALLOW_SIZE_MISMATCH 0 #endif #ifndef GGMATH_DEBUG // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) # define GGMATH_DEBUG 0 #endif // region forward_declarations // TODO: Check if these are really necessary namespace ggmath { template struct vec; namespace vector { template () * std::declval())> constexpr vec cross(const vec& a, const vec& b); template constexpr float length(const vec& _vec); } // namespace vector } // namespace ggmath namespace ggmath::debug { template void throw_if_not_unit(const ggmath::vec& vec); void throw_if_not_equal_length(int n_A, int n_B); } // namespace ggmath::debug // endregion forward_declarations // region macros // NOLINTNEXTLINE(cppcoreguidelines-macro-usage,-warnings-as-errors) #define COMMON_MEMBERS(n) \ \ \ /* region macros::constructors */ \ \ \ constexpr explicit vec() \ { \ data.fill(0); \ } \ \ \ /*NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)*/ \ constexpr explicit vec(T(&_data)[n]) \ { \ data = std::to_array(_data); \ } \ \ \ /* overload and requires clause serves as an alternative for the impossible ifdef \ * inside a macro */ \ /* clang-format off */ \ template \ requires (GGMATH_ALLOW_SIZE_MISMATCH == 1) \ /*NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) */ \ constexpr vec(const vec& other) \ { \ std::copy_n(std::begin(other), std::min(n, n_In), std::begin(data)); \ /* fill remaining values */ \ std::fill_n(std::begin(data) + std::min(n, n_In), (n) - n_In , 0); \ } \ \ template \ requires (GGMATH_ALLOW_SIZE_MISMATCH == 0) \ /*NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) */ \ constexpr vec(const vec& other) \ { \ ggmath::debug::throw_if_not_equal_length(n_In, n); \ std::ranges::copy(other, std::begin(data)); \ } \ /* clang-format on */ \ \ \ constexpr vec(const vec&& other) noexcept : data(std::move(other.data)) {} \ \ \ constexpr vec(std::initializer_list _data) \ { \ std::ranges::copy(_data, std::begin(data)); \ } \ \ \ /* endregion macros::cnstructors */ \ \ \ /* region macros::ierators */ \ \ \ constexpr auto begin() noexcept \ { \ return data.begin(); \ } \ \ \ constexpr auto begin() const noexcept \ { \ return data.begin(); \ } \ \ \ constexpr auto end() noexcept \ { \ return data.end(); \ } \ \ \ constexpr auto end() const noexcept \ { \ return data.end(); \ } \ \ \ constexpr auto cbegin() const noexcept \ { \ return data.cbegin(); \ } \ \ \ constexpr auto cend() const noexcept \ { \ return data.cend(); \ } \ \ \ constexpr auto rbegin() noexcept \ { \ return data.rbegin(); \ } \ \ \ constexpr auto rbegin() const noexcept \ { \ return data.rbegin(); \ } \ \ \ constexpr auto rend() noexcept \ { \ return data.rend(); \ } \ \ \ constexpr auto rend() const noexcept \ { \ return data.rend(); \ } \ \ \ constexpr auto crbegin() const noexcept \ { \ return data.crbegin(); \ } \ \ \ constexpr auto crend() const noexcept \ { \ return data.crend(); \ } \ \ \ /* endregion macros::iterators */ \ \ \ /* region macros::other */ \ \ \ constexpr vec& operator=(const vec& other) \ { \ if (this == &other) \ return *this; \ \ data = other; \ return *this; \ } \ \ \ constexpr vec& operator=(vec&& other) noexcept \ { \ if (this == &other) \ return *this; \ \ data = std::move(other); \ return *this; \ } \ \ \ constexpr T& operator[](size_t i) \ { \ return data[i]; \ } \ \ \ constexpr const T& operator[](size_t i) const \ { \ return data[i]; \ } \ \ ~vec() = default; \ \ \ /* endregion macros::other */ \ \ \ // endregion macros namespace ggmath { // region classes template struct vec { std::array data; COMMON_MEMBERS(n) }; template struct vec { union { std::array data; struct { T x, y; }; }; COMMON_MEMBERS(2) // region classes::constructors constexpr explicit vec(T xy) : data{xy, xy} {} constexpr vec(T x, T y) : data{x, y} {} // endregion classes::constructors }; template struct vec { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) union { std::array data; struct { T x, y, z; }; struct { T r, g, b; }; }; COMMON_MEMBERS(3) // region classes::constructors constexpr explicit vec(T xyz) : data{xyz, xyz, xyz} {} constexpr vec(T x, T y, T z) : data{x, y, z} {} constexpr vec(const vec& _vec, T z) : data{_vec.x, _vec.y, z} {} // endregion classes::constructors }; // TODO: Find out how to correctly handle fourth component template struct vec { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) union { std::array data; struct { T x, y, z, w; }; struct { T r, g, b, a; }; }; COMMON_MEMBERS(4); // region classes::constructors constexpr explicit vec(T xyzw) : data{xyzw, xyzw, xyzw, xyzw} {} constexpr vec(T xyz, T w) : data{xyz, xyz, xyz, w} {} constexpr vec(T x, T y, T z, T w) : data{x, y, z, w} {} constexpr vec(const vec& other, T w) : data{other[0], other[1], other[2], w} {} // endregion classes::constructors }; // endregion classes // region using-directives using vec2f = vec; using vec3f = vec; using vec4f = vec; using vec2d = vec; using vec3d = vec; using vec4d = vec; using vec2i = vec; using vec3i = vec; using vec4i = vec; using color3 = vec; using color4 = vec; // endregion using-directives // region operator_overloads // region operator_overloads::binary // region operator_overloads::binary::vector-vector // Dot product template constexpr float operator*(const vec& a, const vec& b) { return std::inner_product(std::begin(a), std::end(a), std::begin(b), 0.0); } // Cross product template () * std::declval()), int n> constexpr vec operator%(const vec& a, const vec& b) { return ggmath::vector::cross(a, b); } // Vector-vector addition template () + std::declval()), int n> constexpr vec operator+(const vec& a, const vec& b) { auto vec_out = vec(); std::ranges::transform(a, b, std::begin(vec_out), std::plus<>()); return vec_out; } // Vector-vector subtraction template () - std::declval()), int n> constexpr vec operator-(const vec& a, const vec& b) { auto vec_out = vec(); std::ranges::transform(a, b, std::begin(vec_out), std::minus<>()); return vec_out; } // endregion operator_overloads::binary::vector-vector // region operator_overloads::binary::scalar-vector // Scalar-vector multiplication template () + std::declval()), int n> constexpr vec operator*(const T_Scalar scalar, const vec& _vec) { auto vec_out = vec(); std::ranges::transform(_vec, std::begin(vec_out), [scalar](T_Vec element) { return element * scalar; }); return vec_out; } // Scalar-vector multiplication template () * std::declval()), int n> constexpr vec operator*(const vec& _vec, const T_Scalar scalar) { return scalar * _vec; } // Scalar-vector division template () / std::declval()), int n> constexpr vec operator/(const vec& _vec, const T_Scalar scalar) { auto vec_out = vec(); std::ranges::transform(_vec, std::begin(vec_out), [scalar](T_Vec element) { return element / scalar; }); return vec_out; } // endregion operator_overloads::binary::scalar-vector // endregion operator_overloads::binary // region operator_overloads::assignment // region operator_overloads::assignment::scalar-vector // Scalar-vector multiplication assignment template constexpr vec& operator*=(vec& _vec, const T_Scalar scalar) { std::ranges::transform(_vec, std::begin(_vec), [scalar](T_Vec element) { return element * scalar; }); return _vec; } // Scalar-vector division assignment template constexpr vec& operator/=(vec& _vec, const T_Scalar scalar) { std::ranges::transform(_vec, std::begin(_vec), [scalar](T_Vec element) { return element / scalar; }); return _vec; } // endregion operator_overloads::assignment::scalar-vector // region operator_overloads::assignment::vector-vector // Vector-vector addition-assignment template constexpr vec& operator+=(vec& a, const vec& b) { std::ranges::transform(a, b, std::begin(a), std::plus<>()); return a; } // Vector-vector subtraction-assignment template constexpr vec& operator-=(vec& a, const vec& b) { std::ranges::transform(a, b, std::begin(a), std::minus<>()); return a; } // endregion vector-vector // endregion operator_overloads::assignment // region operator_overloads::comparison // region operator_overloads::comparison::vector-vector // Compare component-wise equality template requires std::equality_comparable_with constexpr bool operator==(const vec& a, const vec& b) { return std::ranges::equal(a, b); } // Compare component-wise equality template requires std::equality_comparable_with constexpr bool operator!=(const vec& a, const vec& b) { return !std::ranges::equal(a, b); } // Compare length template requires std::totally_ordered_with constexpr bool operator>(const vec& a, const vec& b) { return ggmath::vector::length(a) > ggmath::vector::length(b); } // Compare length template requires std::totally_ordered_with constexpr bool operator<(const vec& a, const vec& b) { return ggmath::vector::length(a) < ggmath::vector::length(b); } // Compare length template requires std::totally_ordered_with constexpr bool operator>=(const vec& a, const vec& b) { return ggmath::vector::length(a) >= ggmath::vector::length(b); } // Compare length template requires std::totally_ordered_with constexpr bool operator<=(const vec& a, const vec& b) { return ggmath::vector::length(a) <= ggmath::vector::length(b); } // endregion operator_overloads::comparison::vector-vector // region operator_overloads::comparison::scalar-vector // Compare length template requires std::equality_comparable_with constexpr bool operator==(const vec& _vec, T_Scalar scalar) { return difference_within_epsilon(ggmath::vector::length(_vec), scalar); } // Compare length template requires std::equality_comparable_with constexpr bool operator==(T_Scalar scalar, const vec& _vec) { return _vec == scalar; } // Compare length template requires std::equality_comparable_with constexpr bool operator!=(const vec& _vec, T_Scalar scalar) { return ggmath::vector::length(_vec) != scalar; } // Compare length template requires std::equality_comparable_with constexpr bool operator!=(T_Scalar scalar, const vec& _vec) { return _vec != scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator>(const vec& _vec, T_Scalar scalar) { return ggmath::vector::length(_vec) > scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator>(T_Scalar scalar, const vec& _vec) { return _vec > scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator<(const vec& _vec, T_Scalar scalar) { return ggmath::vector::length(_vec) < scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator<(T_Scalar scalar, const vec& _vec) { return _vec < scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator>=(const vec& _vec, T_Scalar scalar) { return ggmath::vector::length(_vec) >= scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator>=(T_Scalar scalar, const vec& _vec) { return _vec >= scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator<=(const vec& _vec, T_Scalar scalar) { return ggmath::vector::length(_vec) <= scalar; } // Compare length template requires std::totally_ordered_with constexpr bool operator<=(T_Scalar scalar, const vec& _vec) { return _vec <= scalar; } // endregion operator_overloads::comparison::scalar-vector // endregion operator_overloads::comparison // region operator_overloads::other // Invert vector template constexpr vec operator-(vec _vec) { std::ranges::transform( std::begin(_vec), std::end(_vec), std::begin(_vec), std::negate<>()); return _vec; } // Format: (data[0],data[2],...,data[n]) template constexpr std::ostream& operator<<(std::ostream& os, const vec& _vec) { const auto last = std::end(_vec) - 1; os << '('; // Loop ends before last std::for_each( std::begin(_vec), last, [&os](T element) { os << element << ','; }); os << *last; os << ')'; return os; } template constexpr std::ostream& operator<<(std::ostream& os, const vec& _vec) { const auto last = std::end(_vec) - 1; os << '('; // Loop ends before last // unary + prints chars as numbers std::for_each( std::begin(_vec), last, [&os](T element) { os << +element << ','; }); os << +*last; os << ')'; return os; } // endregion operator_overloads::other // endregion operator_overloads namespace vector { // region named constructors template constexpr vec unit_x() noexcept { vec vector = vec(); vector[0] = 1; return vector; } template constexpr vec unit_y() noexcept { vec vector = vec(); vector[1] = 1; return vector; } template constexpr vec unit_z() noexcept { vec vector = vec(); vector[2] = 1; return vector; } // Allows mismatched sizes and zero-initializes missing values template constexpr vec from_other( const vec& other) noexcept { vec vector = vec(); std::ranges::copy(other, std::begin(vector)); return vector; } // endregion named constructors // region functions /** * @brief Calculate the cross product(a x b) of two vectors a and b */ template constexpr vec cross(const vec& a, const vec& b) { return vec(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); } /** * @brief Calculate the length of vec */ template constexpr float length(const vec& _vec) { return abs(std::sqrt(_vec * _vec)); } /** * @brief Calculate the squared length of vec * * This function is potentially faster than squaring the length after * calculating it (length(vec) * length(vec)) */ template constexpr float length_squared(const vec& _vec) { return _vec * _vec; } /** * @brief Return a copy of vec scaled to a length of 1 */ template constexpr auto normalized(const vec& _vec) { return _vec / length(_vec); } /** * @brief Return a copy of vec with a length of length * factor */ template () * std::declval()), int n> constexpr vec scaled_by(const vec& _vec, T_Factor factor) { return _vec * factor; } /** * @brief Return a copy of vec with a length of wanted_magnitude */ template () / std::declval()), int n> constexpr vec scaled_to(const vec& _vec, T_Magnitude wanted_magnitude) { float factor = wanted_magnitude / length(_vec); if (!std::isnormal(factor)) { return vec(); } return scaled_by(_vec, factor); } /** * @brief Return the signed distance from a to b */ template constexpr float distance(const vec& a, const vec& b) { return length((a - b)); } /** * @brief Check whetever or not the unit-vectors a and b are parallel (point in * the same direction) * * If the vectors have a length other than 1, the result will be incorrect. * Define the macro GGMATH_DEBUG to throw an exception if one of the parameters * is NOT a unit-vector. */ template constexpr bool parallel(const vec& a, const vec& b) { #ifdef GGMATH_DEBUG debug::throw_if_not_unit(a); debug::throw_if_not_unit(b); #endif return a * b == 1; } /** * @brief Check whetever or not the unit-vectors a and b are anti-parallel(point * in the opposite direction) * * If the vectors have a length other than 1, the result will be incorrect. * Define the macro GGMATH_DEBUG to throw an exception if one of the parameters * is NOT a unit-vector. */ template constexpr bool anti_parallel(const vec& a, const vec& b) { #ifdef GGMATH_DEBUG debug::throw_if_not_unit(a); debug::throw_if_not_unit(b); #endif return a * b == -1; } /** * @brief Check whetever or not the unit-vectors a and b are perpendicular(the * angle between them is 90 deg) * * If the vectors have a length other than 1, the result will be incorrect. * Define the macro GGMATH_DEBUG to throw an exception if one of the parameters * is NOT a unit-vector. */ template constexpr bool perpendicular(const vec& a, const vec& b) { #ifdef GGMATH_DEBUG debug::throw_if_not_unit(a); debug::throw_if_not_unit(b); #endif return difference_within_epsilon(a * b, 0); } /** * @brief Return the angle between the vectors */ template constexpr float angle_between(const vec& a, const vec& b) { return std::acos((a * b) / (std::abs(length(a)) * std::abs(length(b)))); } /** * @brief Return the angle between the unit vectors* * * If the vectors have a length other than 1, the result will be incorrect. * Define the macro GGMATH_DEBUG to throw an exception if one of the parameters * is NOT a unit-vector. */ template constexpr float angle_between_unit(const vec& a, const vec& b) { #ifdef GGMATH_DEBUG debug::throw_if_not_unit(a); debug::throw_if_not_unit(b); #endif return std::acos(a * b); } /** * @brief Check if the given vector has a length of 1 */ template constexpr bool is_unit_vector(const vec& _vec) { return difference_within_epsilon(length(_vec), 1); } /** * @brief Return the smallest element in the vector */ template constexpr T min(const vec& _vec) { return *std::ranges::min_element(_vec); } /** * @brief Return the largest element in the vector */ template constexpr T max(const vec& _vec) { return *std::ranges::max_element(_vec); } /** * @brief Return the 0-based index of the smallest element in the vector */ template constexpr size_t index_min(const vec& _vec) { return std::ranges::distance(std::begin(_vec), std::ranges::min_element(_vec)); } /** * @brief Return the 0-based index of the largest element in the vector */ template constexpr size_t index_max(const vec& _vec) { return std::ranges::distance( std::begin(_vec), std::ranges::max_element(std::begin(_vec), std::end(_vec))); } /** * Return a vector that is the linear interpolation from a to b with a weight of * t */ template () + std::declval() * std::declval()), int n> constexpr vec lerp(const vec& a, const vec& b, T_Weight t) { return a + t * (b - a); } /** * Reflect the vector a about normal * * If the vectors have a length other than 1, the result will be incorrect. * Define the macro GGMATH_DEBUG to throw an exception if one of the parameters * is NOT a unit-vector. */ template () * std::declval()), int n> constexpr vec reflect(const vec& a, const vec& normal) { #ifdef GGMATH_DEBUG debug::throw_if_not_unit(a); debug::throw_if_not_unit(normal); #endif return a - 2 * (a * normal) * normal; } // endregion functions }; // namespace vector }; // namespace ggmath namespace ggmath::debug { /** * @brief Throw an invalid_argument exception if vec has a length other than 1 */ template void throw_if_not_unit(const ggmath::vec& _vec) { // TODO: Probably better to solve with with std::format if (!ggmath::vector::is_unit_vector(_vec)) { std::stringstream ss; ss << "Parameter was expected to be a unit vector" "(A vector with a length of 1). " "Instead, it had a length of " << ggmath::vector::length(_vec); throw std::invalid_argument(ss.str()); } } // NOLINTNEXTLINE(misc-definitions-in-headers) void throw_if_not_equal_length(int n_A, int n_B) { // TODO: Probably better to solve with with std::format if (n_A != n_B) { std::stringstream ss; ss << "Parameter vectors were expected to have equal lengths but they " "had a length of " << n_A << " and " << n_B << " respectively"; throw std::invalid_argument(ss.str()); } } } // namespace ggmath::debug #endif // GG_MATH_VEC_HPP native/drag_handler.cpp // Copyright (c) 2014 The Chromium Embedded Framework 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 "drag_handler.h" #include "jni_util.h" DragHandler::DragHandler(JNIEnv* env, jobject handler) : handle_(env, handler) {} bool DragHandler::OnDragEnter(CefRefPtr browser, CefRefPtr dragData, CefDragHandler::DragOperationsMask mask) { JNIEnv* env = GetJNIEnv(); if (!env) return false; ScopedJNIBrowser jbrowser(env, browser); ScopedJNIDragData jdragData(env, dragData); jdragData.SetTemporary(); jboolean result = JNI_FALSE; JNI_CALL_METHOD( env, handle_, "onDragEnter", "(Lorg/cef/browser/CefBrowser;Lorg/cef/callback/CefDragData;I)Z", Boolean, result, jbrowser.get(), jdragData.get(), (jint)mask); return (result != JNI_FALSE); } hamarb123/dotnet-api-docssamples/snippets/cpp/VS_Snippets_CLR/TestFullName/CPP/TestFullName.cpp // using namespace System; int main() { Type^ t = Array::typeid; Console::WriteLine( "The full name of the Array type is {0}.", t->FullName ); } /* This example produces the following output: The full name of the Array type is System.Array. */ // #include #include #include #include template void safe_delete(T*& a) { delete a; a = NULL; } CStateManager::CStateManager (): current_state ( NULL ) { } CStateManager::~CStateManager() { if ( current_state) current_state -> unload (); safe_delete ( current_state ); } void CStateManager::change ( CState * new_state ) { throw CStateManagerChangeExeption (new_state); } void CStateManager::quit () { throw CStateManagerQuitExeption(); } void CStateManager::run ( CState * init_state ) { if ( ! init_state) throw "no init state"; current_state = init_state; current_state -> load (); while ( true ) { try { CInputManager::update (); current_state -> update (); if ( current_state) current_state -> draw (); CTime::delay_ms (100); } catch ( CStateManagerChangeExeption & e ) { current_state -> unload (); safe_delete ( current_state ); current_state = e.new_state; current_state -> load (); } catch ( CStateManagerQuitExeption & e) { current_state -> unload (); safe_delete ( current_state ); break; } } } test/broker/sys/upstream-test.cc #include "dsa/message.h" #include "dsa/responder.h" #include "dsa/stream.h" #include "dsa/util.h" #include #include "../../sdk/async_test.h" #include "../../sdk/test_config.h" #include "../util/broker_runner.h" #include "broker.h" #include "config/broker_config.h" #include "core/client.h" #include "module/logger.h" #include "responder/value_node_model.h" using namespace dsa; using BrokerSysTest = SetUpBase; TEST_F(BrokerSysTest, UpstreamTest) { Storage::get_config_bucket().remove_all(); TestConfig::create_pem_files(); // First Create Broker auto broker = create_broker(); shared_ptr_ &app = broker->get_app(); broker->run(false); ASYNC_EXPECT_TRUE(1000, *broker->strand, [&]() { return broker->get_active_server_port() != 0; }); int32_t port; switch (protocol()) { case dsa::ProtocolType::PROT_DSS: port = broker->get_active_secure_port(); break; default: port = broker->get_active_server_port(); } EXPECT_TRUE(port != 0); WrapperStrand client_strand1 = get_client_wrapper_strand(broker, "test1", protocol()); auto root_node = make_ref_(client_strand1.strand); auto child_node = make_ref_(client_strand1.strand, "string", [](const Var &) { return StatusDetail(); }); child_node->set_value(Var("hello")); root_node->add_list_child("value", std::move(child_node)); client_strand1.strand->set_responder_model(ModelRef(root_node.get())); auto client_1 = make_ref_(client_strand1); bool upstream_added = false; client_1->connect([&](const shared_ptr_ connection) { client_1->get_session().invoke( CAST_LAMBDA(IncomingInvokeStreamCallback)[&]( IncomingInvokeStream & stream, ref_ && msg) { EXPECT_TRUE(msg->get_status() == Status::DONE); upstream_added = true; }, make_ref_( "sys/upstream/add", Var({{"Node Name", Var("up1")}, {"Connection Name", Var("down1")}, {"Url", Var(string_("127.0.0.1:") + std::to_string(port))}}))); }); WAIT_EXPECT_TRUE(1000, [&]() -> bool { return upstream_added; }); string_ upstream_status = ""; client_strand1.strand->dispatch([&]() { client_1->get_session().subscribe( "sys/upstream/up1/status", CAST_LAMBDA(IncomingSubscribeStreamCallback)[&]( IncomingSubscribeStream &, ref_ && msg) { EXPECT_TRUE(msg->get_status() == Status::OK); upstream_status = msg->get_value().value.to_string(); }); }); WAIT_EXPECT_TRUE(1000, [&]() -> bool { return upstream_status == "Connected"; }); bool value_upstream_checked = false; client_strand1.strand->dispatch([&]() { client_1->get_session().subscribe( "upstream/up1/downstream/test1/value", CAST_LAMBDA(IncomingSubscribeStreamCallback)[&]( IncomingSubscribeStream &, ref_ && msg) { EXPECT_TRUE(msg->get_status() == Status::OK); EXPECT_EQ(msg->get_value().value.to_string(), "hello"); value_upstream_checked = true; }); }); WAIT_EXPECT_TRUE(1000, [&]() -> bool { return value_upstream_checked; }); bool value_downstream_checked = false; client_strand1.strand->dispatch([&]() { client_1->get_session().subscribe( "downstream/down1/downstream/test1/value", CAST_LAMBDA(IncomingSubscribeStreamCallback)[&]( IncomingSubscribeStream &, ref_ && msg) { EXPECT_TRUE(msg->get_status() == Status::OK); EXPECT_EQ(msg->get_value().value.to_string(), "hello"); value_downstream_checked = true; }); }); WAIT_EXPECT_TRUE(1000, [&]() -> bool { return value_downstream_checked; }); client_strand1.strand->post([&]() { client_1->destroy(); client_strand1.destroy(); }); broker->strand->post([&]() { broker->destroy(); }); broker->wait(); EXPECT_TRUE(broker->is_destroyed()); } BacktrackingHelper.cpp #include "sdk.h" #include "BacktrackingHelper.h" #include "global.h" #include "xor.h" #include "Math.h" template inline T clamp(T in, U low, U high) { if (in <= low) return low; else if (in >= high) return high; else return in; } #define TICK_INTERVAL ( g_pGlobals->interval_per_tick ) #define TIME_TO_TICKS( dt ) ( floorf(( 0.5f + (float)(dt) / TICK_INTERVAL ) ) ) #define TICKS_TO_TIME( t ) ( TICK_INTERVAL *( t ) ) CBacktrackHelper* g_BacktrackHelper = new CBacktrackHelper; int CBacktrackHelper::GetDesiredTickCount(float flTargetTime) { static ConVar* cl_interp_ratio = g_pCvar->FindVar(XorStr("cl_interp_ratio")); static ConVar* cl_updaterate = g_pCvar->FindVar(XorStr("cl_updaterate")); static ConVar* sv_client_min_interp_ratio = g_pCvar->FindVar(XorStr("sv_client_min_interp_ratio")); static ConVar* sv_client_max_interp_ratio = g_pCvar->FindVar(XorStr("sv_client_max_interp_ratio")); static ConVar* sv_minupdaterate = g_pCvar->FindVar(XorStr("sv_minupdaterate")); static ConVar* sv_maxupdaterate = g_pCvar->FindVar(XorStr("sv_maxupdaterate")); static ConVar* cl_interp = g_pCvar->FindVar(XorStr("cl_interp")); static ConVar* cl_interpolate = g_pCvar->FindVar(XorStr("cl_interpolate")); //UpdateRate float interp = cl_interp->GetValue(); float flUpdateRate = cl_updaterate->GetValueN(); float interp_ratio = cl_interp_ratio->GetValueN(); if (sv_client_min_interp_ratio->GetValue() > interp_ratio) interp_ratio = sv_client_min_interp_ratio->GetValue(); if (interp_ratio > sv_client_max_interp_ratio->GetValue()) interp_ratio = sv_client_max_interp_ratio->GetValue(); if (sv_maxupdaterate->GetValueN() <= flUpdateRate) flUpdateRate = sv_maxupdaterate->GetValueN(); if (sv_minupdaterate->GetValueN() > flUpdateRate) flUpdateRate = sv_minupdaterate->GetValueN(); float v4 = interp_ratio / flUpdateRate; if (v4 > interp) interp = v4; //I really hope this was a macro which is compiler inserted, otherwise shame on aw return (((1.0 / g_pGlobals->interval_per_tick) * flTargetTime) + 0.5) //TIME_TO_TICKS SHIT + (((1.0 / g_pGlobals->interval_per_tick) * interp) + 0.5); } int CBacktrackHelper::GetLatencyTicks() { double v0; // st7@0 INetChannelInfo* v1; // esi@1 INetChannelInfo* v2; // eax@1 float v3; // ST08_4@1 float v4; // ST0C_4@1 v1 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v2 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v3 = v1->GetAvgLatency(Typetype_t::TYPE_LOCALPLAYER); v4 = v2->GetAvgLatency(Typetype_t::TYPE_GENERIC); float interval_per_tick = 1.0f / g_pGlobals->interval_per_tick; return floorf(((v3 + v4) * interval_per_tick) + 0.5f); } int CBacktrackHelper::GetEstimateServerTickCount() { double v0; // st7@0 INetChannelInfo* v1; // esi@1 INetChannelInfo* v2; // eax@1 float v3; // ST08_4@1 float v4; // ST0C_4@1 v1 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v2 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v3 = v1->GetAvgLatency(Typetype_t::TYPE_LOCALPLAYER); v4 = v2->GetAvgLatency(Typetype_t::TYPE_GENERIC); return floorf(((v3 + v4) / g_pGlobals->interval_per_tick) + 0.5f) + 1 + G::UserCmdForBacktracking->tick_count; } float CBacktrackHelper::GetEstimateServerTime() { double v0; // st7@0 INetChannelInfo* v1; // esi@1 INetChannelInfo* v2; // eax@1 float v3; // ST08_4@1 float v4; // ST0C_4@1 v1 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v2 = (INetChannelInfo*)g_pEngine->GetNetChannelInfo(); v3 = v1->GetAvgLatency(Typetype_t::TYPE_LOCALPLAYER); v4 = v2->GetAvgLatency(Typetype_t::TYPE_GENERIC); //return floorf(((v3 + v4) / g_pGlobals->interval_per_tick) + 0.5f) + 1 + G::UserCmdForBacktracking->tick_count;*/ return v3 + v4 + TICKS_TO_TIME(1) + TICKS_TO_TIME(G::UserCmdForBacktracking->tick_count); } float CBacktrackHelper::GetNetworkLatency() { // Get true latency INetChannelInfo *nci = g_pEngine->GetNetChannelInfo(); if (nci) { //float IncomingLatency = nci->GetAvgLatency(FLOW_INCOMING); //ppl say use only this one, but meh float OutgoingLatency = nci->GetLatency(0); return OutgoingLatency; } return 0.0f; } ConVar* minupdate; ConVar* maxupdate; ConVar * updaterate; ConVar * interprate; ConVar* cmin; ConVar* cmax; ConVar* interp; float CBacktrackHelper::GetLerpTime() { if(!minupdate) minupdate =g_pCvar->FindVar(XorStr("sv_minupdaterate")); if(!maxupdate) maxupdate = g_pCvar->FindVar(XorStr("sv_maxupdaterate")); if(!updaterate) updaterate = g_pCvar->FindVar(XorStr("cl_updaterate")); if(!interprate) interprate = g_pCvar->FindVar(XorStr("cl_interp_ratio")); if(!cmin) cmin = g_pCvar->FindVar(XorStr("sv_client_min_interp_ratio")); if(!cmax) cmax = g_pCvar->FindVar(XorStr("sv_client_max_interp_ratio")); if(!interp) interp = g_pCvar->FindVar(XorStr("cl_interp")); float UpdateRate = updaterate->GetValue(); float LerpRatio = interprate->GetValue(); return max(LerpRatio / UpdateRate, interp->GetValue()); } void CBacktrackHelper::UpdateBacktrackRecords(CBaseEntity* pPlayer) { int i = pPlayer->Index(); for (int j = g_BacktrackHelper->PlayerRecord[i].records.size() - 1; j >= 0; j--) { float lerptime = g_BacktrackHelper->GetLerpTime(); float desired_time = g_BacktrackHelper->PlayerRecord[i].records.at(j).m_flSimulationTime + lerptime; float estimated_time = g_BacktrackHelper->GetEstimateServerTime(); float SV_MAXUNLAG = 1.0f; float latency = g_BacktrackHelper->GetNetworkLatency(); float m_flLerpTime = g_BacktrackHelper->GetLerpTime(); float correct = clamp(latency + m_flLerpTime, 0.0f, SV_MAXUNLAG); float deltaTime = correct - (estimated_time + lerptime - desired_time); if (fabs(deltaTime) > 0.2f) g_BacktrackHelper->PlayerRecord[i].records.erase(g_BacktrackHelper->PlayerRecord[i].records.begin() + j); } static Vector old_origin[64]; if (PlayerRecord[i].records.size() > 0 && pPlayer->GetSimulationTime() == PlayerRecord[i].records.back().m_flSimulationTime) //already got such a record return; if (PlayerRecord[i].records.size() > 0 && PlayerRecord[i].records.back().m_flSimulationTime > pPlayer->GetSimulationTime())//Invalid lag record, maybe from diffrent game? { PlayerRecord[i].records.clear(); return; } Vector cur_origin = pPlayer->GetOrigin(); Vector v = cur_origin - old_origin[i]; bool breaks_lagcomp = v.LengthSqr() > 4096.f; old_origin[i] = cur_origin; //if (breaks_lagcomp) //{ //add a bool to tick_record called extrapolate and set it to true here, then don't return but let the aimbot extrapolate, for now we just skip that //return; //} tick_record new_record; new_record.needs_extrapolation = breaks_lagcomp; static float OldLower[64]; PlayerRecord[i].LowerBodyYawTarget = pPlayer->LowerBodyYaw(); new_record.m_angEyeAngles = pPlayer->GetEyeAngles(); new_record.m_flCycle = pPlayer->GetCycle(); new_record.m_flSimulationTime = pPlayer->GetSimulationTime(); new_record.m_flAnimTime = pPlayer->GetAnimationTime(); new_record.bLowerBodyYawUpdated = false; new_record.m_nSequence = pPlayer->GetSequence(); new_record.m_vecOrigin = pPlayer->GetOrigin(); new_record.m_vecVelocity = pPlayer->GetVelocity(); new_record.m_flUpdateTime = g_pGlobals->curtime; new_record.backtrack_time = new_record.m_flSimulationTime + GetLerpTime(); if (PlayerRecord[i].LowerBodyYawTarget != OldLower[i] || (pPlayer->GetFlags() & FL_ONGROUND && pPlayer->GetVelocity().Length() > 29.f)) new_record.bLowerBodyYawUpdated = true; for (int i = 0; i < 24; i++) new_record.m_flPoseParameter[i] = *(float*)((DWORD)pPlayer + offys.m_flPoseParameter + sizeof(float) * i); int sequence = pPlayer->GetSequence(); if (sequence == Activity::ACT_PLAYER_IDLE_FIRE || sequence == Activity::ACT_PLAYER_RUN_FIRE || sequence == Activity::ACT_PLAYER_WALK_FIRE || sequence == Activity::ACT_PLAYER_CROUCH_FIRE || sequence == Activity::ACT_PLAYER_CROUCH_WALK_FIRE) { new_record.shot_in_that_record = true; } pPlayer->SetupBones(new_record.boneMatrix, 128, 0x00000100, g_pGlobals->curtime); OldLower[i] = PlayerRecord[i].LowerBodyYawTarget; PlayerRecord[i].records.push_back(new_record); } void CBacktrackHelper::UpdateExtrapolationRecords(CBaseEntity* pPlayer) { int index = pPlayer->Index(); if (pPlayer->GetSimulationTime() == this->SimRecord[index][0].simulation_time) return; for (int i = 7; i > 0; i--) { this->SimRecord[index][i].acceleration = this->SimRecord[index][i-1].acceleration; this->SimRecord[index][i].origin = this->SimRecord[index][i - 1].origin; this->SimRecord[index][i].simulation_time = this->SimRecord[index][i - 1].simulation_time; this->SimRecord[index][i].update_time = this->SimRecord[index][i - 1].update_time; this->SimRecord[index][i].velocity = this->SimRecord[index][i - 1].velocity; } this->SimRecord[index][0].simulation_time = pPlayer->GetSimulationTime(); this->SimRecord[index][0].update_time = g_pGlobals->curtime; this->SimRecord[index][0].origin = pPlayer->GetOrigin(); int lost_ticks = TIME_TO_TICKS(this->SimRecord[index][0].simulation_time) - TIME_TO_TICKS(this->SimRecord[index][1].simulation_time); this->SimRecord[index][0].simulation_time_increasment_per_tick = (this->SimRecord[index][0].simulation_time - this->SimRecord[index][1].simulation_time) / lost_ticks; /*calculate velocity by ourselves*/ Vector velocity = this->SimRecord[index][0].origin - this->SimRecord[index][1].origin; /*divide through lost ticks to get the velocity per tick*/ velocity /= lost_ticks; this->SimRecord[index][0].velocity = pPlayer->GetVelocity();//velocity; } #include "PredictionSystem.h" void CBacktrackHelper::ExtrapolatePosition(CBaseEntity* pPlayer, Vector& position, float &simtime, Vector velocity) { auto AirAccelerate = [](CBaseEntity* pPlayer, Vector &wishdir, float wishspeed, float accel, Vector &velo) { float wishspd = wishspeed; if (wishspd > 30.f) wishspd = 30.f; float currentspeed = DotProduct(pPlayer->GetVelocity(), wishdir); float addspeed = wishspd - currentspeed; if (addspeed <= 0) return; float accelspeed = accel * wishspeed * g_pGlobals->frametime * pPlayer->GetFriction(); if (accelspeed > addspeed) accelspeed = addspeed; velo += accelspeed * wishdir; }; auto GetSomeStrangeSimTime = [](simulation_record pre_latest_record, simulation_record latest_record, float difference) -> float { float v2; // ST00_4@1 float v3; // xmm2_4@1 float v4; // ST00_4@1 float v5; // xmm2_4@1 float result; // xmm0_4@2 v2 = atan2(latest_record.velocity.x, latest_record.velocity.y); v3 = v2 * 57.295776; v4 = atan2(pre_latest_record.velocity.x, pre_latest_record.velocity.y); v5 = v3 - (v4 * 57.295776); if (v5 <= 180.0) { if (v5 < -180.0) v5 = v5 + 360.0; result = v5 / (difference/*latest_record.simulation_time - pre_latest_record.simulation_time*/); } else { result = (v5 - 360.0) / (difference/*latest_record.simulation_time - pre_latest_record.simulation_time*/); } return result; }; int index = pPlayer->GetIndex(); simulation_record latest_record = this->SimRecord[index][0]; simulation_record pre_latest_record = this->SimRecord[index][1]; int latency_ticks = GetLatencyTicks(); Vector vel = velocity; float s_time = simtime; INetChannelInfo* nci = g_pEngine->GetNetChannelInfo(); float latency = nci->GetAvgLatency(0) + nci->GetAvgLatency(1); float ticks_per_second = 1.0f / g_pGlobals->interval_per_tick; float server_time = ((floorf(((latency)*ticks_per_second) + 0.5) + G::UserCmdForBacktracking->tick_count + 1) * g_pGlobals->interval_per_tick); float server_time_difference = server_time - s_time; if (server_time_difference > 1.0f) server_time_difference = 1.0f; float sim_time_difference = g_pGlobals->curtime - latest_record.update_time; //proper method int ticks_choked = /*TIME_TO_TICKS(latest_record.simulation_time - pre_latest_record.simulation_time_increasment_per_tick);*/TIME_TO_TICKS(sim_time_difference); if (ticks_choked <= 15) { latency_ticks = 1; if (ticks_choked < 1) ticks_choked = 1; } else ticks_choked = 15; int total_difference = floorf((server_time_difference * ticks_per_second) + 0.5) - ticks_choked; vel.z -= g_pCvar->FindVar("sv_gravity")->GetValue() * g_pGlobals->interval_per_tick; Ray_t ray; trace_t tr; CTraceFilterWorldAndPropsOnly filter; if (total_difference < 0) { return; } else { do { int chokes = ticks_choked; //test, aw has that do statement do { ray.Init(position, position + (vel* g_pGlobals->interval_per_tick), G::LocalPlayer->GetCollision()->VecMins(), G::LocalPlayer->GetCollision()->VecMaxs()); g_pEngineTrace->TraceRay_NEW(ray, MASK_SOLID, &filter, &tr); if (tr.fraction > 0) { position += vel * (g_pGlobals->interval_per_tick); simtime += g_pGlobals->interval_per_tick; } else { return; } /*if (tr.DidHitWorld()) { position = tr.endpos; if (position.z < tr.endpos.z) vel.z *= -1; else { chokes = 0; total_difference = 0; break; } }*/ /*CUserCmd* cmd = G::UserCmdForBacktracking; Math::VectorAngles(pPlayer->GetVelocity(), cmd->viewangles); cmd->aimdirection = cmd->viewangles; cmd->buttons = 0; cmd->command_number = G::UserCmdForBacktracking->command_number; cmd->forwardmove = 400; cmd->sidemove = 0; cmd->hasbeenpredicted = false; cmd->impulse = G::UserCmdForBacktracking->impulse; cmd->mousedx = 0; cmd->mousedy = 0; cmd->random_seed = G::UserCmdForBacktracking->random_seed; cmd->tick_count = TIME_TO_TICKS(pPlayer->GetSimulationTime()); cmd->upmove = 0; cmd->weaponselect = 0; cmd->weaponsubtype = 0; g_pPrediction->RunCommand(pPlayer, cmd, g_pMoveHelper); */ chokes--; /*vel.z -= (g_pCvar->FindVar("sv_gravity")->GetValue() * 0.5f * g_pGlobals->interval_per_tick); vel.z += (vel.z * g_pGlobals->interval_per_tick); float fmove = 400; float smove = 0; QAngle angle = QAngle(); Math::VectorAngles(vel, angle); Vector forward = Vector(); Vector right = Vector(); Vector up = Vector(); Math::AngleVectors(angle, &forward, &right, &up); forward.z = 0; right.z = 0; forward.NormalizeInPlace(); right.NormalizeInPlace(); Vector wishvel = forward * fmove + right * smove; wishvel.z = 0; Vector wishdir = wishvel; float wishspeed = wishdir.Length(); if (wishspeed != 0 && (wishspeed > pPlayer->GetMaxSpeed())) { wishvel *= (pPlayer->GetMaxSpeed() / wishspeed); wishspeed = pPlayer->GetMaxSpeed(); } AirAccelerate(pPlayer, wishdir, wishspeed, g_pCvar->FindVar("sv_airaccelerate")->GetValue(), vel);*/ } while (chokes); total_difference -= ticks_choked; } while (total_difference >= 0); } //position.z = z_origin; //By notwav /* float TimeTotal = nci->GetAvgLatency(FLOW_OUTGOING) + nci->GetAvgLatency(FLOW_INCOMING) + EnemyPing + FudgeFactor; for ( ; TotalTotal >= MinimumTime; TimeTotal -= nci->GetAvgLatency(FLOW_OUTGOING) )*/ /* if (!G::UserCmdForBacktracking) return; CUserCmd* test = G::UserCmdForBacktracking; QAngle angle; SpreadVectorAngles(pPlayer->GetVelocity(), angle); test->upmove = 0; test->forwardmove = 400; test->sidemove = 0; test->aimdirection = angle; test->viewangles = angle; test->buttons = NULL; test->hasbeenpredicted = false; test->tick_count = TIME_TO_TICKS(pPlayer->GetSimulationTime()); //g_pMoveHelper->SetHost(pPlayer); for (int i = ticks_choked; i >= 0; i--) { //ghetto way //position += vel; //simtime += sim_record.simulation_time_increasment_per_tick; // //g_pPrediction->RunCommand(pPlayer, test, g_pMoveHelper); CMoveData m_MoveData; memset(&m_MoveData, 0, sizeof(m_MoveData)); g_pMoveHelper->SetHost(pPlayer); g_pPrediction->SetupMove(pPlayer, test, g_pMoveHelper, &m_MoveData); g_pGameMovement->ProcessMovement(pPlayer, &m_MoveData); g_pPrediction->FinishMove(pPlayer, test, &m_MoveData); } position = pPlayer->GetOrigin(); simtime = pPlayer->GetSimulationTime();*/ /*float gravity = (g_pCvar->FindVar("sv_gravity")->GetValue() * 0.5f * g_pGlobals->interval_per_tick); float basevelocity = (pPlayer->GetBaseVelocity().z * g_pGlobals->interval_per_tick); Vector vel = velocity; vel.z -= gravity; vel.z += basevelocity; vel *= g_pGlobals->interval_per_tick; Vector old_origin, old_velocity, acceleration; for (int i = ticks_choked; i > 0; i--) { old_origin = position; old_velocity = vel; //should be using that tbh //vel += acceleration; position += vel; //vel = position - old_origin; acceleration = vel - old_velocity; }*/ } void CBacktrackHelper::LagCompensate(CBaseEntity* pPlayer) { /*int index = pPlayer->Index(); Vector org_delta = this->PlayerRecord[index].record[0].m_vecOrigin - this->PlayerRecord[index].record[1].m_vecOrigin; Vector min = pPlayer->GetCollision()->VecMins(), max = pPlayer->GetCollision()->VecMaxs(); if (org_delta.Length() > 64) { for (int i = 0; i < 32; i++) { org_delta = this->PlayerRecord[index].record[i].m_vecOrigin - this->PlayerRecord[index].record[i + 1].m_vecOrigin; int LerpTicks = TIME_TO_TICKS(this->GetLerpTime()); int desired = TIME_TO_TICKS(this->PlayerRecord[index].record[i].m_flSimulationTime) + LerpTicks; int estimated = this->GetEstimateServerTickCount(); float SV_MAXUNLAG = 1.0f; float latency = g_BacktrackHelper->GetNetworkLatency(); float m_flLerpTime = g_BacktrackHelper->GetLerpTime(); float correct = clamp(latency + m_flLerpTime, 0.0f, SV_MAXUNLAG); float deltaTime = correct - (TICKS_TO_TIME(estimated + LerpTicks - desired)); if (org_delta.Length2D() <= 64 && fabs(deltaTime) <= 0.2f) { *(Vector*)((DWORD)pPlayer + offys.m_vecOrigin) = this->PlayerRecord[index].record[i].m_vecOrigin; *(float*)((DWORD)pPlayer + offys.m_flSimulationTime) = this->PlayerRecord[index].record[i].m_flSimulationTime; *(float*)((DWORD)pPlayer + offys.m_flCycle) = this->PlayerRecord[index].record[i].m_flCycle; *(int*)((DWORD)pPlayer + offys.m_nSequence) = this->PlayerRecord[index].record[i].m_nSequence; *(Vector*)((DWORD)pPlayer + 0x110) = this->PlayerRecord[index].record[i].m_vecVelocity; //g_pDebugOverlay->AddBoxOverlay(this->PlayerRecord[index].record[0].m_vecOrigin, min, max, pPlayer->GetEyeAngles(), 0, 0, 0, 255, g_pGlobals->interval_per_tick ); //g_pDebugOverlay->AddBoxOverlay(this->PlayerRecord[index].record[i].m_vecOrigin, min, Vector(max.x, max.y, max.z + 52), Vector(0, pPlayer->GetEyeAngles().y, 0), 255, 255, 255, 55, g_pGlobals->interval_per_tick); break; } } }*/ } /* float CHistory::GetLerpTime() { float flUpdateRate = g_pICvar->FindVar( "cl_updaterate" )->GetFloat(); static float flMinUpdateRate = g_pICvar->FindVar( "sv_minupdaterate" )->GetFloat(); static float flMaxUpdateRate = g_pICvar->FindVar( "sv_maxupdaterate" )->GetFloat(); if( flMinUpdateRate && flMaxUpdateRate ) flUpdateRate = clamp( flUpdateRate, flMaxUpdateRate, flMaxUpdateRate ); float flLerpRatio = g_pICvar->FindVar( "cl_interp_ratio" )->GetFloat(); if( flLerpRatio == 0 ) flLerpRatio = 1.0f; float flLerpAmount = g_pICvar->FindVar( "cl_interp" )->GetFloat(); static float flMin = g_pICvar->FindVar( "sv_client_min_interp_ratio" )->GetFloat(); static float flMax = g_pICvar->FindVar( "sv_client_max_interp_ratio" )->GetFloat(); if( flMin && flMax && flMin != -1 ) flLerpRatio = clamp( flLerpRatio, flMin, flMax ); else if( flLerpRatio == 0 ) flLerpRatio = 1.0f; float flLerpTime = max( flLerpAmount, flLerpRatio / flUpdateRate ); return flLerpTime; } int CHistory::TimeToTicks( float flSimulationTime ) { return ( int )( 0.5f + flSimulationTime / g_pGlobalVars->interval_per_tick ); } float CHistory::TicksToTime( int iTicks ) { return g_pGlobalVars->interval_per_tick * iTicks; } void CHistory::InitLagRecord() { for( int i = 0; i <= 32; i++ ) for( int j = 0; j < 9; j++ ) g_History.m_LagRecord[ i ][ j ].m_flSimulationTime = 0.0f; } int CHistory::GetServerTick() { ValveSDK::INetChannelInfo* pNC = g_pEngine->GetNetChannelInfo(); if( !pNC ) return -1.0f; float flOut = pNC->GetLatency( FLOW_OUTGOING ); float flInc = pNC->GetLatency( FLOW_INCOMING ); return floorf( ( ( flOut + flInc ) / g_pGlobalVars->interval_per_tick ) + 0.5f ) + 1 + m_iStartingTickCount; } void CHistory::RecordCBaseEntity( CBaseEntity* pCBaseEntity ) { int nIndex = pCBaseEntity->GetIndex(); CLagRecord* m_LagRecords = this->m_LagRecord[ nIndex ]; if( !pCBaseEntity || !pCBaseEntity->GetGetHealth() > 0 ) { for( int i = 0; i < 9; i++ ) m_LagRecords[ i ].m_flSimulationTime = 0.0f; } if( pCBaseEntity->IsDormant() ) //Do not store useless data... return; float flSimTime = pCBaseEntity->GetSimulationTime();// +this->GetLerpTime(); int nHigestRecordIndex = -1; float flHigestSimTime = 0.0f; for( int i = 0; i < 9; i++ ) { if( m_LagRecords[ i ].m_flSimulationTime > flSimTime ) //Invalid lag record, maybe from diffrent game? m_LagRecords[ i ].m_flSimulationTime = 0.0f; if( m_LagRecords[ i ].m_flSimulationTime == 0.0f ) continue; if( m_LagRecords[ i ].m_flSimulationTime == flSimTime ) return; //Already contains log of current simulation time. if( m_LagRecords[ i ].m_flSimulationTime > flHigestSimTime ) { nHigestRecordIndex = i; flHigestSimTime = m_LagRecords[ i ].m_flSimulationTime; } } nHigestRecordIndex++; nHigestRecordIndex = nHigestRecordIndex % 9; m_LagRecords[ nHigestRecordIndex ].m_vecOrigin = pCBaseEntity->GetOrigin(); Vector vVel; pCBaseEntity->GetEstimatedVelocity( vVel ); m_LagRecords[ nHigestRecordIndex ].m_vecVelocity = vVel; m_LagRecords[ nHigestRecordIndex ].m_flSimulationTime = pCBaseEntity->GetSimulationTime(); m_LagRecords[ nHigestRecordIndex ].m_vecAngles = *( Vector* )( ( DWORD )pCBaseEntity + Offsets::Player::m_angEyeAngles ); m_LagRecords[ nHigestRecordIndex ].m_flCycle = *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flCycle ); m_LagRecords[ nHigestRecordIndex ].m_nSequence = *( int* )( ( DWORD )pCBaseEntity + Offsets::Player::m_nSequence ); m_LagRecords[ nHigestRecordIndex ].m_nFlags = *( int* )( ( DWORD )pCBaseEntity + Offsets::Player::m_fFlags ); m_LagRecords[ nHigestRecordIndex ].m_flLowerBodyYawTarget = *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flLowerBodyYawTarget ); for( int i = 0; i < 24; i++ ) m_LagRecords[ nHigestRecordIndex ].m_flPoseParameter[ i ] = *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flPoseParameter + sizeof( float ) * i ); } void CHistory::ApplyLagRecord( CBaseEntity* pCBaseEntity, CLagRecord _LagRecord ) { if( !pCBaseEntity || _LagRecord.m_flSimulationTime == 0.0f ) return; *( Vector* )( ( DWORD )pCBaseEntity + Offsets::Player::m_vecOrigin ) = _LagRecord.m_vecOrigin; *( Vector* )( ( DWORD )pCBaseEntity + Offsets::Player::m_vecVelocity ) = _LagRecord.m_vecVelocity; *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flSimulationTime ) = _LagRecord.m_flSimulationTime; *( Vector* )( ( DWORD )pCBaseEntity + Offsets::Player::m_angEyeAngles ) = _LagRecord.m_vecAngles; *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flCycle ) = _LagRecord.m_flCycle; *( int* )( ( DWORD )pCBaseEntity + Offsets::Player::m_nSequence ) = _LagRecord.m_nSequence; *( int* )( ( DWORD )pCBaseEntity + Offsets::Player::m_fFlags ) = _LagRecord.m_nFlags; *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flLowerBodyYawTarget ) = _LagRecord.m_flLowerBodyYawTarget; for( int i = 0; i < 24; i++ ) *( float* )( ( DWORD )pCBaseEntity + Offsets::Player::m_flPoseParameter + sizeof( float ) * i ) = _LagRecord.m_flPoseParameter[ i ]; if( pCBaseEntity ) { *( DWORD* )( ( DWORD )pCBaseEntity + Offsets::Player::m_nForceBone + 0x20 ) = 0; // m_BoneAccessor.SetWritableBones( 0 ) static DWORD dwIBC = Base::Util::PatternSearch( "client.dll", ( PBYTE )"\x80\x3D\x00\x00\x00\x00\x00\x74\x16\xA1", "xx????xxxx", NULL, NULL ); reinterpret_cast( dwIBC )( pCBaseEntity ); } } int CHistory::FakeLagFix( CBaseEntity* pCBaseEntity, int nHistoryIndex, bool bStrict ) { int nIndex = pCBaseEntity->GetIndex(); CLagRecord* m_LagRecords = this->m_LagRecord[ nIndex ]; CLagRecord recentLR = m_LagRecords[ nHistoryIndex ]; CLagRecord prevLR; if( nHistoryIndex == 0 ) prevLR = m_LagRecords[ 8 ]; else prevLR = m_LagRecords[ nHistoryIndex - 1 ]; if( recentLR.m_flSimulationTime == 0.0f ) return -1; int iServerTick = this->GetServerTick(); int iLerpTicks = this->TimeToTicks( GetLerpTime() ); float flCorrect = this->TicksToTime( iLerpTicks ); int iTargetTickCount = this->TimeToTicks( recentLR.m_flSimulationTime ) + iLerpTicks; int iMaxFutureServerTick = iServerTick; ValveSDK::ConVar* sv_max_usercmd_future_ticks = g_pICvar->FindVar( "sv_max_usercmd_future_ticks" ); if( sv_max_usercmd_future_ticks ) iMaxFutureServerTick += sv_max_usercmd_future_ticks->GetInt(); ValveSDK::INetChannelInfo* pNCNfo = g_pEngine->GetNetChannelInfo(); if( pNCNfo ) { float flLatOut = pNCNfo->GetLatency( FLOW_OUTGOING ); flCorrect += flLatOut; } flCorrect = clamp( flCorrect, 0.0f, 1.0f ); //sv_maxunlag float flDeltaTime = flCorrect - TicksToTime( iServerTick - iTargetTickCount ); if( fabsf( flDeltaTime ) > 0.2f ) //Too big deltatime, can't lagfix here { return -1; } if( iTargetTickCount > iMaxFutureServerTick ) //Cannot go that much forward { return -1; } if( prevLR.m_flSimulationTime == 0.0f ) { //Found only one valid record, let's use this simulation time if it's valid. if( bStrict ) { return -1; } else { ApplyLagRecord( pCBaseEntity, recentLR ); return iTargetTickCount + 1; } } if( ( recentLR.m_vecOrigin - prevLR.m_vecOrigin ).LengthSqr() > 4096.f ) //Lost track record { m_iShouldExtrapolateHistory = nHistoryIndex; return -1; } ApplyLagRecord( pCBaseEntity, recentLR ); return iTargetTickCount + 1; }*/ /*void LagCompensation::logCBaseEntity(CBaseEntity *player) { int idx = player->getIdx(); LagRecord *m_LagRecords = this->m_LagRecord[idx]; if (!player || !player->getLife() > 0) { for (int i = 0; i < 9; i++) // reset sim time on dead records { m_LagRecords[i].m_fSimulationTime = 0.0f; } } float simTime = player->getSimulTime(); int highestRecordIdx = -1; float highestSimTime = 0.0f; for (int i = 0; i < 9; i++) // here we do some checks so we don't have invalid records and optimize things so we don't store an { // entity which already contains the current sim time if (m_LagRecords[i].m_fSimulationTime > simTime) m_LagRecords[i].m_fSimulationTime = 0.0f; if (m_LagRecords[i].m_fSimulationTime == 0.0f) continue; if (m_LagRecords[i].m_fSimulationTime == simTime) return; if (m_LagRecords[i].m_fSimulationTime > highestSimTime) { highestRecordIdx = i; highestSimTime = m_LagRecords[i].m_fSimulationTime; } } highestRecordIdx++; highestRecordIdx = highestRecordIdx % 9; m_LagRecords[highestRecordIdx].m_bIsFixed = false; m_LagRecords[highestRecordIdx].m_iTargetID = idx; m_LagRecords[highestRecordIdx].m_vAbsOrigin = player->getAbsOrigin(); m_LagRecords[highestRecordIdx].m_vecVelocity = player->getVel(); m_LagRecords[highestRecordIdx].m_fSimulationTime = player->getSimulTime(); m_LagRecords[highestRecordIdx].m_vecAngles = player->getEyeAngles(); m_LagRecords[highestRecordIdx].m_flCycle = player->getCycle(); m_LagRecords[highestRecordIdx].m_nSequence = player->getSequence(); m_LagRecords[highestRecordIdx].flags = player->getFlags(); m_LagRecords[highestRecordIdx].m_flLowerBodyYawTarget = player->getLowBodYtarg(); m_LagRecords[highestRecordIdx].m_vecMins = player->getCollideable()->vecMins(); m_LagRecords[highestRecordIdx].m_vecMax = player->getCollideable()->vecMax(); m_LagRecords[highestRecordIdx].m_fFallVel = player->getFallVel(); // commented out since giving weird results, the backtracked entity is crouching, also this is bad anim fix, currently doing without anim fix /*for (int i = 0; i < 24; i++) m_LagRecords[highestRecordIdx].m_flPoseParameter[i] = player->getPoseParams(i);*/ //} /* void LagCompensation::setCBaseEntity(CBaseEntity *player, LagRecord record) { if (!player || record.m_fSimulationTime == 0.0f) { record.m_bIsFixed = false; return; } unsigned long g_iModelBoneCounter = **(unsigned long**)(offs.invalidateBoneCache + 10); *(int*)((DWORD)player + offs.writeableBones) = 0; *(unsigned int*)((DWORD)player + 0x2914) = 0xFF7FFFFF; // m_flLastBoneSetupTime = -FLT_MAX; *(unsigned int*)((DWORD)player + 0x2680) = (g_iModelBoneCounter - 1); // m_iMostRecentModelBoneCounter = g_iModelBoneCounter - 1; player->setAbsOrigin(record.m_vAbsOrigin); *(Vector*)((DWORD)player + offs.vekVel) = record.m_vecVelocity; *(float*)((DWORD)player + offs.simulTime) = record.m_fSimulationTime; player->setAbsAngles(record.m_vecAngles); *(float*)((DWORD)player + offs.cycle) = record.m_flCycle; *(int*)((DWORD)player + offs.sequence) = record.m_nSequence; *(int*)((DWORD)player + offs.flags) = record.flags; *(float*)((DWORD)player + offs.lowBodYtarg) = record.m_flLowerBodyYawTarget; player->getCollideable()->vecMins() = record.m_vecMins; player->getCollideable()->vecMax() = record.m_vecMax; player->getFallVel() = record.m_fFallVel; //for (int i = 0; i < 24; i++) // *(float*)((DWORD)player + offs.poseParams + sizeof(float) * i) = record.m_flPoseParameter[i]; record.m_bIsFixed = true; p_Console->ConsoleColorPrintf(Color::LightBlue(), "backtracked %ls\n", player->getName(player->getIdx()).c_str()); }*/ /*int LagCompensation::fakeLagFix(CBaseEntity *player, int historyIdx) { int idx = player->getIdx(); LagRecord *m_LagRecords = this->m_LagRecord[idx]; LagRecord recentLR = m_LagRecords[historyIdx]; LagRecord prevLR; if (historyIdx == 0) prevLR = m_LagRecords[8]; else prevLR = m_LagRecords[historyIdx - 1]; if (recentLR.m_fSimulationTime == 0.0f) return -1; INetChannelInfo *nci = p_Engine->getNetChannelInfo(); int predCmdArrivTick = Global::userCMD->tick_count + 1 + TIME_TO_TICKS(nci->GetAvgLatency(FLOW_INCOMING) + nci->GetAvgLatency(FLOW_OUTGOING)); // (c) n0xius @ uc int iLerpTicks = TIME_TO_TICKS(lerpTime()); int iTargetTickCount = TIME_TO_TICKS(recentLR.m_fSimulationTime) + iLerpTicks; float flCorrect = clamp(lerpTime() + nci->GetLatency(FLOW_OUTGOING), 0.f, 1.f) - TICKS_TO_TIME(predCmdArrivTick + TIME_TO_TICKS(lerpTime()) - iTargetTickCount); // (c) n0xius @ uc if (fabs(flCorrect) > 0.2f) // Too big deltatime, can't lagfix here { p_Console->ConsoleColorPrintf(Color::Red(), "StartLagCompensation: delta too big (%.3f)\n", flCorrect); return -1; } if ((recentLR.m_vAbsOrigin - prevLR.m_vAbsOrigin).lengthSqr() > 4096.f) { for (auto i = 0; i <= player->getChockedTicks(); i++) { rebGameMovement->FullWalkMove(player); // resimulate } recentLR.m_bIsBreakingLagComp = true; p_Console->ConsoleColorPrintf(Color::Green(), "m_bIsBreakingLagComp: true\n"); return -1; } else { setCBaseEntity(player, recentLR); } //p_Console->ConsoleColorPrintf(Color::LightBlue(), "tickcount: %d\n", (iTargetTickCount + 1)); return iTargetTickCount /*+ 1*///wrong;/* //}*/ /*int LagCompensation::fixTickcount(CBaseEntity *player) { int idx = player->getIdx(); LagRecord *m_LagRecords = this->m_LagRecord[idx]; LagRecord recentLR = m_LagRecords[mVars.historyIdx]; if (recentLR.m_fSimulationTime == 0.0f) return TIME_TO_TICKS(player->getSimulTime() + lerpTime()) + 1; int iLerpTicks = TIME_TO_TICKS(lerpTime()); int iTargetTickCount = TIME_TO_TICKS(recentLR.m_fSimulationTime) + iLerpTicks; p_Console->ConsoleColorPrintf(Color::Blue(), "tickcount: %d\n", (iTargetTickCount + 1)); return iTargetTickCount;// wrong + 1; }*/#include using namespace std; typedef pair pii; typedef vector vii; typedef vector vi; #define pb push_back int main() { vector AdjList; vii vectorOfPairs; vectorOfPairs.pb(make_pair(1, 50)); // Vertice 0 connected with vertice 1 and weight 50 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(0, 50)); // Vertice 0 connected with vertice 1 and weight 50 vectorOfPairs.pb(make_pair(2, 20)); // Vertice 1 connected with vertice 2 and weight 20 vectorOfPairs.pb(make_pair(3, 30)); // Vertice 1 connected with vertice 3 and weight 30 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(1, 20)); // Vertice 2 connected with vertice 1 and weight 20 vectorOfPairs.pb(make_pair(3, 40)); // Vertice 2 connected with vertice 3 and weight 40 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(1, 30)); // Vertice 3 connected with vertice 1 and weight 30 vectorOfPairs.pb(make_pair(2, 40)); // Vertice 2 connected with vertice 3 and weight 40 vectorOfPairs.pb(make_pair(4, 60)); // Vertice 3 connected with vertice 4 and weight 60 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(3, 60)); // Vertice 4 connected with vertice 3 and weight 60 AdjList.pb(vectorOfPairs); for (int i = 0; i < AdjList.size(); i++) { for (int j = 0; j < AdjList[i].size(); j++) { cout << "Vertice: " << i; cout << " connected with vertice " << AdjList[i][j].first; cout << " with weight " << AdjList[i][j].second << endl; } cout << endl; } return 0; } #include #include "entity/linklist.h" int main() { for (int range = 2; range < 500; range += 10) { std::cout << "--------- stats @ " << range << "-------------\n"; int count = 0; SLL list; while (count++ < range) { list.push_back(count); } list.reverse_iter(); list.reverse_recurse(); std::cout << "\n\n"; } }chenxy285/directions-api-clients /** * GraphHopper Directions API * You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various constraints like time window and capacity restrictions. Also it is possible to get all distances between all locations with our fast Matrix API. * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "SWGVehicle.h" #include "SWGHelpers.h" #include #include #include #include namespace Swagger { SWGVehicle::SWGVehicle(QString* json) { init(); this->fromJson(*json); } SWGVehicle::SWGVehicle() { init(); } SWGVehicle::~SWGVehicle() { this->cleanup(); } void SWGVehicle::init() { vehicle_id = new QString(""); m_vehicle_id_isSet = false; type_id = new QString(""); m_type_id_isSet = false; start_address = new SWGAddress(); m_start_address_isSet = false; end_address = new SWGAddress(); m_end_address_isSet = false; _break = new SWGBreak(); m__break_isSet = false; return_to_depot = false; m_return_to_depot_isSet = false; earliest_start = 0L; m_earliest_start_isSet = false; latest_end = 0L; m_latest_end_isSet = false; skills = new QList(); m_skills_isSet = false; max_distance = 0L; m_max_distance_isSet = false; max_driving_time = 0L; m_max_driving_time_isSet = false; max_jobs = 0; m_max_jobs_isSet = false; max_activities = 0; m_max_activities_isSet = false; } void SWGVehicle::cleanup() { if(vehicle_id != nullptr) { delete vehicle_id; } if(type_id != nullptr) { delete type_id; } if(start_address != nullptr) { delete start_address; } if(end_address != nullptr) { delete end_address; } if(_break != nullptr) { delete _break; } if(skills != nullptr) { auto arr = skills; for(auto o: *arr) { delete o; } delete skills; } } SWGVehicle* SWGVehicle::fromJson(QString &json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGVehicle::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&vehicle_id, pJson["vehicle_id"], "QString", "QString"); ::Swagger::setValue(&type_id, pJson["type_id"], "QString", "QString"); ::Swagger::setValue(&start_address, pJson["start_address"], "SWGAddress", "SWGAddress"); ::Swagger::setValue(&end_address, pJson["end_address"], "SWGAddress", "SWGAddress"); ::Swagger::setValue(&_break, pJson["break"], "SWGBreak", "SWGBreak"); ::Swagger::setValue(&return_to_depot, pJson["return_to_depot"], "bool", ""); ::Swagger::setValue(&earliest_start, pJson["earliest_start"], "qint64", ""); ::Swagger::setValue(&latest_end, pJson["latest_end"], "qint64", ""); ::Swagger::setValue(&skills, pJson["skills"], "QList", "QString"); ::Swagger::setValue(&max_distance, pJson["max_distance"], "qint64", ""); ::Swagger::setValue(&max_driving_time, pJson["max_driving_time"], "qint64", ""); ::Swagger::setValue(&max_jobs, pJson["max_jobs"], "qint32", ""); ::Swagger::setValue(&max_activities, pJson["max_activities"], "qint32", ""); } QString SWGVehicle::asJson () { QJsonObject* obj = this->asJsonObject(); QJsonDocument doc(*obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject* SWGVehicle::asJsonObject() { QJsonObject* obj = new QJsonObject(); if(vehicle_id != nullptr && *vehicle_id != QString("")){ toJsonValue(QString("vehicle_id"), vehicle_id, obj, QString("QString")); } if(type_id != nullptr && *type_id != QString("")){ toJsonValue(QString("type_id"), type_id, obj, QString("QString")); } if((start_address != nullptr) && (start_address->isSet())){ toJsonValue(QString("start_address"), start_address, obj, QString("SWGAddress")); } if((end_address != nullptr) && (end_address->isSet())){ toJsonValue(QString("end_address"), end_address, obj, QString("SWGAddress")); } if((_break != nullptr) && (_break->isSet())){ toJsonValue(QString("break"), _break, obj, QString("SWGBreak")); } if(m_return_to_depot_isSet){ obj->insert("return_to_depot", QJsonValue(return_to_depot)); } if(m_earliest_start_isSet){ obj->insert("earliest_start", QJsonValue(earliest_start)); } if(m_latest_end_isSet){ obj->insert("latest_end", QJsonValue(latest_end)); } if(skills->size() > 0){ toJsonArray((QList*)skills, obj, "skills", "QString"); } if(m_max_distance_isSet){ obj->insert("max_distance", QJsonValue(max_distance)); } if(m_max_driving_time_isSet){ obj->insert("max_driving_time", QJsonValue(max_driving_time)); } if(m_max_jobs_isSet){ obj->insert("max_jobs", QJsonValue(max_jobs)); } if(m_max_activities_isSet){ obj->insert("max_activities", QJsonValue(max_activities)); } return obj; } QString* SWGVehicle::getVehicleId() { return vehicle_id; } void SWGVehicle::setVehicleId(QString* vehicle_id) { this->vehicle_id = vehicle_id; this->m_vehicle_id_isSet = true; } QString* SWGVehicle::getTypeId() { return type_id; } void SWGVehicle::setTypeId(QString* type_id) { this->type_id = type_id; this->m_type_id_isSet = true; } SWGAddress* SWGVehicle::getStartAddress() { return start_address; } void SWGVehicle::setStartAddress(SWGAddress* start_address) { this->start_address = start_address; this->m_start_address_isSet = true; } SWGAddress* SWGVehicle::getEndAddress() { return end_address; } void SWGVehicle::setEndAddress(SWGAddress* end_address) { this->end_address = end_address; this->m_end_address_isSet = true; } SWGBreak* SWGVehicle::getBreak() { return _break; } void SWGVehicle::setBreak(SWGBreak* _break) { this->_break = _break; this->m__break_isSet = true; } bool SWGVehicle::isReturnToDepot() { return return_to_depot; } void SWGVehicle::setReturnToDepot(bool return_to_depot) { this->return_to_depot = return_to_depot; this->m_return_to_depot_isSet = true; } qint64 SWGVehicle::getEarliestStart() { return earliest_start; } void SWGVehicle::setEarliestStart(qint64 earliest_start) { this->earliest_start = earliest_start; this->m_earliest_start_isSet = true; } qint64 SWGVehicle::getLatestEnd() { return latest_end; } void SWGVehicle::setLatestEnd(qint64 latest_end) { this->latest_end = latest_end; this->m_latest_end_isSet = true; } QList* SWGVehicle::getSkills() { return skills; } void SWGVehicle::setSkills(QList* skills) { this->skills = skills; this->m_skills_isSet = true; } qint64 SWGVehicle::getMaxDistance() { return max_distance; } void SWGVehicle::setMaxDistance(qint64 max_distance) { this->max_distance = max_distance; this->m_max_distance_isSet = true; } qint64 SWGVehicle::getMaxDrivingTime() { return max_driving_time; } void SWGVehicle::setMaxDrivingTime(qint64 max_driving_time) { this->max_driving_time = max_driving_time; this->m_max_driving_time_isSet = true; } qint32 SWGVehicle::getMaxJobs() { return max_jobs; } void SWGVehicle::setMaxJobs(qint32 max_jobs) { this->max_jobs = max_jobs; this->m_max_jobs_isSet = true; } qint32 SWGVehicle::getMaxActivities() { return max_activities; } void SWGVehicle::setMaxActivities(qint32 max_activities) { this->max_activities = max_activities; this->m_max_activities_isSet = true; } bool SWGVehicle::isSet(){ bool isObjectUpdated = false; do{ if(vehicle_id != nullptr && *vehicle_id != QString("")){ isObjectUpdated = true; break;} if(type_id != nullptr && *type_id != QString("")){ isObjectUpdated = true; break;} if(start_address != nullptr && start_address->isSet()){ isObjectUpdated = true; break;} if(end_address != nullptr && end_address->isSet()){ isObjectUpdated = true; break;} if(_break != nullptr && _break->isSet()){ isObjectUpdated = true; break;} if(m_return_to_depot_isSet){ isObjectUpdated = true; break;} if(m_earliest_start_isSet){ isObjectUpdated = true; break;} if(m_latest_end_isSet){ isObjectUpdated = true; break;} if(skills->size() > 0){ isObjectUpdated = true; break;} if(m_max_distance_isSet){ isObjectUpdated = true; break;} if(m_max_driving_time_isSet){ isObjectUpdated = true; break;} if(m_max_jobs_isSet){ isObjectUpdated = true; break;} if(m_max_activities_isSet){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } } alex-cornejo/pdisp_ckcmain.cpp /* File : main.cpp Project : Heuristic for CVPCP Developer : Date : Nov 13 2013 Institution: PISIS - FIME - UANL */ #include "global.h" #include "readInstance.h" #include "IGVND.h" using namespace std; int main(int argc, const char *argv[]) { if (argc < 5) { cout << "Missing parameters.\n"; return -1; } // cout << argv[1] << endl; if (!read(argv[1])) { cout << "File not found.\n"; return -1; } r_max = atoi(argv[2]); alpha = atof(argv[3]); e = atoi(argv[4]); int iterations = atoi(argv[6]); time_start = getCPUTime(); // start time clock_t begin = clock(); // seed = get_seed(); seed = 0; solution best; for (int i = 0; i < iterations; ++i) { srand(seed++); result = IGVND(r_max, alpha, e, 0, 0, 0); if (i == 0 || result.f < best.f) { best = result; } } time_stop = getCPUTime(); // finish time clock_t end = clock(); double time_spent = (double) (end - begin) / CLOCKS_PER_SEC; result = best; // print(result); cout << result.f <<","< 5) // save(argv[5], result); // print solution in console // for (int k = 0; k < p; ++k) { // cout << result.P[k]; // cout << " |"; // for (auto j = result.X[k].begin(); j != result.X[k].end(); ++j) { // cout << " "; // cout << *j; // } // cout << "\n"; // } finalize(); return 0; } 1-10 /* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "EndpointPolicyTracer.hpp" #include "EndpointPolicyTracerImp.hpp" #include #include #include #include "CSV.hpp" #include "Agent.hpp" #include "Environment.hpp" #include "Helper.hpp" #include "PlatformIO.hpp" #include "PlatformTopo.hpp" #include "geopm_time.h" #include "config.h" namespace geopm { std::unique_ptr EndpointPolicyTracer::make_unique(void) { return geopm::make_unique(); } EndpointPolicyTracerImp::EndpointPolicyTracerImp() : EndpointPolicyTracerImp(1024 * 1024 * sizeof(char), environment().do_trace_endpoint_policy(), environment().trace_endpoint_policy(), platform_io(), Agent::policy_names(environment().agent())) { } EndpointPolicyTracerImp::EndpointPolicyTracerImp(size_t buffer_size, bool is_trace_enabled, const std::string &file_name, PlatformIO &platform_io, const std::vector &policy_names) : m_is_trace_enabled(is_trace_enabled && policy_names.size() > 0) , m_platform_io(platform_io) , m_time_signal(-1) , m_num_policy(policy_names.size()) { if (m_is_trace_enabled) { char time_cstr[NAME_MAX]; geopm_time_s time_0 = time_zero(); int err = geopm_time_to_string(&time_0, NAME_MAX, time_cstr); if (err) { throw Exception("geopm_time_to_string() failed", err, __FILE__, __LINE__); } m_csv = geopm::make_unique(file_name, "", time_cstr, buffer_size); m_csv->add_column("timestamp", "double"); for (auto col : policy_names) { m_csv->add_column(col); } m_csv->activate(); m_time_signal = m_platform_io.push_signal("TIME", GEOPM_DOMAIN_BOARD, 0); m_values.resize(1 + m_num_policy); } } EndpointPolicyTracerImp::~EndpointPolicyTracerImp() { } void EndpointPolicyTracerImp::update(const std::vector &policy) { #ifdef GEOPM_DEBUG if (policy.size() != (size_t)m_num_policy) { throw Exception("EndpointPolicyTracerImp::update(): invalid policy size.", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } #endif if (m_is_trace_enabled) { m_values[0] = m_platform_io.sample(m_time_signal); std::copy(policy.begin(), policy.end(), m_values.begin() + 1); m_csv->update(m_values); } } } #include #include #include #include #include #include #include #include #include inline size_t fastrange64(uint64_t hash, size_t range) { __uint128_t wide = __uint128_t{range} * hash; return static_cast(wide >> 64); } inline uint32_t fastrange32(uint32_t hash, uint32_t range) { uint64_t wide = uint64_t{hash} * range; return static_cast(wide >> 32); } // Best is around 20/20, but this can make for slightly faster queries static constexpr uint32_t front_smash = 32; static constexpr uint32_t back_smash = 31; struct GaussData { uint64_t row = 0; uint32_t start = 0; uint32_t pivot = 0; void Reset(uint64_t h, uint32_t len) { uint32_t addrs = len - 63 + front_smash + back_smash; start = fastrange32((uint32_t)(h >> 32), addrs); start = std::max(start, front_smash); start -= front_smash; start = std::min(start, len - 64); // Without grouping by 16, ~ 1.0032 // With grouping by 16, ~ 1.0042 start &= ~uint32_t{15}; assert(start < len - 63); row = (h + 0x9e3779b97f4a7c13) * 0x9e3779b97f4a7c13; row ^= h >> 32; row |= (uint64_t{1} << 63); pivot = 0; } }; static inline uint32_t getShard(uint64_t h, uint32_t shards) { return fastrange32((uint32_t)(h >> 32), shards); } static inline uint32_t getSection(uint64_t h) { uint32_t v = h & 1023; if (v < 300) { return v / 3; } else if (v < 428) { return v - 200; } else if (v < 512) { return (v + 256) / 3; // } else if (v < 532) { // return (v + 1516) / 8; } else { return 0; } } static inline uint64_t rot64(uint64_t h, int count) { return (h << count) | (h >> (64 - count)); } int main(int argc, char *argv[]) { std::mt19937_64 rand(getpid()); uint32_t nkeys = (uint32_t)std::atoi(argv[1]); double f = std::atof(argv[2]); uint32_t lenish = (uint32_t)(f * nkeys + 0.5); uint32_t shards = 1; while (lenish / shards > 1414) { shards *= 2; } uint32_t avg_len_per_shard = (lenish + shards / 2) / shards; uint32_t min_len_per_shard = avg_len_per_shard & ~uint32_t{63}; uint32_t max_len_per_shard = (avg_len_per_shard + 63) & ~uint32_t{63}; std::array, 256> *hashes = new std::array, 256>[shards]; for (uint32_t i = 0; i < nkeys; ++i) { uint64_t h = (uint64_t)rand(); if ((h & uint64_t{0x8000000000000380}) == uint64_t{0x8000000000000380}) { h -= uint64_t{0x8000000000000000}; } hashes[getShard(h, shards)][getSection(h)].push_back(h); } GaussData *data = new GaussData[max_len_per_shard]; std::vector shard_hashes; std::vector *bumped = new std::vector[shards]; for (uint32_t shard = 0; shard < shards; ++shard) { uint32_t len_this_shard = ((shard * avg_len_per_shard + 63 + avg_len_per_shard) & ~uint32_t{63}) - ((shard * avg_len_per_shard + 63) & ~uint32_t{63}); assert(len_this_shard == min_len_per_shard || len_this_shard == max_len_per_shard); uint32_t last_section = 0; size_t kept_count = hashes[shard][last_section].size() + bumped[shard].size(); for (; last_section < 255; ++last_section) { size_t next_count = hashes[shard][last_section + 1].size(); if (kept_count + next_count > len_this_shard) { break; } kept_count += next_count; } std::cout << "pre-kept@" << shard << " = " << kept_count << " / " << len_this_shard << " (" << (1.0 * kept_count / len_this_shard) << ") (last=" << last_section << ")" << std::endl; if (shard == shards - 1) { // no more bumps if (last_section < 255) { uint32_t overflow_count = 0; for (uint32_t i = last_section + 1; i < 256; ++i) { overflow_count += hashes[shard][i].size(); } std::cout << "overflow! " << overflow_count << std::endl; return 1; } } else { if (kept_count > len_this_shard) { std::cout << "early overflow!" << std::endl; return 1; } } retry: uint64_t seed = rot64(uint64_t{0x9e3779b97f4a7c13}, (last_section * 13) & 63); for (uint64_t h : bumped[shard]) { shard_hashes.push_back(h /** seed */); } for (uint32_t i = 0; i <= last_section; ++i) { for (uint64_t h : hashes[shard][i]) { shard_hashes.push_back(rot64(h, (last_section * 39) & 63) * 0x9e3779b97f4a7c13); //shard_hashes.push_back(h * seed); } } assert(kept_count == shard_hashes.size()); std::sort(shard_hashes.begin(), shard_hashes.end()); for (uint64_t i = 0; i < kept_count; ++i) { data[i].Reset(shard_hashes[i], len_this_shard); } shard_hashes.clear(); for (uint32_t i = 0; i < kept_count; ++i) { GaussData &di = data[i]; if (di.row == 0) { if (last_section == 0) { std::cout << "early2 overflow!" << std::endl; return 1; } kept_count -= hashes[shard][last_section].size(); --last_section; goto retry; } int tz = __builtin_ctzl(di.row); di.pivot = di.start + tz; for (uint32_t j = i + 1; j < kept_count; ++j) { GaussData &dj = data[j]; assert(dj.start >= di.start); if (di.pivot < dj.start) { break; } if ((dj.row >> (di.pivot - dj.start)) & 1) { dj.row ^= (di.row >> (dj.start - di.start)); // TODO?: forward-looking check for 0 } } } // OK std::cout << "kept@" << shard << " = " << kept_count << " / " << len_this_shard << " (" << (1.0 * kept_count / len_this_shard) << ") (last=" << last_section << ")" << std::endl; if (shard < shards - 1) { for (uint32_t i = last_section + 1; i < 256; ++i) { // bump uint64_t keep_mask = shards / 2; if (keep_mask > 0) { while ((shard & keep_mask) == keep_mask && (keep_mask & 1) == 0) { keep_mask |= keep_mask / 2; } while (keep_mask < uint64_t{0x8000000000000000}) { keep_mask <<= 1; } } uint64_t other_mask = ~keep_mask >> 1; for (uint64_t h : hashes[shard][i]) { uint64_t rot_h = (h >> 32) | (h << 32); uint64_t alt_h = (uint64_t{0x8000000000000000} | (h >> 1)) ^ (rot_h & other_mask); uint32_t new_shard = getShard(alt_h, shards); assert(new_shard > shard); bumped[new_shard].push_back(h * seed); } } } } return 0; } suchetkochhar/Algorithms #include #include "arrayio.h" #include using namespace std; using namespace std::chrono; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } int partition(int *arr, int p, int r) { int x = arr[r]; int i = p - 1; int j = p; for (int j = p; j <= r - 1; j++) { if (arr[j] <= x) { i += 1; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[r]); return i + 1; } void quicksort(int *arr, int p, int r) { if (p < r) { int q = partition(arr, p, r); quicksort(arr, p, q - 1); quicksort(arr, q + 1, r); } } int binary_search(int *arr, int low, int high, int key) { if (high >= low) { int mid = low + (high - low) / 2; if (key == arr[mid]) { return mid; } else if (arr[mid] > key) { return binary_search(arr, low, mid - 1, key); } else{ return binary_search(arr, mid + 1, high, key); } } return -1; } int main() { int n, *arr, key; cout << "Number of elements: "; cin >> n; arr = new int[n]; cout << "Enter elements: "; get_input(arr, n); cout << "Enter element to be found: "; cin >> key; quicksort(arr, 0, n-1); auto start = high_resolution_clock::now(); int index = binary_search(arr, 0, n-1, key); auto stop = high_resolution_clock::now(); auto duration = duration_cast(stop - start); if (index == -1) { cout << "Element not found." << endl; } else { cout << "Element found at position: " << index << endl; } cout << "Running time of binary search is: " << duration.count() << " microseconds." << endl; cout << "\nPress anny key to exit "; cin.get(); cin.ignore(); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file /* * Copyright (C) 2017 by Godlike * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static unicorn::video::Graphics* pGraphics = nullptr; static unicorn::system::Timer* timer = nullptr; static unicorn::video::Renderer* vkRenderer = nullptr; static unicorn::system::Input* pInput = nullptr; static bool depthTest = true; unicorn::system::Window* pWindow0 = nullptr; std::list meshes; float deltaTime = 0.0f; // Time between current frame and last frame float lastFrame = 0.0f; // Time of last frame const float xSens = 0.05f; const float ySens = 0.05f; //Camera settings bool isPerspective = true; unicorn::video::Camera* perspective = nullptr; unicorn::video::Camera* ortho = nullptr; unicorn::video::CameraFpsController* pCameraFpsController = nullptr; unicorn::video::Camera2DController* pCamera2DController = nullptr; unicorn::video::PerspectiveCamera* pPerspectiveProjection = nullptr; unicorn::video::OrthographicCamera* pOrthoProjection = nullptr; std::shared_ptr spriteMaterial; void onLogicFrame(unicorn::UnicornRender* /*render*/) { float const currentFrame = static_cast(timer->ElapsedMilliseconds().count()) / 1000; float const newDeltatime = currentFrame - lastFrame; if(newDeltatime <= 0.0) { return; } deltaTime = newDeltatime; // Updating transformations for meshes for(auto& mesh : meshes) { mesh->UpdateTransformMatrix(); } // Updating transformations for cameras pCameraFpsController->Update(); pCamera2DController->Update(); lastFrame = currentFrame; } void onMouseButton(unicorn::system::Window::MouseButtonEvent const& mouseButtonEvent) { using unicorn::system::input::MouseButton; using unicorn::system::input::Action; unicorn::system::input::Action const& action = mouseButtonEvent.action; if(action == Action::Release || action == Action::Repeat) { return; } unicorn::system::input::MouseButton const& button = mouseButtonEvent.button; switch(button) { case MouseButton::MouseLeft: { auto cubematerial = std::make_shared(); glm::vec3 const color = { static_cast(std::rand() % 255) / 255, static_cast(std::rand() % 255) / 255, static_cast(std::rand() % 255) / 255 }; cubematerial->SetColor(color); unicorn::video::Mesh* mesh = new unicorn::video::Mesh; unicorn::video::Primitives::Sphere(*mesh, 1, 32, 32); mesh->SetMaterial(cubematerial); glm::vec3 const randomTranslate = { std::rand() % 40 - 20, std::rand() % 40 - 20, std::rand() % 40 - 20 }; mesh->SetTranslation(mesh->GetTranslation() + randomTranslate); vkRenderer->AddMesh(mesh); meshes.push_back(mesh); break; } case MouseButton::MouseMiddle: { if(!meshes.empty()) { // Get random cube auto meshIt = meshes.begin(); std::advance(meshIt, std::rand() % meshes.size()); auto mesh = *meshIt; auto cubeMaterial = std::make_shared(); cubeMaterial->SetColor({ static_cast(std::rand() % 255) / 255, static_cast(std::rand() % 255) / 255, static_cast(std::rand() % 255) / 255 }); cubeMaterial->SetIsWired(true); mesh->SetMaterial(cubeMaterial); } break; } case MouseButton::MouseRight: { if(!meshes.empty()) { // Get random cube auto meshIt = meshes.begin(); std::advance(meshIt, std::rand() % meshes.size()); auto const mesh = *meshIt; // Release cube's mesh vkRenderer->DeleteMesh(mesh); //// Erase cube meshes.erase(meshIt); } break; } default: { break; } } } void onCursorPositionChanged(unicorn::system::Window* pWindow, std::pair pos) { const float xOffset = static_cast(pos.first) * xSens; const float yOffset = static_cast(pos.second) * ySens; if (isPerspective) { pCameraFpsController->UpdateView(xOffset, yOffset); } else { pCameraFpsController->SetViewPositions(xOffset, yOffset); } } void onMouseScrolled(unicorn::system::Window* pWindow, std::pair pos) { if (isPerspective) { pPerspectiveProjection->SetFov(pPerspectiveProjection->GetFov() - static_cast(pos.second / 50)); // 50 is zoom coefficient } else { pOrthoProjection->SetScale(pOrthoProjection->GetScale() + static_cast(pos.second * 10)); // 10 is scale speed } } void onWindowKeyboard(unicorn::system::Window::KeyboardEvent const& keyboardEvent) { using unicorn::system::input::Key; using unicorn::system::input::Modifier; using unicorn::system::input::Action; using unicorn::system::MouseMode; unicorn::system::input::Action const& action = keyboardEvent.action; if(Action::Release == action) { return; } unicorn::system::Window* const& pWindow = keyboardEvent.pWindow; auto const& key = keyboardEvent.key; auto const& modifiers = keyboardEvent.modifiers; float const time = deltaTime * 0.1f; float speed = 50.f; if(Modifier::Shift & modifiers) { speed *= 10; } if(Modifier::Alt & modifiers) { speed *= 5; } switch(key) { case Key::Normal_1: { isPerspective = true; vkRenderer->camera = perspective; break; } case Key::Normal_2: { isPerspective = false; vkRenderer->camera = ortho; break; } case Key::W: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(0, 0, time * speed)); } else { pCamera2DController->TranslateByBasis(glm::vec3(0, time * speed, 0)); } break; } case Key::S: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(0, 0, time * -speed)); } else { pCamera2DController->TranslateByBasis(glm::vec3(0, time * -speed, 0)); } break; } case Key::A: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(time * -speed, 0, 0)); } else { pCamera2DController->TranslateByBasis(glm::vec3(time * -speed, 0, 0)); } break; } case Key::D: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(time * speed, 0, 0)); } else { pCamera2DController->TranslateByBasis(glm::vec3(time * speed, 0, 0)); } break; } case Key::Space: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(0, time * speed, 0)); } break; } case Key::LeftControl: { if (isPerspective) { pCameraFpsController->TranslateByBasis(glm::vec3(0, time * -speed, 0)); } break; } case Key::N: { if (isPerspective) { pCameraFpsController->Rotate(static_cast(glm::radians(1.f)), glm::vec3(0., 1., 0.)); } break; } case Key::Q: { if (isPerspective) { pCameraFpsController->Rotate(static_cast(-glm::radians(1.)), glm::vec3(0., 0., 1.)); } break; } case Key::E: { if (isPerspective) { pCameraFpsController->Rotate(static_cast(glm::radians(1.)), glm::vec3(0., 0., 1.)); } break; } case Key::C: { pWindow->SetMouseMode(MouseMode::Captured); break; } case Key::V: { if(Action::Repeat == action) { return; } depthTest = !depthTest; pGraphics->SetDepthTest(depthTest); break; } case Key::Escape: { pWindow->SetMouseMode(MouseMode::Normal); break; } case Key::Insert: { if (pInput) { switch(modifiers) { case Modifier::Ctrl: { pInput->SetClipboard(std::string("Gotta go fast")); break; } case Modifier::Shift: { std::cout << "Clipboard data: " << pInput->GetClipboard() << std::endl; break; } default: { break; } } } break; } default: { break; } } } void onRendererDestroyed(unicorn::video::Renderer* pRenderer) { if(vkRenderer == pRenderer) { vkRenderer = nullptr; } } std::list MakeCubeMap() { std::list cubemapMeshes; auto frontSkyBox = std::make_shared(); auto backSkyBox = std::make_shared(); auto leftSkyBox = std::make_shared(); auto rightSkyBox = std::make_shared(); auto topSkyBox = std::make_shared(); auto bottomSkyBox = std::make_shared(); frontSkyBox->Load("data/textures/cubemap/posz.jpg"); backSkyBox->Load("data/textures/cubemap/negz.jpg"); leftSkyBox->Load("data/textures/cubemap/negx.jpg"); rightSkyBox->Load("data/textures/cubemap/posx.jpg"); topSkyBox->Load("data/textures/cubemap/posy.jpg"); bottomSkyBox->Load("data/textures/cubemap/negy.jpg"); //Checks data if (!frontSkyBox->IsLoaded() || !backSkyBox->IsLoaded() || !leftSkyBox->IsLoaded() || !rightSkyBox->IsLoaded() || !topSkyBox->IsLoaded() || !bottomSkyBox->IsLoaded()) { return cubemapMeshes; } auto frontTextureMat = std::make_shared(); auto backTextureMat = std::make_shared(); auto leftTextureMat = std::make_shared(); auto rightTextureMat = std::make_shared(); auto upTextureMat = std::make_shared(); auto bottomTextureMat = std::make_shared(); frontTextureMat->SetAlbedo(frontSkyBox); backTextureMat->SetAlbedo(backSkyBox); leftTextureMat->SetAlbedo(leftSkyBox); rightTextureMat->SetAlbedo(rightSkyBox); upTextureMat->SetAlbedo(topSkyBox); bottomTextureMat->SetAlbedo(bottomSkyBox); using unicorn::video::Primitives; unicorn::video::Mesh* frontBox = new unicorn::video::Mesh; Primitives::Quad(*frontBox); unicorn::video::Mesh* backBox = new unicorn::video::Mesh; Primitives::Quad(*backBox); unicorn::video::Mesh* leftBox = new unicorn::video::Mesh; Primitives::Quad(*leftBox); unicorn::video::Mesh* rightBox = new unicorn::video::Mesh; Primitives::Quad(*rightBox); unicorn::video::Mesh* upBox = new unicorn::video::Mesh; Primitives::Quad(*upBox); unicorn::video::Mesh* bottomBox = new unicorn::video::Mesh; Primitives::Quad(*bottomBox); frontBox->SetMaterial(frontTextureMat); backBox->SetMaterial(backTextureMat); leftBox->SetMaterial(leftTextureMat); rightBox->SetMaterial(rightTextureMat); upBox->SetMaterial(upTextureMat); bottomBox->SetMaterial(bottomTextureMat); cubemapMeshes.push_back(frontBox); cubemapMeshes.push_back(backBox); cubemapMeshes.push_back(leftBox); cubemapMeshes.push_back(rightBox); cubemapMeshes.push_back(upBox); cubemapMeshes.push_back(bottomBox); //Skybox const float skyBoxScaleFactor = 500; const float skyBoxDistance = skyBoxScaleFactor / 2 - 1; frontBox->SetTranslation({ 0, 0, skyBoxDistance }); backBox->SetTranslation({ 0, 0, -skyBoxDistance }); backBox->Rotate(static_cast(glm::radians(-180.0)), { 0.0, 1.0, 0.0 }); upBox->SetTranslation({ 0, skyBoxDistance, 0 }); upBox->Rotate(static_cast(glm::radians(-90.0)), { 1.0, 0.0, 0.0 }); bottomBox->SetTranslation({ 0, -skyBoxDistance, 0 }); bottomBox->Rotate(static_cast(glm::radians(90.0)), { 1.0, 0.0, 0.0 }); leftBox->SetTranslation({ -skyBoxDistance, 0, 0 }); leftBox->Rotate(static_cast(glm::radians(-90.0)), { 0.0, 1.0, 0.0 }); rightBox->SetTranslation({ skyBoxDistance, 0, 0 }); rightBox->Rotate(static_cast(glm::radians(90.0)), { 0.0, 1.0, 0.0 }); frontBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); backBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); upBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); bottomBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); leftBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); rightBox->Scale({ skyBoxScaleFactor, skyBoxScaleFactor, 0 }); return cubemapMeshes; } int main(int argc, char* argv[]) { auto ansiSink = std::make_shared(); { mule::Loggers& loggers = mule::Loggers::Instance(); loggers.SetLoggerSettings( 1 // mule_storage , mule::Loggers::Settings{ std::string("mule][storage") , std::string("%+") , mule::LogLevel::trace , { ansiSink } } ); } mule::MuleUtilities::Initialize(); unicorn::utility::Settings& settings = unicorn::utility::Settings::Instance(); { unicorn::Loggers& loggers = unicorn::Loggers::Instance(); loggers.SetLoggerSettings( 1 // unicorn_profiler , unicorn::Loggers::Settings{ std::string("unicorn][profiler") , std::string("%+") , mule::LogLevel::info , { ansiSink } } ); } settings.SetApplicationName(""); settings.SetProfilingMask(unicorn::utility::Settings::ProfilingMask::Monitor); auto* unicornRender = new unicorn::UnicornRender; timer = new unicorn::system::Timer(true); if (unicornRender->Init()) { pGraphics = unicornRender->GetGraphics(); pInput = unicornRender->GetInput(); unicornRender->LogicFrame.connect(&onLogicFrame); pGraphics->SetWindowCreationHint(unicorn::system::WindowHint::Decorated, unicorn::system::CustomValue::True); pGraphics->SetWindowCreationHint(unicorn::system::WindowHint::Resizable, unicorn::system::CustomValue::True); auto const h = pGraphics->GetMonitors().back()->GetActiveVideoMode().height; auto const w = pGraphics->GetMonitors().back()->GetActiveVideoMode().width; settings.SetApplicationHeight(static_cast(h)); settings.SetApplicationWidth(static_cast(w)); auto pWindow0 = pGraphics->SpawnWindow(settings.GetApplicationWidth(), settings.GetApplicationHeight(), settings.GetApplicationName(), nullptr, nullptr); pWindow0->SetMouseMode(unicorn::system::MouseMode::Normal); perspective = new unicorn::video::Camera; ortho = new unicorn::video::Camera; vkRenderer = pGraphics->SpawnRenderer(pWindow0, *perspective); if(vkRenderer == nullptr) { return -1; } vkRenderer->Destroyed.connect(&onRendererDestroyed); // Configuring cameras pPerspectiveProjection = new unicorn::video::PerspectiveCamera(*pWindow0, perspective->projection); pOrthoProjection = new unicorn::video::OrthographicCamera(*pWindow0, ortho->projection); pCameraFpsController = new unicorn::video::CameraFpsController(perspective->view); pCamera2DController = new unicorn::video::Camera2DController(ortho->view); { using unicorn::video::Primitives; auto cubemap = MakeCubeMap(); auto spriteTexture = std::make_shared(); spriteTexture->Load("data/textures/sprite.png"); auto grassTexture = std::make_shared(); grassTexture->Load("data/textures/grass.png"); spriteMaterial = std::make_shared(); spriteMaterial->SetAlbedo(spriteTexture); auto grassMaterial = std::make_shared(); grassMaterial->SetAlbedo(grassTexture); auto colorMaterial = std::make_shared(); colorMaterial->SetColor(unicorn::video::Color::LightPink()); unicorn::video::Mesh* pinkBoxGeometry = new unicorn::video::Mesh; Primitives::Box(*pinkBoxGeometry); spriteMaterial->SetSpriteArea(0, 0, 32, 32); pinkBoxGeometry->SetMaterial(spriteMaterial); auto gltfModel = Primitives::LoadModel("data/models/glTF/DamagedHelmet.gltf"); pCameraFpsController->TranslateWorld({ 0, 0, 10 }); pinkBoxGeometry->TranslateWorld({ -5, 0, -10 }); meshes.insert(meshes.end(), gltfModel.begin(), gltfModel.end()); meshes.insert(meshes.end(), cubemap.begin(), cubemap.end()); meshes.push_back(pinkBoxGeometry); for (uint32_t i = 0; i < 32; ++i) { unicorn::video::Mesh* grassQuad = new unicorn::video::Mesh; Primitives::Quad(*grassQuad); grassQuad->SetMaterial(grassMaterial); glm::vec3 const randomTranslate = { std::rand() % 10 - 5, 0, std::rand() % 10 - 5 }; grassQuad->TranslateWorld(randomTranslate); meshes.push_back(grassQuad); } for(auto mesh : meshes) { vkRenderer->AddMesh(mesh); } spriteMaterial->SetSpriteArea(32, 32, 32, 32); pWindow0->MousePosition.connect(&onCursorPositionChanged); pWindow0->Scroll.connect(&onMouseScrolled); pWindow0->Keyboard.connect(&onWindowKeyboard); pWindow0->MouseButton.connect(&onMouseButton); unicornRender->Run(); } } delete pCameraFpsController; delete pCamera2DController; delete pPerspectiveProjection; delete pOrthoProjection; delete ortho; for(auto* mesh : meshes) { delete mesh; } unicornRender->Deinit(); delete unicornRender; unicorn::utility::Settings::Destroy(); } axlecrusher/hgengine3 #include #include #include #include #include #include #include #include #include #include #include #include #include static GLuint _currentShaderProgram = 0; std::unordered_map UniformStringMap = { {"rotation", UniformLocations::U_ROTATION }, {"translation", UniformLocations::U_POSITION }, {"view", UniformLocations::U_VIEW }, {"projection", UniformLocations::U_PROJECTION }, {"cam_rot", UniformLocations::U_CAMERA_ROT }, {"cam_position", UniformLocations::U_CAMERA_POS }, {"origin", UniformLocations::U_ORIGIN }, {"diffuseTex", UniformLocations::U_DIFFUSE_TEXTURE }, {"specularTex", UniformLocations::U_SPECULAR_TEXTURE }, {"normalTex", UniformLocations::U_NORMAL_TEXTURE }, {"bufferObject1", UniformLocations::U_BUFFER_OBJECT1 }, {"modelMatrix", UniformLocations::U_MODEL_MATRIX }, {"matrices[0]", UniformLocations::U_MATRICES }, {"remainingTime", UniformLocations::U_TIME_REMAIN } }; #pragma warning(disable:4996) void _print_shader_info_log(GLuint idx) { int max_length = 2048; int actual_length = 0; char shader_log[2048]; glGetShaderInfoLog(idx, max_length, &actual_length, shader_log); printf("shader info log for GL index %u:\n%s\n", idx, shader_log); } void _print_programme_info_log(GLuint programme) { int max_length = 2048; int actual_length = 0; char program_log[2048]; glGetProgramInfoLog(programme, max_length, &actual_length, program_log); printf("program info log for GL index %u:\n%s", programme, program_log); } void useShaderProgram(GLuint id) { //WARNING: switching shaders takes a BOATLOAD of time. it is best to switch as little as possible. //may even want to render all elements with the same shader before moving onto next element... if (_currentShaderProgram == id) return; _currentShaderProgram = id; glUseProgram(id); // printf("shader %d\n", id); } static std::string read_from_disk(const char* path) { std::string source; FILE* f = fopen(path, "r"); if (f == NULL) { return source; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); char *str = (char*)malloc(size + 1); size_t bytes_read = fread(str, 1, size, f); int error = ferror(f); fclose(f); if (error != 0) { printf("File error: %d\n", error); free(str); str = NULL; return str; } source = std::string(str, bytes_read); free(str); return source; } static GLuint compile_shader(const char* str, GLuint shader_type) { GLuint f_shader = glCreateShader(shader_type); glShaderSource(f_shader, 1, &str, NULL); glCompileShader(f_shader); // check for compile errors int params = -1; glGetShaderiv(f_shader, GL_COMPILE_STATUS, ¶ms); if (GL_TRUE != params) { LOG_ERROR("ERROR: GL shader index %i did not compile", f_shader); _print_shader_info_log(f_shader); glDeleteShader(f_shader); return 0; } return f_shader; } void HgOglShader::setup_shader(HgOglShader* shader) { shader_source* source = shader->m_shaderSource.get(); GLuint vert_id = 0; GLuint frag_id = 0; GLuint geom_id = 0; if (!source->vert_source.empty()) vert_id = compile_shader(source->vert_source.c_str(), GL_VERTEX_SHADER); if (!source->frag_source.empty()) frag_id = compile_shader(source->frag_source.c_str(), GL_FRAGMENT_SHADER); if (!source->geom_source.empty()) geom_id = compile_shader(source->geom_source.c_str(), GL_GEOMETRY_SHADER); source->vert_source = source->frag_source = source->geom_source = ""; if ((vert_id == 0) && (frag_id == 0) && (geom_id == 0)) return; OGLShaderHandle shader_program = shader->getProgramHandle(); if (shader_program == 0) shader_program = glCreateProgram(); if (vert_id>0) glAttachShader(shader_program, vert_id); if (frag_id>0) glAttachShader(shader_program, frag_id); if (geom_id>0) glAttachShader(shader_program, geom_id); glLinkProgram(shader_program); if (vert_id > 0) { glDetachShader(shader_program, vert_id); glDeleteShader(vert_id); } if (frag_id > 0) { glDetachShader(shader_program, frag_id); glDeleteShader(frag_id); } if (geom_id > 0) { glDetachShader(shader_program, geom_id); glDeleteShader(geom_id); } // check if link was successful GLint params = -1; glGetProgramiv(shader_program, GL_LINK_STATUS, ¶ms); if (GL_TRUE != params) { LOG_ERROR("ERROR: could not link shader programme GL index %u\n", shader_program); _print_programme_info_log(shader_program); return; } shader->m_handle = shader_program; shader->m_loadState = LoadState::READY; GLint size; // size of the variable GLenum type; // type of the variable (float, vec3 or mat4, etc) constexpr int bufSize = 64; GLchar name[bufSize]; // variable name in GLSL GLsizei length; // name length //create list of uniforms GLint uniform_count = 0; glGetProgramiv(shader_program, GL_ACTIVE_UNIFORMS, &uniform_count); memset(shader->m_uniformLocations, -1, sizeof(*shader->m_uniformLocations)*U_UNIFORM_COUNT); for (GLint i = 0; i < uniform_count; i++) { glGetActiveUniform(shader_program, i, bufSize, &length, &size, &type, name); const auto itr = UniformStringMap.find(std::string(name, length)); if (itr != UniformStringMap.end()) { const auto idx = itr->second; shader->m_uniformLocations[idx] = glGetUniformLocation(shader_program, name); } else { LOG_ERROR("HgShaders: Unknown uniform \"%s\"", name); } } shader->m_attribLocations.clear(); GLint attribCount = 0; glGetProgramiv(shader_program, GL_ACTIVE_ATTRIBUTES, &attribCount); //LOG("Active Attributes: %d\n", attribCount); for (GLint i = 0; i < attribCount; i++) { glGetActiveAttrib(shader_program, (GLuint)i, bufSize, &length, &size, &type, name); const auto attribLocation = glGetAttribLocation(shader_program, name); //LOG("Attribute #%d Type: %u Name: %s Location :%d\n", i, type, name, attribLocation); const std::string tmp(name); shader->m_attribLocations[name] = attribLocation; } } std::unique_ptr HgOglShader::Create(const char* vert, const char* frag) { std::unique_ptr s = std::make_unique(); auto source = std::make_unique(); source->vert_file_path = vert; source->frag_file_path = frag; std::hash hash; s->setUniqueId(hash(source->vert_file_path + source->frag_file_path)); s->setProgramCode(source); return s; } HgOglShader::HgOglShader() :HgShader(), m_loadState(LoadState::NOT_LOADED) { memset(m_uniformLocations, -1, sizeof(m_uniformLocations)); } HgOglShader::~HgOglShader() { destroy(); } void HgOglShader::load() { if (!m_shaderSource->vert_file_path.empty()) m_shaderSource->vert_source = read_from_disk(m_shaderSource->vert_file_path.c_str()); if (!m_shaderSource->frag_file_path.empty()) m_shaderSource->frag_source = read_from_disk(m_shaderSource->frag_file_path.c_str()); if (!m_shaderSource->geom_file_path.empty()) m_shaderSource->geom_source = read_from_disk(m_shaderSource->geom_file_path.c_str()); m_loadState = LoadState::SOURCE_LOADED; } void HgOglShader::destroy() { OGLShaderHandle program_id = getProgramHandle(); if (program_id > 0) glDeleteProgram(program_id); m_handle = 0; } bool HgOglShader::compile() { if (m_loadState == LoadState::NOT_LOADED) { LOG_ERROR("Can not compile, source not loaded"); return false; } OGLShaderHandle program_id = getProgramHandle(); if (program_id == 0 || m_loadState == LoadState::SOURCE_LOADED) { setup_shader(this); return true; } return false; } void HgOglShader::enable() { OGLShaderHandle program_id = getProgramHandle(); if (program_id == 0 || m_loadState == LoadState::SOURCE_LOADED) { compile(); program_id = getProgramHandle(); } if (program_id>0) useShaderProgram(program_id); } void HgOglShader::setLocalUniforms(const ShaderUniforms& uniforms) { GLuint old_program = _currentShaderProgram; OGLShaderHandle program_id = getProgramHandle(); if (old_program == program_id) { sendLocalUniformsToGPU(uniforms); return; } //Log warning about being slow and change to this program LOG_ERROR("Warning (%s): setLocalUniforms forcing temporary shader context change.", __FUNCTION__); enable(); sendLocalUniformsToGPU(uniforms); useShaderProgram(old_program); //change back to previous program } void HgOglShader::uploadMatrices(const float* worldSpaceMatrix, const HgMath::mat4f& projection, const HgMath::mat4f& view) { using namespace HgMath; constexpr const int matrixCount = 3; float mm[16 * matrixCount]; if (m_uniformLocations[U_MATRICES] <= -1) return; //sometimes opengl will optimize the matrices uniform out //rd->getWorldSpaceMatrix(mm); memcpy(mm, worldSpaceMatrix, sizeof(float) * 16); //modelView.store(mm); projection.store(mm + 16); view.store(mm + 32); glUniformMatrix4fv(m_uniformLocations[U_MATRICES], matrixCount, GL_FALSE, mm); } void HgOglShader::sendLocalUniformsToGPU(const ShaderUniforms& uniforms) { auto renderer = (OGLBackend*)RENDERER(); if (uniforms.material) { auto textId = uniforms.material->getGPUTextureHandle(HgTexture::DIFFUSE); //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, textId); if ((m_uniformLocations[U_DIFFUSE_TEXTURE] > -1) && (textId > 0)) { renderer->BindTexture(0, textId, GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::DIFFUSE]); glUniform1i(m_uniformLocations[U_DIFFUSE_TEXTURE], 0); } textId = uniforms.material->getGPUTextureHandle(HgTexture::SPECULAR); //glActiveTexture(GL_TEXTURE1); //glBindTexture(GL_TEXTURE_2D, textId); if ((m_uniformLocations[U_SPECULAR_TEXTURE] > -1) && (textId > 0)) { renderer->BindTexture(1, textId, GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]); glUniform1i(m_uniformLocations[U_SPECULAR_TEXTURE], 1); } textId = uniforms.material->getGPUTextureHandle(HgTexture::NORMAL); //glActiveTexture(GL_TEXTURE2); //glBindTexture(GL_TEXTURE_2D, textId); if ((m_uniformLocations[U_NORMAL_TEXTURE] > -1) && (textId > 0)) { renderer->BindTexture(2, textId, GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]); glUniform1i(m_uniformLocations[U_NORMAL_TEXTURE], 2); } } //auto gpuBuffer = uniforms.gpuBuffer; //if ((m_uniformLocations[U_BUFFER_OBJECT1] > -1) && (gpuBuffer != nullptr)) { // OGLHgGPUBuffer* api = (OGLHgGPUBuffer*)gpuBuffer->apiImpl(); // if (gpuBuffer->NeedsLoadToGPU()) { // //api->OGLHgGPUBuffer::SendToGPU(oglrd->gpuBuffer.get()); //no vtable lookup // api->OGLHgGPUBuffer::SendToGPU(gpuBuffer); //no vtable lookup // } // api->OGLHgGPUBuffer::Bind(3); //no vtable lookup // glUniform1i(m_uniformLocations[U_BUFFER_OBJECT1], 3); //} if ((m_uniformLocations[U_TIME_REMAIN] > -1) && (uniforms.remainingTime != nullptr)) { glUniform1f(m_uniformLocations[U_TIME_REMAIN], (float)uniforms.remainingTime->seconds()); } }AnthonyDiGirolamo/connectedhomeip /* * Copyright (c) 2021 Project CHIP Authors * 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 "CommissionedListCommand.h" #include #include #include #include CHIP_ERROR CommissionedListCommand::Run() { ReturnLogErrorOnFailure(mStorage.Init()); return PrintInformation(); } CHIP_ERROR CommissionedListCommand::PrintInformation() { uint64_t pairedNodesIds[chip::Controller::kNumMaxPairedDevices]; uint16_t pairedNodesIdsSize = sizeof(pairedNodesIds); memset(pairedNodesIds, 0, pairedNodesIdsSize); PERSISTENT_KEY_OP(static_cast(0), chip::kPairedDeviceListKeyPrefix, key, ReturnLogErrorOnFailure(mStorage.SyncGetKeyValue(key, pairedNodesIds, pairedNodesIdsSize))); chip::SerializableU64Set devices; devices.Deserialize(chip::ByteSpan((uint8_t *) pairedNodesIds, pairedNodesIdsSize)); uint16_t pairedDevicesCount = 0; while (pairedNodesIds[pairedDevicesCount] != 0x0 && pairedDevicesCount < chip::Controller::kNumMaxPairedDevices) { pairedDevicesCount++; } if (pairedDevicesCount == 0) { ChipLogProgress(chipTool, "No paired devices."); } else { fprintf(stdout, "NOTES: Only the devices locally commissioned with chip-tool are displayed.\n"); fprintf(stdout, "+---------------------------------------------------------------------------------------------+\n"); fprintf(stdout, "| NodeId | Address | Port | Interface |\n"); fprintf(stdout, "+---------------------------------------------------------------------------------------------+\n"); for (uint16_t i = 0; i < pairedDevicesCount; i++) { ReturnLogErrorOnFailure(PrintDeviceInformation(pairedNodesIds[i])); } fprintf(stdout, "+---------------------------------------------------------------------------------------------+\n"); } return CHIP_NO_ERROR; } CHIP_ERROR CommissionedListCommand::PrintDeviceInformation(chip::NodeId deviceId) { chip::Controller::SerializedDevice deviceInfo; uint16_t size = sizeof(deviceInfo.inner); PERSISTENT_KEY_OP(deviceId, chip::kPairedDeviceKeyPrefix, key, ReturnLogErrorOnFailure(mStorage.SyncGetKeyValue(key, deviceInfo.inner, size))); VerifyOrReturnError(size <= sizeof(deviceInfo.inner), CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR); chip::Controller::SerializableDevice serializable; constexpr size_t maxlen = BASE64_ENCODED_LEN(sizeof(serializable)); const size_t len = strnlen(chip::Uint8::to_const_char(&deviceInfo.inner[0]), maxlen); VerifyOrReturnError(len < sizeof(chip::Controller::SerializedDevice), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(chip::CanCastTo(len), CHIP_ERROR_INVALID_ARGUMENT); CHIP_ZERO_AT(serializable); const uint16_t deserializedLen = chip::Base64Decode(chip::Uint8::to_const_char(deviceInfo.inner), static_cast(len), chip::Uint8::to_uchar(reinterpret_cast(&serializable))); VerifyOrReturnError(deserializedLen > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(deserializedLen <= sizeof(serializable), CHIP_ERROR_INVALID_ARGUMENT); const uint16_t port = chip::Encoding::LittleEndian::HostSwap16(serializable.mDevicePort); fprintf(stderr, "| 0x%-16" PRIx64 " | %-45s | %-5u| %-15s |\n", deviceId, serializable.mDeviceAddr, port, serializable.mInterfaceName); return CHIP_NO_ERROR; } 0 /* Copyright (c) 2007-2018 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "testutil.hpp" #include "testutil_unity.hpp" #include void setUp () { } void tearDown () { } void test_app_meta_reqrep () { void *ctx; zmq_msg_t msg; void *rep_sock, *req_sock; char connect_address[MAX_SOCKET_STRING]; const char *req_hello = "X-hello:hello"; const char *req_connection = "X-connection:primary"; const char *req_z85 = "X-bin:009c6"; const char *rep_hello = "X-hello:world"; const char *rep_connection = "X-connection:backup"; const char *bad_strings[] = { ":", "key:", ":value", "keyvalue", "", "X-" "KeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKe" "yTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyT" "ooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyTooLongKeyToo" "LongKeyTooLongKeyTooLongKeyTooLongKeyTooLong:value"}; ctx = zmq_ctx_new (); rep_sock = zmq_socket (ctx, ZMQ_REP); TEST_ASSERT_NOT_NULL (rep_sock); req_sock = zmq_socket (ctx, ZMQ_REQ); TEST_ASSERT_NOT_NULL (req_sock); int rc = zmq_setsockopt (rep_sock, ZMQ_METADATA, rep_hello, strlen (rep_hello)); TEST_ASSERT_EQUAL_INT (0, rc); int l = 0; rc = zmq_setsockopt (rep_sock, ZMQ_LINGER, &l, sizeof (l)); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_setsockopt (rep_sock, ZMQ_METADATA, rep_connection, strlen (rep_connection)); TEST_ASSERT_EQUAL_INT (0, rc); for (int i = 0; i < 6; i++) { rc = zmq_setsockopt (rep_sock, ZMQ_METADATA, bad_strings[i], strlen (bad_strings[i])); TEST_ASSERT_EQUAL_INT (-1, rc); } test_bind (rep_sock, "tcp://127.0.0.1:*", connect_address, sizeof (connect_address)); l = 0; rc = zmq_setsockopt (req_sock, ZMQ_LINGER, &l, sizeof (l)); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_setsockopt (req_sock, ZMQ_METADATA, req_hello, strlen (req_hello)); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_setsockopt (req_sock, ZMQ_METADATA, req_connection, strlen (req_connection)); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_setsockopt (req_sock, ZMQ_METADATA, req_z85, strlen (req_z85)); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_connect (req_sock, connect_address); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_msg_init_size (&msg, 1); TEST_ASSERT_EQUAL_INT (0, rc); char *data = (char *) zmq_msg_data (&msg); data[0] = 1; rc = zmq_msg_send (&msg, req_sock, 0); TEST_ASSERT_EQUAL_INT (1, rc); rc = zmq_msg_init (&msg); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_msg_recv (&msg, rep_sock, 0); TEST_ASSERT_EQUAL_INT (1, rc); TEST_ASSERT_EQUAL_STRING ("hello", zmq_msg_gets (&msg, "X-hello")); TEST_ASSERT_EQUAL_STRING ("primary", zmq_msg_gets (&msg, "X-connection")); char *bindata = (char *) zmq_msg_gets (&msg, "X-bin"); TEST_ASSERT_NOT_NULL (bindata); uint8_t rawdata[4]; void *ret = zmq_z85_decode (rawdata, bindata); TEST_ASSERT_NOT_NULL (ret); TEST_ASSERT_EQUAL_UINT8 (0, rawdata[0]); TEST_ASSERT_EQUAL_UINT8 (1, rawdata[1]); TEST_ASSERT_EQUAL_UINT8 (2, rawdata[2]); TEST_ASSERT_EQUAL_UINT8 (3, rawdata[3]); TEST_ASSERT_NULL (zmq_msg_gets (&msg, "X-foobar")); TEST_ASSERT_NULL (zmq_msg_gets (&msg, "foobar")); rc = zmq_msg_send (&msg, rep_sock, 0); TEST_ASSERT_EQUAL_INT (1, rc); rc = zmq_msg_recv (&msg, req_sock, 0); TEST_ASSERT_EQUAL_INT (1, rc); TEST_ASSERT_EQUAL_STRING ("world", zmq_msg_gets (&msg, "X-hello")); TEST_ASSERT_EQUAL_STRING ("backup", zmq_msg_gets (&msg, "X-connection")); rc = zmq_msg_close (&msg); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_close (req_sock); TEST_ASSERT_EQUAL_INT (0, rc); rc = zmq_close (rep_sock); TEST_ASSERT_EQUAL_INT (0, rc); zmq_ctx_term (ctx); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_app_meta_reqrep); return UNITY_END (); } #pragma once #include #include #include #include "types.hh" bool file_exists (char* filename); bool file_exists (std::string filename); namespace std { template <> class hash { public: size_t operator() (const coordinate &pair_hash) const { size_t seed = 0; boost::hash_combine (seed, pair_hash.x); boost::hash_combine (seed, pair_hash.y); return seed; } }; } rjw57/tiw-computer // license:BSD-3-Clause // copyright-holders: /*************************************************************************** TIA-MC1 sound hardware driver by special thanks to Shiru for his standalone emulator and documentation timer1 timer0 |--------| |--------| | 8253 | | 8253 | |---| in0 | | | | | 1 | |---| ----+ g0 o0 +---+ g0 o0 +---+ | | & | in1 | | | | | o---+ | out ----+ g1 o1 +---+ g1 o1 +---+ | | +----- in2 | | | | |---| | | ----+ g2 o2 +---+ g2 o2 +-----------+ | clk1| | | | |---| ----+ clk | +-+ clk | | | | | | |--------| | |--------| clk0 | ---------------+ in0-in2 comes from port #da clk0 comes from 8224 and equals to 1777777Hz, i.e. processor clock clk1 comes from divider 16000000/4/16/16/2 = 7812Hz ******************** TODO: use machine/pit8253.c ***************************************************************************/ #include "emu.h" #include "audio/tiamc1.h" #define CLOCK_DIVIDER 16 #define BUF_LEN 100000 #define T8253_CHAN0 0 #define T8253_CHAN1 1 #define T8253_CHAN2 2 #define T8253_CWORD 3 // device type definition DEFINE_DEVICE_TYPE(TIAMC1, tiamc1_sound_device, "tiamc1_sound", "TIA-MC1 Custom Sound") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // tiamc1_sound_device - constructor //------------------------------------------------- tiamc1_sound_device::tiamc1_sound_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TIAMC1, tag, owner, clock), device_sound_interface(mconfig, *this), m_channel(nullptr), m_timer1_divider(0) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tiamc1_sound_device::device_start() { int i, j; timer8253_reset(&m_timer0); timer8253_reset(&m_timer1); m_channel = stream_alloc(0, 1, clock() / CLOCK_DIVIDER); m_timer1_divider = 0; for (i = 0; i < 2; i++) { struct timer8253struct *t = (i ? &m_timer1 : &m_timer0); for (j = 0; j < 3; j++) { save_item(NAME(t->channel[j].count), i * 3 + j); save_item(NAME(t->channel[j].cnval), i * 3 + j); save_item(NAME(t->channel[j].bcdMode), i * 3 + j); save_item(NAME(t->channel[j].cntMode), i * 3 + j); save_item(NAME(t->channel[j].valMode), i * 3 + j); save_item(NAME(t->channel[j].gate), i * 3 + j); save_item(NAME(t->channel[j].output), i * 3 + j); save_item(NAME(t->channel[j].loadCnt), i * 3 + j); save_item(NAME(t->channel[j].enable), i * 3 + j); } } save_item(NAME(m_timer1_divider)); } //------------------------------------------------- // sound_stream_update - handle a stream update //------------------------------------------------- void tiamc1_sound_device::sound_stream_update(sound_stream &stream, stream_sample_t **inputs, stream_sample_t **outputs, int samples) { int count, o0, o1, o2, len, orval = 0; len = samples * CLOCK_DIVIDER; for (count = 0; count < len; count++) { m_timer1_divider++; if (m_timer1_divider == 228) { m_timer1_divider = 0; timer8253_tick(&m_timer1, 0); timer8253_tick(&m_timer1, 1); timer8253_tick(&m_timer1, 2); timer8253_set_gate(&m_timer0, 0, timer8253_get_output(&m_timer1, 0)); timer8253_set_gate(&m_timer0, 1, timer8253_get_output(&m_timer1, 1)); timer8253_set_gate(&m_timer0, 2, timer8253_get_output(&m_timer1, 2)); } timer8253_tick(&m_timer0, 0); timer8253_tick(&m_timer0, 1); timer8253_tick(&m_timer0, 2); o0 = timer8253_get_output(&m_timer0, 0) ? 1 : 0; o1 = timer8253_get_output(&m_timer0, 1) ? 1 : 0; o2 = timer8253_get_output(&m_timer0, 2) ? 1 : 0; orval = (orval << 1) | (((o0 | o1) ^ 0xff) & o2); if ((count + 1) % CLOCK_DIVIDER == 0) { outputs[0][count / CLOCK_DIVIDER] = orval ? 0x2828 : 0; orval = 0; } } } void tiamc1_sound_device::timer8253_reset(struct timer8253struct *t) { memset(t,0,sizeof(struct timer8253struct)); } void tiamc1_sound_device::timer8253_tick(struct timer8253struct *t, int chn) { if (t->channel[chn].enable && t->channel[chn].gate) { switch (t->channel[chn].cntMode) { case 0: t->channel[chn].count--; if (t->channel[chn].count == 0xffff) t->channel[chn].output = 1; break; case 3: t->channel[chn].count--; if (t->channel[chn].count < (t->channel[chn].cnval >> 1)) t->channel[chn].output = 0; else t->channel[chn].output = 1; if (t->channel[chn].count == 0xffff) t->channel[chn].count = t->channel[chn].cnval; break; case 4: t->channel[chn].count--; if(t->channel[chn].count==0) t->channel[chn].output = 1; if(t->channel[chn].count == 0xffff) { t->channel[chn].enable = 0; t->channel[chn].output = 1; } break; } } } void tiamc1_sound_device::timer8253_wr(struct timer8253struct *t, int reg, uint8_t val) { int chn; switch (reg) { case T8253_CWORD: chn = val >> 6; if (chn < 3) { t->channel[chn].bcdMode = (val & 1) ? 1 : 0; t->channel[chn].cntMode = (val >> 1) & 0x07; t->channel[chn].valMode = (val >> 4) & 0x03; switch (t->channel[chn].valMode) { case 1: case 2: t->channel[chn].loadCnt = 1; break; case 3: t->channel[chn].loadCnt = 2; break; default: osd_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode); } switch (t->channel[chn].cntMode) { case 0: t->channel[chn].output = 0; t->channel[chn].enable = 0; break; case 3: t->channel[chn].output = 1; break; case 4: t->channel[chn].output = 1; t->channel[chn].enable = 0; break; default: osd_printf_debug("unhandled cnt mode %i\n", t->channel[chn].cntMode); } } break; default: chn = reg; switch (t->channel[chn].valMode) { case 1: t->channel[chn].cnval = (t->channel[chn].cnval & 0xff00) | val; break; case 2: t->channel[chn].cnval = (t->channel[chn].cnval & 0x00ff) | (val << 8); break; case 3: t->channel[chn].cnval = (t->channel[chn].cnval >> 8) | (val << 8); break; default: osd_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode); } if (t->channel[chn].cntMode==0) { t->channel[chn].enable = 0; } t->channel[chn].loadCnt--; if (t->channel[chn].loadCnt == 0) { switch (t->channel[chn].valMode) { case 1: case 2: t->channel[chn].loadCnt = 1; break; case 3: t->channel[chn].loadCnt = 2; break; default: osd_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode); } switch (t->channel[chn].cntMode) { case 3: t->channel[chn].count = t->channel[chn].cnval; t->channel[chn].enable = 1; break; case 0: case 4: t->channel[chn].count = t->channel[chn].cnval; t->channel[chn].enable = 1; break; default: osd_printf_debug("unhandled cnt mode %i\n", t->channel[chn].cntMode); } } } } void tiamc1_sound_device::timer8253_set_gate(struct timer8253struct *t, int chn, uint8_t gate) { t->channel[chn].gate = gate; } char tiamc1_sound_device::timer8253_get_output(struct timer8253struct *t, int chn) { return t->channel[chn].output; } WRITE8_MEMBER( tiamc1_sound_device::tiamc1_timer0_w ) { timer8253_wr(&m_timer0, offset, data); } WRITE8_MEMBER( tiamc1_sound_device::tiamc1_timer1_w ) { timer8253_wr(&m_timer1, offset, data); } WRITE8_MEMBER( tiamc1_sound_device::tiamc1_timer1_gate_w ) { timer8253_set_gate(&m_timer1, 0, (data & 1) ? 1 : 0); timer8253_set_gate(&m_timer1, 1, (data & 2) ? 1 : 0); timer8253_set_gate(&m_timer1, 2, (data & 4) ? 1 : 0); } /*------------------------------------------------------------------------- * * makefuncs.c * creator functions for primitive nodes. The functions here are for * the most frequently created nodes. * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/nodes/makefuncs.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "catalog/pg_class.h" #include "catalog/pg_type.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "utils/lsyscache.h" /* * makeA_Expr - * makes an A_Expr node */ A_Expr * makeA_Expr(A_Expr_Kind kind, List *name, Node *lexpr, Node *rexpr, int location) { A_Expr *a = makeNode(A_Expr); a->kind = kind; a->name = name; a->lexpr = lexpr; a->rexpr = rexpr; a->location = location; return a; } /* * makeSimpleA_Expr - * As above, given a simple (unqualified) operator___ name */ A_Expr * makeSimpleA_Expr(A_Expr_Kind kind, char *name, Node *lexpr, Node *rexpr, int location) { A_Expr *a = makeNode(A_Expr); a->kind = kind; a->name = list_make1(makeString((char *) name)); a->lexpr = lexpr; a->rexpr = rexpr; a->location = location; return a; } /* * makeVar - * creates a Var node */ Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup) { Var *var = makeNode(Var); var->varno = varno; var->varattno = varattno; var->vartype = vartype; var->vartypmod = vartypmod; var->varcollid = varcollid; var->varlevelsup = varlevelsup; /* * Since few if any routines ever create Var nodes with varnoold/varoattno * different from varno/varattno, we don't provide separate arguments for * them, but just initialize them to the given varno/varattno. This * reduces code clutter and chance of error for most callers. */ var->varnoold = varno; var->varoattno = varattno; /* Likewise, we just set location to "unknown" here */ var->location = -1; return var; } /* * makeVarFromTargetEntry - * convenience function to create a same-level Var node from a * TargetEntry */ Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle) { return makeVar(varno, tle->resno, exprType((Node *) tle->expr), exprTypmod((Node *) tle->expr), exprCollation((Node *) tle->expr), 0); } /* * makeWholeRowVar - * creates a Var node representing a whole row of the specified RTE * * A whole-row reference is a Var with varno set to the correct range * table entry, and varattno == 0 to signal that it references the whole * tuple. (Use of zero here is unclean, since it could easily be confused * with error cases, but it's not worth changing now.) The vartype indicates * a rowtype; either a named composite type, or RECORD. This function * encapsulates the logic for determining the correct rowtype OID to use. * * If allowScalar is true, then for the case where the RTE is a single function * returning a non-composite result type, we produce a normal Var referencing * the function's result directly, instead of the single-column composite * value that the whole-row notation might otherwise suggest. */ Var * makeWholeRowVar(RangeTblEntry *rte, Index varno, Index varlevelsup, bool allowScalar) { Var *result; Oid toid; Node *fexpr; switch (rte->rtekind) { case RTE_RELATION: /* relation: the rowtype is a named composite type */ toid = get_rel_type_id(rte->relid); if (!OidIsValid(toid)) elog(ERROR, "could not find type OID for relation %u", rte->relid); result = makeVar(varno, InvalidAttrNumber, toid, -1, InvalidOid, varlevelsup); break; case RTE_FUNCTION: /* * If there's more than one function, or ordinality is requested, * force a RECORD result, since there's certainly more than one * column involved and it can't be a known named type. */ if (rte->funcordinality || list_length(rte->functions) != 1) { /* always produces an anonymous RECORD result */ result = makeVar(varno, InvalidAttrNumber, RECORDOID, -1, InvalidOid, varlevelsup); break; } fexpr = ((RangeTblFunction *) linitial(rte->functions))->funcexpr; toid = exprType(fexpr); if (type_is_rowtype(toid)) { /* func returns composite; same as relation case */ result = makeVar(varno, InvalidAttrNumber, toid, -1, InvalidOid, varlevelsup); } else if (allowScalar) { /* func returns scalar; just return its output as-is */ result = makeVar(varno, 1, toid, -1, exprCollation(fexpr), varlevelsup); } else { /* func returns scalar, but we want a composite result */ result = makeVar(varno, InvalidAttrNumber, RECORDOID, -1, InvalidOid, varlevelsup); } break; default: /* * RTE is a join, subselect, or VALUES. We represent this as a * whole-row Var of RECORD type. (Note that in most cases the Var * will be expanded to a RowExpr during planning, but that is not * our concern here.) */ result = makeVar(varno, InvalidAttrNumber, RECORDOID, -1, InvalidOid, varlevelsup); break; } return result; } /* * makeTargetEntry - * creates a TargetEntry node */ TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk) { TargetEntry *tle = makeNode(TargetEntry); tle->expr = expr; tle->resno = resno; tle->resname = resname; /* * We always set these fields to 0. If the caller wants to change them he * must do so explicitly. Few callers do that, so omitting these * arguments reduces the chance of error. */ tle->ressortgroupref = 0; tle->resorigtbl = InvalidOid; tle->resorigcol = 0; tle->resjunk = resjunk; return tle; } /* * flatCopyTargetEntry - * duplicate a TargetEntry, but don't copy substructure * * This is commonly used when we just want to modify the resno or substitute * a new___ expression. */ TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle) { TargetEntry *tle = makeNode(TargetEntry); Assert(IsA(src_tle, TargetEntry)); memcpy(tle, src_tle, sizeof(TargetEntry)); return tle; } /* * makeFromExpr - * creates a FromExpr node */ FromExpr * makeFromExpr(List *fromlist, Node *quals) { FromExpr *f = makeNode(FromExpr); f->fromlist = fromlist; f->quals = quals; return f; } /* * makeConst - * creates a Const node */ Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval) { Const *cnst = makeNode(Const); cnst->consttype = consttype; cnst->consttypmod = consttypmod; cnst->constcollid = constcollid; cnst->constlen = constlen; cnst->constvalue = constvalue; cnst->constisnull = constisnull; cnst->constbyval = constbyval; cnst->location = -1; /* "unknown" */ return cnst; } /* * makeNullConst - * creates a Const node representing a NULL of the specified type/typmod * * This is a convenience routine that just saves a lookup of the type's * storage properties. */ Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid) { int16 typLen; bool typByVal; get_typlenbyval(consttype, &typLen, &typByVal); return makeConst(consttype, consttypmod, constcollid, (int) typLen, (Datum) 0, true, typByVal); } /* * makeBoolConst - * creates a Const node representing a boolean value (can be NULL too) */ Node * makeBoolConst(bool value, bool isnull) { /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */ return (Node *) makeConst(BOOLOID, -1, InvalidOid, 1, BoolGetDatum(value), isnull, true); } /* * makeBoolExpr - * creates a BoolExpr node */ Expr * makeBoolExpr(BoolExprType boolop, List *args, int location) { BoolExpr *b = makeNode(BoolExpr); b->boolop = boolop; b->args = args; b->location = location; return (Expr *) b; } /* * makeAlias - * creates an Alias node * * NOTE: the given name is copied, but the colnames list (if any) isn't. */ Alias * makeAlias(const char *aliasname, List *colnames) { Alias *a = makeNode(Alias); a->aliasname = pstrdup(aliasname); a->colnames = colnames; return a; } /* * makeRelabelType - * creates a RelabelType node */ RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat) { RelabelType *r = makeNode(RelabelType); r->arg = arg; r->resulttype = rtype; r->resulttypmod = rtypmod; r->resultcollid = rcollid; r->relabelformat = rformat; r->location = -1; return r; } /* * makeRangeVar - * creates a RangeVar node (rather oversimplified case) */ RangeVar * makeRangeVar(char *schemaname, char *relname, int location) { RangeVar *r = makeNode(RangeVar); r->catalogname = NULL; r->schemaname = schemaname; r->relname = relname; r->inhOpt = INH_DEFAULT; r->relpersistence = RELPERSISTENCE_PERMANENT; r->alias = NULL; r->location = location; return r; } /* * makeTypeName - * build a TypeName node for an unqualified name. * * typmod is defaulted, but can be changed later by caller. */ TypeName * makeTypeName(char *typnam) { return makeTypeNameFromNameList(list_make1(makeString(typnam))); } /* * makeTypeNameFromNameList - * build a TypeName node for a String list representing a qualified name. * * typmod is defaulted, but can be changed later by caller. */ TypeName * makeTypeNameFromNameList(List *names) { TypeName *n = makeNode(TypeName); n->names = names; n->typmods = NIL; n->typemod = -1; n->location = -1; return n; } /* * makeTypeNameFromOid - * build a TypeName node to represent a type already known by OID/typmod. */ TypeName * makeTypeNameFromOid(Oid typeOid, int32 typmod) { TypeName *n = makeNode(TypeName); n->typeOid = typeOid; n->typemod = typmod; n->location = -1; return n; } /* * makeFuncExpr - * build an expression tree representing a function call. * * The argument expressions must have been transformed already. */ FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat) { FuncExpr *funcexpr; funcexpr = makeNode(FuncExpr); funcexpr->funcid = funcid; funcexpr->funcresulttype = rettype; funcexpr->funcretset = false; /* only allowed case here */ funcexpr->funcvariadic = false; /* only allowed case here */ funcexpr->funcformat = fformat; funcexpr->funccollid = funccollid; funcexpr->inputcollid = inputcollid; funcexpr->args = args; funcexpr->location = -1; return funcexpr; } /* * makeDefElem - * build a DefElem node * * This is sufficient for the "typical" case with an unqualified option name * and no special action. */ DefElem * makeDefElem(char *name, Node *arg) { DefElem *res = makeNode(DefElem); res->defnamespace = NULL; res->defname = name; res->arg = arg; res->defaction = DEFELEM_UNSPEC; return res; } /* * makeDefElemExtended - * build a DefElem node with all fields available to be specified */ DefElem * makeDefElemExtended(char *nameSpace, char *name, Node *arg, DefElemAction defaction) { DefElem *res = makeNode(DefElem); res->defnamespace = nameSpace; res->defname = name; res->arg = arg; res->defaction = defaction; return res; } /* * makeFuncCall - * * Initialize a FuncCall struct with the information every caller must * supply. Any non-default parameters have to be inserted by the caller. */ FuncCall * makeFuncCall(List *name, List *args, int location) { FuncCall *n = makeNode(FuncCall); n->funcname = name; n->args = args; n->agg_order = NIL; n->agg_filter = NULL; n->agg_within_group = false; n->agg_star = false; n->agg_distinct = false; n->func_variadic = false; n->over = NULL; n->location = location; return n; } /* * makeGroupingSet * */ GroupingSet * makeGroupingSet(GroupingSetKind kind, List *content, int location) { GroupingSet *n = makeNode(GroupingSet); n->kind = kind; n->content = content; n->location = location; return n; } ShadowGameStudio/Project-Unknown #include "StdAfx.h" #include "AIComponent.h" #include #include "Player.h" static void RegisterAIComponent(Schematyc::IEnvRegistrar& registrar) { Schematyc::CEnvRegistrationScope scope = registrar.Scope(IEntity::GetEntityScopeGUID()); { Schematyc::CEnvRegistrationScope componentScope = scope.Register(SCHEMATYC_MAKE_ENV_COMPONENT(CAIComponent)); // Functions { } } } CRY_STATIC_AUTO_REGISTER_FUNCTION(&RegisterAIComponent) void CAIComponent::Initialize() { m_pAIController = m_pEntity->GetComponent(); m_pAnimationComponent = m_pEntity->GetComponent(); m_pAnimationComponent->LoadFromDisk(); m_idleFragmentId = m_pAnimationComponent->GetFragmentId("Idle"); m_walkFragmentId = m_pAnimationComponent->GetFragmentId("Walk"); m_rotateTagId = m_pAnimationComponent->GetTagId("Rotate"); //if (m_pAnimationComponent && m_pAIController) { // m_pAnimationComponent->ResetCharacter(); // m_pAIController->Physicalize(); //} } uint64 CAIComponent::GetEventMask() const { return ENTITY_EVENT_BIT(ENTITY_EVENT_TIMER) | ENTITY_EVENT_BIT(ENTITY_EVENT_UPDATE) | ENTITY_EVENT_BIT(ENTITY_EVENT_START_GAME); } void CAIComponent::ProcessEvent(const SEntityEvent & event) { switch (event.event) { case ENTITY_EVENT_TIMER: if (event.nParam[0] == Timer_Speed) { //Generates random moving speed srand((unsigned)time(NULL)); int speed = rand() % 300 + 100; m_fMoveSpeed = (float)speed; m_bTimerSet = false; } break; case ENTITY_EVENT_START_GAME: m_bGameStarted = true; break; case ENTITY_EVENT_UPDATE: SEntityUpdateContext *pCtx = (SEntityUpdateContext*)event.nParam[0]; UpdateMode(pCtx->fFrameTime); UpdateMovementRequest(pCtx->fFrameTime); UpdateAnimation(pCtx->fFrameTime); UpdateVicinity(pCtx->fFrameTime); UpdateLookOrientation(pCtx->fFrameTime); break; } } void CAIComponent::ReflectType(Schematyc::CTypeDesc& desc) { desc.SetGUID("{8E53C807-64C3-4DA0-9F1F-C0E0885D5EF4}"_cry_guid); desc.SetEditorCategory("AI"); desc.SetLabel("AI Component"); desc.SetDescription("Handels all the basic AI functionality"); desc.SetComponentFlags({ IEntityComponent::EFlags::Transform, IEntityComponent::EFlags::Socket, IEntityComponent::EFlags::Attach }); }10-100 #include "types.h" /* Generated from dpostproc .section .ctors, "wa" # 0x80472F00 - 0x804732C0 .4byte __sinit_PSMainSide_Sound_cpp .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_8049DC30 lbl_8049DC30: .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .global smACosPrm__Q23PSM7SeSound smACosPrm__Q23PSM7SeSound: .4byte 0x40490FD8 .4byte 0x403C3D92 .4byte 0x4036E62E .4byte 0x4032C782 .4byte 0x402F49C3 .4byte 0x402C323C .4byte 0x402962D8 .4byte 0x4026C9C9 .4byte 0x40245B68 .4byte 0x40220FAE .4byte 0x401FE0BD .4byte 0x401DCA21 .4byte 0x401BC871 .4byte 0x4019D8F5 .4byte 0x4017F96E .4byte 0x4016280B .4byte 0x40146345 .4byte 0x4012A9D2 .4byte 0x4010FA98 .4byte 0x400F549B .4byte 0x400DB70F .4byte 0x400C212D .4byte 0x400A9258 .4byte 0x400909F6 .4byte 0x40078787 .4byte 0x40060A91 .4byte 0x400492A7 .4byte 0x40031F64 .4byte 0x4001B075 .4byte 0x4000457C .4byte 0x3FFDBC6F .4byte 0x3FFAF4B6 .4byte 0x3FF83340 .4byte 0x3FF5779F .4byte 0x3FF2C15D .4byte 0x3FF01006 .4byte 0x3FED633D .4byte 0x3FEABA95 .4byte 0x3FE815B1 .4byte 0x3FE57447 .4byte 0x3FE2D5F1 .4byte 0x3FE03A6D .4byte 0x3FDDA15E .4byte 0x3FDB0A81 .4byte 0x3FD87582 .4byte 0x3FD5E226 .4byte 0x3FD3501A .4byte 0x3FD0BF1A .4byte 0x3FCE2EEC .4byte 0x3FCB9F45 .4byte 0x3FC90FD8 .4byte 0x3FC68073 .4byte 0x3FC3F0CC .4byte 0x3FC16095 .4byte 0x3FBECF9E .4byte 0x3FBC3D92 .4byte 0x3FB9AA37 .4byte 0x3FB71538 .4byte 0x3FB47E5A .4byte 0x3FB1E54B .4byte 0x3FAF49C7 .4byte 0x3FACAB71 .4byte 0x3FAA0A07 .4byte 0x3FA76523 .4byte 0x3FA4BC7B .4byte 0x3FA20FB2 .4byte 0x3F9F5E5B .4byte 0x3F9CA811 .4byte 0x3F99EC70 .4byte 0x3F972B02 .4byte 0x3F946349 .4byte 0x3F9194B8 .4byte 0x3F8EBECF .4byte 0x3F8BE0E7 .4byte 0x3F88FA6A .4byte 0x3F860A96 .4byte 0x3F8310A1 .4byte 0x3F800BC4 .4byte 0x3F79F612 .4byte 0x3F73BABA .4byte 0x3F6D6335 .4byte 0x3F66ED03 .4byte 0x3F605511 .4byte 0x3F599829 .4byte 0x3F52B25B .4byte 0x3F4B9F45 .4byte 0x3F4459B8 .4byte 0x3F3CDB9C .4byte 0x3F351D9B .4byte 0x3F2D16EC .4byte 0x3F24BC7B .4byte 0x3F1C00B9 .4byte 0x3F12D1BF .4byte 0x3F09184C .4byte 0x3EFD67FD .4byte 0x3EE6ED03 .4byte 0x3ECE30CB .4byte 0x3EB242D0 .4byte 0x3E914D72 .4byte 0x3E4D249E .4byte 0x00000000 .global lbl_8049DDD0 lbl_8049DDD0: .4byte 0x50534D61 .4byte 0x696E5369 .4byte 0x64655F53 .4byte 0x6F756E64 .4byte 0x2E637070 .4byte 0x00000000 .global lbl_8049DDE8 lbl_8049DDE8: .asciz "P2Assert" .skip 3 .4byte 0x5053436F .4byte 0x6D6D6F6E .4byte 0x2E680000 .4byte 0x50535379 .4byte 0x7374656D .4byte 0x49462E68 .4byte 0x00000000 .global lbl_8049DE10 lbl_8049DE10: .4byte 0x50534761 .4byte 0x6D652E68 .4byte 0x00000000 .4byte 0x50535363 .4byte 0x656E652E .4byte 0x68000000 .4byte 0x0A534520 .4byte 0x63616C6C .4byte 0x65642061 .4byte 0x7420696E .4byte 0x76616C69 .4byte 0x64207469 .4byte 0x6D6D696E .4byte 0x670A2825 .4byte 0x30387829 .4byte 0x0A000000 .4byte 0x67657420 .4byte 0x736F756E .4byte 0x64207363 .4byte 0x656E6520 .4byte 0x61740A69 .4byte 0x6E76616C .4byte 0x69642074 .4byte 0x696D6D69 .4byte 0x6E670A00 .4byte 0x00000000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global lbl_804EF9A8 lbl_804EF9A8: .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .global __vt__Q23PSM7SeSound __vt__Q23PSM7SeSound: .4byte 0 .4byte 0 .4byte setPortData__5JAISeFUcUs .4byte getPortData__5JAISeFUc .4byte start__8JAISoundFUl .4byte stop__5JAISeFUl .4byte release__8JAISoundFv .4byte setVolume__5JAISeFfUlUc .4byte getVolume__5JAISeFUc .4byte setPan__5JAISeFfUlUc .4byte getPan__5JAISeFUc .4byte setPitch__5JAISeFfUlUc .4byte getPitch__5JAISeFUc .4byte setFxmix__5JAISeFfUlUc .4byte getFxmix__5JAISeFUc .4byte setDolby__5JAISeFfUlUc .4byte getDolby__5JAISeFUc .4byte setTempoProportion__8JAISoundFfUl .4byte getTempoProportion__8JAISoundFv .4byte setVolumeU7__5JAISeFUcUlUc .4byte getVolumeU7__5JAISeFUc .4byte setPanU7__5JAISeFUcUlUc .4byte getPanU7__5JAISeFUc .4byte setFxmixU7__5JAISeFUcUlUc .4byte getFxmixU7__5JAISeFUc .4byte setDolbyU7__5JAISeFUcUlUc .4byte getDolbyU7__5JAISeFUc .4byte setDirectVolume__8JAISoundFfUl .4byte setDirectPan__8JAISoundFfUl .4byte setDirectPitch__8JAISoundFfUl .4byte setDirectFxmix__8JAISoundFfUl .4byte setDirectDolby__8JAISoundFfUl .4byte setDemoVolume__8JAISoundFfUl .4byte setDemoPan__8JAISoundFfUl .4byte setDemoPitch__8JAISoundFfUl .4byte setDemoFxmix__8JAISoundFfUl .4byte setDemoDolby__8JAISoundFfUl .4byte setDemoVolumeU7__8JAISoundFUcUl .4byte setDemoPanU7__8JAISoundFUcUl .4byte setDemoFxmixU7__8JAISoundFUcUl .4byte setDemoDolbyU7__8JAISoundFUcUl .4byte getFadeCounter__5JAISeFv .4byte setPrepareFlag__8JAISoundFUc .4byte checkReady__8JAISoundFv .4byte setDistanceParameterMoveTime__8JAISoundFUc .4byte setAdjustPriority__8JAISoundFs .4byte setPositionDopplarCommon__8JAISoundFUl .4byte setDistanceVolumeCommon__Q23PSM7SeSoundFfUc .4byte setDistancePanCommon__8JAISoundFv .4byte setDistanceDolbyCommon__8JAISoundFv .4byte initParameter__Q23PSM7SeSoundFPvPQ27JAInter5ActorUlUlUcPQ27JAInter9SoundInfo .4byte onGet__Q23PSM7SeSoundFv .4byte onRelease__Q23PSM7SeSoundFv .4byte setSeDistanceParameters__5JAISeFv .4byte setSeDistanceVolume__5JAISeFUc .4byte setSeDistancePan__Q23PSM7SeSoundFUc .4byte setSeDistancePitch__5JAISeFUc .4byte setSeDistanceFxmix__5JAISeFUc .4byte setSeDistanceFir__5JAISeFUc .4byte setSeDistanceDolby__Q23PSM7SeSoundFUc .4byte setSePositionDopplar__5JAISeFv .section .sdata, "wa" # 0x80514680 - 0x80514D80 .global cDol_0Rad__Q23PSM7SeSound cDol_0Rad__Q23PSM7SeSound: .float 1.0316 .global cDol_HalfRad__Q23PSM7SeSound cDol_HalfRad__Q23PSM7SeSound: .float 1.5708 .global cDol_FullRad__Q23PSM7SeSound cDol_FullRad__Q23PSM7SeSound: .float 2.11 .global cPan_MaxAmp__Q23PSM7SeSound cPan_MaxAmp__Q23PSM7SeSound: .float 0.98 .global cCenterRad__Q23PSM7SeSound cCenterRad__Q23PSM7SeSound: .float 1.57 .section .sbss # 0x80514D80 - 0x80516360 .global lbl_80516330 lbl_80516330: .skip 0x4 .global lbl_80516334 lbl_80516334: .skip 0x4 .global panRatio$3853 panRatio$3853: .skip 0x4 .global init$3854_1 init$3854_1: .skip 0x4 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_80520D90 lbl_80520D90: .float 1.0 .global lbl_80520D94 lbl_80520D94: .4byte 0x00000000 .global lbl_80520D98 lbl_80520D98: .4byte 0x42480000 .global lbl_80520D9C lbl_80520D9C: .4byte 0x41700000 .global lbl_80520DA0 lbl_80520DA0: .4byte 0x43300000 .4byte 0x00000000 .global lbl_80520DA8 lbl_80520DA8: .float 0.5 .global lbl_80520DAC lbl_80520DAC: .4byte 0x40490E56 */ namespace PSM { /* * --INFO-- * Address: 80470F0C * Size: 000078 */ void SeSound::makeSeSound() { /* stwu r1, -0x10(r1) mflr r0 li r3, 0x4a4 stw r0, 0x14(r1) stw r31, 0xc(r1) bl __nw__FUl or. r31, r3, r3 beq lbl_80470F6C bl __ct__5JAISeFv lis r3, __vt__Q23PSM7SeSound@ha lfs f1, lbl_80520D90@sda21(r2) addi r0, r3, __vt__Q23PSM7SeSound@l lfs f0, lbl_80520D94@sda21(r2) stw r0, 0x10(r31) li r0, 0 stfs f1, 0x484(r31) stfs f0, 0x488(r31) stfs f0, 0x48c(r31) stfs f0, 0x490(r31) stfs f0, 0x494(r31) stb r0, 0x498(r31) stb r0, 0x499(r31) stb r0, 0x49c(r31) stfs f1, 0x4a0(r31) lbl_80470F6C: lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 80470F84 * Size: 000004 */ void SeSound::onGet() { } /* * --INFO-- * Address: 80470F88 * Size: 0000A4 */ void SeSound::onRelease() { /* stwu r1, -0x10(r1) mflr r0 lis r4, lbl_8049DC30@ha stw r0, 0x14(r1) stw r31, 0xc(r1) addi r31, r4, lbl_8049DC30@l stw r30, 8(r1) lbz r0, 0x1a(r3) cmplwi r0, 0 beq lbl_80471014 lwz r0, 0x38(r3) cmplwi r0, 0 beq lbl_80471014 mr r30, r0 bne lbl_80470FD8 addi r3, r31, 0x1a0 addi r5, r31, 0x1b8 li r4, 0xb8 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80470FD8: mr r3, r30 bl getPlayingHandleNum__Q23PSM8CreatureFv clrlwi. r0, r3, 0x18 bne lbl_80471014 lwz r0, "sInstance__Q28PSSystem28SingletonBase"@sda21(r13) cmplwi r0, 0 bne lbl_80471008 addi r3, r31, 0x1c4 addi r5, r31, 0x1b8 li r4, 0x89 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471008: lwz r3, "sInstance__Q28PSSystem28SingletonBase"@sda21(r13) mr r4, r30 bl remove__10JSUPtrListFP10JSUPtrLink lbl_80471014: lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8047102C * Size: 000154 */ void SeSound::initParameter(void*, JAInter::Actor*, unsigned long, unsigned long, unsigned char, JAInter::SoundInfo*) { /* .loc_0x0: stwu r1, -0x20(r1) mflr r0 lis r10, 0x804A stw r0, 0x24(r1) stw r31, 0x1C(r1) subi r31, r10, 0x23D0 stw r30, 0x18(r1) stw r29, 0x14(r1) mr r29, r9 stw r28, 0x10(r1) mr r28, r3 bl -0x3BBA44 li r0, 0 stb r0, 0x498(r28) lbz r0, 0x1A(r28) cmplwi r0, 0 beq- .loc_0xA8 lwz r0, 0x38(r28) cmplwi r0, 0 beq- .loc_0xA8 mr r30, r0 bne- .loc_0x6C addi r3, r31, 0x1A0 addi r5, r31, 0x1B8 li r4, 0xD0 crclr 6, 0x6 bl -0x446A54 .loc_0x6C: mr r3, r30 bl -0x13E48 rlwinm. r0,r3,0,24,31 bne- .loc_0xA8 lwz r0, -0x6E44(r13) cmplwi r0, 0 bne- .loc_0x9C addi r3, r31, 0x1C4 addi r5, r31, 0x1B8 li r4, 0x89 crclr 6, 0x6 bl -0x446A84 .loc_0x9C: lwz r3, -0x6E44(r13) mr r4, r30 bl -0x44A7EC .loc_0xA8: cmplwi r29, 0 bne- .loc_0xC4 addi r3, r31, 0x1A0 addi r5, r31, 0x1B8 li r4, 0xD7 crclr 6, 0x6 bl -0x446AAC .loc_0xC4: lwz r0, 0x0(r29) rlwinm. r30,r0,4,28,31 beq- .loc_0x12C bl -0x3B6C08 lis r0, 0x4330 stw r30, 0xC(r1) lfd f3, 0x2A40(r2) stw r0, 0x8(r1) lfs f0, 0x2A3C(r2) lfd f2, 0x8(r1) lfs f4, 0x2A34(r2) fsubs f2, f2, f3 fdivs f0, f2, f0 fmuls f0, f0, f1 stfs f0, 0x4A0(r28) lfs f0, 0x4A0(r28) fcmpo cr0, f0, f4 bge- .loc_0x110 b .loc_0x124 .loc_0x110: lfs f4, 0x2A30(r2) fcmpo cr0, f0, f4 ble- .loc_0x120 b .loc_0x124 .loc_0x120: fmr f4, f0 .loc_0x124: stfs f4, 0x4A0(r28) b .loc_0x134 .loc_0x12C: lfs f0, 0x2A34(r2) stfs f0, 0x4A0(r28) .loc_0x134: lwz r0, 0x24(r1) lwz r31, 0x1C(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 80471180 * Size: 0002D8 */ void SeSound::setDistanceVolumeCommon(float, unsigned char) { /* stwu r1, -0x40(r1) mflr r0 stw r0, 0x44(r1) stfd f31, 0x30(r1) psq_st f31, 56(r1), 0, qr0 stfd f30, 0x20(r1) psq_st f30, 40(r1), 0, qr0 stw r31, 0x1c(r1) stw r30, 0x18(r1) stw r29, 0x14(r1) lwz r12, 0x10(r3) lis r5, lbl_8049DC30@ha mr r29, r4 mr r31, r3 lwz r12, 0x34(r12) addi r30, r5, lbl_8049DC30@l lfs f1, cSeFxMix__Q23PSM11CreaturePrm@sda21(r2) li r4, 0 li r5, 1 mtctr r12 bctrl lwz r0, 0x20(r31) lwz r3, 0x34(r31) rlwinm. r4, r0, 2, 0x1e, 0x1f lfs f31, 0x18(r3) rlwinm r3, r0, 0x14, 0x1c, 0x1f bne lbl_804711F0 b lbl_80471244 lbl_804711F0: cmplwi r4, 2 bne lbl_80471210 addi r3, r30, 0x1d0 addi r5, r30, 0x1b8 li r4, 0x1f crclr 6 bl panic_f__12JUTExceptionFPCciPCce b lbl_8047122C lbl_80471210: cmplwi r4, 3 bne lbl_8047122C addi r3, r30, 0x1d0 addi r5, r30, 0x1b8 li r4, 0x23 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8047122C: addi r3, r30, 0x1d0 addi r5, r30, 0x1b8 li r4, 0x25 crclr 6 bl panic_f__12JUTExceptionFPCciPCce li r3, 0 lbl_80471244: lbz r0, 0x498(r31) clrlwi r4, r3, 0x18 cmplwi r0, 1 bne lbl_80471264 fmr f1, f31 mr r3, r31 bl calcVolumeSpecialized__Q23PSM7SeSoundFf b lbl_80471270 lbl_80471264: fmr f1, f31 mr r3, r29 bl calcVolume__Q23PSM7SeSoundFfUcUc lbl_80471270: lfs f0, 0x4a0(r31) lbz r0, 0x1a(r31) fsubs f30, f1, f0 cmplwi r0, 0 beq lbl_80471290 lwz r0, 0x38(r31) cmplwi r0, 0 beq lbl_80471408 lbl_80471290: lwz r0, spSceneMgr__8PSSystem@sda21(r13) cmplwi r0, 0 bne lbl_804712B0 addi r3, r30, 0x1e0 addi r5, r30, 0x1b8 li r4, 0x1d3 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804712B0: lwz r29, spSceneMgr__8PSSystem@sda21(r13) cmplwi r29, 0 bne lbl_804712D0 addi r3, r30, 0x1e0 addi r5, r30, 0x1b8 li r4, 0x1dc crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804712D0: lwz r0, 8(r29) cmplwi r0, 0 bne lbl_804712F0 addi r3, r30, 0x1ec addi r5, r30, 0x1b8 li r4, 0xa1 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804712F0: lwz r29, 8(r29) cmplwi r29, 0 bne lbl_80471310 addi r3, r30, 0x1a0 addi r5, r30, 0x1b8 li r4, 0x105 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471310: mr r3, r29 lbz r4, 0x49c(r31) lwz r12, 0(r29) lwz r12, 0x28(r12) mtctr r12 bctrl fmr f31, f1 lfs f0, lbl_80520D94@sda21(r2) fcmpu cr0, f0, f31 bne lbl_80471350 lwz r6, 0x20(r31) addi r3, r30, 0x1a0 addi r5, r30, 0x1f8 li r4, 0x10d crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471350: lwz r0, spSceneMgr__8PSSystem@sda21(r13) fmuls f30, f30, f31 cmplwi r0, 0 bne lbl_80471374 addi r3, r30, 0x1e0 addi r5, r30, 0x1b8 li r4, 0x1d3 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471374: lwz r29, spSceneMgr__8PSSystem@sda21(r13) cmplwi r29, 0 bne lbl_80471394 addi r3, r30, 0x1e0 addi r5, r30, 0x1b8 li r4, 0x1dc crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471394: lwz r0, 4(r29) cmplwi r0, 0 bne lbl_804713B4 addi r3, r30, 0x1ec addi r5, r30, 0x1b8 li r4, 0xcf crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804713B4: lwz r3, 4(r29) lwz r29, 4(r3) cmplwi r29, 0 bne lbl_804713D8 addi r3, r30, 0x1ec addi r5, r30, 0x220 li r4, 0xd1 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804713D8: mr r3, r29 lwz r12, 0(r29) lwz r12, 0x30(r12) mtctr r12 bctrl mr r3, r31 li r4, 0 lwz r12, 0x10(r31) li r5, 2 lwz r12, 0x34(r12) mtctr r12 bctrl lbl_80471408: lfs f1, lbl_80520D94@sda21(r2) fcmpo cr0, f30, f1 bge lbl_80471418 b lbl_8047142C lbl_80471418: lfs f1, lbl_80520D90@sda21(r2) fcmpo cr0, f30, f1 ble lbl_80471428 b lbl_8047142C lbl_80471428: fmr f1, f30 lbl_8047142C: psq_l f31, 56(r1), 0, qr0 lfd f31, 0x30(r1) psq_l f30, 40(r1), 0, qr0 lfd f30, 0x20(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r0, 0x44(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 80471458 * Size: 000044 */ void SeSound::specializePerspCalc(const PSGame::SoundTable::SePerspInfo&) { /* lfs f0, 0(r4) li r0, 1 lfs f1, 4(r4) stfs f0, 0x484(r3) lfs f0, 8(r4) stfs f1, 0x488(r3) lfs f1, 0xc(r4) stfs f0, 0x48c(r3) lfs f0, 0x10(r4) stfs f1, 0x490(r3) lbz r5, 0x14(r4) stfs f0, 0x494(r3) lbz r4, 0x15(r4) stb r5, 0x498(r3) stb r4, 0x499(r3) stb r0, 0x498(r3) blr */ } /* * --INFO-- * Address: 8047149C * Size: 00006C */ void SeSound::calcVolumeSpecialized(float) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stfd f31, 0x18(r1) fmr f31, f1 stw r31, 0x14(r1) mr r31, r3 lbz r0, 0x498(r3) cmplwi r0, 1 beq lbl_804714E0 lis r3, lbl_8049DDD0@ha lis r5, lbl_8049DDE8@ha addi r3, r3, lbl_8049DDD0@l li r4, 0x126 addi r5, r5, lbl_8049DDE8@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_804714E0: fmr f1, f31 addi r3, r31, 0x484 li r4, 0 bl getDistVol__Q36PSGame10SoundTable11SePerspInfoFfUc lwz r0, 0x24(r1) lfd f31, 0x18(r1) lwz r31, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 80471508 * Size: 00008C */ void SeSound::calcVolume(float, unsigned char, unsigned char) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stfd f31, 0x18(r1) fmr f31, f1 stw r31, 0x14(r1) stw r30, 0x10(r1) rlwinm r30, r4, 2, 0x16, 0x1d stw r29, 0xc(r1) mr r29, r3 lwz r31, "sInstance__Q28PSSystem49SingletonBase"@sda21(r13) add r3, r31, r30 lwz r0, 4(r3) cmplwi r0, 0 bne lbl_80471560 lis r3, lbl_8049DE10@ha lis r5, lbl_8049DDE8@ha addi r3, r3, lbl_8049DE10@l li r4, 0x5d addi r5, r5, lbl_8049DDE8@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471560: add r3, r31, r30 fmr f1, f31 lwz r3, 4(r3) mr r4, r29 bl getDistVol__Q36PSGame10SoundTable11SePerspInfoFfUc lwz r0, 0x24(r1) lfd f31, 0x18(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) lwz r29, 0xc(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 80471594 * Size: 0000B8 */ void SeSound::setSeDistancePan(unsigned char) { /* stwu r1, -0x20(r1) mflr r0 lfs f1, lbl_80520DA8@sda21(r2) stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) mr r30, r4 stw r29, 0x14(r1) mr r29, r3 lbz r0, 0x1a(r3) cmplwi r0, 0 bne lbl_804715D4 lwz r3, 0x34(r29) lfs f1, 0x18(r3) bl calcPan__Q23PSM7SeSoundFRC3Vecf b lbl_8047161C lbl_804715D4: lwz r0, 0x38(r29) cmplwi r0, 0 beq lbl_8047161C mr r31, r0 bne lbl_80471604 lis r3, lbl_8049DDD0@ha lis r5, lbl_8049DDE8@ha addi r3, r3, lbl_8049DDD0@l li r4, 0x151 addi r5, r5, lbl_8049DDE8@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80471604: mr r3, r31 lwz r12, 0x28(r31) lwz r12, 0x24(r12) mtctr r12 bctrl lfs f1, 0x38(r3) lbl_8047161C: mr r3, r29 clrlwi r5, r30, 0x18 li r4, 4 li r6, 0 bl setSeInterPan__5JAISeFUcfUlUc lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 8047164C * Size: 0000C8 */ void SeSound::calcPan(const Vec&, float) { /* lfs f0, lbl_80520D94@sda21(r2) stwu r1, -0x10(r1) fcmpo cr0, f1, f0 cror 2, 0, 2 bne lbl_80471668 lfs f2, cCenterRad__Q23PSM7SeSound@sda21(r13) b lbl_804716CC lbl_80471668: lfs f0, 0(r3) lfs f2, lbl_80520D90@sda21(r2) fneg f0, f0 lfs f3, lbl_80520D98@sda21(r2) fdivs f0, f0, f1 fadds f0, f2, f0 fmuls f0, f3, f0 fctiwz f0, f0 stfd f0, 8(r1) lwz r0, 0xc(r1) cmpwi r0, 0 bge lbl_804716A4 lis r3, smACosPrm__Q23PSM7SeSound@ha lfs f2, smACosPrm__Q23PSM7SeSound@l(r3) b lbl_804716CC lbl_804716A4: cmpwi r0, 0x65 blt lbl_804716BC lis r3, smACosPrm__Q23PSM7SeSound@ha addi r3, r3, smACosPrm__Q23PSM7SeSound@l lfs f2, 0x190(r3) b lbl_804716CC lbl_804716BC: lis r3, smACosPrm__Q23PSM7SeSound@ha slwi r0, r0, 2 addi r3, r3, smACosPrm__Q23PSM7SeSound@l lfsx f2, r3, r0 lbl_804716CC: lbz r0, init$3854_1@sda21(r13) extsb. r0, r0 bne lbl_804716F0 lfs f1, cPan_MaxAmp__Q23PSM7SeSound@sda21(r13) li r0, 1 lfs f0, lbl_80520DAC@sda21(r2) stb r0, init$3854_1@sda21(r13) fdivs f0, f1, f0 stfs f0, panRatio$3853@sda21(r13) lbl_804716F0: lfs f0, panRatio$3853@sda21(r13) lfs f1, lbl_80520D90@sda21(r2) fmuls f0, f0, f2 fcmpo cr0, f0, f1 ble lbl_80471708 b lbl_8047170C lbl_80471708: fmr f1, f0 lbl_8047170C: addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 80471714 * Size: 000088 */ void SeSound::setSeDistanceDolby(unsigned char) { /* stwu r1, -0x10(r1) mflr r0 lfs f1, lbl_80520D94@sda21(r2) stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) mr r30, r3 lbz r0, 0x1a(r3) cmplwi r0, 0 bne lbl_80471750 lwz r3, 0x34(r30) lfs f1, 0x18(r3) bl calcDolby__Q23PSM7SeSoundFRC3Vecf b lbl_80471770 lbl_80471750: lwz r3, 0x38(r30) cmplwi r3, 0 beq lbl_80471770 lwz r12, 0x28(r3) lwz r12, 0x24(r12) mtctr r12 bctrl lfs f1, 0x3c(r3) lbl_80471770: mr r3, r30 clrlwi r5, r31, 0x18 li r4, 4 li r6, 0 bl setSeInterDolby__5JAISeFUcfUlUc lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8047179C * Size: 00010C */ void SeSound::calcDolby(const Vec&, float) { /* lfs f0, lbl_80520D94@sda21(r2) stwu r1, -0x10(r1) fcmpo cr0, f1, f0 cror 2, 0, 2 bne lbl_804717B8 fmr f1, f0 b lbl_804718A0 lbl_804717B8: lfs f0, 8(r3) lfs f2, lbl_80520D90@sda21(r2) fneg f0, f0 lfs f3, lbl_80520D98@sda21(r2) fdivs f0, f0, f1 fadds f0, f2, f0 fmuls f0, f3, f0 fctiwz f0, f0 stfd f0, 8(r1) lwz r0, 0xc(r1) cmpwi r0, 0 bge lbl_804717F4 lis r3, smACosPrm__Q23PSM7SeSound@ha lfs f0, smACosPrm__Q23PSM7SeSound@l(r3) b lbl_8047181C lbl_804717F4: cmpwi r0, 0x65 blt lbl_8047180C lis r3, smACosPrm__Q23PSM7SeSound@ha addi r3, r3, smACosPrm__Q23PSM7SeSound@l lfs f0, 0x190(r3) b lbl_8047181C lbl_8047180C: lis r3, smACosPrm__Q23PSM7SeSound@ha slwi r0, r0, 2 addi r3, r3, smACosPrm__Q23PSM7SeSound@l lfsx f0, r3, r0 lbl_8047181C: lfs f3, cDol_0Rad__Q23PSM7SeSound@sda21(r13) fcmpo cr0, f0, f3 bge lbl_80471830 lfs f0, lbl_80520D94@sda21(r2) b lbl_8047187C lbl_80471830: lfs f4, cDol_HalfRad__Q23PSM7SeSound@sda21(r13) fcmpo cr0, f0, f4 bge lbl_80471854 fsubs f1, f4, f3 lfs f2, lbl_80520DA8@sda21(r2) fsubs f0, f0, f3 fdivs f1, f2, f1 fmuls f0, f1, f0 b lbl_8047187C lbl_80471854: lfs f1, cDol_FullRad__Q23PSM7SeSound@sda21(r13) fcmpo cr0, f0, f1 bge lbl_80471878 fsubs f1, f1, f4 lfs f2, lbl_80520DA8@sda21(r2) fsubs f0, f0, f4 fdivs f1, f2, f1 fmadds f0, f1, f0, f2 b lbl_8047187C lbl_80471878: lfs f0, lbl_80520D90@sda21(r2) lbl_8047187C: lfs f1, lbl_80520D90@sda21(r2) fcmpo cr0, f0, f1 ble lbl_8047188C b lbl_804718A0 lbl_8047188C: lfs f1, lbl_80520D94@sda21(r2) fcmpo cr0, f0, f1 bge lbl_8047189C b lbl_804718A0 lbl_8047189C: fmr f1, f0 lbl_804718A0: addi r1, r1, 0x10 blr */ } } // namespace PSM /* * --INFO-- * Address: 804718A8 * Size: 000028 */ void __sinit_PSMainSide_Sound_cpp(void) { /* lis r4, __float_nan@ha li r0, -1 lfs f0, __float_nan@l(r4) lis r3, lbl_804EF9A8@ha stw r0, lbl_80516330@sda21(r13) stfsu f0, lbl_804EF9A8@l(r3) stfs f0, lbl_80516334@sda21(r13) stfs f0, 4(r3) stfs f0, 8(r3) blr */ } // // Copyright (c) .NET Foundation and Contributors // See LICENSE file in the project root for full license information. // #include "sys_dev_i2c_native_target.h" static const char *TAG = "I2C"; typedef Library_sys_dev_i2c_native_System_Device_I2c_I2cConnectionSettings I2cConnectionSettings; typedef Library_sys_dev_i2c_native_System_Device_I2c_I2cTransferResult I2cTransferResult; typedef Library_corlib_native_System_SpanByte SpanByte; static char Esp_I2C_Initialised_Flag[I2C_NUM_MAX] = {0, 0}; // need to declare these as external // TODO move them here after Windows.Devices.I2c is removed extern void Esp32_I2c_UnitializeAll(); extern void SetConfig(i2c_port_t bus, CLR_RT_HeapBlock *config); HRESULT Library_sys_dev_i2c_native_System_Device_I2c_I2cDevice::NativeInit___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pConfig; // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // get a pointer to the managed spi connectionSettings object instance pConfig = pThis[FIELD___connectionSettings].Dereference(); // get bus index // subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)(pConfig[I2cConnectionSettings::FIELD___busId].NumericByRef().s4 - 1); if (bus != I2C_NUM_0 && bus != I2C_NUM_1) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Set the Bus parameters SetConfig(bus, pConfig); // If this is first device on Bus then init driver if (Esp_I2C_Initialised_Flag[bus] == 0) { esp_err_t res = i2c_driver_install(bus, I2C_MODE_MASTER, 0, 0, 0); if (res != ESP_OK) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Ensure driver gets unitialized during soft reboot HAL_AddSoftRebootHandler(Esp32_I2c_UnitializeAll); Esp_I2C_Initialised_Flag[bus]++; } } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_i2c_native_System_Device_I2c_I2cDevice::NativeDispose___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pConfig; // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // get a pointer to the managed spi connectionSettings object instance pConfig = pThis[FIELD___connectionSettings].Dereference(); // get bus index // subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)(pConfig[I2cConnectionSettings::FIELD___busId].NumericByRef().s4 - 1); Esp_I2C_Initialised_Flag[bus]--; if (Esp_I2C_Initialised_Flag[bus] <= 0) { i2c_driver_delete(bus); Esp_I2C_Initialised_Flag[bus] = 0; } } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_i2c_native_System_Device_I2c_I2cDevice:: NativeTransmit___SystemDeviceI2cI2cTransferResult__SystemSpanByte__SystemSpanByte(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { unsigned char *writeData = NULL; unsigned char *readData = NULL; int writeOffset = 0; int writeSize = 0; int readOffset = 0; int readSize = 0; esp_err_t i2cStatus; CLR_RT_HeapBlock *result; CLR_RT_HeapBlock *writeSpanByte; CLR_RT_HeapBlock *readSpanByte; CLR_RT_HeapBlock_Array *writeBuffer = NULL; CLR_RT_HeapBlock_Array *readBuffer = NULL; // create the return object (I2cTransferResult) CLR_RT_HeapBlock &top = stack.PushValueAndClear(); // get a pointer to the managed object instance and check that it's not NULL CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // get a pointer to the managed spi connectionSettings object instance CLR_RT_HeapBlock *pConfig = pThis[FIELD___connectionSettings].Dereference(); // get bus index // subtract 1 to get ESP32 bus number i2c_port_t bus = (i2c_port_t)(pConfig[I2cConnectionSettings::FIELD___busId].NumericByRef().s4 - 1); int slaveAddress = pConfig[I2cConnectionSettings::FIELD___deviceAddress].NumericByRef().s4; // dereference the write and read SpanByte from the arguments writeSpanByte = stack.Arg1().Dereference(); if (writeSpanByte != NULL) { writeBuffer = writeSpanByte[SpanByte::FIELD___array].DereferenceArray(); if (writeBuffer != NULL) { // Get the write offset, only the elements defined by the span must be written, not the whole array writeOffset = writeSpanByte[SpanByte::FIELD___start].NumericByRef().s4; // grab the pointer to the array by starting and the offset specified in the span writeData = writeBuffer->GetElement(writeOffset); // use the span length as write size, only the elements defined by the span must be written writeSize = writeSpanByte[SpanByte::FIELD___length].NumericByRef().s4; } } readSpanByte = stack.Arg2().Dereference(); if (readSpanByte != 0) { readBuffer = readSpanByte[SpanByte::FIELD___array].DereferenceArray(); if (readBuffer != NULL) { // Get the read offset, only the elements defined by the span must be read, not the whole array readOffset = readSpanByte[SpanByte::FIELD___start].NumericByRef().s4; // grab the pointer to the array by starting and the offset specified in the span readData = readBuffer->GetElement(readOffset); // use the span length as read size, only the elements defined by the span must be read readSize = readSpanByte[SpanByte::FIELD___length].NumericByRef().s4; } } i2c_cmd_handle_t cmd = i2c_cmd_link_create(); if (writeSize != 0) // Write { i2c_master_start(cmd); i2c_master_write_byte(cmd, (slaveAddress << 1) | I2C_MASTER_WRITE, 1); i2cStatus = i2c_master_write(cmd, &writeData[0], writeSize, true); if (i2cStatus != ESP_OK) ESP_LOGE(TAG, "i2c_master_write error:%d", i2cStatus); } if (readSize != 0) // Read { i2c_master_start(cmd); i2c_master_write_byte(cmd, (slaveAddress << 1) | I2C_MASTER_READ, 1); if (readSize > 1) { // Additional read bytes with ACK i2c_master_read(cmd, &readData[0], readSize - 1, I2C_MASTER_ACK); } // Last read byte with NACK i2c_master_read_byte(cmd, &readData[readSize - 1], I2C_MASTER_NACK); } i2c_master_stop(cmd); i2cStatus = i2c_master_cmd_begin(bus, cmd, 1000 / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); // create return object NANOCLR_CHECK_HRESULT( g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_I2cTransferResult)); result = top.Dereference(); FAULT_ON_NULL(result); if (i2cStatus != ESP_OK) { uint32_t transferResult = I2cTransferStatus_FullTransfer; // set the result field if (i2cStatus == ESP_FAIL) { transferResult = I2cTransferStatus_SlaveAddressNotAcknowledged; } else if (i2cStatus == ESP_ERR_TIMEOUT) { transferResult = I2cTransferStatus_ClockStretchTimeout; } else { transferResult = I2cTransferStatus_UnknownError; } result[I2cTransferResult::FIELD___status].SetInteger((CLR_UINT32)transferResult); // set the bytes transferred field result[I2cTransferResult::FIELD___bytesTransferred].SetInteger(0); } else { result[I2cTransferResult::FIELD___status].SetInteger((CLR_UINT32)I2cTransferStatus_FullTransfer); // set the bytes transferred field result[I2cTransferResult::FIELD___bytesTransferred].SetInteger((CLR_UINT32)(writeSize + readSize)); } } NANOCLR_NOCLEANUP(); } src/FusionEKF.cpp #include "FusionEKF.h" #include #include "Eigen/Dense" #include "tools.h" using Eigen::MatrixXd; using Eigen::VectorXd; using std::cout; using std::endl; using std::vector; /** * Constructor. */ FusionEKF::FusionEKF() { is_initialized_ = false; previous_timestamp_ = 0; // initializing matrices x = VectorXd(4); F = MatrixXd(4,4); P = MatrixXd(4,4); I = MatrixXd::Identity(2, 2); Q = MatrixXd(4,4); R_laser_ = MatrixXd(2, 2); R_radar_ = MatrixXd(3, 3); H_laser_ = MatrixXd(2, 4); //object state x << 0 , 0 , 0, 0; //State transition matrix F << 1 , 0, 1, 0, 0, 1, 0, 1, 0, 0, 1 , 0, 0 , 0, 0, 1; //state covariance matrix P << 1, 0, 0, 0, 0 , 1 ,0, 0, 0, 0 , 1000, 0, 0, 0, 0, 1000; /** * Set the process and measurement noises */ // process covariance matrix Q << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; //measurement covariance matrix - laser R_laser_ << 0.0225, 0, 0, 0.0225; //measurement covariance matrix - radar R_radar_ << 0.09, 0, 0, 0, 0.0009, 0, 0, 0, 0.09; //measurement matrix - laser H_laser_ << 1 , 0, 0, 0, 0 , 1 , 0 , 0; //Initialize enhanced kalman filter with the matrices used for lidar data ekf_.Init(x, P, F, H_laser_, R_laser_, Q); //set the acceleration noise components noise_ax = 9; noise_ay = 9; } /** * Destructor. */ FusionEKF::~FusionEKF() {} void FusionEKF::ProcessMeasurement(const MeasurementPackage &measurement_pack) { /** * Initialization */ if (!is_initialized_) { /** * - Initialize the state ekf_.x_ with the first measurement. */ // first measurement cout << "EKF: " << endl; ekf_.x_ = VectorXd(4); ekf_.x_ << 1, 1, 1, 1; if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { //Convert radar from polar to cartesian coordinates // and initialize state. ekf_.x_ << measurement_pack.raw_measurements_[0]*cos(measurement_pack.raw_measurements_[1]), measurement_pack.raw_measurements_[0]*sin(measurement_pack.raw_measurements_[1]), 0, 0; } else if (measurement_pack.sensor_type_ == MeasurementPackage::LASER) { //Initialize state. // set the state with the initial location and zero velocity ekf_.x_ << measurement_pack.raw_measurements_[0], measurement_pack.raw_measurements_[1], 0, 0; } previous_timestamp_ = measurement_pack.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; return; } /** * Prediction */ // compute the time elapsed between the current and previous measurements // dt - expressed in seconds float dt = (measurement_pack.timestamp_ - previous_timestamp_) / 1000000.0; previous_timestamp_ = measurement_pack.timestamp_; // 1. Modify the F matrix so that the time is integrated /** * Update the state transition matrix F according to the new elapsed time. * Time is measured in seconds. */ ekf_.F_(0,2) = dt; ekf_.F_(1,3) = dt; // 2. Set the process covariance matrix Q /** Update the process noise covariance matrix. * Use noise_ax = 9 and noise_ay = 9 for your Q matrix. */ ekf_.Q_ = MatrixXd(4, 4); ekf_.Q_ << (pow(dt,4)/4)*noise_ax, 0, (pow(dt,3)/2)*noise_ax, 0 , 0, (pow(dt,4)/4)*noise_ay, 0, (pow(dt,3)/2)*noise_ay, (pow(dt,3)/2)*noise_ax, 0, pow(dt,2)*noise_ax, 0 , 0, (pow(dt,3)/2)*noise_ay, 0, pow(dt,2)*noise_ay; ekf_.Predict(); /** * Update */ /** * - Use the sensor type to perform the update step. * - Update the state and covariance matrices. */ if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { /** * Radar updates */ //Define the measurement matrix Hj with the jacobian for radar data ekf_.H_ = tools.CalculateJacobian(ekf_.x_); //Define the measurement covariance matrix for radar data ekf_.R_ = R_radar_; //Call the enhanced kalman filter function to update the state given new radar measurements ekf_.UpdateEKF(measurement_pack.raw_measurements_); } else { /** * Laser updates */ //Define the measurement matrix H for laser data ekf_.H_ = H_laser_; //Define the measurement covariance matrix for laser data ekf_.R_ = R_laser_; //Call the kalman filter function to update the state given new laser measurements ekf_.Update(measurement_pack.raw_measurements_); } // print the output cout << "Type of sensor: " << measurement_pack.sensor_type_ << endl; cout << "x_ = " << ekf_.x_ << endl; cout << "P_ = " << ekf_.P_ << endl; } #include using namespace std; int main() { long long int arr[4] ,a=0; for (int i=0;i<4;i++) { cin>>arr[i]; } for(int i=0;i<3;i++){ for(int j=i+1;j<4;j++) { if(arr[i]==arr[j]) a++; } } if(a>3) cout<<3; else if(a==3) cout<<2; else cout <kyranet/drakhtar-telemetry // Copyright 2021 the Drakhtar authors. All rights reserved. MIT license. #include "Serialization/Json/JsonObject.h" void JsonObject::open() { stream_ << START_OBJECT; } void JsonObject::close() { if (addedFirstElement_) { stream_ << NEW_LINE << padding_.outter << END_OBJECT; } else { stream_ << END_OBJECT; } } void JsonObject::clear() noexcept { stream_.str(""); } std::string JsonObject::toString() const noexcept { return stream_.str(); } /*========================================================================= Program: ParaView Module: pqEventPlayer.h Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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. =========================================================================*/ // Qt includes #include // QtTesting includes #include "pqEventTranslator.h" #include "pqSpinBoxEventTranslator.h" #include "pqTestUtility.h" #include "pqTreeViewEventTranslator.h" #include "pqTest.h" // ---------------------------------------------------------------------------- class pqEventTranslatorTester : public QObject { Q_OBJECT private Q_SLOTS: void testDefaults(); void testAddWidgetEventTranslator(); void testAddWidgetEventTranslator_data(); void testRemoveWidgetEventTranslator(); void testRemoveWidgetEventTranslator_data(); void testGetWidgetEventTranslator(); void testAddDefaultWidgetEventTranslators(); void testAddDefaultWidgetEventTranslators_data(); }; // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testDefaults() { pqEventTranslator eventTranslator; QCOMPARE(eventTranslator.translators().count(), 0); } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testAddWidgetEventTranslator() { pqEventTranslator eventTranslator; QFETCH(QObject*, widget1); QFETCH(int, newCount1); QFETCH(QObject*, widget2); QFETCH(int, newCount2); // When we add the widgetEventPlayer into the eventPlayer, it is automaticaly // reparented to the eventPlayer. So its deletion would be automatic. eventTranslator.addWidgetEventTranslator( dynamic_cast(widget1)); QCOMPARE(eventTranslator.translators().count(), newCount1); eventTranslator.addWidgetEventTranslator( dynamic_cast(widget2)); QCOMPARE(eventTranslator.translators().count(), newCount2); } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testAddWidgetEventTranslator_data() { QTest::addColumn("widget1"); QTest::addColumn("newCount1"); QTest::addColumn("widget2"); QTest::addColumn("newCount2"); pqWidgetEventTranslator* nullWidget = NULL; QTest::newRow("empty_empty") << qobject_cast(nullWidget) << 0 << qobject_cast(nullWidget) << 0; QTest::newRow("empty_pqSpinBox") << qobject_cast(nullWidget) << 0 << qobject_cast(new pqSpinBoxEventTranslator()) << 1; QTest::newRow("pqSpinBox_pqSpinBox") << qobject_cast(new pqSpinBoxEventTranslator()) << 1 << qobject_cast(new pqSpinBoxEventTranslator()) << 1; QTest::newRow("pqSpinBox_pqTreeView") << qobject_cast(new pqSpinBoxEventTranslator()) << 1 << qobject_cast(new pqTreeViewEventTranslator()) << 2; } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testRemoveWidgetEventTranslator() { pqEventTranslator eventTranslator; QFETCH(QString, nameToRemove); QFETCH(bool, firstResult); QFETCH(bool, secondResult); QFETCH(int, newCount); QFETCH(bool, thirdResult); QCOMPARE(eventTranslator.removeWidgetEventTranslator(nameToRemove), firstResult); // When we add the widgetEventPlayer into the eventPlayer, it is automaticaly // reparented to the eventPlayer. So its deletion would be automatic. pqTreeViewEventTranslator* treeView = new pqTreeViewEventTranslator(); eventTranslator.addWidgetEventTranslator(treeView); QCOMPARE(eventTranslator.translators().count(), 1); QCOMPARE(eventTranslator.removeWidgetEventTranslator(nameToRemove), secondResult); QCOMPARE(eventTranslator.translators().count(), newCount); QCOMPARE(eventTranslator.removeWidgetEventTranslator(nameToRemove), thirdResult); } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testRemoveWidgetEventTranslator_data() { QTest::addColumn("nameToRemove"); QTest::addColumn("firstResult"); QTest::addColumn("secondResult"); QTest::addColumn("newCount"); QTest::addColumn("thirdResult"); QTest::newRow("empty") << "" << false << false << 1 << false; QTest::newRow("wrong") << "pqSpinBoxEventTranslator" << false << false << 1 << false; QTest::newRow("right") << "pqTreeViewEventTranslator" << false << true << 0 << false; } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testGetWidgetEventTranslator() { pqEventTranslator eventTranslator; pqSpinBoxEventTranslator* nullWidget = NULL; QCOMPARE(eventTranslator.getWidgetEventTranslator(0), nullWidget); QCOMPARE(eventTranslator.getWidgetEventTranslator("pqSpinBoxEventTranslator"), nullWidget); // When we add the widgetEventPlayer into the eventPlayer, it is automaticaly // reparented to the eventPlayer. So its deletion would be automatic. pqSpinBoxEventTranslator* spinBox = new pqSpinBoxEventTranslator(); eventTranslator.addWidgetEventTranslator(spinBox); QCOMPARE(eventTranslator.getWidgetEventTranslator(0), nullWidget); QCOMPARE(eventTranslator.getWidgetEventTranslator("pqTreeViewEventTranslator"), nullWidget); QCOMPARE(eventTranslator.getWidgetEventTranslator("pqSpinBoxEventTranslator"), spinBox); } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testAddDefaultWidgetEventTranslators() { pqEventTranslator eventTranslator; pqTestUtility testUtility; eventTranslator.addDefaultWidgetEventTranslators(&testUtility); QList translators = eventTranslator.translators(); QFETCH(int, index); QFETCH(QString, widgetEventTranslatorName); QCOMPARE(QString(translators.at(index)->metaObject()->className()), widgetEventTranslatorName); } // ---------------------------------------------------------------------------- void pqEventTranslatorTester::testAddDefaultWidgetEventTranslators_data() { QTest::addColumn("index"); QTest::addColumn("widgetEventTranslatorName"); QTest::newRow("0") << 0 << "pqNativeFileDialogEventTranslator"; QTest::newRow("1") << 1 << "pq3DViewEventTranslator"; QTest::newRow("2") << 2 << "pqListViewEventTranslator"; QTest::newRow("3") << 3 << "pqTableViewEventTranslator"; QTest::newRow("4") << 4 << "pqTreeViewEventTranslator"; QTest::newRow("5") << 5 << "pqTabBarEventTranslator"; QTest::newRow("6") << 6 << "pqSpinBoxEventTranslator"; QTest::newRow("7") << 7 << "pqMenuEventTranslator"; QTest::newRow("8") << 8 << "pqLineEditEventTranslator"; QTest::newRow("9") << 9 << "pqDoubleSpinBoxEventTranslator"; QTest::newRow("10") << 10 << "pqComboBoxEventTranslator"; QTest::newRow("11") << 11 << "pqAbstractSliderEventTranslator"; QTest::newRow("12") << 12 << "pqAbstractItemViewEventTranslator"; QTest::newRow("13") << 13 << "pqAbstractButtonEventTranslator"; QTest::newRow("14") << 14 << "pqBasicWidgetEventTranslator"; } // ---------------------------------------------------------------------------- CTK_TEST_MAIN(pqEventTranslatorTest) #include "moc_pqEventTranslatorTest.cpp" binji/variant-lite // Copyright 2016-2018 by // // https://github.com/martinmoene/variant-lite // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #ifndef NONSTD_VARIANT_LITE_HPP #define NONSTD_VARIANT_LITE_HPP #define variant_lite_MAJOR 1 #define variant_lite_MINOR 2 #define variant_lite_PATCH 2 #define variant_lite_VERSION variant_STRINGIFY(variant_lite_MAJOR) "." variant_STRINGIFY(variant_lite_MINOR) "." variant_STRINGIFY(variant_lite_PATCH) #define variant_STRINGIFY( x ) variant_STRINGIFY_( x ) #define variant_STRINGIFY_( x ) #x // variant-lite configuration: #define variant_VARIANT_DEFAULT 0 #define variant_VARIANT_NONSTD 1 #define variant_VARIANT_STD 2 #if !defined( variant_CONFIG_SELECT_VARIANT ) # define variant_CONFIG_SELECT_VARIANT ( variant_HAVE_STD_VARIANT ? variant_VARIANT_STD : variant_VARIANT_NONSTD ) #endif #ifndef variant_CONFIG_OMIT_VARIANT_SIZE_V_MACRO # define variant_CONFIG_OMIT_VARIANT_SIZE_V_MACRO 0 #endif #ifndef variant_CONFIG_OMIT_VARIANT_ALTERNATIVE_T_MACRO # define variant_CONFIG_OMIT_VARIANT_ALTERNATIVE_T_MACRO 0 #endif // Control presence of exception handling (try and auto discover): #ifndef variant_CONFIG_NO_EXCEPTIONS # if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND) # define variant_CONFIG_NO_EXCEPTIONS 0 # else # define variant_CONFIG_NO_EXCEPTIONS 1 # endif #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. #ifndef variant_CPLUSPLUS # if defined(_MSVC_LANG ) && !defined(__clang__) # define variant_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) # else # define variant_CPLUSPLUS __cplusplus # endif #endif #define variant_CPP98_OR_GREATER ( variant_CPLUSPLUS >= 199711L ) #define variant_CPP11_OR_GREATER ( variant_CPLUSPLUS >= 201103L ) #define variant_CPP11_OR_GREATER_ ( variant_CPLUSPLUS >= 201103L ) #define variant_CPP14_OR_GREATER ( variant_CPLUSPLUS >= 201402L ) #define variant_CPP17_OR_GREATER ( variant_CPLUSPLUS >= 201703L ) #define variant_CPP20_OR_GREATER ( variant_CPLUSPLUS >= 202000L ) // Use C++17 std::variant if available and requested: #if variant_CPP17_OR_GREATER && defined(__has_include ) # if __has_include( ) # define variant_HAVE_STD_VARIANT 1 # else # define variant_HAVE_STD_VARIANT 0 # endif #else # define variant_HAVE_STD_VARIANT 0 #endif #define variant_USES_STD_VARIANT ( (variant_CONFIG_SELECT_VARIANT == variant_VARIANT_STD) || ((variant_CONFIG_SELECT_VARIANT == variant_VARIANT_DEFAULT) && variant_HAVE_STD_VARIANT) ) // // in_place: code duplicated in any-lite, expected-lite, optional-lite, value-ptr-lite, variant-lite: // #ifndef nonstd_lite_HAVE_IN_PLACE_TYPES #define nonstd_lite_HAVE_IN_PLACE_TYPES 1 // C++17 std::in_place in : #if variant_CPP17_OR_GREATER #include namespace nonstd { using std::in_place; using std::in_place_type; using std::in_place_index; using std::in_place_t; using std::in_place_type_t; using std::in_place_index_t; #define nonstd_lite_in_place_t( T) std::in_place_t #define nonstd_lite_in_place_type_t( T) std::in_place_type_t #define nonstd_lite_in_place_index_t(K) std::in_place_index_t #define nonstd_lite_in_place( T) std::in_place_t{} #define nonstd_lite_in_place_type( T) std::in_place_type_t{} #define nonstd_lite_in_place_index(K) std::in_place_index_t{} } // namespace nonstd #else // variant_CPP17_OR_GREATER #include namespace nonstd { namespace detail { template< class T > struct in_place_type_tag {}; template< std::size_t K > struct in_place_index_tag {}; } // namespace detail struct in_place_t {}; template< class T > inline in_place_t in_place( detail::in_place_type_tag = detail::in_place_type_tag() ) { return in_place_t(); } template< std::size_t K > inline in_place_t in_place( detail::in_place_index_tag = detail::in_place_index_tag() ) { return in_place_t(); } template< class T > inline in_place_t in_place_type( detail::in_place_type_tag = detail::in_place_type_tag() ) { return in_place_t(); } template< std::size_t K > inline in_place_t in_place_index( detail::in_place_index_tag = detail::in_place_index_tag() ) { return in_place_t(); } // mimic templated typedef: #define nonstd_lite_in_place_t( T) nonstd::in_place_t(&)( nonstd::detail::in_place_type_tag ) #define nonstd_lite_in_place_type_t( T) nonstd::in_place_t(&)( nonstd::detail::in_place_type_tag ) #define nonstd_lite_in_place_index_t(K) nonstd::in_place_t(&)( nonstd::detail::in_place_index_tag ) #define nonstd_lite_in_place( T) nonstd::in_place_type #define nonstd_lite_in_place_type( T) nonstd::in_place_type #define nonstd_lite_in_place_index(K) nonstd::in_place_index } // namespace nonstd #endif // variant_CPP17_OR_GREATER #endif // nonstd_lite_HAVE_IN_PLACE_TYPES // // Use C++17 std::variant: // #if variant_USES_STD_VARIANT #include // std::hash<> #include #if ! variant_CONFIG_OMIT_VARIANT_SIZE_V_MACRO # define variant_size_V(T) nonstd::variant_size::value #endif #if ! variant_CONFIG_OMIT_VARIANT_ALTERNATIVE_T_MACRO # define variant_alternative_T(K,T) typename nonstd::variant_alternative::type #endif namespace nonstd { using std::variant; using std::monostate; using std::bad_variant_access; using std::variant_size; using std::variant_size_v; using std::variant_alternative; using std::variant_alternative_t; using std::hash; using std::visit; using std::holds_alternative; using std::get; using std::get_if; using std::operator==; using std::operator!=; using std::operator<; using std::operator<=; using std::operator>; using std::operator>=; using std::swap; constexpr auto variant_npos = std::variant_npos; } #else // variant_USES_STD_VARIANT #include #include #include #include #if variant_CONFIG_NO_EXCEPTIONS # include #else # include #endif // variant-lite type and visitor argument count configuration (script/generate_header.py): #define variant_CONFIG_MAX_TYPE_COUNT 16 #define variant_CONFIG_MAX_VISITOR_ARG_COUNT 5 // variant-lite alignment configuration: #ifndef variant_CONFIG_MAX_ALIGN_HACK # define variant_CONFIG_MAX_ALIGN_HACK 0 #endif #ifndef variant_CONFIG_ALIGN_AS // no default, used in #if defined() #endif #ifndef variant_CONFIG_ALIGN_AS_FALLBACK # define variant_CONFIG_ALIGN_AS_FALLBACK double #endif // half-open range [lo..hi): #define variant_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) // Compiler versions: // // MSVC++ 6.0 _MSC_VER == 1200 variant_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) // MSVC++ 7.0 _MSC_VER == 1300 variant_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) // MSVC++ 7.1 _MSC_VER == 1310 variant_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) // MSVC++ 8.0 _MSC_VER == 1400 variant_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) // MSVC++ 9.0 _MSC_VER == 1500 variant_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) // MSVC++ 10.0 _MSC_VER == 1600 variant_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) // MSVC++ 11.0 _MSC_VER == 1700 variant_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) // MSVC++ 12.0 _MSC_VER == 1800 variant_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) // MSVC++ 14.0 _MSC_VER == 1900 variant_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) // MSVC++ 14.1 _MSC_VER >= 1910 variant_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) // MSVC++ 14.2 _MSC_VER >= 1920 variant_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) #if defined(_MSC_VER ) && !defined(__clang__) # define variant_COMPILER_MSVC_VER (_MSC_VER ) # define variant_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) #else # define variant_COMPILER_MSVC_VER 0 # define variant_COMPILER_MSVC_VERSION 0 #endif #define variant_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) #if defined(__clang__) # define variant_COMPILER_CLANG_VERSION variant_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) #else # define variant_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) # define variant_COMPILER_GNUC_VERSION variant_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else # define variant_COMPILER_GNUC_VERSION 0 #endif #if variant_BETWEEN( variant_COMPILER_MSVC_VER, 1300, 1900 ) # pragma warning( push ) # pragma warning( disable: 4345 ) // initialization behavior changed #endif // Presence of language and library features: #define variant_HAVE( feature ) ( variant_HAVE_##feature ) #ifdef _HAS_CPP0X # define variant_HAS_CPP0X _HAS_CPP0X #else # define variant_HAS_CPP0X 0 #endif // Unless defined otherwise below, consider VC14 as C++11 for variant-lite: #if variant_COMPILER_MSVC_VER >= 1900 # undef variant_CPP11_OR_GREATER # define variant_CPP11_OR_GREATER 1 #endif #define variant_CPP11_90 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1500) #define variant_CPP11_100 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1600) #define variant_CPP11_110 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1700) #define variant_CPP11_120 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1800) #define variant_CPP11_140 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1900) #define variant_CPP11_141 (variant_CPP11_OR_GREATER_ || variant_COMPILER_MSVC_VER >= 1910) #define variant_CPP14_000 (variant_CPP14_OR_GREATER) #define variant_CPP17_000 (variant_CPP17_OR_GREATER) // Presence of C++11 language features: #define variant_HAVE_CONSTEXPR_11 variant_CPP11_140 #define variant_HAVE_INITIALIZER_LIST variant_CPP11_120 #define variant_HAVE_NOEXCEPT variant_CPP11_140 #define variant_HAVE_NULLPTR variant_CPP11_100 #define variant_HAVE_OVERRIDE variant_CPP11_140 // Presence of C++14 language features: #define variant_HAVE_CONSTEXPR_14 variant_CPP14_000 // Presence of C++17 language features: // no flag // Presence of C++ library features: #define variant_HAVE_CONDITIONAL variant_CPP11_120 #define variant_HAVE_REMOVE_CV variant_CPP11_120 #define variant_HAVE_STD_ADD_POINTER variant_CPP11_90 #define variant_HAVE_TYPE_TRAITS variant_CPP11_90 #define variant_HAVE_TR1_TYPE_TRAITS (!! variant_COMPILER_GNUC_VERSION ) #define variant_HAVE_TR1_ADD_POINTER (!! variant_COMPILER_GNUC_VERSION ) // C++ feature usage: #if variant_HAVE_CONSTEXPR_11 # define variant_constexpr constexpr #else # define variant_constexpr /*constexpr*/ #endif #if variant_HAVE_CONSTEXPR_14 # define variant_constexpr14 constexpr #else # define variant_constexpr14 /*constexpr*/ #endif #if variant_HAVE_NOEXCEPT # define variant_noexcept noexcept #else # define variant_noexcept /*noexcept*/ #endif #if variant_HAVE_NULLPTR # define variant_nullptr nullptr #else # define variant_nullptr NULL #endif #if variant_HAVE_OVERRIDE # define variant_override override #else # define variant_override /*override*/ #endif // additional includes: #if variant_CPP11_OR_GREATER # include // std::hash #endif #if variant_HAVE_INITIALIZER_LIST # include #endif #if variant_HAVE_TYPE_TRAITS # include #elif variant_HAVE_TR1_TYPE_TRAITS # include #endif // Method enabling #if variant_CPP11_OR_GREATER #define variant_REQUIRES_0(...) \ template< bool B = (__VA_ARGS__), typename std::enable_if::type = 0 > #define variant_REQUIRES_T(...) \ , typename = typename std::enable_if< (__VA_ARGS__), nonstd::variants::detail::enabler >::type #define variant_REQUIRES_R(R, ...) \ typename std::enable_if< (__VA_ARGS__), R>::type #define variant_REQUIRES_A(...) \ , typename std::enable_if< (__VA_ARGS__), void*>::type = nullptr #endif // // variant: // namespace nonstd { namespace variants { // C++11 emulation: namespace std11 { #if variant_HAVE_STD_ADD_POINTER using std::add_pointer; #elif variant_HAVE_TR1_ADD_POINTER using std::tr1::add_pointer; #else template< class T > struct remove_reference { typedef T type; }; template< class T > struct remove_reference { typedef T type; }; template< class T > struct add_pointer { typedef typename remove_reference::type * type; }; #endif // variant_HAVE_STD_ADD_POINTER #if variant_HAVE_REMOVE_CV using std::remove_cv; #else template< class T > struct remove_const { typedef T type; }; template< class T > struct remove_const { typedef T type; }; template< class T > struct remove_volatile { typedef T type; }; template< class T > struct remove_volatile { typedef T type; }; template< class T > struct remove_cv { typedef typename remove_volatile::type>::type type; }; #endif // variant_HAVE_REMOVE_CV #if variant_HAVE_CONDITIONAL using std::conditional; #else template< bool Cond, class Then, class Else > struct conditional; template< class Then, class Else > struct conditional< true , Then, Else > { typedef Then type; }; template< class Then, class Else > struct conditional< false, Then, Else > { typedef Else type; }; #endif // variant_HAVE_CONDITIONAL } // namespace std11 /// type traits C++17: namespace std17 { #if variant_CPP17_OR_GREATER using std::is_swappable; using std::is_nothrow_swappable; #elif variant_CPP11_OR_GREATER namespace detail { using std::swap; struct is_swappable { template< typename T, typename = decltype( swap( std::declval(), std::declval() ) ) > static std::true_type test( int ); template< typename > static std::false_type test(...); }; struct is_nothrow_swappable { // wrap noexcept(epr) in separate function as work-around for VC140 (VS2015): template< typename T > static constexpr bool test() { return noexcept( swap( std::declval(), std::declval() ) ); } template< typename T > static auto test( int ) -> std::integral_constant()>{} template< typename > static std::false_type test(...); }; } // namespace detail // is [nothow] swappable: template< typename T > struct is_swappable : decltype( detail::is_swappable::test(0) ){}; template< typename T > struct is_nothrow_swappable : decltype( detail::is_nothrow_swappable::test(0) ){}; #endif // variant_CPP17_OR_GREATER } // namespace std17 // detail: namespace detail { // for variant_REQUIRES_T(): /*enum*/ class enabler{}; // typelist: #define variant_TL1( T1 ) detail::typelist< T1, detail::nulltype > #define variant_TL2( T1, T2) detail::typelist< T1, variant_TL1( T2) > #define variant_TL3( T1, T2, T3) detail::typelist< T1, variant_TL2( T2, T3) > #define variant_TL4( T1, T2, T3, T4) detail::typelist< T1, variant_TL3( T2, T3, T4) > #define variant_TL5( T1, T2, T3, T4, T5) detail::typelist< T1, variant_TL4( T2, T3, T4, T5) > #define variant_TL6( T1, T2, T3, T4, T5, T6) detail::typelist< T1, variant_TL5( T2, T3, T4, T5, T6) > #define variant_TL7( T1, T2, T3, T4, T5, T6, T7) detail::typelist< T1, variant_TL6( T2, T3, T4, T5, T6, T7) > #define variant_TL8( T1, T2, T3, T4, T5, T6, T7, T8) detail::typelist< T1, variant_TL7( T2, T3, T4, T5, T6, T7, T8) > #define variant_TL9( T1, T2, T3, T4, T5, T6, T7, T8, T9) detail::typelist< T1, variant_TL8( T2, T3, T4, T5, T6, T7, T8, T9) > #define variant_TL10( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) detail::typelist< T1, variant_TL9( T2, T3, T4, T5, T6, T7, T8, T9, T10) > #define variant_TL11( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) detail::typelist< T1, variant_TL10( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) > #define variant_TL12( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) detail::typelist< T1, variant_TL11( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) > #define variant_TL13( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) detail::typelist< T1, variant_TL12( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) > #define variant_TL14( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) detail::typelist< T1, variant_TL13( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) > #define variant_TL15( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) detail::typelist< T1, variant_TL14( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) > #define variant_TL16( T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) detail::typelist< T1, variant_TL15( T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) > // variant parameter unused type tags: template< class T > struct TX : T { inline TX operator+ ( ) const { return TX(); } inline TX operator- ( ) const { return TX(); } inline TX operator! ( ) const { return TX(); } inline TX operator~ ( ) const { return TX(); } inline TX*operator& ( ) const { return variant_nullptr; } template< class U > inline TX operator* ( U const & ) const { return TX(); } template< class U > inline TX operator/ ( U const & ) const { return TX(); } template< class U > inline TX operator% ( U const & ) const { return TX(); } template< class U > inline TX operator+ ( U const & ) const { return TX(); } template< class U > inline TX operator- ( U const & ) const { return TX(); } template< class U > inline TX operator<<( U const & ) const { return TX(); } template< class U > inline TX operator>>( U const & ) const { return TX(); } inline bool operator==( T const & ) const { return false; } inline bool operator< ( T const & ) const { return false; } template< class U > inline TX operator& ( U const & ) const { return TX(); } template< class U > inline TX operator| ( U const & ) const { return TX(); } template< class U > inline TX operator^ ( U const & ) const { return TX(); } template< class U > inline TX operator&&( U const & ) const { return TX(); } template< class U > inline TX operator||( U const & ) const { return TX(); } }; struct S0{}; typedef TX T0; struct S1{}; typedef TX T1; struct S2{}; typedef TX T2; struct S3{}; typedef TX T3; struct S4{}; typedef TX T4; struct S5{}; typedef TX T5; struct S6{}; typedef TX T6; struct S7{}; typedef TX T7; struct S8{}; typedef TX T8; struct S9{}; typedef TX T9; struct S10{}; typedef TX T10; struct S11{}; typedef TX T11; struct S12{}; typedef TX T12; struct S13{}; typedef TX T13; struct S14{}; typedef TX T14; struct S15{}; typedef TX T15; struct nulltype{}; template< class Head, class Tail > struct typelist { typedef Head head; typedef Tail tail; }; // typelist max element size: template< class List > struct typelist_max; template<> struct typelist_max< nulltype > { enum V { value = 0 } ; typedef void type; }; template< class Head, class Tail > struct typelist_max< typelist > { private: enum TV { tail_value = size_t( typelist_max::value ) }; typedef typename typelist_max::type tail_type; public: enum V { value = (sizeof( Head ) > tail_value) ? sizeof( Head ) : std::size_t( tail_value ) } ; typedef typename std11::conditional< (sizeof( Head ) > tail_value), Head, tail_type>::type type; }; #if variant_CPP11_OR_GREATER // typelist max alignof element type: template< class List > struct typelist_max_alignof; template<> struct typelist_max_alignof< nulltype > { enum V { value = 0 } ; }; template< class Head, class Tail > struct typelist_max_alignof< typelist > { private: enum TV { tail_value = size_t( typelist_max_alignof::value ) }; public: enum V { value = (alignof( Head ) > tail_value) ? alignof( Head ) : std::size_t( tail_value ) }; }; #endif // typelist size (length): template< class List > struct typelist_size { enum V { value = 1 }; }; template<> struct typelist_size< T0 > { enum V { value = 0 }; }; template<> struct typelist_size< T1 > { enum V { value = 0 }; }; template<> struct typelist_size< T2 > { enum V { value = 0 }; }; template<> struct typelist_size< T3 > { enum V { value = 0 }; }; template<> struct typelist_size< T4 > { enum V { value = 0 }; }; template<> struct typelist_size< T5 > { enum V { value = 0 }; }; template<> struct typelist_size< T6 > { enum V { value = 0 }; }; template<> struct typelist_size< T7 > { enum V { value = 0 }; }; template<> struct typelist_size< T8 > { enum V { value = 0 }; }; template<> struct typelist_size< T9 > { enum V { value = 0 }; }; template<> struct typelist_size< T10 > { enum V { value = 0 }; }; template<> struct typelist_size< T11 > { enum V { value = 0 }; }; template<> struct typelist_size< T12 > { enum V { value = 0 }; }; template<> struct typelist_size< T13 > { enum V { value = 0 }; }; template<> struct typelist_size< T14 > { enum V { value = 0 }; }; template<> struct typelist_size< T15 > { enum V { value = 0 }; }; template<> struct typelist_size< nulltype > { enum V { value = 0 } ; }; template< class Head, class Tail > struct typelist_size< typelist > { enum V { value = typelist_size::value + typelist_size::value }; }; // typelist index of type: template< class List, class T > struct typelist_index_of; template< class T > struct typelist_index_of< nulltype, T > { enum V { value = -1 }; }; template< class Tail, class T > struct typelist_index_of< typelist, T > { enum V { value = 0 }; }; template< class Head, class Tail, class T > struct typelist_index_of< typelist, T > { private: enum TV { nextVal = typelist_index_of::value }; public: enum V { value = nextVal == -1 ? -1 : 1 + nextVal } ; }; // typelist type at index: template< class List, std::size_t i> struct typelist_type_at; template< class Head, class Tail > struct typelist_type_at< typelist, 0 > { typedef Head type; }; template< class Head, class Tail, std::size_t i > struct typelist_type_at< typelist, i > { typedef typename typelist_type_at::type type; }; #if variant_CONFIG_MAX_ALIGN_HACK // Max align, use most restricted type for alignment: #define variant_UNIQUE( name ) variant_UNIQUE2( name, __LINE__ ) #define variant_UNIQUE2( name, line ) variant_UNIQUE3( name, line ) #define variant_UNIQUE3( name, line ) name ## line #define variant_ALIGN_TYPE( type ) \ type variant_UNIQUE( _t ); struct_t< type > variant_UNIQUE( _st ) template< class T > struct struct_t { T _; }; union max_align_t { variant_ALIGN_TYPE( char ); variant_ALIGN_TYPE( short int ); variant_ALIGN_TYPE( int ); variant_ALIGN_TYPE( long int ); variant_ALIGN_TYPE( float ); variant_ALIGN_TYPE( double ); variant_ALIGN_TYPE( long double ); variant_ALIGN_TYPE( char * ); variant_ALIGN_TYPE( short int * ); variant_ALIGN_TYPE( int * ); variant_ALIGN_TYPE( long int * ); variant_ALIGN_TYPE( float * ); variant_ALIGN_TYPE( double * ); variant_ALIGN_TYPE( long double * ); variant_ALIGN_TYPE( void * ); #ifdef HAVE_LONG_LONG variant_ALIGN_TYPE( long long ); #endif struct Unknown; Unknown ( * variant_UNIQUE(_) )( Unknown ); Unknown * Unknown::* variant_UNIQUE(_); Unknown ( Unknown::* variant_UNIQUE(_) )( Unknown ); struct_t< Unknown ( * )( Unknown) > variant_UNIQUE(_); struct_t< Unknown * Unknown::* > variant_UNIQUE(_); struct_t< Unknown ( Unknown::* )(Unknown) > variant_UNIQUE(_); }; #undef variant_UNIQUE #undef variant_UNIQUE2 #undef variant_UNIQUE3 #undef variant_ALIGN_TYPE #elif defined( variant_CONFIG_ALIGN_AS ) // variant_CONFIG_MAX_ALIGN_HACK // Use user-specified type for alignment: #define variant_ALIGN_AS( unused ) \ variant_CONFIG_ALIGN_AS #else // variant_CONFIG_MAX_ALIGN_HACK // Determine POD type to use for alignment: #define variant_ALIGN_AS( to_align ) \ typename detail::type_of_size< detail::alignment_types, detail::alignment_of< to_align >::value >::type template< typename T > struct alignment_of; template< typename T > struct alignment_of_hack { char c; T t; alignment_of_hack(); }; template< size_t A, size_t S > struct alignment_logic { enum V { value = A < S ? A : S }; }; template< typename T > struct alignment_of { enum V { value = alignment_logic< sizeof( alignment_of_hack ) - sizeof(T), sizeof(T) >::value }; }; template< typename List, size_t N > struct type_of_size { typedef typename std11::conditional< N == sizeof( typename List::head ), typename List::head, typename type_of_size::type >::type type; }; template< size_t N > struct type_of_size< nulltype, N > { typedef variant_CONFIG_ALIGN_AS_FALLBACK type; }; template< typename T> struct struct_t { T _; }; #define variant_ALIGN_TYPE( type ) \ typelist< type , typelist< struct_t< type > struct Unknown; typedef variant_ALIGN_TYPE( char ), variant_ALIGN_TYPE( short ), variant_ALIGN_TYPE( int ), variant_ALIGN_TYPE( long ), variant_ALIGN_TYPE( float ), variant_ALIGN_TYPE( double ), variant_ALIGN_TYPE( long double ), variant_ALIGN_TYPE( char *), variant_ALIGN_TYPE( short * ), variant_ALIGN_TYPE( int * ), variant_ALIGN_TYPE( long * ), variant_ALIGN_TYPE( float * ), variant_ALIGN_TYPE( double * ), variant_ALIGN_TYPE( long double * ), variant_ALIGN_TYPE( Unknown ( * )( Unknown ) ), variant_ALIGN_TYPE( Unknown * Unknown::* ), variant_ALIGN_TYPE( Unknown ( Unknown::* )( Unknown ) ), nulltype > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > alignment_types; #undef variant_ALIGN_TYPE #endif // variant_CONFIG_MAX_ALIGN_HACK #if variant_CPP11_OR_GREATER template< typename T> inline std::size_t hash( T const & v ) { return std::hash()( v ); } inline std::size_t hash( T0 const & ) { return 0; } inline std::size_t hash( T1 const & ) { return 0; } inline std::size_t hash( T2 const & ) { return 0; } inline std::size_t hash( T3 const & ) { return 0; } inline std::size_t hash( T4 const & ) { return 0; } inline std::size_t hash( T5 const & ) { return 0; } inline std::size_t hash( T6 const & ) { return 0; } inline std::size_t hash( T7 const & ) { return 0; } inline std::size_t hash( T8 const & ) { return 0; } inline std::size_t hash( T9 const & ) { return 0; } inline std::size_t hash( T10 const & ) { return 0; } inline std::size_t hash( T11 const & ) { return 0; } inline std::size_t hash( T12 const & ) { return 0; } inline std::size_t hash( T13 const & ) { return 0; } inline std::size_t hash( T14 const & ) { return 0; } inline std::size_t hash( T15 const & ) { return 0; } #endif // variant_CPP11_OR_GREATER template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > struct helper { typedef signed char type_index_t; typedef variant_TL16( T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15 ) variant_types; template< class U > static U * as( void * data ) { return reinterpret_cast( data ); } template< class U > static U const * as( void const * data ) { return reinterpret_cast( data ); } static type_index_t to_index_t( std::size_t index ) { return static_cast( index ); } static void destroy( type_index_t index, void * data ) { switch ( index ) { case 0: as( data )->~T0(); break; case 1: as( data )->~T1(); break; case 2: as( data )->~T2(); break; case 3: as( data )->~T3(); break; case 4: as( data )->~T4(); break; case 5: as( data )->~T5(); break; case 6: as( data )->~T6(); break; case 7: as( data )->~T7(); break; case 8: as( data )->~T8(); break; case 9: as( data )->~T9(); break; case 10: as( data )->~T10(); break; case 11: as( data )->~T11(); break; case 12: as( data )->~T12(); break; case 13: as( data )->~T13(); break; case 14: as( data )->~T14(); break; case 15: as( data )->~T15(); break; } } #if variant_CPP11_OR_GREATER template< class T, class... Args > static type_index_t construct_t( void * data, Args&&... args ) { new( data ) T( std::forward(args)... ); return to_index_t( detail::typelist_index_of< variant_types, T>::value ); } template< std::size_t K, class... Args > static type_index_t construct_i( void * data, Args&&... args ) { using type = typename detail::typelist_type_at< variant_types, K >::type; construct_t< type >( data, std::forward(args)... ); return to_index_t( K ); } static type_index_t move_construct( type_index_t const from_index, void * from_value, void * to_value ) { switch ( from_index ) { case 0: new( to_value ) T0( std::move( *as( from_value ) ) ); break; case 1: new( to_value ) T1( std::move( *as( from_value ) ) ); break; case 2: new( to_value ) T2( std::move( *as( from_value ) ) ); break; case 3: new( to_value ) T3( std::move( *as( from_value ) ) ); break; case 4: new( to_value ) T4( std::move( *as( from_value ) ) ); break; case 5: new( to_value ) T5( std::move( *as( from_value ) ) ); break; case 6: new( to_value ) T6( std::move( *as( from_value ) ) ); break; case 7: new( to_value ) T7( std::move( *as( from_value ) ) ); break; case 8: new( to_value ) T8( std::move( *as( from_value ) ) ); break; case 9: new( to_value ) T9( std::move( *as( from_value ) ) ); break; case 10: new( to_value ) T10( std::move( *as( from_value ) ) ); break; case 11: new( to_value ) T11( std::move( *as( from_value ) ) ); break; case 12: new( to_value ) T12( std::move( *as( from_value ) ) ); break; case 13: new( to_value ) T13( std::move( *as( from_value ) ) ); break; case 14: new( to_value ) T14( std::move( *as( from_value ) ) ); break; case 15: new( to_value ) T15( std::move( *as( from_value ) ) ); break; } return from_index; } static type_index_t move_assign( type_index_t const from_index, void * from_value, void * to_value ) { switch ( from_index ) { case 0: *as( to_value ) = std::move( *as( from_value ) ); break; case 1: *as( to_value ) = std::move( *as( from_value ) ); break; case 2: *as( to_value ) = std::move( *as( from_value ) ); break; case 3: *as( to_value ) = std::move( *as( from_value ) ); break; case 4: *as( to_value ) = std::move( *as( from_value ) ); break; case 5: *as( to_value ) = std::move( *as( from_value ) ); break; case 6: *as( to_value ) = std::move( *as( from_value ) ); break; case 7: *as( to_value ) = std::move( *as( from_value ) ); break; case 8: *as( to_value ) = std::move( *as( from_value ) ); break; case 9: *as( to_value ) = std::move( *as( from_value ) ); break; case 10: *as( to_value ) = std::move( *as( from_value ) ); break; case 11: *as( to_value ) = std::move( *as( from_value ) ); break; case 12: *as( to_value ) = std::move( *as( from_value ) ); break; case 13: *as( to_value ) = std::move( *as( from_value ) ); break; case 14: *as( to_value ) = std::move( *as( from_value ) ); break; case 15: *as( to_value ) = std::move( *as( from_value ) ); break; } return from_index; } #endif static type_index_t copy_construct( type_index_t const from_index, const void * from_value, void * to_value ) { switch ( from_index ) { case 0: new( to_value ) T0( *as( from_value ) ); break; case 1: new( to_value ) T1( *as( from_value ) ); break; case 2: new( to_value ) T2( *as( from_value ) ); break; case 3: new( to_value ) T3( *as( from_value ) ); break; case 4: new( to_value ) T4( *as( from_value ) ); break; case 5: new( to_value ) T5( *as( from_value ) ); break; case 6: new( to_value ) T6( *as( from_value ) ); break; case 7: new( to_value ) T7( *as( from_value ) ); break; case 8: new( to_value ) T8( *as( from_value ) ); break; case 9: new( to_value ) T9( *as( from_value ) ); break; case 10: new( to_value ) T10( *as( from_value ) ); break; case 11: new( to_value ) T11( *as( from_value ) ); break; case 12: new( to_value ) T12( *as( from_value ) ); break; case 13: new( to_value ) T13( *as( from_value ) ); break; case 14: new( to_value ) T14( *as( from_value ) ); break; case 15: new( to_value ) T15( *as( from_value ) ); break; } return from_index; } static type_index_t copy_assign( type_index_t const from_index, const void * from_value, void * to_value ) { switch ( from_index ) { case 0: *as( to_value ) = *as( from_value ); break; case 1: *as( to_value ) = *as( from_value ); break; case 2: *as( to_value ) = *as( from_value ); break; case 3: *as( to_value ) = *as( from_value ); break; case 4: *as( to_value ) = *as( from_value ); break; case 5: *as( to_value ) = *as( from_value ); break; case 6: *as( to_value ) = *as( from_value ); break; case 7: *as( to_value ) = *as( from_value ); break; case 8: *as( to_value ) = *as( from_value ); break; case 9: *as( to_value ) = *as( from_value ); break; case 10: *as( to_value ) = *as( from_value ); break; case 11: *as( to_value ) = *as( from_value ); break; case 12: *as( to_value ) = *as( from_value ); break; case 13: *as( to_value ) = *as( from_value ); break; case 14: *as( to_value ) = *as( from_value ); break; case 15: *as( to_value ) = *as( from_value ); break; } return from_index; } }; } // namespace detail // // Variant: // template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > class variant; // 19.7.8 Class monostate class monostate{}; // 19.7.9 monostate relational operators inline variant_constexpr bool operator< ( monostate, monostate ) variant_noexcept { return false; } inline variant_constexpr bool operator> ( monostate, monostate ) variant_noexcept { return false; } inline variant_constexpr bool operator<=( monostate, monostate ) variant_noexcept { return true; } inline variant_constexpr bool operator>=( monostate, monostate ) variant_noexcept { return true; } inline variant_constexpr bool operator==( monostate, monostate ) variant_noexcept { return true; } inline variant_constexpr bool operator!=( monostate, monostate ) variant_noexcept { return false; } // 19.7.4 variant helper classes // obtain the size of the variant's list of alternatives at compile time template< class T > struct variant_size; /* undefined */ template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > struct variant_size< variant > { enum _ { value = detail::typelist_size< variant_TL16(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) >::value }; }; #if variant_CPP14_OR_GREATER template< class T > constexpr std::size_t variant_size_v = variant_size::value; #endif #if ! variant_CONFIG_OMIT_VARIANT_SIZE_V_MACRO # define variant_size_V(T) nonstd::variant_size::value #endif // obtain the type of the alternative specified by its index, at compile time: template< std::size_t K, class T > struct variant_alternative; /* undefined */ template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > struct variant_alternative< K, variant > { typedef typename detail::typelist_type_at::type type; }; #if variant_CPP11_OR_GREATER template< std::size_t K, class T > using variant_alternative_t = typename variant_alternative::type; #endif #if ! variant_CONFIG_OMIT_VARIANT_ALTERNATIVE_T_MACRO # define variant_alternative_T(K,T) typename nonstd::variant_alternative::type #endif // NTS:implement specializes the std::uses_allocator type trait // std::uses_allocator // index of the variant in the invalid state (constant) #if variant_CPP11_OR_GREATER variant_constexpr std::size_t variant_npos = static_cast( -1 ); #else static const std::size_t variant_npos = static_cast( -1 ); #endif #if ! variant_CONFIG_NO_EXCEPTIONS // 19.7.11 Class bad_variant_access class bad_variant_access : public std::exception { public: #if variant_CPP11_OR_GREATER virtual const char* what() const variant_noexcept variant_override #else virtual const char* what() const throw() #endif { return "bad variant access"; } }; #endif // variant_CONFIG_NO_EXCEPTIONS // 19.7.3 Class template variant template< class T0, class T1 = detail::T1, class T2 = detail::T2, class T3 = detail::T3, class T4 = detail::T4, class T5 = detail::T5, class T6 = detail::T6, class T7 = detail::T7, class T8 = detail::T8, class T9 = detail::T9, class T10 = detail::T10, class T11 = detail::T11, class T12 = detail::T12, class T13 = detail::T13, class T14 = detail::T14, class T15 = detail::T15 > class variant { typedef detail::helper< T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15 > helper_type; typedef variant_TL16( T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15 ) variant_types; public: // 19.7.3.1 Constructors variant() : type_index( 0 ) { new( ptr() ) T0(); } variant( T0 const & t0 ) : type_index( 0 ) { new( ptr() ) T0( t0 ); } variant( T1 const & t1 ) : type_index( 1 ) { new( ptr() ) T1( t1 ); } variant( T2 const & t2 ) : type_index( 2 ) { new( ptr() ) T2( t2 ); } variant( T3 const & t3 ) : type_index( 3 ) { new( ptr() ) T3( t3 ); } variant( T4 const & t4 ) : type_index( 4 ) { new( ptr() ) T4( t4 ); } variant( T5 const & t5 ) : type_index( 5 ) { new( ptr() ) T5( t5 ); } variant( T6 const & t6 ) : type_index( 6 ) { new( ptr() ) T6( t6 ); } variant( T7 const & t7 ) : type_index( 7 ) { new( ptr() ) T7( t7 ); } variant( T8 const & t8 ) : type_index( 8 ) { new( ptr() ) T8( t8 ); } variant( T9 const & t9 ) : type_index( 9 ) { new( ptr() ) T9( t9 ); } variant( T10 const & t10 ) : type_index( 10 ) { new( ptr() ) T10( t10 ); } variant( T11 const & t11 ) : type_index( 11 ) { new( ptr() ) T11( t11 ); } variant( T12 const & t12 ) : type_index( 12 ) { new( ptr() ) T12( t12 ); } variant( T13 const & t13 ) : type_index( 13 ) { new( ptr() ) T13( t13 ); } variant( T14 const & t14 ) : type_index( 14 ) { new( ptr() ) T14( t14 ); } variant( T15 const & t15 ) : type_index( 15 ) { new( ptr() ) T15( t15 ); } #if variant_CPP11_OR_GREATER variant( T0 && t0 ) : type_index( 0 ) { new( ptr() ) T0( std::move(t0) ); } variant( T1 && t1 ) : type_index( 1 ) { new( ptr() ) T1( std::move(t1) ); } variant( T2 && t2 ) : type_index( 2 ) { new( ptr() ) T2( std::move(t2) ); } variant( T3 && t3 ) : type_index( 3 ) { new( ptr() ) T3( std::move(t3) ); } variant( T4 && t4 ) : type_index( 4 ) { new( ptr() ) T4( std::move(t4) ); } variant( T5 && t5 ) : type_index( 5 ) { new( ptr() ) T5( std::move(t5) ); } variant( T6 && t6 ) : type_index( 6 ) { new( ptr() ) T6( std::move(t6) ); } variant( T7 && t7 ) : type_index( 7 ) { new( ptr() ) T7( std::move(t7) ); } variant( T8 && t8 ) : type_index( 8 ) { new( ptr() ) T8( std::move(t8) ); } variant( T9 && t9 ) : type_index( 9 ) { new( ptr() ) T9( std::move(t9) ); } variant( T10 && t10 ) : type_index( 10 ) { new( ptr() ) T10( std::move(t10) ); } variant( T11 && t11 ) : type_index( 11 ) { new( ptr() ) T11( std::move(t11) ); } variant( T12 && t12 ) : type_index( 12 ) { new( ptr() ) T12( std::move(t12) ); } variant( T13 && t13 ) : type_index( 13 ) { new( ptr() ) T13( std::move(t13) ); } variant( T14 && t14 ) : type_index( 14 ) { new( ptr() ) T14( std::move(t14) ); } variant( T15 && t15 ) : type_index( 15 ) { new( ptr() ) T15( std::move(t15) ); } #endif variant(variant const & other) : type_index( other.type_index ) { (void) helper_type::copy_construct( other.type_index, other.ptr(), ptr() ); } #if variant_CPP11_OR_GREATER variant( variant && other ) noexcept( std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value) : type_index( other.type_index ) { (void) helper_type::move_construct( other.type_index, other.ptr(), ptr() ); } template< std::size_t K > using type_at_t = typename detail::typelist_type_at< variant_types, K >::type; template< class T, class... Args variant_REQUIRES_T( std::is_constructible< T, Args...>::value ) > explicit variant( nonstd_lite_in_place_type_t(T), Args&&... args) { type_index = variant_npos_internal(); type_index = helper_type::template construct_t( ptr(), std::forward(args)... ); } template< class T, class U, class... Args variant_REQUIRES_T( std::is_constructible< T, std::initializer_list&, Args...>::value ) > explicit variant( nonstd_lite_in_place_type_t(T), std::initializer_list il, Args&&... args ) { type_index = variant_npos_internal(); type_index = helper_type::template construct_t( ptr(), il, std::forward(args)... ); } template< std::size_t K, class... Args variant_REQUIRES_T( std::is_constructible< type_at_t, Args...>::value ) > explicit variant( nonstd_lite_in_place_index_t(K), Args&&... args ) { type_index = variant_npos_internal(); type_index = helper_type::template construct_i( ptr(), std::forward(args)... ); } template< size_t K, class U, class... Args variant_REQUIRES_T( std::is_constructible< type_at_t, std::initializer_list&, Args...>::value ) > explicit variant( nonstd_lite_in_place_index_t(K), std::initializer_list il, Args&&... args ) { type_index = variant_npos_internal(); type_index = helper_type::template construct_i( ptr(), il, std::forward(args)... ); } #endif // variant_CPP11_OR_GREATER // 19.7.3.2 Destructor ~variant() { if ( ! valueless_by_exception() ) { helper_type::destroy( type_index, ptr() ); } } // 19.7.3.3 Assignment variant & operator=( variant const & other ) { return copy_assign( other ); } #if variant_CPP11_OR_GREATER variant & operator=( variant && other ) noexcept( std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value) { return move_assign( std::move( other ) ); } variant & operator=( T0 && t0 ) { return assign_value<0>( std::move( t0 ) ); } variant & operator=( T1 && t1 ) { return assign_value<1>( std::move( t1 ) ); } variant & operator=( T2 && t2 ) { return assign_value<2>( std::move( t2 ) ); } variant & operator=( T3 && t3 ) { return assign_value<3>( std::move( t3 ) ); } variant & operator=( T4 && t4 ) { return assign_value<4>( std::move( t4 ) ); } variant & operator=( T5 && t5 ) { return assign_value<5>( std::move( t5 ) ); } variant & operator=( T6 && t6 ) { return assign_value<6>( std::move( t6 ) ); } variant & operator=( T7 && t7 ) { return assign_value<7>( std::move( t7 ) ); } variant & operator=( T8 && t8 ) { return assign_value<8>( std::move( t8 ) ); } variant & operator=( T9 && t9 ) { return assign_value<9>( std::move( t9 ) ); } variant & operator=( T10 && t10 ) { return assign_value<10>( std::move( t10 ) ); } variant & operator=( T11 && t11 ) { return assign_value<11>( std::move( t11 ) ); } variant & operator=( T12 && t12 ) { return assign_value<12>( std::move( t12 ) ); } variant & operator=( T13 && t13 ) { return assign_value<13>( std::move( t13 ) ); } variant & operator=( T14 && t14 ) { return assign_value<14>( std::move( t14 ) ); } variant & operator=( T15 && t15 ) { return assign_value<15>( std::move( t15 ) ); } #endif variant & operator=( T0 const & t0 ) { return assign_value<0>( t0 ); } variant & operator=( T1 const & t1 ) { return assign_value<1>( t1 ); } variant & operator=( T2 const & t2 ) { return assign_value<2>( t2 ); } variant & operator=( T3 const & t3 ) { return assign_value<3>( t3 ); } variant & operator=( T4 const & t4 ) { return assign_value<4>( t4 ); } variant & operator=( T5 const & t5 ) { return assign_value<5>( t5 ); } variant & operator=( T6 const & t6 ) { return assign_value<6>( t6 ); } variant & operator=( T7 const & t7 ) { return assign_value<7>( t7 ); } variant & operator=( T8 const & t8 ) { return assign_value<8>( t8 ); } variant & operator=( T9 const & t9 ) { return assign_value<9>( t9 ); } variant & operator=( T10 const & t10 ) { return assign_value<10>( t10 ); } variant & operator=( T11 const & t11 ) { return assign_value<11>( t11 ); } variant & operator=( T12 const & t12 ) { return assign_value<12>( t12 ); } variant & operator=( T13 const & t13 ) { return assign_value<13>( t13 ); } variant & operator=( T14 const & t14 ) { return assign_value<14>( t14 ); } variant & operator=( T15 const & t15 ) { return assign_value<15>( t15 ); } std::size_t index() const { return variant_npos_internal() == type_index ? variant_npos : static_cast( type_index ); } // 19.7.3.4 Modifiers #if variant_CPP11_OR_GREATER template< class T, class... Args variant_REQUIRES_T( std::is_constructible< T, Args...>::value ) > T& emplace( Args&&... args ) { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); type_index = helper_type::template construct_t( ptr(), std::forward(args)... ); return *as(); } template< class T, class U, class... Args variant_REQUIRES_T( std::is_constructible< T, std::initializer_list&, Args...>::value ) > T& emplace( std::initializer_list il, Args&&... args ) { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); type_index = helper_type::template construct_t( ptr(), il, std::forward(args)... ); return *as(); } template< size_t K, class... Args variant_REQUIRES_T( std::is_constructible< type_at_t, Args...>::value ) > variant_alternative_t & emplace( Args&&... args ) { return this->template emplace< type_at_t >( std::forward(args)... ); } template< size_t K, class U, class... Args variant_REQUIRES_T( std::is_constructible< type_at_t, std::initializer_list&, Args...>::value ) > variant_alternative_t & emplace( std::initializer_list il, Args&&... args ) { return this->template emplace< type_at_t >( il, std::forward(args)... ); } #endif // variant_CPP11_OR_GREATER // 19.7.3.5 Value status bool valueless_by_exception() const { return type_index == variant_npos_internal(); } // 19.7.3.6 Swap void swap( variant & other ) #if variant_CPP11_OR_GREATER noexcept( std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value ) #endif { if ( valueless_by_exception() && other.valueless_by_exception() ) { // no effect } else if ( type_index == other.type_index ) { this->swap_value( type_index, other ); } else { #if variant_CPP11_OR_GREATER variant tmp( std::move( *this ) ); *this = std::move( other ); other = std::move( tmp ); #else variant tmp( *this ); *this = other; other = tmp; #endif } } // // non-standard: // template< class T > static variant_constexpr std::size_t index_of() variant_noexcept { return to_size_t( detail::typelist_index_of::type >::value ); } template< class T > T & get() { const std::size_t i = index_of(); #if variant_CONFIG_NO_EXCEPTIONS assert( i == index() ); #else if ( i != index() ) { throw bad_variant_access(); } #endif return *as(); } template< class T > T const & get() const { const std::size_t i = index_of(); #if variant_CONFIG_NO_EXCEPTIONS assert( i == index() ); #else if ( i != index() ) { throw bad_variant_access(); } #endif return *as(); } template< std::size_t K > typename variant_alternative< K, variant >::type & get() { return this->template get< typename detail::typelist_type_at< variant_types, K >::type >(); } template< std::size_t K > typename variant_alternative< K, variant >::type const & get() const { return this->template get< typename detail::typelist_type_at< variant_types, K >::type >(); } private: typedef typename helper_type::type_index_t type_index_t; void * ptr() variant_noexcept { return &data; } void const * ptr() const variant_noexcept { return &data; } template< class U > U * as() { return reinterpret_cast( ptr() ); } template< class U > U const * as() const { return reinterpret_cast( ptr() ); } template< class U > static variant_constexpr std::size_t to_size_t( U index ) { return static_cast( index ); } variant_constexpr type_index_t variant_npos_internal() const variant_noexcept { return static_cast( -1 ); } variant & copy_assign( variant const & other ) { if ( valueless_by_exception() && other.valueless_by_exception() ) { // no effect } else if ( ! valueless_by_exception() && other.valueless_by_exception() ) { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); } else if ( index() == other.index() ) { type_index = helper_type::copy_assign( other.type_index, other.ptr(), ptr() ); } else { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); type_index = helper_type::copy_construct( other.type_index, other.ptr(), ptr() ); } return *this; } #if variant_CPP11_OR_GREATER variant & move_assign( variant && other ) { if ( valueless_by_exception() && other.valueless_by_exception() ) { // no effect } else if ( ! valueless_by_exception() && other.valueless_by_exception() ) { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); } else if ( index() == other.index() ) { type_index = helper_type::move_assign( other.type_index, other.ptr(), ptr() ); } else { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); type_index = helper_type::move_construct( other.type_index, other.ptr(), ptr() ); } return *this; } template< std::size_t K, class T > variant & assign_value( T && value ) { if( index() == K ) { *as() = std::forward( value ); } else { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); new( ptr() ) T( std::forward( value ) ); type_index = K; } return *this; } #endif // variant_CPP11_OR_GREATER template< std::size_t K, class T > variant & assign_value( T const & value ) { if( index() == K ) { *as() = value; } else { helper_type::destroy( type_index, ptr() ); type_index = variant_npos_internal(); new( ptr() ) T( value ); type_index = K; } return *this; } void swap_value( type_index_t index, variant & other ) { using std::swap; switch( index ) { case 0: swap( this->get<0>(), other.get<0>() ); break; case 1: swap( this->get<1>(), other.get<1>() ); break; case 2: swap( this->get<2>(), other.get<2>() ); break; case 3: swap( this->get<3>(), other.get<3>() ); break; case 4: swap( this->get<4>(), other.get<4>() ); break; case 5: swap( this->get<5>(), other.get<5>() ); break; case 6: swap( this->get<6>(), other.get<6>() ); break; case 7: swap( this->get<7>(), other.get<7>() ); break; case 8: swap( this->get<8>(), other.get<8>() ); break; case 9: swap( this->get<9>(), other.get<9>() ); break; case 10: swap( this->get<10>(), other.get<10>() ); break; case 11: swap( this->get<11>(), other.get<11>() ); break; case 12: swap( this->get<12>(), other.get<12>() ); break; case 13: swap( this->get<13>(), other.get<13>() ); break; case 14: swap( this->get<14>(), other.get<14>() ); break; case 15: swap( this->get<15>(), other.get<15>() ); break; } } private: enum { data_size = detail::typelist_max< variant_types >::value }; #if variant_CPP11_OR_GREATER enum { data_align = detail::typelist_max_alignof< variant_types >::value }; using aligned_storage_t = typename std::aligned_storage< data_size, data_align >::type; aligned_storage_t data; #elif variant_CONFIG_MAX_ALIGN_HACK typedef union { unsigned char data[ data_size ]; } aligned_storage_t; detail::max_align_t hack; aligned_storage_t data; #else typedef typename detail::typelist_max< variant_types >::type max_type; typedef variant_ALIGN_AS( max_type ) align_as_type; typedef union { align_as_type data[ 1 + ( data_size - 1 ) / sizeof(align_as_type) ]; } aligned_storage_t; aligned_storage_t data; // # undef variant_ALIGN_AS #endif // variant_CONFIG_MAX_ALIGN_HACK type_index_t type_index; }; // 19.7.5 Value access template< class T, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool holds_alternative( variant const & v ) variant_noexcept { return v.index() == variant::template index_of(); } template< class R, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline R & get( variant & v, nonstd_lite_in_place_type_t(R) = nonstd_lite_in_place_type(R) ) { return v.template get(); } template< class R, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline R const & get( variant const & v, nonstd_lite_in_place_type_t(R) = nonstd_lite_in_place_type(R) ) { return v.template get(); } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename variant_alternative< K, variant >::type & get( variant & v, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { #if variant_CONFIG_NO_EXCEPTIONS assert( K == v.index() ); #else if ( K != v.index() ) { throw bad_variant_access(); } #endif return v.template get(); } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename variant_alternative< K, variant >::type const & get( variant const & v, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { #if variant_CONFIG_NO_EXCEPTIONS assert( K == v.index() ); #else if ( K != v.index() ) { throw bad_variant_access(); } #endif return v.template get(); } #if variant_CPP11_OR_GREATER template< class R, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline R && get( variant && v, nonstd_lite_in_place_type_t(R) = nonstd_lite_in_place_type(R) ) { return std::move(v.template get()); } template< class R, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline R const && get( variant const && v, nonstd_lite_in_place_type_t(R) = nonstd_lite_in_place_type(R) ) { return std::move(v.template get()); } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename variant_alternative< K, variant >::type && get( variant && v, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { #if variant_CONFIG_NO_EXCEPTIONS assert( K == v.index() ); #else if ( K != v.index() ) { throw bad_variant_access(); } #endif return std::move(v.template get()); } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename variant_alternative< K, variant >::type const && get( variant const && v, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { #if variant_CONFIG_NO_EXCEPTIONS assert( K == v.index() ); #else if ( K != v.index() ) { throw bad_variant_access(); } #endif return std::move(v.template get()); } #endif // variant_CPP11_OR_GREATER template< class T, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename std11::add_pointer::type get_if( variant * pv, nonstd_lite_in_place_type_t(T) = nonstd_lite_in_place_type(T) ) { return ( pv->index() == variant::template index_of() ) ? &get( *pv ) : variant_nullptr; } template< class T, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename std11::add_pointer::type get_if( variant const * pv, nonstd_lite_in_place_type_t(T) = nonstd_lite_in_place_type(T)) { return ( pv->index() == variant::template index_of() ) ? &get( *pv ) : variant_nullptr; } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename std11::add_pointer< typename variant_alternative >::type >::type get_if( variant * pv, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { return ( pv->index() == K ) ? &get( *pv ) : variant_nullptr; } template< std::size_t K, class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline typename std11::add_pointer< const typename variant_alternative >::type >::type get_if( variant const * pv, nonstd_lite_in_place_index_t(K) = nonstd_lite_in_place_index(K) ) { return ( pv->index() == K ) ? &get( *pv ) : variant_nullptr; } // 19.7.10 Specialized algorithms template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 #if variant_CPP11_OR_GREATER variant_REQUIRES_T( std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value && std::is_move_constructible::value && std17::is_swappable::value ) #endif > inline void swap( variant & a, variant & b ) #if variant_CPP11_OR_GREATER noexcept( noexcept( a.swap( b ) ) ) #endif { a.swap( b ); } // 19.7.7 Visitation // Variant 'visitor' implementation namespace detail { template< typename R, typename VT > struct VisitorApplicatorImpl { template< typename Visitor, typename T > static R apply(Visitor const& v, T const& arg) { return v(arg); } }; template< typename R, typename VT > struct VisitorApplicatorImpl > { template< typename Visitor, typename T > static R apply(Visitor const&, T) { return R(); } }; template struct VisitorApplicator; template< typename R, typename Visitor, typename V1 > struct VisitorUnwrapper; #if variant_CPP11_OR_GREATER template< size_t NumVars, typename R, typename Visitor, typename ... T > #else template< size_t NumVars, typename R, typename Visitor, typename T1, typename T2 = S0, typename T3 = S0, typename T4 = S0, typename T5 = S0 > #endif struct TypedVisitorUnwrapper; template< typename R, typename Visitor, typename T2 > struct TypedVisitorUnwrapper<2, R, Visitor, T2> { const Visitor& visitor; T2 const& val2; TypedVisitorUnwrapper(const Visitor& visitor_, T2 const& val2_) : visitor(visitor_) , val2(val2_) { } template R operator()(const T& val1) const { return visitor(val1, val2); } }; template< typename R, typename Visitor, typename T2, typename T3 > struct TypedVisitorUnwrapper<3, R, Visitor, T2, T3> { const Visitor& visitor; T2 const& val2; T3 const& val3; TypedVisitorUnwrapper(const Visitor& visitor_, T2 const& val2_, T3 const& val3_) : visitor(visitor_) , val2(val2_) , val3(val3_) { } template R operator()(const T& val1) const { return visitor(val1, val2, val3); } }; template< typename R, typename Visitor, typename T2, typename T3, typename T4 > struct TypedVisitorUnwrapper<4, R, Visitor, T2, T3, T4> { const Visitor& visitor; T2 const& val2; T3 const& val3; T4 const& val4; TypedVisitorUnwrapper(const Visitor& visitor_, T2 const& val2_, T3 const& val3_, T4 const& val4_) : visitor(visitor_) , val2(val2_) , val3(val3_) , val4(val4_) { } template R operator()(const T& val1) const { return visitor(val1, val2, val3, val4); } }; template< typename R, typename Visitor, typename T2, typename T3, typename T4, typename T5 > struct TypedVisitorUnwrapper<5, R, Visitor, T2, T3, T4, T5> { const Visitor& visitor; T2 const& val2; T3 const& val3; T4 const& val4; T5 const& val5; TypedVisitorUnwrapper(const Visitor& visitor_, T2 const& val2_, T3 const& val3_, T4 const& val4_, T5 const& val5_) : visitor(visitor_) , val2(val2_) , val3(val3_) , val4(val4_) , val5(val5_) { } template R operator()(const T& val1) const { return visitor(val1, val2, val3, val4, val5); } }; template struct VisitorUnwrapper { const Visitor& visitor; const V2& r; VisitorUnwrapper(const Visitor& visitor_, const V2& r_) : visitor(visitor_) , r(r_) { } template< typename T1 > R operator()(T1 const& val1) const { typedef TypedVisitorUnwrapper<2, R, Visitor, T1> visitor_type; return VisitorApplicator::apply(visitor_type(visitor, val1), r); } template< typename T1, typename T2 > R operator()(T1 const& val1, T2 const& val2) const { typedef TypedVisitorUnwrapper<3, R, Visitor, T1, T2> visitor_type; return VisitorApplicator::apply(visitor_type(visitor, val1, val2), r); } template< typename T1, typename T2, typename T3 > R operator()(T1 const& val1, T2 const& val2, T3 const& val3) const { typedef TypedVisitorUnwrapper<4, R, Visitor, T1, T2, T3> visitor_type; return VisitorApplicator::apply(visitor_type(visitor, val1, val2, val3), r); } template< typename T1, typename T2, typename T3, typename T4 > R operator()(T1 const& val1, T2 const& val2, T3 const& val3, T4 const& val4) const { typedef TypedVisitorUnwrapper<5, R, Visitor, T1, T2, T3, T4> visitor_type; return VisitorApplicator::apply(visitor_type(visitor, val1, val2, val3, val4), r); } template< typename T1, typename T2, typename T3, typename T4, typename T5 > R operator()(T1 const& val1, T2 const& val2, T3 const& val3, T4 const& val4, T5 const& val5) const { typedef TypedVisitorUnwrapper<6, R, Visitor, T1, T2, T3, T4, T5> visitor_type; return VisitorApplicator::apply(visitor_type(visitor, val1, val2, val3, val4, val5), r); } }; template struct VisitorApplicator { template static R apply(const Visitor& v, const V1& arg) { switch( arg.index() ) { case 0: return apply_visitor<0>(v, arg); case 1: return apply_visitor<1>(v, arg); case 2: return apply_visitor<2>(v, arg); case 3: return apply_visitor<3>(v, arg); case 4: return apply_visitor<4>(v, arg); case 5: return apply_visitor<5>(v, arg); case 6: return apply_visitor<6>(v, arg); case 7: return apply_visitor<7>(v, arg); case 8: return apply_visitor<8>(v, arg); case 9: return apply_visitor<9>(v, arg); case 10: return apply_visitor<10>(v, arg); case 11: return apply_visitor<11>(v, arg); case 12: return apply_visitor<12>(v, arg); case 13: return apply_visitor<13>(v, arg); case 14: return apply_visitor<14>(v, arg); case 15: return apply_visitor<15>(v, arg); default: return R(); } } template static R apply_visitor(const Visitor& v, const V1& arg) { #if variant_CPP11_OR_GREATER typedef typename variant_alternative::type>::type value_type; #else typedef typename variant_alternative::type value_type; #endif return VisitorApplicatorImpl::apply(v, get(arg)); } #if variant_CPP11_OR_GREATER template static R apply(const Visitor& v, const V1& arg1, const V2& arg2, const V ... args) { typedef VisitorUnwrapper Unwrapper; Unwrapper unwrapper(v, arg1); return apply(unwrapper, arg2, args ...); } #else template< typename Visitor, typename V1, typename V2 > static R apply(const Visitor& v, V1 const& arg1, V2 const& arg2) { typedef VisitorUnwrapper Unwrapper; Unwrapper unwrapper(v, arg1); return apply(unwrapper, arg2); } template< typename Visitor, typename V1, typename V2, typename V3 > static R apply(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3) { typedef VisitorUnwrapper Unwrapper; Unwrapper unwrapper(v, arg1); return apply(unwrapper, arg2, arg3); } template< typename Visitor, typename V1, typename V2, typename V3, typename V4 > static R apply(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3, V4 const& arg4) { typedef VisitorUnwrapper Unwrapper; Unwrapper unwrapper(v, arg1); return apply(unwrapper, arg2, arg3, arg4); } template< typename Visitor, typename V1, typename V2, typename V3, typename V4, typename V5 > static R apply(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3, V4 const& arg4, V5 const& arg5) { typedef VisitorUnwrapper Unwrapper; Unwrapper unwrapper(v, arg1); return apply(unwrapper, arg2, arg3, arg4, arg5); } #endif }; #if variant_CPP11_OR_GREATER template< size_t NumVars, typename Visitor, typename ... V > struct VisitorImpl { typedef decltype(std::declval()(get<0>(static_cast(std::declval()))...)) result_type; typedef VisitorApplicator applicator_type; }; #endif } // detail #if variant_CPP11_OR_GREATER // No perfect forwarding here in order to simplify code template< typename Visitor, typename ... V > inline auto visit(Visitor const& v, V const& ... vars) -> typename detail::VisitorImpl ::result_type { typedef detail::VisitorImpl impl_type; return impl_type::applicator_type::apply(v, vars...); } #else template< typename R, typename Visitor, typename V1 > inline R visit(const Visitor& v, V1 const& arg1) { return detail::VisitorApplicator::apply(v, arg1); } template< typename R, typename Visitor, typename V1, typename V2 > inline R visit(const Visitor& v, V1 const& arg1, V2 const& arg2) { return detail::VisitorApplicator::apply(v, arg1, arg2); } template< typename R, typename Visitor, typename V1, typename V2, typename V3 > inline R visit(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3) { return detail::VisitorApplicator::apply(v, arg1, arg2, arg3); } template< typename R, typename Visitor, typename V1, typename V2, typename V3, typename V4 > inline R visit(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3, V4 const& arg4) { return detail::VisitorApplicator::apply(v, arg1, arg2, arg3, arg4); } template< typename R, typename Visitor, typename V1, typename V2, typename V3, typename V4, typename V5 > inline R visit(const Visitor& v, V1 const& arg1, V2 const& arg2, V3 const& arg3, V4 const& arg4, V5 const& arg5) { return detail::VisitorApplicator::apply(v, arg1, arg2, arg3, arg4, arg5); } #endif // 19.7.6 Relational operators namespace detail { template< class Variant > struct Comparator { static inline bool equal( Variant const & v, Variant const & w ) { switch( v.index() ) { case 0: return get<0>( v ) == get<0>( w ); case 1: return get<1>( v ) == get<1>( w ); case 2: return get<2>( v ) == get<2>( w ); case 3: return get<3>( v ) == get<3>( w ); case 4: return get<4>( v ) == get<4>( w ); case 5: return get<5>( v ) == get<5>( w ); case 6: return get<6>( v ) == get<6>( w ); case 7: return get<7>( v ) == get<7>( w ); case 8: return get<8>( v ) == get<8>( w ); case 9: return get<9>( v ) == get<9>( w ); case 10: return get<10>( v ) == get<10>( w ); case 11: return get<11>( v ) == get<11>( w ); case 12: return get<12>( v ) == get<12>( w ); case 13: return get<13>( v ) == get<13>( w ); case 14: return get<14>( v ) == get<14>( w ); case 15: return get<15>( v ) == get<15>( w ); default: return false; } } static inline bool less_than( Variant const & v, Variant const & w ) { switch( v.index() ) { case 0: return get<0>( v ) < get<0>( w ); case 1: return get<1>( v ) < get<1>( w ); case 2: return get<2>( v ) < get<2>( w ); case 3: return get<3>( v ) < get<3>( w ); case 4: return get<4>( v ) < get<4>( w ); case 5: return get<5>( v ) < get<5>( w ); case 6: return get<6>( v ) < get<6>( w ); case 7: return get<7>( v ) < get<7>( w ); case 8: return get<8>( v ) < get<8>( w ); case 9: return get<9>( v ) < get<9>( w ); case 10: return get<10>( v ) < get<10>( w ); case 11: return get<11>( v ) < get<11>( w ); case 12: return get<12>( v ) < get<12>( w ); case 13: return get<13>( v ) < get<13>( w ); case 14: return get<14>( v ) < get<14>( w ); case 15: return get<15>( v ) < get<15>( w ); default: return false; } } }; } //namespace detail template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator==( variant const & v, variant const & w ) { if ( v.index() != w.index() ) return false; else if ( v.valueless_by_exception() ) return true; else return detail::Comparator< variant >::equal( v, w ); } template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator!=( variant const & v, variant const & w ) { return ! ( v == w ); } template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator<( variant const & v, variant const & w ) { if ( w.valueless_by_exception() ) return false; else if ( v.valueless_by_exception() ) return true; else if ( v.index() < w.index() ) return true; else if ( v.index() > w.index() ) return false; else return detail::Comparator< variant >::less_than( v, w ); } template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator>( variant const & v, variant const & w ) { return w < v; } template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator<=( variant const & v, variant const & w ) { return ! ( v > w ); } template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > inline bool operator>=( variant const & v, variant const & w ) { return ! ( v < w ); } } // namespace variants using namespace variants; } // namespace nonstd #if variant_CPP11_OR_GREATER // 19.7.12 Hash support namespace std { template<> struct hash< nonstd::monostate > { std::size_t operator()( nonstd::monostate ) const variant_noexcept { return 42; } }; template< class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 > struct hash< nonstd::variant > { std::size_t operator()( nonstd::variant const & v ) const variant_noexcept { namespace nvd = nonstd::variants::detail; switch( v.index() ) { case 0: return nvd::hash( 0 ) ^ nvd::hash( get<0>( v ) ); case 1: return nvd::hash( 1 ) ^ nvd::hash( get<1>( v ) ); case 2: return nvd::hash( 2 ) ^ nvd::hash( get<2>( v ) ); case 3: return nvd::hash( 3 ) ^ nvd::hash( get<3>( v ) ); case 4: return nvd::hash( 4 ) ^ nvd::hash( get<4>( v ) ); case 5: return nvd::hash( 5 ) ^ nvd::hash( get<5>( v ) ); case 6: return nvd::hash( 6 ) ^ nvd::hash( get<6>( v ) ); case 7: return nvd::hash( 7 ) ^ nvd::hash( get<7>( v ) ); case 8: return nvd::hash( 8 ) ^ nvd::hash( get<8>( v ) ); case 9: return nvd::hash( 9 ) ^ nvd::hash( get<9>( v ) ); case 10: return nvd::hash( 10 ) ^ nvd::hash( get<10>( v ) ); case 11: return nvd::hash( 11 ) ^ nvd::hash( get<11>( v ) ); case 12: return nvd::hash( 12 ) ^ nvd::hash( get<12>( v ) ); case 13: return nvd::hash( 13 ) ^ nvd::hash( get<13>( v ) ); case 14: return nvd::hash( 14 ) ^ nvd::hash( get<14>( v ) ); case 15: return nvd::hash( 15 ) ^ nvd::hash( get<15>( v ) ); default: return 0; } } }; } //namespace std #endif // variant_CPP11_OR_GREATER #if variant_BETWEEN( variant_COMPILER_MSVC_VER, 1300, 1900 ) # pragma warning( pop ) #endif #endif // variant_USES_STD_VARIANT #endif // NONSTD_VARIANT_LITE_HPP // ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, & Freie Universität Berlin // Copyright (c) 2016-2019, & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE // ----------------------------------------------------------------------------------------------------- //! [semialphabet] #include // alphabet concept checks struct dna2 { uint8_t rank{}; // semialphabet static constexpr size_t alphabet_size = 2; uint8_t to_rank() const noexcept { return rank; } dna2 & assign_rank(uint8_t const rk) noexcept { assert(rk < alphabet_size); rank = rk; return *this; } // Equality and inequality operators ... // Comparison operators ... }; //! [semialphabet] bool operator==(dna2 const & lhs, dna2 const & rhs) noexcept { return lhs.rank == rhs.rank; } bool operator!=(dna2 const & lhs, dna2 const & rhs) noexcept { return !(lhs == rhs); } bool operator<(dna2 const & lhs, dna2 const & rhs) noexcept { return lhs.rank < rhs.rank; } bool operator<=(dna2 const & lhs, dna2 const & rhs) noexcept { return lhs.rank <= rhs.rank; } bool operator>(dna2 const & lhs, dna2 const & rhs) noexcept { return lhs.rank > rhs.rank; } bool operator>=(dna2 const & lhs, dna2 const & rhs) noexcept { return lhs.rank >= rhs.rank; } //! [writable_semialphabet_concept] static_assert(seqan3::semialphabet); // ok static_assert(seqan3::writable_semialphabet); // ok //! [writable_semialphabet_concept] //! [free_functions] int main () { dna2 chr{}; seqan3::assign_rank_to(1, chr); // chr is assigned rank 1 uint8_t rnk = seqan3::to_rank(chr); // query rank value => 1 } //! [free_functions] CxAalto/lcelib /* DavidsenStepRmvLink 2007 July 25 Author: To compile: g++ -O -Wall DavidsenStepRmvLink.cpp -o DavidsenStepRmvLink To run: ./DavidsenStepRmvLink [params] > net.edg 2> net.log Example: ./DavidsenStepRmvLink 7000 0.04 38926 > net.edg 2> net.log [params] = N p randseed */ //#define DEBUG // for debugging code to be run #define NDEBUG // to turn assertions off #include #include #include // instead of the #includes below, you can alternatively use #include Models.H //#include "../NetExtras.H" #include "../models/Davidsen.H" //typedef float EdgeData; //typedef SymmNet NetType; typedef SymmNet NetType; int main(int argc, char* argv[]) { struct DavidsenArgs args; readDavidsenArgs(args, argc, argv); outputDavidsenArgs(args); RandNumGen<> generator(args.randseed); NetType net(args.netSize); DavidsenStepRmvLink(net, args, generator); outputEdgesAndWeights(net); } /****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ // // Created by ripopov on 7/6/18. // #include #include SC_MODULE(top) { SC_CTOR(top) { SC_METHOD(test_method); sensitive << din; } sc_signal din; void test_method () { int x = 0; x++; int y = 0; switch (x) { case 0: y = 1; break; case 1+1: y = 3; break; } sct_assert_const(y == 0); switch (x) { case 0: y+=1; break; case 1: y+=2; break; case 2: y+=3; break; default: y = -1; break; } sct_assert_const(x == 1); sct_assert_const(y == 2); switch (din.read()) { case 0: x = 12; y = 1; break; case 1: x = 12; y = 2; break; default: x = 12; y = 2; break; } sct_assert_const(x == 12); sct_assert_unknown(y); } }; int sc_main (int argc, char ** argv ) { top t_inst{"t_inst"}; sc_start(); return 0; } include/xul/net/http/detail/http_filter.hpp #pragma once #include #include namespace xul { class url_request; class url_response; class http_filter : public object { public: virtual const char* name() const = 0; virtual void set_next(http_filter* next_filter) = 0; virtual bool init(url_request* req, url_response* resp) = 0; virtual bool process(url_request* req, url_response* resp, const uint8_t* data, int size) = 0; virtual bool finish(url_request* req, url_response* resp, const uint8_t* data, int size) = 0; //virtual void abort(url_request* req, url_response* resp) = 0; virtual void handle_error(url_request* req, url_response* resp, int errcode) = 0; }; } // { dg-do run { target c++11 } } // Copyright (C) 2011-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // . #include #include #include #include #include using __gnu_test::uneq_allocator; struct Element { typedef uneq_allocator allocator_type; allocator_type alloc; Element(const allocator_type& a = allocator_type()) : alloc(a) { } Element(std::allocator_arg_t, const allocator_type& a, int = 0) : alloc(a) { } Element(std::allocator_arg_t, const allocator_type& a, const Element&) : alloc(a) { } const allocator_type& get_allocator() const { return alloc; } }; void test01() { typedef std::scoped_allocator_adaptor alloc1_type; typedef std::vector EltVec; alloc1_type a1(1); Element e; EltVec ev1(1, e, a1); VERIFY( ev1.get_allocator().get_personality() == 1 ); VERIFY( ev1[0].get_allocator().get_personality() == 1 ); } void test02() { typedef std::scoped_allocator_adaptor inner_alloc_type; typedef std::vector EltVec; typedef std::scoped_allocator_adaptor alloc_type; typedef std::vector EltVecVec; alloc_type a(1, Element::allocator_type(2)); // outer=1, inner=2 Element e; EltVec ev(1, e); EltVecVec evv(1, ev, a); VERIFY( evv.get_allocator().get_personality() == 1 ); VERIFY( evv[0].get_allocator().get_personality() == 2 ); VERIFY( evv[0][0].get_allocator().get_personality() == 2 ); alloc_type a2(3, Element::allocator_type(4)); // outer=3, inner=4 EltVecVec evv2(evv, a2); // copy with a different allocator VERIFY( evv2.get_allocator().get_personality() == 3 ); VERIFY( evv2[0].get_allocator().get_personality() == 4 ); VERIFY( evv2[0][0].get_allocator().get_personality() == 4 ); EltVecVec evv3(std::move(evv), a2); // move with a different allocator VERIFY( evv3.get_allocator().get_personality() == 3 ); VERIFY( evv3[0].get_allocator().get_personality() == 4 ); VERIFY( evv3[0][0].get_allocator().get_personality() == 4 ); } int main() { test01(); test02(); } 1-10 /* * Student: * Grupa: 344C4 * * Lucrare: Ecuatia undelor pentru acustica 2D * Fisier: acoustics_alg.h * Descriere: Fisier sursa care contine implementarile pentru algoritmul utilizat (in cazul nostru MDF pentru ecuatia propagarii undei) */ #include "acoustics.h" #include "tbb/tbb.h" using namespace tbb; int on_edge(int x, int y) { if (x == 0 && y != 0 && y != nx - 1) return N_EDGE; if (x == ny - 1 && y != 0 && y != nx - 1) return S_EDGE; if (y == 0 && x != 0 && x != ny - 1) return W_EDGE; if (y == nx - 1 && x != 0 && x != ny - 1) return E_EDGE; return 0; } int on_corner(int x, int y) { if (x == 0 && y == 0) return NW_CORNER; if (x == 0 && y == nx - 1) return NE_CORNER; if (x == ny - 1 && y == 0) return SW_CORNER; if (x == ny - 1 && y == nx - 1) return SE_CORNER; return 0; } int on_structure_edge(int x, int y) { int i; for (i = 0; i < scenario[scn_index].nr_struct; i++) { if (y > scenario[scn_index].structure[i].c_points[0][1] && y < scenario[scn_index].structure[i].c_points[1][1]) if (x == scenario[scn_index].structure[i].c_points[0][0]) return N_EDGE; if (x > scenario[scn_index].structure[i].c_points[1][0] && x < scenario[scn_index].structure[i].c_points[2][0]) if (y == scenario[scn_index].structure[i].c_points[1][1]) return E_EDGE; if (y > scenario[scn_index].structure[i].c_points[3][1] && y < scenario[scn_index].structure[i].c_points[2][1]) if (x == scenario[scn_index].structure[i].c_points[3][0]) return S_EDGE; if (x > scenario[scn_index].structure[i].c_points[0][0] && x < scenario[scn_index].structure[i].c_points[3][0]) if (y == scenario[scn_index].structure[i].c_points[0][1]) return W_EDGE; } return 0; } int on_structure_corner(int x, int y) { int i; for (i = 0; i < scenario[scn_index].nr_struct; i++) { if (x == scenario[scn_index].structure[i].c_points[0][0] && y == scenario[scn_index].structure[i].c_points[0][1]) return NW_CORNER; if (x == scenario[scn_index].structure[i].c_points[1][0] && y == scenario[scn_index].structure[i].c_points[1][1]) return NE_CORNER; if (x == scenario[scn_index].structure[i].c_points[2][0] && y == scenario[scn_index].structure[i].c_points[2][1]) return SE_CORNER; if (x == scenario[scn_index].structure[i].c_points[3][0] && y == scenario[scn_index].structure[i].c_points[3][1]) return SW_CORNER; } return 0; } int in_structure(int x, int y) { int i; for (i = 0; i < scenario[scn_index].nr_struct; i++) { if (x > scenario[scn_index].structure[i].c_points[0][0] && x < scenario[scn_index].structure[i].c_points[3][0]) if (y > scenario[scn_index].structure[i].c_points[0][1] && y < scenario[scn_index].structure[i].c_points[1][1]) return 1; } return 0; } double compute_node(int x, int y) { return (2 * ub[x][y] - ua[x][y] + pow(TIME_STEP, 2) / pow(H, 2) * (ub[x + 1][y] - 4 * ub[x][y] + ub[x - 1][y] + ub[x][y + 1] + ub[x][y - 1])); } double compute_edge_node(int i, int j, int side) { switch (side) { case N_EDGE: return ub[i + 1][j]; case E_EDGE: return ub[i][j - 1]; case S_EDGE: return ub[i - 1][j]; case W_EDGE: return ub[i][j + 1]; default: return 0; } } double compute_corner_node(int i, int j, int corner) { switch (corner) { case NW_CORNER: return (ub[i][j + 1] + ub[i + 1][j]) / 2; case NE_CORNER: return (ub[i + 1][j] + ub[i][j - 1]) / 2; case SE_CORNER: return (ub[i][j - 1] + ub[i - 1][j]) / 2; case SW_CORNER: return (ub[i - 1][j] + ub[i][j + 1]) / 2; default: return 0; } } double compute_structure_corner_node(int i, int j, int corner) { switch (corner) { case NW_CORNER: return (ub[i][j - 1] + ub[i - 1][j]) / 2; case NE_CORNER: return (ub[i - 1][j] + ub[i][j + 1]) / 2; case SE_CORNER: return (ub[i][j + 1] + ub[i + 1][j]) / 2; case SW_CORNER: return (ub[i + 1][j] + ub[i][j - 1]) / 2; default: return 0; } } double compute_structure_edge_node(int i, int j, int side) { switch (side) { case N_EDGE: return ub[i - 1][j]; case E_EDGE: return ub[i][j + 1]; case S_EDGE: return ub[i + 1][j]; case W_EDGE: return ub[i][j - 1]; default: return 0; } } int is_source(int x, int y, int radius, int source_active) { if (!source_active) return 0; if (sqrt(pow(scenario[scn_index].source.x - x, 2) + pow(scenario[scn_index].source.y - y, 2)) <= radius) return 1; return 0; } void pulse_source(int radius, int step, double amp) { int i, j; for (i = 0; i < ny; i++) for (j = 0; j < nx; j++) if (is_source(i, j, radius, 1)) uc[i][j] = amp * fabs(sin(step * M_PI / 4)); } double P_0; double tau; double P_r[2000][2000]; double chi[2000][2000]; void free_path_loss() { double G = 10; double sigma = 1; double L = 0.051; // Initial 1 double f = 3 * 1000000; double lightspeed = 3 * 1000000;// missing one zero maybe double env_pent = 1.001; double lambda = lightspeed / f; double R; /*t x, y; for (x = 0; x < nx; x++){ for (y = 0; y < ny; y++){ R = sqrt(x * x + y * y); P_r[x][y] = P_0 * G * G * sigma * lambda * lambda; P_r[x][y] /= (pow(4 * M_PI, 3) * pow(R, env_pent) * L) ; chi[x][y] = sqrt(P_r[x][y] / P_0); chi[x][y] /= 10; chi[x][y] += 0.9; //printf("Chi[%d][%d]=%lf\n", x, y, chi[x][y]); } }*/ parallel_for(blocked_range(0, nx), [&](const blocked_range &r) { for (int x = r.begin(); x < r.end(); x++){ for(int y = 0; y < ny; y++) { R = sqrt(x * x + y * y); P_r[x][y] = P_0 * G * G * sigma * lambda * lambda; P_r[x][y] /= (pow(4 * M_PI, 3) * pow(R, env_pent) * L) ; chi[x][y] = sqrt(P_r[x][y] / P_0); chi[x][y] /= 10; chi[x][y] += 0.9; } } }); } void init_power(double amp) { tau = 1; P_0 = tau * (amp * amp); } void s_compute_acoustics() { init_power(scenario[scn_index].source.p_amp); free_path_loss(); int i, j; int step = 0; int source_active = 1; //int place; int radius = scenario[scn_index].source.radius; while (step < (int)(MAX_TIME / TIME_STEP)) { if (step < (int)(MAX_TIME / TIME_STEP) / 2) pulse_source(radius, step, scenario[scn_index].source.p_amp); else if (source_active) { parallel_for(blocked_range(0, ny), [&](const blocked_range &r) { for (int i = r.begin(); i < r.end(); i++) for (int j = 0; j < nx; j++) { if (is_source(i, j, radius, source_active)) uc[i][j] = ub[i][j] = ua[i][j] = 0; } }); source_active = 0; } parallel_for(blocked_range(0, ny), [&](const blocked_range &r) { for (int i = r.begin(); i < r.end(); i++) { int place; for (int j = 0; j < nx; j++) { if (!on_corner(i, j) && !on_edge(i, j) && !is_source(i, j, radius, source_active) && !on_structure_edge(i, j) && !on_structure_corner(i, j) && !in_structure(i, j)) uc[i][j] = compute_node(i, j); else if ((place = on_edge(i, j))) uc[i][j] = compute_edge_node(i, j, place); else if ((place = on_corner(i, j))) uc[i][j] = compute_corner_node(i, j, place); else if ((place = on_structure_edge(i, j))) uc[i][j] = compute_structure_edge_node(i, j, place); else if ((place = on_structure_corner(i, j))) uc[i][j] = compute_structure_corner_node(i, j, place); ua[i][j] = 0; } } }); if (step % SAVE_TIME == 0) export_to_vtk(step); parallel_for(blocked_range(0, nx), [&](const blocked_range &r) { for (int i = r.begin(); i < r.end(); i++){ for(int j = 0; j < ny; j++) { uc[i][j] *= chi[i][j]; } } }); xchg = ua; ua = ub; ub = uc; uc = xchg; step++; } } // Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 #include "dali/test/dali_operator_test.h" #include "dali/test/dali_operator_test_utils.h" #include "dali/pipeline/data/tensor.h" namespace dali { namespace testing { namespace { constexpr int kBbStructSize = 4; constexpr float kEpsilon = 0.001f; /** * Roi can be represented in two ways: * 1. Upper-left corner, width, height * (x1, y1, w, h) * 2. Upper-left and Lower-right corners * (x1, y1, x2, y2) * * Both of them have coordinates in image coordinate system * (i.e. 0.0-1.0) */ using Roi = std::array; /** * Test data for BbFlip operator. Data consists of: * 0 -> reference data input * 1 -> reference data horizontally flipped * 2 -> reference data vertically flipped */ using TestSample = Roi[3]; const TestSample rois_wh[] = { {{.2, .2, .4, .3}, {.4, .2, .4, .3}, {.2, .5, .4, .3}}, {{.0, .0, .5, .5}, {.5, .0, .5, .5}, {.0, .5, .5, .5}}, {{.3, .2, .1, .1}, {.6, .2, .1, .1}, {.3, .7, .1, .1}}, {{.0, .0, .2, .3}, {.8, .0, .2, .3}, {.0, .7, .2, .3}}, {{.0, .0, .1, .1}, {.9, .0, .1, .1}, {.0, .9, .1, .1}}, {{.5, .5, .1, .1}, {.4, .5, .1, .1}, {.5, .4, .1, .1}}, {{.0, .6, .7, .4}, {.3, .6, .7, .4}, {.0, .0, .7, .4}}, {{.6, .2, .3, .3}, {.1, .2, .3, .3}, {.6, .5, .3, .3}}, {{.4, .3, .5, .5}, {.1, .3, .5, .5}, {.4, .2, .5, .5}}, {{.25, .25, .5, .5}, {.25, .25, .5, .5}, {.25, .25, .5, .5}}, }; const TestSample rois_ltrb[] = { {{.2, .2, .6, .5}, {.4, .2, .8, .5}, {.2, .5, .6, .8}}, {{.0, .0, .5, .5}, {.5, .0, 1., .5}, {.0, .5, .5, 1.}}, {{.3, .2, .4, .3}, {.6, .2, .7, .3}, {.3, .7, .4, .8}}, {{.0, .0, .2, .3}, {.8, .0, 1., .3}, {.0, .7, .2, 1.}}, {{.0, .0, .1, .1}, {.9, .0, 1., .1}, {.0, .9, .1, 1.}}, {{.5, .5, .6, .6}, {.4, .5, .5, .6}, {.5, .4, .6, .5}}, {{.0, .6, .7, .9}, {.3, .6, 1., .9}, {.0, .1, .7, .4}}, {{.6, .2, .9, .5}, {.1, .2, .4, .5}, {.6, .5, .9, .8}}, {{.4, .3, .9, .8}, {.1, .3, .6, .8}, {.4, .2, .9, .7}}, {{.25, .25, .75, .75}, {.25, .25, .75, .75}, {.25, .25, .75, .75}}, }; template const TestSample &FindSample(const TestSample (&dataset)[N], const Roi &roi) { for (auto &sample : dataset) { if (sample[0] == roi) { return sample; } } DALI_FAIL("TestSample for provided `roi` has not been found"); } /** * Create TensorList from TestSample data * * @tparam Idx index of data @see TestSample * @tparam Backend * @tparam N size of TestSample data * @param sample * @return */ template std::unique_ptr> ToTensorList(const TestSample (&sample)[N]) { std::unique_ptr> tl(new TensorList()); tl->Resize({N, {kBbStructSize}}); auto ptr = tl->template mutable_data(); for (size_t n = 0; n < N; n++) { for (size_t i = 0; i < kBbStructSize; i++) { *ptr++ = sample[n][Idx][i]; } } return tl; } template std::vector FromTensorListPtr(const TensorList *tl) { auto ptr = tl->template data(); std::vector ret; for (size_t i = 0; i < tl->ntensor(); i++) { Roi roi; for (float &val : roi) { val = *ptr++; } ret.emplace_back(roi); } return ret; } template std::vector FromTensorWrapper(TensorListWrapper tw) { if (tw.has()) { auto *tl = tw.get(); ASSERT_NE(nullptr, tl), std::vector(); ASSERT_LE(kBbStructSize, tl->size()), std::vector(); return FromTensorListPtr(tl); } else { return FromTensorListPtr(tw.CopyTo().get()); } } template void BbVerify(TensorListWrapper input, TensorListWrapper output, Arguments args) { auto input_rois = FromTensorWrapper(input); auto output_rois = FromTensorWrapper(output); ASSERT_EQ(output_rois.size(), input_rois.size()); for (size_t sample_idx = 0; sample_idx < output_rois.size(); sample_idx++) { auto input_roi = input_rois[sample_idx]; auto output_roi = output_rois[sample_idx]; DALI_ENFORCE(!(args["horizontal"].GetValue() && args["vertical"].GetValue()), "No test data for given arguments"); // Index of corresponding reference data in TestSample arrays int reference_data_idx = args["horizontal"].GetValue() * 1 + args["vertical"].GetValue() * 2; Roi anticipated_output_roi = Ltrb ? FindSample(rois_ltrb, input_roi)[reference_data_idx] : FindSample(rois_wh, input_roi)[reference_data_idx]; ASSERT_EQ(anticipated_output_roi.size(), output_roi.size()) << "Inconsistent sizes (input vs output)"; for (size_t i = 0; i < output_roi.size(); i++) { EXPECT_GT(kEpsilon, std::fabs(output_roi[i] - anticipated_output_roi[i])) << "Error exceeds allowed value"; } } } std::vector arguments = { {{"horizontal", 1}, {"vertical", 0}}, {{"horizontal", 0}, {"vertical", 1}}, {{"horizontal", 0}, {"vertical", 0}}, }; std::vector devices = { {{"device", std::string{"cpu"}}}, {{"device", std::string{"gpu"}}}, }; } // namespace class BbFlipTest : public testing::DaliOperatorTest { GraphDescr GenerateOperatorGraph() const override { GraphDescr graph("BbFlip"); return graph; } }; TEST_P(BbFlipTest, WhRoisTest) { constexpr bool ltrb = false; auto args = GetParam(); args.emplace("ltrb", ltrb); auto tlin = ToTensorList<0, CPUBackend>(rois_wh); TensorListWrapper tlout; this->RunTest(tlin.get(), tlout, args, BbVerify); } TEST_P(BbFlipTest, LtrbRoisTest) { constexpr bool ltrb = true; auto args = GetParam(); args.emplace("ltrb", ltrb); auto tlin = ToTensorList<0, CPUBackend>(rois_ltrb); TensorListWrapper tlout; this->RunTest(tlin.get(), tlout, args, BbVerify); } INSTANTIATE_TEST_CASE_P(RoisTest, BbFlipTest, ::testing::ValuesIn(testing::cartesian(devices, arguments))); } // namespace testing } // namespace dali src/FiniteAutomataBase.cpp #include "FiniteAutomataBase.h" #include using namespace std; void FiniteAutomataBase::addState(uint32_t state) { assert(_states.find(state) == _states.end() && "State already exists!\n"); _states.insert(state); } void FiniteAutomataBase::removeState(uint32_t state) { auto it = _states.find(state); assert(it != _states.end() && "state does not exists!\n"); assert(!hasTransitionFrom(state) && "Cannot remove a state which already has transitions from it!\n"); assert(!hasTransitionTo(state) && "Cannot remove a state which already has transitions to it!\n"); _states.erase(it); if (isAcceptState(state)) { _acceptStates.erase(_acceptStates.find(state)); } } void FiniteAutomataBase::setStartState(uint32_t state) { assert(hasState(state) && "Does not have this state!\n"); _startState = state; } void FiniteAutomataBase::setAcceptState(uint32_t state) { assert(hasState(state) && "Does not have this state!\n"); _acceptStates.insert(state); } void FiniteAutomataBase::setAlphabet(unordered_set &alphabet) { _alphabet.clear(); _alphabet.insert(alphabet.begin(), alphabet.end()); }/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/stats-module.h" using namespace ns3; NS_LOG_COMPONENT_DEFINE ("SeventhScriptExample"); // =========================================================================== // // node 0 node 1 // +----------------+ +----------------+ // | ns-3 TCP | | ns-3 TCP | // +----------------+ +----------------+ // | 10.1.1.1 | | 10.1.1.2 | // +----------------+ +----------------+ // | point-to-point | | point-to-point | // +----------------+ +----------------+ // | | // +---------------------+ // 5 Mbps, 2 ms // // // We want to look at changes in the ns-3 TCP congestion window. We need // to crank up a flow and hook the CongestionWindow attribute on the socket // of the sender. Normally one would use an on-off application to generate a // flow, but this has a couple of problems. First, the socket of the on-off // application is not created until Application Start time, so we wouldn't be // able to hook the socket (now) at configuration time. Second, even if we // could arrange a call after start time, the socket is not public so we // couldn't get at it. // // So, we can cook up a simple version of the on-off application that does what // we want. On the plus side we don't need all of the complexity of the on-off // application. On the minus side, we don't have a helper, so we have to get // a little more involved in the details, but this is trivial. // // So first, we create a socket and do the trace connect on it; then we pass // this socket into the constructor of our simple application which we then // install in the source node. // // NOTE: If this example gets modified, do not forget to update the .png figure // in src/stats/docs/seventh-packet-byte-count.png // =========================================================================== // class MyApp : public Application { public: MyApp (); virtual ~MyApp (); /** * Register this type. * \return The TypeId. */ static TypeId GetTypeId (void); void Setup (Ptr socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate); private: virtual void StartApplication (void); virtual void StopApplication (void); void ScheduleTx (void); void SendPacket (void); Ptr m_socket; Address m_peer; uint32_t m_packetSize; uint32_t m_nPackets; DataRate m_dataRate; EventId m_sendEvent; bool m_running; uint32_t m_packetsSent; }; MyApp::MyApp () : m_socket (0), m_peer (), m_packetSize (0), m_nPackets (0), m_dataRate (0), m_sendEvent (), m_running (false), m_packetsSent (0) { } MyApp::~MyApp () { m_socket = 0; } /* static */ TypeId MyApp::GetTypeId (void) { static TypeId tid = TypeId ("MyApp") .SetParent () .SetGroupName ("Tutorial") .AddConstructor () ; return tid; } void MyApp::Setup (Ptr socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate) { m_socket = socket; m_peer = address; m_packetSize = packetSize; m_nPackets = nPackets; m_dataRate = dataRate; } void MyApp::StartApplication (void) { m_running = true; m_packetsSent = 0; if (InetSocketAddress::IsMatchingType (m_peer)) { m_socket->Bind (); } else { m_socket->Bind6 (); } m_socket->Connect (m_peer); SendPacket (); } void MyApp::StopApplication (void) { m_running = false; if (m_sendEvent.IsRunning ()) { Simulator::Cancel (m_sendEvent); } if (m_socket) { m_socket->Close (); } } void MyApp::SendPacket (void) { Ptr packet = Create (m_packetSize); m_socket->Send (packet); if (++m_packetsSent < m_nPackets) { ScheduleTx (); } } void MyApp::ScheduleTx (void) { if (m_running) { Time tNext (Seconds (m_packetSize * 8 / static_cast (m_dataRate.GetBitRate ()))); m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this); } } static void CwndChange (Ptr stream, uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd); *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" << newCwnd << std::endl; } static void RxDrop (Ptr file, Ptr p) { NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ()); file->Write (Simulator::Now (), p); } int main (int argc, char *argv[]) { bool useV6 = false; CommandLine cmd (__FILE__); cmd.AddValue ("useIpv6", "Use Ipv6", useV6); cmd.Parse (argc, argv); NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer devices; devices = pointToPoint.Install (nodes); Ptr em = CreateObject (); em->SetAttribute ("ErrorRate", DoubleValue (0.00001)); devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em)); InternetStackHelper stack; stack.Install (nodes); uint16_t sinkPort = 8080; Address sinkAddress; Address anyAddress; std::string probeType; std::string tracePath; if (useV6 == false) { Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = address.Assign (devices); sinkAddress = InetSocketAddress (interfaces.GetAddress (1), sinkPort); anyAddress = InetSocketAddress (Ipv4Address::GetAny (), sinkPort); probeType = "ns3::Ipv4PacketProbe"; tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx"; } else { Ipv6AddressHelper address; address.SetBase ("2001:0000:f00d:cafe::", Ipv6Prefix (64)); Ipv6InterfaceContainer interfaces = address.Assign (devices); sinkAddress = Inet6SocketAddress (interfaces.GetAddress (1,1), sinkPort); anyAddress = Inet6SocketAddress (Ipv6Address::GetAny (), sinkPort); probeType = "ns3::Ipv6PacketProbe"; tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx"; } PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", anyAddress); ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1)); sinkApps.Start (Seconds (0.)); sinkApps.Stop (Seconds (20.)); Ptr ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ()); Ptr app = CreateObject (); app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps")); nodes.Get (0)->AddApplication (app); app->SetStartTime (Seconds (1.)); app->SetStopTime (Seconds (20.)); AsciiTraceHelper asciiTraceHelper; Ptr stream = asciiTraceHelper.CreateFileStream ("seventh.cwnd"); ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream)); PcapHelper pcapHelper; Ptr file = pcapHelper.CreateFile ("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP); devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, file)); // Use GnuplotHelper to plot the packet byte count over time GnuplotHelper plotHelper; // Configure the plot. The first argument is the file name prefix // for the output files generated. The second, third, and fourth // arguments are, respectively, the plot title, x-axis, and y-axis labels plotHelper.ConfigurePlot ("seventh-packet-byte-count", "Packet Byte Count vs. Time", "Time (Seconds)", "Packet Byte Count"); // Specify the probe type, trace source path (in configuration namespace), and // probe output trace source ("OutputBytes") to plot. The fourth argument // specifies the name of the data series label on the plot. The last // argument formats the plot by specifying where the key should be placed. plotHelper.PlotProbe (probeType, tracePath, "OutputBytes", "Packet Byte Count", GnuplotAggregator::KEY_BELOW); // Use FileHelper to write out the packet byte count over time FileHelper fileHelper; // Configure the file to be written, and the formatting of output data. fileHelper.ConfigureFile ("seventh-packet-byte-count", FileAggregator::FORMATTED); // Set the labels for this formatted output file. fileHelper.Set2dFormat ("Time (Seconds) = %.3e\tPacket Byte Count = %.0f"); // Specify the probe type, trace source path (in configuration namespace), and // probe output trace source ("OutputBytes") to write. fileHelper.WriteProbe (probeType, tracePath, "OutputBytes"); Simulator::Stop (Seconds (20)); Simulator::Run (); Simulator::Destroy (); return 0; } Backtracking/N-Queen Problem/Solution_1.cpp #include using namespace std; #define N 5 int board[N][N]; void printSolution(int board[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("\n"); } } bool isSafe(int row, int col){ for (int i = 0; i < col; i++) if (board[row][i]) return false; for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; for (int i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true; } bool solveRec(int col){ if (col == N) return true; for (int i = 0; i < N; i++) { if (isSafe(i, col)) { board[i][col] = 1; if (solveRec(col + 1)) return true; board[i][col] = 0; } } return false; } bool solve(){ if (solveRec(0) == false) { printf("Solution does not exist"); return false; } printSolution(board); return true; } int main() { solve(); return 0; } #include "PID.h" using namespace std; /* * TODO: Complete the PID class. */ PID::PID() {} PID::~PID() {} void PID::Init(double Kp_in, double Ki_in, double Kd_in) { // this->Kp = Kp; Kp = Kp_in; Ki = Ki_in; Kd = Kd_in; p_error = 0; i_error = 0; d_error = 0; } void PID::UpdateError(double vel_error) { // trick for d_error d_error = vel_error - p_error; p_error = vel_error; i_error += vel_error; //d_error = cte - cte_before; //cte_before = cte; } double PID::TotalError() { double error_cal; return error_cal = -Kp * p_error - Ki * i_error - Kd * d_error; } /*******************************************************************/ /* */ /* ADOBE CONFIDENTIAL */ /* _ _ _ _ _ _ _ _ _ _ _ _ _ */ /* */ /* Copyright 2007 Adobe Systems Incorporated */ /* All Rights Reserved. */ /* */ /* NOTICE: All information contained herein is, and remains the */ /* property of Adobe Systems Incorporated and its suppliers, if */ /* any. The intellectual and technical concepts contained */ /* herein are proprietary to Adobe Systems Incorporated and its */ /* suppliers and may be covered by U.S. and Foreign Patents, */ /* patents in process, and are protected by trade secret or */ /* copyright law. Dissemination of this information or */ /* reproduction of this material is strictly forbidden unless */ /* prior written permission is obtained from Adobe Systems */ /* Incorporated. */ /* */ /*******************************************************************/ #include "Custom_ECW_UI.h" #include "AEFX_SuiteHelper.h" #include // Function to convert and copy string literals to A_UTF16Char. // On Win: Pass the input directly to the output // On Mac: All conversion happens through the CFString format static void copyConvertStringLiteralIntoUTF16( const wchar_t* inputString, A_UTF16Char* destination) { #ifdef AE_OS_MAC int length = wcslen(inputString); CFRange range = {0, 256}; range.length = length; CFStringRef inputStringCFSR = CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast(inputString), length * sizeof(wchar_t), kCFStringEncodingUTF32LE, false); CFStringGetBytes(inputStringCFSR, range, kCFStringEncodingUTF16, 0, false, reinterpret_cast(destination), length * (sizeof (A_UTF16Char)), NULL); destination[length] = 0; // Set NULL-terminator, since CFString calls don't set it CFRelease(inputStringCFSR); #elif defined AE_OS_WIN size_t length = wcslen(inputString); wcscpy_s(reinterpret_cast(destination), length + 1, inputString); #endif } static PF_Err DrawEvent( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output, PF_EventExtra *event_extra) { PF_Err err = PF_Err_NONE, err2 = PF_Err_NONE; DRAWBOT_DrawRef drawing_ref = NULL; DRAWBOT_SurfaceRef surface_ref = NULL; DRAWBOT_SupplierRef supplier_ref = NULL; DRAWBOT_BrushRef brush_ref = NULL; DRAWBOT_BrushRef string_brush_ref = NULL; DRAWBOT_PathRef path_ref = NULL; DRAWBOT_FontRef font_ref = NULL; DRAWBOT_Suites drawbotSuites; DRAWBOT_ColorRGBA drawbot_color; DRAWBOT_RectF32 rectR; float default_font_sizeF = 0.0; // Acquire all the Drawbot suites in one go; it should be matched with release routine. // You can also use C++ style AEFX_DrawbotSuitesScoper which doesn't need release routine. ERR(AEFX_AcquireDrawbotSuites(in_data, out_data, &drawbotSuites)); PF_EffectCustomUISuite1 *effectCustomUISuiteP; ERR(AEFX_AcquireSuite(in_data, out_data, kPFEffectCustomUISuite, kPFEffectCustomUISuiteVersion1, NULL, (void**)&effectCustomUISuiteP)); if (!err && effectCustomUISuiteP) { // Get the drawing reference by passing context to this new api ERR((*effectCustomUISuiteP->PF_GetDrawingReference)(event_extra->contextH, &drawing_ref)); AEFX_ReleaseSuite(in_data, out_data, kPFEffectCustomUISuite, kPFEffectCustomUISuiteVersion1, NULL); } // Get the Drawbot supplier from drawing reference; it shouldn't be released like pen or brush (see below) ERR(drawbotSuites.drawbot_suiteP->GetSupplier(drawing_ref, &supplier_ref)); // Get the Drawbot surface from drawing reference; it shouldn't be released like pen or brush (see below) ERR(drawbotSuites.drawbot_suiteP->GetSurface(drawing_ref, &surface_ref)); // Premiere Pro/Elements does not support a standard parameter type // with custom UI (bug #1235407), so we can't use the color values. // Use an static grey value instead. if (in_data->appl_id != 'PrMr') { drawbot_color.red = static_cast(params[ECW_UI_COLOR]->u.cd.value.red) / PF_MAX_CHAN8; drawbot_color.green = static_cast(params[ECW_UI_COLOR]->u.cd.value.green) / PF_MAX_CHAN8; drawbot_color.blue = static_cast(params[ECW_UI_COLOR]->u.cd.value.blue) / PF_MAX_CHAN8; } else { static float gray = 0; drawbot_color.red = fmod(gray, 1); drawbot_color.green = fmod(gray, 1); drawbot_color.blue = fmod(gray, 1); gray += 0.01f; } drawbot_color.alpha = 1.0; if (PF_EA_CONTROL == event_extra->effect_win.area) { // Create a new path. It should be matched with release routine. // You can also use C++ style DRAWBOT_PathP that releases automatically at the end of scope. ERR(drawbotSuites.supplier_suiteP->NewPath(supplier_ref, &path_ref)); // Create a new brush taking color as input; it should be matched with release routine. // You can also use C++ style DRAWBOT_BrushP which doesn't require release routine. ERR(drawbotSuites.supplier_suiteP->NewBrush(supplier_ref, &drawbot_color, &brush_ref)); rectR.left = event_extra->effect_win.current_frame.left + 0.5; // Center of the pixel in new drawing model is (0.5, 0.5) rectR.top = event_extra->effect_win.current_frame.top + 0.5; rectR.width = static_cast( event_extra->effect_win.current_frame.right - event_extra->effect_win.current_frame.left); rectR.height = static_cast( event_extra->effect_win.current_frame.bottom - event_extra->effect_win.current_frame.top); // Add the rectangle to path ERR(drawbotSuites.path_suiteP->AddRect(path_ref, &rectR)); // Fill the path with the brush created ERR(drawbotSuites.surface_suiteP->FillPath(surface_ref, brush_ref, path_ref, kDRAWBOT_FillType_Default)); // Get the default font size. ERR(drawbotSuites.supplier_suiteP->GetDefaultFontSize(supplier_ref, &default_font_sizeF)); // Create default font with default size. Note that you can provide a different font size. ERR(drawbotSuites.supplier_suiteP->NewDefaultFont(supplier_ref, default_font_sizeF, &font_ref)); DRAWBOT_UTF16Char unicode_string[256]; copyConvertStringLiteralIntoUTF16(CUSTOM_UI_STRING, unicode_string); // Draw string with white color drawbot_color.red = drawbot_color.green = drawbot_color.blue = drawbot_color.alpha = 1.0; ERR(drawbotSuites.supplier_suiteP->NewBrush(supplier_ref, &drawbot_color, &string_brush_ref)); DRAWBOT_PointF32 text_origin; text_origin.x = event_extra->effect_win.current_frame.left + 5.0; text_origin.y = event_extra->effect_win.current_frame.top + 50.0; ERR(drawbotSuites.surface_suiteP->DrawString( surface_ref, string_brush_ref, font_ref, &unicode_string[0], &text_origin, kDRAWBOT_TextAlignment_Default, kDRAWBOT_TextTruncation_None, 0.0f)); if (string_brush_ref) { ERR2(drawbotSuites.supplier_suiteP->ReleaseObject(reinterpret_cast(string_brush_ref))); } if (font_ref) { ERR2(drawbotSuites.supplier_suiteP->ReleaseObject(reinterpret_cast(font_ref))); } // Release/destroy the brush. Otherwise, it will lead to memory leak. if (brush_ref) { ERR2(drawbotSuites.supplier_suiteP->ReleaseObject(reinterpret_cast(brush_ref))); } // Release/destroy the path. Otherwise, it will lead to memory leak. if (path_ref) { ERR2(drawbotSuites.supplier_suiteP->ReleaseObject(reinterpret_cast(path_ref))); } } // Release the earlier acquired Drawbot suites ERR2(AEFX_ReleaseDrawbotSuites(in_data, out_data)); if (!err){ event_extra->evt_out_flags = PF_EO_HANDLED_EVENT; } return err; } static PF_Err DoDrag( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output, PF_EventExtra *event_extra) { PF_Err err = PF_Err_NONE; PF_ContextH contextH = event_extra->contextH; PF_Point mouse_down; if (PF_Window_EFFECT == (*contextH)->w_type){ if (PF_EA_CONTROL == event_extra->effect_win.area) { mouse_down = event_extra->u.do_click.screen_point; event_extra->u.do_click.continue_refcon[1] = mouse_down.h; params[ECW_UI_COLOR]->u.cd.value.red = (unsigned char)((mouse_down.h << 8) / UI_BOX_WIDTH); params[ECW_UI_COLOR]->u.cd.value.blue = (unsigned char)((mouse_down.v << 8) / UI_BOX_HEIGHT); params[ECW_UI_COLOR]->u.cd.value.green = (unsigned char)(params[ECW_UI_COLOR]->u.cd.value.red + params[ECW_UI_COLOR]->u.cd.value.blue); params[ECW_UI_COLOR]->u.cd.value.alpha = (unsigned char)0xFF; params[ECW_UI_COLOR]->uu.change_flags = PF_ChangeFlag_CHANGED_VALUE; } } return err; } static PF_Err DoClick( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output, PF_EventExtra *event_extra) { PF_Err err = PF_Err_NONE; AEGP_SuiteHandler suites(in_data->pica_basicP); PF_ExtendedSuiteTool tool = PF_ExtendedSuiteTool_MAGNIFY; // Premiere Pro/Elements does not support this suite if (in_data->appl_id != 'PrMr') { ERR(suites.HelperSuite2()->PF_SetCurrentExtendedTool(tool)); } else { event_extra->u.adjust_cursor.set_cursor = PF_Cursor_MAGNIFY; } if (!err){ event_extra->u.do_click.send_drag = TRUE; event_extra->evt_out_flags = PF_EO_HANDLED_EVENT; } return err; } static PF_Err ChangeCursor( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output, PF_EventExtra *event_extra) { if (PF_Mod_SHIFT_KEY & event_extra->u.adjust_cursor.modifiers) { event_extra->u.adjust_cursor.set_cursor = PF_Cursor_EYEDROPPER; } else { if (PF_Mod_CMD_CTRL_KEY & event_extra->u.adjust_cursor.modifiers) { event_extra->u.adjust_cursor.set_cursor = PF_Cursor_CROSSHAIRS; } } return PF_Err_NONE; } PF_Err HandleEvent( PF_InData *in_data, PF_OutData *out_data, PF_ParamDef *params[], PF_LayerDef *output, PF_EventExtra *extra) { PF_Err err = PF_Err_NONE; switch (extra->e_type) { case PF_Event_DO_CLICK: err = DoClick(in_data, out_data, params, output, extra); break; case PF_Event_DRAG: err = DoDrag( in_data, out_data, params, output, extra); break; case PF_Event_DRAW: err = DrawEvent( in_data, out_data, params, output, extra); break; case PF_Event_ADJUST_CURSOR: err = ChangeCursor( in_data, out_data, params, output, extra); break; default: break; } return err; } #ifndef NALL_PNG_HPP #define NALL_PNG_HPP //PNG image decoder //author: byuu #include #include namespace nall { struct png { //colorType: //0 = L //2 = R,G,B //3 = P //4 = L,A //6 = R,G,B,A struct Info { unsigned width; unsigned height; unsigned bitDepth; unsigned colorType; unsigned compressionMethod; unsigned filterType; unsigned interlaceMethod; unsigned bytesPerPixel; unsigned pitch; uint8_t palette[256][3]; } info; uint8_t *data; unsigned size; inline bool decode(const string &filename); inline bool decode(const uint8_t *sourceData, unsigned sourceSize); inline unsigned readbits(const uint8_t *&data); unsigned bitpos; inline png(); inline ~png(); protected: enum class FourCC : unsigned { IHDR = 0x49484452, PLTE = 0x504c5445, IDAT = 0x49444154, IEND = 0x49454e44, }; inline unsigned interlace(unsigned pass, unsigned index); inline unsigned inflateSize(); inline bool deinterlace(const uint8_t *&inputData, unsigned pass); inline bool filter(uint8_t *outputData, const uint8_t *inputData, unsigned width, unsigned height); inline unsigned read(const uint8_t *data, unsigned length); }; bool png::decode(const string &filename) { uint8_t *data; unsigned size; if(file::read(filename, data, size) == false) return false; bool result = decode(data, size); delete[] data; return result; } bool png::decode(const uint8_t *sourceData, unsigned sourceSize) { if(sourceSize < 8) return false; if(read(sourceData + 0, 4) != 0x89504e47) return false; if(read(sourceData + 4, 4) != 0x0d0a1a0a) return false; uint8_t *compressedData = 0; unsigned compressedSize = 0; unsigned offset = 8; while(offset < sourceSize) { unsigned length = read(sourceData + offset + 0, 4); unsigned fourCC = read(sourceData + offset + 4, 4); unsigned checksum = read(sourceData + offset + 8 + length, 4); if(fourCC == (unsigned)FourCC::IHDR) { info.width = read(sourceData + offset + 8, 4); info.height = read(sourceData + offset + 12, 4); info.bitDepth = read(sourceData + offset + 16, 1); info.colorType = read(sourceData + offset + 17, 1); info.compressionMethod = read(sourceData + offset + 18, 1); info.filterType = read(sourceData + offset + 19, 1); info.interlaceMethod = read(sourceData + offset + 20, 1); if(info.bitDepth == 0 || info.bitDepth > 16) return false; if(info.bitDepth & (info.bitDepth - 1)) return false; //not a power of two if(info.compressionMethod != 0) return false; if(info.filterType != 0) return false; if(info.interlaceMethod != 0 && info.interlaceMethod != 1) return false; switch(info.colorType) { case 0: info.bytesPerPixel = info.bitDepth * 1; break; //L case 2: info.bytesPerPixel = info.bitDepth * 3; break; //R,G,B case 3: info.bytesPerPixel = info.bitDepth * 1; break; //P case 4: info.bytesPerPixel = info.bitDepth * 2; break; //L,A case 6: info.bytesPerPixel = info.bitDepth * 4; break; //R,G,B,A default: return false; } if(info.colorType == 2 || info.colorType == 4 || info.colorType == 6) if(info.bitDepth != 8 && info.bitDepth != 16) return false; if(info.colorType == 3 && info.bitDepth == 16) return false; info.bytesPerPixel = (info.bytesPerPixel + 7) / 8; info.pitch = (int)info.width * info.bytesPerPixel; } if(fourCC == (unsigned)FourCC::PLTE) { if(length % 3) return false; for(unsigned n = 0, p = offset + 8; n < length / 3; n++) { info.palette[n][0] = sourceData[p++]; info.palette[n][1] = sourceData[p++]; info.palette[n][2] = sourceData[p++]; } } if(fourCC == (unsigned)FourCC::IDAT) { compressedData = (uint8_t*)realloc(compressedData, compressedSize + length); memcpy(compressedData + compressedSize, sourceData + offset + 8, length); compressedSize += length; } if(fourCC == (unsigned)FourCC::IEND) { break; } offset += 4 + 4 + length + 4; } unsigned interlacedSize = inflateSize(); uint8_t *interlacedData = new uint8_t[interlacedSize]; bool result = inflate(interlacedData, interlacedSize, compressedData + 2, compressedSize - 6); delete[] compressedData; if(result == false) { delete[] interlacedData; return false; } size = info.width * info.height * info.bytesPerPixel; data = new uint8_t[size]; if(info.interlaceMethod == 0) { if(filter(data, interlacedData, info.width, info.height) == false) { delete[] interlacedData; delete[] data; data = 0; return false; } } else { const uint8_t *passData = interlacedData; for(unsigned pass = 0; pass < 7; pass++) { if(deinterlace(passData, pass) == false) { delete[] interlacedData; delete[] data; data = 0; return false; } } } delete[] interlacedData; return true; } unsigned png::interlace(unsigned pass, unsigned index) { static const unsigned data[7][4] = { //x-distance, y-distance, x-origin, y-origin { 8, 8, 0, 0 }, { 8, 8, 4, 0 }, { 4, 8, 0, 4 }, { 4, 4, 2, 0 }, { 2, 4, 0, 2 }, { 2, 2, 1, 0 }, { 1, 2, 0, 1 }, }; return data[pass][index]; } unsigned png::inflateSize() { if(info.interlaceMethod == 0) { return info.width * info.height * info.bytesPerPixel + info.height; } unsigned size = 0; for(unsigned pass = 0; pass < 7; pass++) { unsigned xd = interlace(pass, 0), yd = interlace(pass, 1); unsigned xo = interlace(pass, 2), yo = interlace(pass, 3); unsigned width = (info.width + (xd - xo - 1)) / xd; unsigned height = (info.height + (yd - yo - 1)) / yd; if(width == 0 || height == 0) continue; size += width * height * info.bytesPerPixel + height; } return size; } bool png::deinterlace(const uint8_t *&inputData, unsigned pass) { unsigned xd = interlace(pass, 0), yd = interlace(pass, 1); unsigned xo = interlace(pass, 2), yo = interlace(pass, 3); unsigned width = (info.width + (xd - xo - 1)) / xd; unsigned height = (info.height + (yd - yo - 1)) / yd; if(width == 0 || height == 0) return true; unsigned outputSize = width * height * info.bytesPerPixel; uint8_t *outputData = new uint8_t[outputSize]; bool result = filter(outputData, inputData, width, height); const uint8_t *rd = outputData; for(unsigned y = yo; y < info.height; y += yd) { uint8_t *wr = data + y * info.pitch; for(unsigned x = xo; x < info.width; x += xd) { for(unsigned b = 0; b < info.bytesPerPixel; b++) { wr[x * info.bytesPerPixel + b] = *rd++; } } } inputData += outputSize + height; delete[] outputData; return result; } bool png::filter(uint8_t *outputData, const uint8_t *inputData, unsigned width, unsigned height) { uint8_t *wr = outputData; const uint8_t *rd = inputData; int bpp = info.bytesPerPixel, pitch = width * bpp; for(int y = 0; y < height; y++) { uint8_t filter = *rd++; switch(filter) { case 0x00: //None for(int x = 0; x < pitch; x++) { wr[x] = rd[x]; } break; case 0x01: //Subtract for(int x = 0; x < pitch; x++) { wr[x] = rd[x] + (x - bpp < 0 ? 0 : wr[x - bpp]); } break; case 0x02: //Above for(int x = 0; x < pitch; x++) { wr[x] = rd[x] + (y - 1 < 0 ? 0 : wr[x - pitch]); } break; case 0x03: //Average for(int x = 0; x < pitch; x++) { short a = x - bpp < 0 ? 0 : wr[x - bpp]; short b = y - 1 < 0 ? 0 : wr[x - pitch]; wr[x] = rd[x] + (uint8_t)((a + b) / 2); } break; case 0x04: //Paeth for(int x = 0; x < pitch; x++) { short a = x - bpp < 0 ? 0 : wr[x - bpp]; short b = y - 1 < 0 ? 0 : wr[x - pitch]; short c = x - bpp < 0 || y - 1 < 0 ? 0 : wr[x - pitch - bpp]; short p = a + b - c; short pa = p > a ? p - a : a - p; short pb = p > b ? p - b : b - p; short pc = p > c ? p - c : c - p; uint8_t paeth = (uint8_t)((pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c); wr[x] = rd[x] + paeth; } break; default: //Invalid return false; } rd += pitch; wr += pitch; } return true; } unsigned png::read(const uint8_t *data, unsigned length) { unsigned result = 0; while(length--) result = (result << 8) | (*data++); return result; } unsigned png::readbits(const uint8_t *&data) { unsigned result = 0; switch(info.bitDepth) { case 1: result = (*data >> bitpos) & 1; bitpos++; if(bitpos == 8) { data++; bitpos = 0; } break; case 2: result = (*data >> bitpos) & 3; bitpos += 2; if(bitpos == 8) { data++; bitpos = 0; } break; case 4: result = (*data >> bitpos) & 15; bitpos += 4; if(bitpos == 8) { data++; bitpos = 0; } break; case 8: result = *data++; break; case 16: result = (data[0] << 8) | (data[1] << 0); data += 2; break; } return result; } png::png() : data(nullptr) { bitpos = 0; } png::~png() { if(data) delete[] data; } } #endif 0 /* * Copyright (c) 2022 Fachgebiet Simulation, Systemoptimierung und Robotik, TU Darmstadt. * * This file is part of RoboTrace * (see https://github.com/tu-darmstadt-ros-pkg/robo_trace) * and is governed by a BSD-style license * that can be found in the LICENSE file. */ #pragma once // Std #include #include // Mongo #include "robo_trace/config.h" #include // Project #include "robo_trace/storage/container.hpp" #include "robo_trace/storage/connector.hpp" #include "robo_trace/processing/stage/stage.hpp" namespace robo_trace { class BlobDecouplingBackwardStage final : public ProcessingStage { public: /** * */ BlobDecouplingBackwardStage(const std::shared_ptr& connection, const std::string& database); /** * */ virtual ~BlobDecouplingBackwardStage(); /** * */ virtual ProcessingMode getMode() const final override; /** * */ virtual void process(const ProcessingContext::Ptr& context) final override; private: /** * */ void couple(mongo::BSONObjBuilder& builder_decoupled, const mongo::BSONObj& serialized); private: /** */ const std::string m_database_name; /** */ const std::shared_ptr m_connection; /** */ const std::shared_ptr m_grid_filesystem; }; }// Copyright 2018 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 // // 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 "riegeli/records/skipped_region.h" #include #include #include "absl/strings/str_cat.h" namespace riegeli { std::string SkippedRegion::ToString() const { return absl::StrCat("[", begin_, ", ", end_, "): ", message_); } std::ostream& operator<<(std::ostream& out, const SkippedRegion& skipped_region) { return out << skipped_region.ToString(); } } // namespace riegeli amedayo/audacity /********************************************************************** Audacity: A Digital Audio Editor TrackPanelResizeHandle.cpp split from TrackPanel.cpp **********************************************************************/ #include "Audacity.h" #include "TrackPanelResizeHandle.h" #include "MemoryX.h" #include #include #include "HitTestResult.h" #include "Project.h" #include "RefreshCode.h" #include "Track.h" #include "TrackPanelMouseEvent.h" #include "tracks/ui/TrackControls.h" HitTestPreview TrackPanelResizeHandle::HitPreview(bool bLinked) { // TODO: more-than-two-channels-message static wxCursor resizeCursor{ wxCURSOR_SIZENS }; /// When in the resize area we can adjust size or relative size. // Check to see whether it is the first channel of a stereo track if (bLinked) { // If we are in the label we got here 'by mistake' and we're // not actually in the resize area at all. (The resize area // is shorter when it is between stereo tracks). return { _("Click and drag to adjust relative size of stereo tracks."), &resizeCursor }; } else { return { _("Click and drag to resize the track."), &resizeCursor }; } } TrackPanelResizeHandle::~TrackPanelResizeHandle() { } UIHandle::Result TrackPanelResizeHandle::Click (const TrackPanelMouseEvent &WXUNUSED(evt), AudacityProject *WXUNUSED(pProject)) { return RefreshCode::RefreshNone; } TrackPanelResizeHandle::TrackPanelResizeHandle ( const std::shared_ptr &track, int y ) : mpTrack{ track } , mMouseClickY( y ) { // TODO: more-than-two-channels //STM: Determine whether we should rescale one or two tracks auto channels = TrackList::Channels(track.get()); auto last = *channels.rbegin(); mInitialTrackHeight = last->GetHeight(); mInitialActualHeight = last->GetActualHeight(); mInitialMinimized = last->GetMinimized(); if (channels.size() > 1) { auto first = *channels.begin(); mInitialUpperTrackHeight = first->GetHeight(); mInitialUpperActualHeight = first->GetActualHeight(); if (track.get() == *channels.rbegin()) // capturedTrack is the lowest track mMode = IsResizingBelowLinkedTracks; else // capturedTrack is not the lowest track mMode = IsResizingBetweenLinkedTracks; } else mMode = IsResizing; } UIHandle::Result TrackPanelResizeHandle::Drag (const TrackPanelMouseEvent &evt, AudacityProject *pProject) { auto pTrack = pProject->GetTracks()->Lock(mpTrack); if ( !pTrack ) return RefreshCode::Cancelled; const wxMouseEvent &event = evt.event; TrackList *const tracks = pProject->GetTracks(); int delta = (event.m_y - mMouseClickY); // On first drag, jump out of minimized mode. Initial height // will be height of minimized track. // // This used to be in HandleResizeClick(), but simply clicking // on a resize border would switch the minimized state. if (pTrack->GetMinimized()) { auto channels = TrackList::Channels( pTrack.get() ); for (auto channel : channels) { channel->SetHeight(channel->GetHeight()); channel->SetMinimized(false); } if (channels.size() > 1) { // Initial values must be reset since they weren't based on the // minimized heights. mInitialUpperTrackHeight = (*channels.begin())->GetHeight(); mInitialTrackHeight = (*channels.rbegin())->GetHeight(); } } // Common pieces of code for MONO_WAVE_PAN and otherwise. auto doResizeBelow = [&] (Track *prev, bool WXUNUSED(vStereo)) { // TODO: more-than-two-channels double proportion = static_cast < double >(mInitialTrackHeight) / (mInitialTrackHeight + mInitialUpperTrackHeight); int newTrackHeight = static_cast < int > (mInitialTrackHeight + delta * proportion); int newUpperTrackHeight = static_cast < int > (mInitialUpperTrackHeight + delta * (1.0 - proportion)); //make sure neither track is smaller than its minimum height if (newTrackHeight < pTrack->GetMinimizedHeight()) newTrackHeight = pTrack->GetMinimizedHeight(); if (newUpperTrackHeight < prev->GetMinimizedHeight()) newUpperTrackHeight = prev->GetMinimizedHeight(); pTrack->SetHeight(newTrackHeight); prev->SetHeight(newUpperTrackHeight); }; auto doResizeBetween = [&] (Track *next, bool WXUNUSED(vStereo)) { // TODO: more-than-two-channels int newUpperTrackHeight = mInitialUpperTrackHeight + delta; int newTrackHeight = mInitialTrackHeight - delta; // make sure neither track is smaller than its minimum height if (newTrackHeight < next->GetMinimizedHeight()) { newTrackHeight = next->GetMinimizedHeight(); newUpperTrackHeight = mInitialUpperTrackHeight + mInitialTrackHeight - next->GetMinimizedHeight(); } if (newUpperTrackHeight < pTrack->GetMinimizedHeight()) { newUpperTrackHeight = pTrack->GetMinimizedHeight(); newTrackHeight = mInitialUpperTrackHeight + mInitialTrackHeight - pTrack->GetMinimizedHeight(); } pTrack->SetHeight(newUpperTrackHeight); next->SetHeight(newTrackHeight); }; auto doResize = [&] { int newTrackHeight = mInitialTrackHeight + delta; if (newTrackHeight < pTrack->GetMinimizedHeight()) newTrackHeight = pTrack->GetMinimizedHeight(); pTrack->SetHeight(newTrackHeight); }; //STM: We may be dragging one or two (stereo) tracks. // If two, resize proportionally if we are dragging the lower track, and // adjust compensatively if we are dragging the upper track. switch( mMode ) { case IsResizingBelowLinkedTracks: { auto prev = * -- tracks->Find(pTrack.get()); doResizeBelow(prev, false); break; } case IsResizingBetweenLinkedTracks: { auto next = * ++ tracks->Find(pTrack.get()); doResizeBetween(next, false); break; } case IsResizing: { doResize(); break; } default: // don't refresh in this case. return RefreshCode::RefreshNone; } return RefreshCode::RefreshAll; } HitTestPreview TrackPanelResizeHandle::Preview (const TrackPanelMouseState &, const AudacityProject *) { return HitPreview(mMode == IsResizingBetweenLinkedTracks); } UIHandle::Result TrackPanelResizeHandle::Release (const TrackPanelMouseEvent &, AudacityProject *pProject, wxWindow *) { /// This happens when the button is released from a drag. /// Since we actually took care of resizing the track when /// we got drag events, all we have to do here is clean up. /// We also modify the undo state (the action doesn't become /// undo-able, but it gets merged with the previous undo-able /// event). pProject->ModifyState(false); return RefreshCode::FixScrollbars; } UIHandle::Result TrackPanelResizeHandle::Cancel(AudacityProject *pProject) { auto pTrack = pProject->GetTracks()->Lock(mpTrack); if ( !pTrack ) return RefreshCode::Cancelled; TrackList *const tracks = pProject->GetTracks(); switch (mMode) { case IsResizing: { pTrack->SetHeight(mInitialActualHeight); pTrack->SetMinimized(mInitialMinimized); } break; case IsResizingBetweenLinkedTracks: { Track *const next = * ++ tracks->Find(pTrack.get()); pTrack->SetHeight(mInitialUpperActualHeight); pTrack->SetMinimized(mInitialMinimized); next->SetHeight(mInitialActualHeight); next->SetMinimized(mInitialMinimized); } break; case IsResizingBelowLinkedTracks: { Track *const prev = * -- tracks->Find(pTrack.get()); pTrack->SetHeight(mInitialActualHeight); pTrack->SetMinimized(mInitialMinimized); prev->SetHeight(mInitialUpperActualHeight); prev->SetMinimized(mInitialMinimized); } break; } return RefreshCode::RefreshAll; } // This file is subject to the terms and conditions defined in the file 'LICENSE.txt'. #ifndef NSMEM_MEM_DEFINES_HPP #define NSMEM_MEM_DEFINES_HPP #include // std::size_t #include // std::int32_t #ifndef mem_inline # ifdef _MSC_VER # define mem_inline __forceinline # else # define mem_inline inline # endif #endif #ifndef mem_snprintf # ifdef _MSC_VER # define mem_snprintf std::snprintf # else # define mem_snprintf std::snprintf # endif #endif #ifndef mem_assert #include # define mem_assert( TEST ) assert( TEST ) #endif #ifndef mem_decltype # define mem_decltype( EXPR ) decltype( EXPR ) #endif namespace mem { typedef unsigned char mbyte; typedef std::uint32_t msize; namespace _impl { union Browser { void * address; mbyte * pByte; msize * pSize; }; } mem_inline std::size_t GB( double size ) { return static_cast< std::size_t >( (size * 1024.0 * 1024.0 * 1024.0 ) + 0.5 ); } mem_inline std::size_t MB( double size ) { return static_cast< std::size_t >( (size * 1024.0 * 1024.0 ) + 0.5 ); } mem_inline std::size_t KB( double size ) { return static_cast< std::size_t >( (size * 1024.0 ) + 0.5 ); } mem_inline std::size_t B( std::size_t size ) { return size; } struct LogInfo; } #endif // NSMEM_MEM_DEFINES_HPP #include "tracklist.h" #include #include bool TrackList::binarySearch(const QDateTime time, int &a, int &b) { if (b < a) return false; // qDebug() << "bs:" << time << ":" << this->at(a).time << "," << this->at(b).time; if (b - a <= 1) { return true; } if (time < this->at(a).time) { return false; } if (time > this->at(b).time) { return false; } int x = (a + b) / 2; if (time >= this->at(x).time) { a = x; } else { b = x; } return binarySearch(time, a, b); } TrackPoint TrackList::search(QDateTime time) { int a = 0, b = this->size() - 1; if (binarySearch(time, a, b)) { return TrackPoint::interpolate(this->at(a), this->at(b), time); } else { TrackPoint a; return a; } } Mime.cpp // // Created by cheng on 2019/4/28. // #include #include #include "Mime.h" using namespace std; Mime::Mime() = default; Mime::~Mime() = default; void Mime::insert(const string &ext, const string &type) { mimeMap.emplace(ext, type); } const string &Mime::getType(const string &filename) const { size_t pos = filename.find_last_of('.'); if (pos == string::npos) { return defaultType; } pos++; string ext = filename.substr(pos); for_each(ext.begin(), ext.end(), ::tolower); auto &&it = mimeMap.find(ext); if (it != mimeMap.end()) { return it->second; } return defaultType; } void Mime::setDefaultType(const string &type) { defaultType = type; } TonyBrewer/OpenHT10-100 /* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT toolset located at: * * https://github.com/TonyBrewer/OpenHT * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ #include "CnyHt.h" #include "DsnInfo.h" void CDsnInfo::GenPersBanner(CHtFile &htFile, const char *unitName, const char *dsnName, bool is_h, const char *incName) { if (!htFile) return; char fileBase[256]; sprintf(fileBase, "Pers%s%s", unitName, dsnName); fprintf(htFile, "/*****************************************************************************/\n"); #ifdef _WIN32 fprintf(htFile, "// Generated with htl\n"); #else fprintf(htFile, "// Generated with htl %s-%s (%s)\n", VERSION, VCSREV, BLDDTE); #endif fprintf(htFile, "//\n"); fprintf(htFile, "// Hybrid Thread File - %s.%s\n", fileBase, is_h ? "h" : "cpp"); fprintf(htFile, "//\n"); fprintf(htFile, "/*****************************************************************************/\n"); if (is_h) { fprintf(htFile, "#pragma once\n\n"); fprintf(htFile, "#include \"Pers%sCommon.h\"\n\n", !g_appArgs.IsModuleUnitNamesEnabled() ? unitName : ""); } else { fprintf(htFile, "#include \"Ht.h\"\n"); fprintf(htFile, "\n"); fprintf(htFile, "#define PERS_%s\n", CHtString(dsnName).Upper().c_str()); if (incName) fprintf(htFile, "#include \"Pers%s.h\"\n\n", incName); else fprintf(htFile, "#include \"%s.h\"\n\n", fileBase); } } void CDsnInfo::GenerateBanner(CHtFile &htFile, const char *fileName, bool is_h) { if (!htFile) return; fprintf(htFile, "/*****************************************************************************/\n"); #ifdef _WIN32 fprintf(htFile, "// Generated with htl\n"); #else fprintf(htFile, "// Generated with htl %s-%s (%s)\n", VERSION, VCSREV, BLDDTE); #endif fprintf(htFile, "//\n"); fprintf(htFile, "// Hybrid Thread File - %s\n", fileName); fprintf(htFile, "//\n"); fprintf(htFile, "/*****************************************************************************/\n"); if (is_h) { fprintf(htFile, "#pragma once\n\n"); } } II semester/programming-techniques/labovi/T3/Z4/main.cpp #include #include /* TP 2016/2017: Tutorijal 3, Zadatak 4 Autotestove pisao . Sva pitanja sugestije i prijave gresaka mozete slati na mail: */ std::deque IzdvojiElemente(const std::deque v, bool Vrijednost){ std::deque Novi; for(int x : v){ bool manji = false; if(x<0) { manji=true; x*=-1; } int suma(0); int pamti=x; while(pamti!=0){ int zadnjaCifra = pamti % 10; suma += zadnjaCifra; pamti/=10; } if(manji) x*=-1; if(suma%2==0 && Vrijednost) Novi.push_front(x); // parna suma if(suma%2!=0 && !Vrijednost) Novi.push_front(x); // neparna suma } return Novi; } int main () { int n; std::cout << "Koliko zelite unijeti elemenata: "; std::cin >> n; if(n<=0) { std::cout << "Broj elemenata mora biti veci od 0!"; return 0; } int element; std::deque a; std::deque b; std::deque c; std::cout << "Unesite elemente: "; for(int i=0; i> element; a.push_back(element); } b = IzdvojiElemente(a, true); c = IzdvojiElemente(a, false); for(unsigned int i=0; iinclude/sad/backend/ostream_serializer.hpp // The MIT License (MIT) // // Copyright (c) 2015 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef __SAD__BACKEND_OSTREAM_SERIALIZER__20160213__ #define __SAD__BACKEND_OSTREAM_SERIALIZER__20160213__ #include #include #include #include #include #include "../schema.hpp" #include "../utility.hpp" #include "../tuple_utils.hpp" #include "../type_traits.hpp" #include "../maybe_null.hpp" #include "../container_adapter_helper.hpp" namespace sad { namespace backend { namespace detail { namespace basic_ostream { // declarations // std::basic_string template inline void print_field_value(std::basic_ostream& os, const std::basic_string& s); // char template inline void print_field_value(std::basic_ostream& os, const char& c); // numbers template ::value>::type* = nullptr> inline void print_field_value(std::basic_ostream& os, const T& t); // any object template ::value && !sad::traits::is_maybe_null_v && !sad::traits::has_iterator_v>::type* = nullptr> inline void print_field_value(std::basic_ostream& os, const T& t); // containers (std::list, std::vector, std::deque, std::forward_list ...) template class C, typename T, typename Allocator = std::allocator> inline void print_field_value(std::basic_ostream& os, const C& t); // std::pair template inline void print_field_value(std::basic_ostream& os, const std::pair& p); // std::tuple template inline void print_field_value(std::basic_ostream& os, const std::tuple& t); // sad::maybe_null template inline void print_field_value(std::basic_ostream& os, const sad::maybe_null& mt); // std::array support template class Array, typename T, std::size_t N> inline void print_field_value(std::basic_ostream& os, const Array& a); // std::stack template inline void print_field_value(std::basic_ostream& os, const std::stack& s); // std::queue template inline void print_field_value(std::basic_ostream& os, const std::queue& q); // std::priority_queue template inline void print_field_value(std::basic_ostream& os, const std::priority_queue& pq); // std::unordered_map / std::unorederd_multimap template class UMap, typename Key, typename T, typename Hash = std::hash, typename KeyEqual = std::equal_to, typename Allocator = std::allocator>> inline void print_field_value(std::basic_ostream& os, const UMap& m); // std::map / std::multimap template class Map, typename Key, typename T, typename Compare = std::less, typename Allocator = std::allocator>> inline void print_field_value(std::basic_ostream& os, const Map& m); // std::set / std::multset template class Set, typename Key, typename Compare = std::less, typename Allocator = std::allocator> inline void print_field_value(std::basic_ostream& os, const Set& s); // schema template inline void print_field_value(std::basic_ostream& os, const sad::schema_mapper& schema); // definitions // std::basic_string template inline void print_field_value(std::basic_ostream& os, const std::basic_string& s) { os << "\"" << s << "\""; } // char template inline void print_field_value(std::basic_ostream& os, const char& c) { os << "'" << c << "'"; } // numbers template ::value>::type*> inline void print_field_value(std::basic_ostream& os, const T& t) { if (sad::traits::is_bool_v) { os << std::boolalpha << t; } else { os << t; }; } // any objects template ::value && !sad::traits::is_maybe_null_v && !sad::traits::has_iterator_v>::type*> inline void print_field_value(std::basic_ostream& os, const T& t) { print_field_value(os, sad::schema()(t)); } // containers template class C, typename T, typename Allocator> inline void print_field_value(std::basic_ostream& os, const C& t) { auto first = true; os << "["; std::for_each(t.cbegin(), t.cend(), [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } print_field_value(os, e); }); os << "]"; } // pairs template inline void print_field_value(std::basic_ostream& os, const std::pair& p) { os << "{'first': "; print_field_value(os, p.first); os << ", 'second': "; print_field_value(os, p.second); os << "}"; } // tuples template inline void print_field_value(std::basic_ostream& os, const std::tuple& t) { auto first = true; os << "("; auto f = [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } print_field_value(os, e); }; sad::tuple_utils::for_each(t, f); os << ")"; } // sad::maybe_null template inline void print_field_value(std::basic_ostream& os, const sad::maybe_null& mt) { if (mt.is_null()) { os << "null"; } else { print_field_value(os, *mt); } } // std::array support template class Array, typename T, std::size_t N> inline void print_field_value(std::basic_ostream& os, const Array& a) { auto first = true; os << "["; std::for_each(a.cbegin(), a.cend(), [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } print_field_value(os, e); }); os << "]"; } // stack / queue / priority_queue // std::stack template inline void print_field_value(std::basic_ostream& os, const std::stack& s) { auto& c = sad::helper::get_internal_container(s); print_field_value(os, c); } // std::queue template inline void print_field_value(std::basic_ostream& os, const std::queue& q) { auto& c = sad::helper::get_internal_container(q); print_field_value(os, c); } // std::priority_queue template inline void print_field_value(std::basic_ostream& os, const std::priority_queue& pq) { auto& c = sad::helper::get_internal_container(pq); print_field_value(os, c); } // std::unordered_map / std::unorederd_multimap template class UMap, typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator> inline void print_field_value(std::basic_ostream& os, const UMap& m) { auto first = true; os << "{"; std::for_each(m.cbegin(), m.cend(), [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } os << "("; print_field_value(os, e.first); os << ", "; print_field_value(os, e.second); os << ")"; }); os << "}"; } // std::unordered_map / std::unorederd_multimap template class Map, typename Key, typename T, typename KeyEqual, typename Allocator> inline void print_field_value(std::basic_ostream& os, const Map& m) { auto first = true; os << "{"; std::for_each(m.cbegin(), m.cend(), [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } os << "("; print_field_value(os, e.first); os << ", "; print_field_value(os, e.second); os << ")"; }); os << "}"; } // std::set / std::multset template class Set, typename Key, typename Compare, typename Allocator> inline void print_field_value(std::basic_ostream& os, const Set& s) { auto first = true; os << "{"; std::for_each(s.cbegin(), s.cend(), [&first, &os](const auto& e) { if (not first) { os << ", "; } else { first = false; } print_field_value(os, e); }); os << "}"; } template inline void print_field_value(std::basic_ostream& os, const sad::schema_mapper& schema) { auto first = true; os << "{"; schema.for_each([&first, &os](const auto& f) { if (not first) { os << ", "; } else { first = false; } os << "'" << f.name << "': "; detail::basic_ostream::print_field_value(os, f.value); }); os << "}"; } }} template > struct basic_ostream_serializer { private: std::basic_ostream& out; bool pretty_ = false; public: using serialized_type = std::basic_ostream&; basic_ostream_serializer() = delete; basic_ostream_serializer(std::basic_ostream& os) : out(os) {} ~basic_ostream_serializer() = default; basic_ostream_serializer& pretty(bool pretty_ = true) { this->pretty_ = pretty_; return *this; } template std::basic_ostream& serialize(const T& value) { detail::basic_ostream::print_field_value(this->out, sad::schema()(value)); return this->out; } }; // basic serializers using ostream_serializer = basic_ostream_serializer; using wostream_serializer = basic_ostream_serializer; // same as std::cout static ostream_serializer cout_serializer{std::cout}; }} #endif/*! * Copyright (c) 2017 by Contributors * \file packed_func_ext.cc * \brief Registeration of extension type. */ #include #include #include #include #include #include #include "./node_attr.h" #include "compile_engine.h" namespace tvm { namespace runtime { TVM_REGISTER_EXT_TYPE(nnvm::Graph); TVM_REGISTER_EXT_TYPE(nnvm::Symbol); TVM_REGISTER_EXT_TYPE(nnvm::compiler::AttrDict); } // namespace runtime } // namespace tvm namespace nnvm { DMLC_JSON_ENABLE_ANY(int, int); } // namespace nnvm namespace nnvm { namespace compiler { using tvm::Tensor; using tvm::Array; using tvm::Node; using tvm::runtime::TVMArgs; using tvm::runtime::TVMRetValue; TVM_REGISTER_GLOBAL("nnvm.compiler._dict_get") .set_body([](TVMArgs args, TVMRetValue *rv) { const AttrDict& dict = args[0].AsExtension(); std::string key = args[1]; auto it = dict.find(key); if (it != dict.end()) { *rv = it->second; } else { *rv = nullptr; } }); TVM_REGISTER_GLOBAL("nnvm.compiler._dict_size") .set_body([](TVMArgs args, TVMRetValue *rv) { const AttrDict& dict = args[0].AsExtension(); *rv = static_cast(dict.size()); }); TVM_REGISTER_GLOBAL("nnvm.compiler._dict_keys") .set_body([](TVMArgs args, TVMRetValue *rv) { const AttrDict& dict = args[0].AsExtension(); tvm::Array keys; for (const auto& kv : dict) { keys.push_back(kv.first); } *rv = keys; }); TVM_REGISTER_GLOBAL("nnvm.compiler._register_alter_op_layout") .set_body([](TVMArgs args, TVMRetValue *rv) { // Intentionally copy and not de-allocate it, to avoid free pyobject during shutdown PackedFunc* f = new PackedFunc(args[1].operator PackedFunc()); Op& op = ::dmlc::Registry::Get()->__REGISTER_OR_GET__(args[0]); auto fpack = [f](const NodeAttrs& attrs, const Symbol& inputs, const Array& tinfos, Symbol* ret_symbol) { TVMRetValue ret = (*f)(GetAttrDict(attrs), inputs, tinfos); if (ret.type_code() == TVMTypeCode::kNull) { return false; } CHECK_EQ(ret.type_code(), tvm::runtime::extension_class_info::code) << " expected " << "Symbol (code = " << tvm::runtime::extension_class_info::code << ") but get code = " << ret.type_code(); *ret_symbol = *(static_cast(ret.value().v_handle)); return true; }; op.set_attr("FTVMAlterOpLayout", fpack, args[2]); }); // custom version of TVM compute TVM_REGISTER_GLOBAL("nnvm._register_compute") .set_body([](TVMArgs args, TVMRetValue *rv) { // Intentionally copy and not de-allocate it, to avoid free pyobject during shutdown PackedFunc* f = new PackedFunc(args[1].operator PackedFunc()); Op& op = ::dmlc::Registry::Get()->__REGISTER_OR_GET__(args[0]); auto fcompute = [f](const NodeAttrs& attrs, const Array& inputs, const Array& out_info) -> Array { TVMRetValue ret = (*f)(GetAttrDict(attrs), inputs, out_info); if ((*ret.ptr >())->derived_from()) { return {ret.operator Tensor()}; } else { return ret; } }; op.set_attr("FTVMCompute", fcompute, args[2]); }); TVM_REGISTER_GLOBAL("nnvm._register_schedule") .set_body([](TVMArgs args, TVMRetValue *rv) { // Intentionally copy and not de-allocate it, to avoid free pyobject during shutdown PackedFunc* f = new PackedFunc(args[1].operator PackedFunc()); Op& op = ::dmlc::Registry::Get()->__REGISTER_OR_GET__(args[0]); auto fschedule = [f](const NodeAttrs& attrs, const Array& outs, const std::string& target) { return (*f)(GetAttrDict(attrs), outs, target).operator Schedule(); }; op.set_attr("FTVMSchedule", fschedule, args[2]); }); TVM_REGISTER_GLOBAL("nnvm._register_pattern") .set_body([](TVMArgs args, TVMRetValue *rv) { Op& op = ::dmlc::Registry::Get()->__REGISTER_OR_GET__(args[0]); op.set_attr("TOpPattern", args[1].operator int(), args[2]); }); TVM_REGISTER_GLOBAL("nnvm.graph._move_module") .set_body([](TVMArgs args, TVMRetValue *rv) { const nnvm::Graph& g = args[0].AsExtension(); *rv = const_cast(&g)-> MoveCopyAttr(args[1]); }); TVM_REGISTER_GLOBAL("nnvm.graph._move_graph") .set_body([](TVMArgs args, TVMRetValue *rv) { const nnvm::Graph& g = args[0].AsExtension(); std::string key = args[1]; if (g.attrs.count(key)) { *rv = const_cast(&g)-> MoveCopyAttr(key); } else { *rv = nullptr; } }); } // namespace compiler } // namespace nnvm #ifndef _MEMORYMANAGER_H_ #define _MEMORYMANAGER_H_ #include "common.hh" #include "utils.hh" #include "objects.hh" #include #include #include HASH_SET_H _START_LAMBDACHINE_NAMESPACE class MemoryManager; class Capability; // Only one OS thread should allocate to each block. class Block { public: // Start of data in this block. inline char *start() const { return start_; } // First free byte in the block. inline char *free() const { return free_; } // Points past last free byte. inline char *end() const { return end_; } // Size of block in bytes. inline size_t size() const { return (size_t)(end() - start()); } // Allocate a number of bytes in this block. Returns NULL // if no room left. inline char *alloc(size_t bytes) { char *ptr = free_; free_ += bytes; if (LC_UNLIKELY(free_ > end_)) { free_ = ptr; return NULL; } return ptr; } static const int kBlockSizeLog2 = 15; // 32K static const size_t kBlockSize = ((size_t)1) << kBlockSizeLog2; static const Word kBlockMask = kBlockSize - 1; #define DEFINE_CONTENT_TYPE(_) \ _(Uninitialized, FREE) \ _(Closures, HEAP) \ _(StaticClosures, STAT) \ _(InfoTables, INFO) \ _(Strings, STRG) \ _(Bytecode, CODE) \ _(Metadata, META) typedef enum { #define DEF_CONTENT_CONST(name, shortname) k##name, DEFINE_CONTENT_TYPE(DEF_CONTENT_CONST) kMaxContentType, #undef DEF_CONTENT_CONST kContentsMask = 0xff, kScavenged = 0x100, kFull = 0x200, } Flags; inline Flags flags() const { return static_cast(flags_); } inline bool getFlag(Flags flag) const { return flags_ & (uint32_t)flag; } inline Flags contents() const { return static_cast(flags_ & kContentsMask); } friend std::ostream& operator<<(std::ostream&, const Block&); private: friend class Region; friend class MemoryManager; Block() {}; // Hidden ~Block() {}; inline void setFlag(Flags flag) { flags_ |= (uint32_t)flag; } inline void clearFlag(Flags flag) { flags_ &= ~((uint32_t)flag); } inline void markAsFree() { flags_ = (uint32_t)Block::kUninitialized; free_ = start_; #if !defined(NDEBUG) memset(free_, 0, end_ - free_); #endif } void operator delete(void *) {}; // Forbid deleting Blocks char *start_; char *end_; char *free_; Block *link_; uint32_t flags_; #if LC_ARCH_BITS == 64 uint32_t padding; #endif }; class Region { public: typedef enum { kSmallObjectRegion = 1, // The region is subdivided into blocks. kLargeObjectRegion // The region contains large objects. } RegionType; static const int kRegionSizeLog2 = 20; /* 1MB */ static const size_t kRegionSize = 1UL << kRegionSizeLog2; static const Word kBlocksPerRegion = kRegionSize / Block::kBlockSize; static const Word kRegionMask = kRegionSize - 1; // Allocate a new memory region from the OS. static Region *newRegion(RegionType); static inline char* alignToRegionBoundary(char *ptr) { Word w = reinterpret_cast(ptr); return reinterpret_cast(roundUpToPowerOf2(kRegionSizeLog2, w)); }; static inline char* alignToBlockBoundary(char *ptr) { Word w = reinterpret_cast(ptr); return reinterpret_cast (roundUpToPowerOf2(Block::kBlockSizeLog2, w)); }; static inline Region *regionFromPointer(void *p) { return reinterpret_cast((Word)p & ~kRegionMask); } static inline Block *blockFromPointer(void *p) { Region *r = regionFromPointer(p); LC_ASSERT(r->isSmallObjectRegion()); SmallObjectRegionData *rd = r->smallSelf(); Word index = ((Word)p & kRegionMask) >> Block::kBlockSizeLog2; LC_ASSERT(0 <= index && index < kBlocksPerRegion); return &rd->blocks_[index]; } // Unlink and return a free block from the region. // // Returns NULL if this region has no more free blocks. Block *grabFreeBlock(); static void operator delete(void *p); ~Region(); friend std::ostream& operator<<(std::ostream& out, const Region&); friend std::ostream& operator<<(std::ostream& out, const MemoryManager&); inline const char *regionId() const { return (const char*)this; } static inline Word maxLargeObjectSize() { return kRegionSize - sizeof(LargeObjectRegionData) - sizeof(LargeObject); } private: Region() {} // Hidden typedef struct { Word magic_; Word region_info_; Region *region_link_; } RegionHeader; typedef struct _SmallObjectRegionData { RegionHeader header_; Block blocks_[Region::kBlocksPerRegion]; Block *next_free_; } SmallObjectRegionData; typedef struct { RegionHeader header_; char *end_; char *free_; } LargeObjectRegionData; inline bool isSmallObjectRegion() const { return meta_.region_info_ == kSmallObjectRegion; } inline bool isLargeObjectRegion() const { return meta_.region_info_ == kLargeObjectRegion; } static void initBlocks(SmallObjectRegionData *); inline bool inRegion(void *p) { return (void *)this <= p && p < (void *)((char *)this + kRegionSize); } inline SmallObjectRegionData *smallSelf() const { LC_ASSERT(isSmallObjectRegion()); return (SmallObjectRegionData *)&meta_; } inline LargeObjectRegionData *largeSelf() const { LC_ASSERT(!isSmallObjectRegion()); return (LargeObjectRegionData *)&meta_; } #define REGION_MAGIC 0x7413828213897431UL // Pointers Regions are cast to the proper region metadata type. RegionHeader meta_; friend class MemoryManager; }; class AllocInfoTableHandle; // forward decl class MemoryManager { // void *allocInfoTable(Word nwords); public: MemoryManager(); ~MemoryManager(); InfoTable *allocInfoTable(AllocInfoTableHandle&, Word nwords); inline char *allocString(size_t length) { return reinterpret_cast(allocInto(&strings_, length + 1)); } inline Closure *allocStaticClosure(size_t payloadSize) { return static_cast (allocInto(&static_closures_, (wordsof(ClosureHeader) + payloadSize) * sizeof(Word))); } inline void *allocCode(size_t instrs, size_t bitmaps) { return allocInto(&bytecode_, sizeof(BcIns) * instrs + sizeof(u2) * bitmaps); } inline Closure *allocClosure(InfoTable *info, size_t payloadWords) { Closure *cl = reinterpret_cast (allocInto(&closures_, (wordsof(ClosureHeader) + payloadWords) * sizeof(Word))); Closure::initHeader(cl, info); return cl; } bool looksLikeInfoTable(void *p); bool looksLikeClosure(void *p); unsigned int infoTables(); friend std::ostream& operator<<(std::ostream& out, const MemoryManager&); void debugPrint(); inline uint64_t allocated() const { return allocated_; } inline uint32_t numGCs() const { return num_gcs_; }; static const u4 kNoMask = ~0; inline void setTopOfStackMask(u4 mask) { topOfStackMask_ = mask; }; static const u4 kDefaultGCTrigger = 2; // blocks inline bool gcInProgress() const { return nextGC_ == 0; } // TODO: This API should be made better or private. inline void setNextGC(u4 blocks) { LC_ASSERT(blocks > 0); nextGC_ = blocks; } inline void setMinHeapSize(size_t bytes) { minHeapSize_ = idivCeil(bytes, Block::kBlockSize); if (minHeapSize_ < 2) minHeapSize_ = 2; } private: inline void *allocInto(Block **block, size_t bytes) { char *ptr = (*block)->alloc(bytes); while (LC_UNLIKELY(ptr == NULL)) { blockFull(block); ptr = (*block)->alloc(bytes); } allocated_ += bytes; return ptr; } inline bool isGCd(Block *block) const { return block->contents() == Block::kClosures; } friend class Capability; // There must not be any other allocation occurring to this block. inline void getBumpAllocatorBounds(char **heap, char **heaplim) { *heap = closures_->free(); *heaplim = closures_->end(); LC_ASSERT(isWordAligned(*heap)); LC_ASSERT(isWordAligned(*heaplim)); } inline void sync(char *heap, char *heaplim) { // heaplim == NULL can happen if we want to force a thread to // yield. LC_ASSERT(heaplim == NULL || heaplim == closures_->end()); LC_ASSERT(closures_->free() <= heap && heap <= closures_->end()); allocated_ += static_cast(heap - closures_->free()); closures_->free_ = heap; } void bumpAllocatorFull(char **heap, char **heaplim, Capability *cap); // Returns non-zero if GC is necessary. If result is 0, then *heap // and *heaplim point to a new block. int bumpAllocatorFullNoGC(char **heap, char **heaplim); bool markBlockReadOnly(const Block *block); bool markBlockReadWrite(const Block *block); Block *grabFreeBlock(Block::Flags); void blockFull(Block **); void performGC(Capability *cap); void scavengeStack(Word *base, Word *top, const BcIns *pc); void scavengeFrame(Word *base, Word *top, const u2 *bitmask); void scavengeBlock(Block *); void scavengeStaticRoots(Closure *); void scavengeLarge(); void sweepLargeObjects(); Closure *allocLarge(Word nbytes); void evacuate(Closure **); void evacuateLarge(Closure *); # define SEEN_SET_TYPE HASH_NAMESPACE::HASH_SET_CLASS bool sanityCheckClosure(SEEN_SET_TYPE &seen, Closure *cl); bool sanityCheckFrame(SEEN_SET_TYPE &seen, Word *base, Word *top, const u2 *bitmask); bool sanityCheckStack(SEEN_SET_TYPE &seen, Word *base, Word *top, const BcIns *pc); bool sanityCheckStaticRoots(SEEN_SET_TYPE &seen, Closure *cl); void sanityCheckHeap(Capability *cap); bool inRegions(void *p); void beginAllocInfoTable(); void endAllocInfoTable(); Region *region_; Region *largeObjectRegion_; Block *free_; Block *info_tables_; Block *static_closures_; Block *closures_; Block *strings_; Block *bytecode_; Block *old_heap_; // Only non-NULL during GC u4 topOfStackMask_; int beginAllocInfoTableLevel_; LargeObject *largeObjects_; LargeObject *evacuatedLargeObjects_; LargeObject *scavengedLargeObjects_; LargeObject *freeLargeRegions_; uint64_t minHeapSize_; // in blocks u4 nextGC_; // if zero, a GC gets triggered. // Assuming an allocation rate of 16GB/s (pretty high), this counter // will overflow in 2^30 seconds, or about 34 years. That appears // to be fine for now (it's for statistical purposes only). uint64_t allocated_; uint64_t num_gcs_; friend class AllocInfoTableHandle; }; // Utility to avoid lots of system calls during load time. // // When loading a program we allocate a lot of info tables. Once we // are done loading, however, we want to mark memory used by info // tables as read-only. This helps detect memory corruption, for // example. // // The private functions beginAllocInfoTable and endAllocInfoTable // take care of lifting and setting these memory protections and must // always be called in pairs. This class ensures that we always make // both calls. To allocate an info table we must simply construct a // handle on the stack. When the handle goes out of scope, the // destructor takes care of making a matching call. // // { // AllocInfoTableHandle hdl(mm); // itbl = mm.allocInfoTable(hdl, size); // ... // } // class AllocInfoTableHandle { public: AllocInfoTableHandle(MemoryManager &mm) : mm_(mm) { mm_.beginAllocInfoTable(); } ~AllocInfoTableHandle() { mm_.endAllocInfoTable(); } private: MemoryManager &mm_; }; _END_LAMBDACHINE_NAMESPACE #endif /* _MEMORYMANAGER_H_ */ _resources/Extra - Drawing Text/Renderer.cpp /* In this code tutorial, we're going to do something you've probably been wondering how to do for a while, render text! We're going to render text in two slightly different forms - one in orthographic mode (really handy for drawing GUIs) and once in world space (handy for info text above a character or something?) The font is white, so can be tinted to any other colour easily enough. To make the text drawing easy, we're going to use a subclass of Mesh, so text drawing should fit neatly into any program based on this framework :) If you run the program, you should see a line of text in the top left of the screen, drawn in orthographic mode, and a line of text in 'world space', at a position near the origin. The font for this tutorial was generated using a nice easy program obtained from: //http://www.lmnopc.com/bitmapfontbuilder/bitmap-font-builder-download/ We could take this further and use more advanced font generation programs, which support kerning (look it up!), but monospaced fonts are good enough for now! */ #include "Renderer.h" Renderer::Renderer(Window &parent) : OGLRenderer(parent) { camera = new Camera(); //A camera! //Again there's no fancy shader stuff, so it's just tutorial 3 again... currentShader = new Shader(TEXTUREDIR"TexturedVertex.glsl", TEXTUREDIR"TexturedFragment.glsl"); if(!currentShader->LinkProgram()) { return; } /* Just makes a new 'font', a struct containing a texture (of the tahoma font) and how many characters across each axis the font contains. (look at the font texture in paint.net if you don't quite 'get' this) */ basicFont = new Font(SOIL_load_OGL_texture(SHADERDIR"fonts/Tahoma.tga",SOIL_LOAD_AUTO,SOIL_CREATE_NEW_ID,SOIL_FLAG_COMPRESS_TO_DXT),16,16); //The font is not alpha blended! It has a black background. //but that doesn't matter, we can fiddle blend func to do //'additive blending', meaning black won't show up ;) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); init = true; } /* Keep it clean! */ Renderer::~Renderer(void) { delete camera; delete basicFont; } /* Keep it moving! */ void Renderer::UpdateScene(float msec) { camera->UpdateCamera(msec); } void Renderer::RenderScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer glUseProgram(currentShader->GetProgram()); //Enable the shader... //And turn on texture unit 0 glUniform1i(glGetUniformLocation(currentShader->GetProgram(), "diffuseTex"), 0); //Render function to encapsulate our font rendering! DrawText("This is orthographic text!", Vector3(0,0,0), 16.0f); DrawText("This is perspective text!!!!", Vector3(0,0,-1000), 64.0f, true); glUseProgram(0); //That's everything! SwapBuffers(); } /* Draw a line of text on screen. If we were to have a 'static' line of text, we'd probably want to keep the TextMesh around to save processing it every frame, but for a simple demonstration, this is fine... */ void Renderer::DrawText(const std::string &text, const Vector3 &position, const float size, const bool perspective) { //Create a new temporary TextMesh, using our line of text and our font TextMesh* mesh = new TextMesh(text,*basicFont); //This just does simple matrix setup to render in either perspective or //orthographic mode, there's nothing here that's particularly tricky. if(perspective) { modelMatrix = Matrix4::Translation(position) * Matrix4::Scale(Vector3(size,size,1)); viewMatrix = camera->BuildViewMatrix(); projMatrix = Matrix4::Perspective(1.0f,10000.0f,(float)width / (float)height, 45.0f); } else{ //In ortho mode, we subtract the y from the height, so that a height of 0 //is at the top left of the screen, which is more intuitive //(for me anyway...) modelMatrix = Matrix4::Translation(Vector3(position.x,height-position.y, position.z)) * Matrix4::Scale(Vector3(size,size,1)); viewMatrix.ToIdentity(); projMatrix = Matrix4::Orthographic(-1.0f,1.0f,(float)width, 0.0f,(float)height, 0.0f); } //Either way, we update the matrices, and draw the mesh UpdateShaderMatrices(); mesh->Draw(); delete mesh; //Once it's drawn, we don't need it anymore! }vitalir2/AlgorithmsCpp #include #include #include #include #include #include #include #include "bst.h" bool height_comp(const std::string& lhs, const std::string& rhs) { std::string_view sv1(lhs); std::string_view sv2(rhs); sv1.remove_prefix(sv1.find('=')+1); sv2.remove_prefix(sv2.find('=')+1); sv1.remove_suffix(sv1.rfind(' ')); sv2.remove_suffix(sv2.rfind(' ')); int h1 = std::stoi(std::string(sv1)); int h2 = std::stoi(std::string(sv2)); return h1 < h2; } int main() { BST dic; /* dic.insert(5, 4.5); dic.insert(4, 5.1); dic.insert(1, 2.1); dic.print(std::cout); std::cout << std::endl; std::cout << dic.minKey() << std::endl; dic.deleteElem(1); dic.print(std::cout); */ std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution dist(1, 50); for (int i = 0; i < 10; ++i) { int rdv = dist(gen); dic.insert(rdv, static_cast(rdv)); } dic.insert(25, 25); dic.print(std::cout); std::cout << std::endl; // dic.deleteElem(25); // dic.print(std::cout); // std::cout << std::endl; std::stringstream sstream; dic.printDebug(sstream); std::vector debug_lines; for (std::string line; std::getline(sstream, line);) { debug_lines.push_back(line); } std::sort(debug_lines.begin(), debug_lines.end(), height_comp); std::cout << dic.size() << std::endl; for (const std::string& line: debug_lines) { std::cout << line << std::endl; } /* for (auto x: dic) { std::cout << x << " "; } std::cout << std::endl; */ return 0; } CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493 #include "TransitionsTest.h" #include "../testResource.h" #include "CCConfiguration.h" #define TRANSITION_DURATION (1.2f) class FadeWhiteTransition : public CCTransitionFade { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFade::transitionWithDuration(t, s, ccWHITE); } }; class FlipXLeftOver : public CCTransitionFlipX { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipX::transitionWithDuration(t, s, kOrientationLeftOver); } }; class FlipXRightOver : public CCTransitionFlipX { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipX::transitionWithDuration(t, s, kOrientationRightOver); } }; class FlipYUpOver : public CCTransitionFlipY { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipY::transitionWithDuration(t, s, kOrientationUpOver); } }; class FlipYDownOver : public CCTransitionFlipY { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipY::transitionWithDuration(t, s, kOrientationDownOver); } }; class FlipAngularLeftOver : public CCTransitionFlipAngular { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipAngular::transitionWithDuration(t, s, kOrientationLeftOver); } }; class FlipAngularRightOver : public CCTransitionFlipAngular { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionFlipAngular::transitionWithDuration(t, s, kOrientationRightOver); } }; class ZoomFlipXLeftOver : public CCTransitionZoomFlipX { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipX::transitionWithDuration(t, s, kOrientationLeftOver); } }; class ZoomFlipXRightOver : public CCTransitionZoomFlipX { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipX::transitionWithDuration(t, s, kOrientationRightOver); } }; class ZoomFlipYUpOver : public CCTransitionZoomFlipY { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipY::transitionWithDuration(t, s, kOrientationUpOver); } }; class ZoomFlipYDownOver : public CCTransitionZoomFlipY { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipY::transitionWithDuration(t, s, kOrientationDownOver); } }; class ZoomFlipAngularLeftOver : public CCTransitionZoomFlipAngular { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipAngular::transitionWithDuration(t, s, kOrientationLeftOver); } }; class ZoomFlipAngularRightOver : public CCTransitionZoomFlipAngular { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionZoomFlipAngular::transitionWithDuration(t, s, kOrientationRightOver); } }; class PageTransitionForward : public CCTransitionPageTurn { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionPageTurn::transitionWithDuration(t, s, false); } }; class PageTransitionBackward : public CCTransitionPageTurn { public: static CCTransitionScene* transitionWithDuration(ccTime t, CCScene* s) { return CCTransitionPageTurn::transitionWithDuration(t, s, true); } }; #define MAX_LAYER 37 static std::string transitions[MAX_LAYER] = { "JumpZoomTransition", "FadeTransition", "FadeWhiteTransition", "FlipXLeftOver", "FlipXRightOver", "FlipYUpOver", "FlipYDownOver", "FlipAngularLeftOver", "FlipAngularRightOver", "ZoomFlipXLeftOver", "ZoomFlipXRightOver", "ZoomFlipYUpOver", "ZoomFlipYDownOver", "ZoomFlipAngularLeftOver", "ZoomFlipAngularRightOver", "ShrinkGrowTransition", "RotoZoomTransition", "MoveInLTransition", "MoveInRTransition", "MoveInTTransition", "MoveInBTransition", "SlideInLTransition", "SlideInRTransition", "SlideInTTransition", "SlideInBTransition", "CCTransitionCrossFade", "CCTransitionRadialCCW", "CCTransitionRadialCW", "PageTransitionForward", "PageTransitionBackward", "FadeTRTransition", "FadeBLTransition", "FadeUpTransition", "FadeDownTransition", "TurnOffTilesTransition", "SplitRowsTransition", "SplitColsTransition", }; static int s_nSceneIdx = 0; CCTransitionScene* createTransition(int nIndex, ccTime t, CCScene* s) { switch(nIndex) { case 0: return CCTransitionJumpZoom::transitionWithDuration(t, s); case 1: return CCTransitionFade::transitionWithDuration(t, s); case 2: return FadeWhiteTransition::transitionWithDuration(t, s); case 3: return FlipXLeftOver::transitionWithDuration(t, s); case 4: return FlipXRightOver::transitionWithDuration(t, s); case 5: return FlipYUpOver::transitionWithDuration(t, s); case 6: return FlipYDownOver::transitionWithDuration(t, s); case 7: return FlipAngularLeftOver::transitionWithDuration(t, s); case 8: return FlipAngularRightOver::transitionWithDuration(t, s); case 9: return ZoomFlipXLeftOver::transitionWithDuration(t, s); case 10: return ZoomFlipXRightOver::transitionWithDuration(t, s); case 11: return ZoomFlipYUpOver::transitionWithDuration(t, s); case 12: return ZoomFlipYDownOver::transitionWithDuration(t, s); case 13: return ZoomFlipAngularLeftOver::transitionWithDuration(t, s); case 14: return ZoomFlipAngularRightOver::transitionWithDuration(t, s); case 15: return CCTransitionShrinkGrow::transitionWithDuration(t, s); case 16: return CCTransitionRotoZoom::transitionWithDuration(t, s); case 17: return CCTransitionMoveInL::transitionWithDuration(t, s); case 18: return CCTransitionMoveInR::transitionWithDuration(t, s); case 19: return CCTransitionMoveInT::transitionWithDuration(t, s); case 20: return CCTransitionMoveInB::transitionWithDuration(t, s); case 21: return CCTransitionSlideInL::transitionWithDuration(t, s); case 22: return CCTransitionSlideInR::transitionWithDuration(t, s); case 23: return CCTransitionSlideInT::transitionWithDuration(t, s); case 24: return CCTransitionSlideInB::transitionWithDuration(t, s); case 25: { if (CCConfiguration::sharedConfiguration()->getGlesVersion() <= GLES_VER_1_0) { CCMessageBox("The Opengl ES version is lower than 1.1, and TransitionCrossFade may not run correctly, it is ignored.", "Cocos2d-x Hint"); return NULL; } else { return CCTransitionCrossFade::transitionWithDuration(t,s); } } break; case 26: { if (CCConfiguration::sharedConfiguration()->getGlesVersion() <= GLES_VER_1_0) { CCMessageBox("The Opengl ES version is lower than 1.1, and TransitionRadialCCW may not run correctly, it is ignored.", "Cocos2d-x Hint"); return NULL; } else { return CCTransitionRadialCCW::transitionWithDuration(t,s); } } break; case 27: { if (CCConfiguration::sharedConfiguration()->getGlesVersion() <= GLES_VER_1_0) { CCMessageBox("The Opengl ES version is lower than 1.1, and TransitionRadialCW may not run correctly, it is ignored.", "Cocos2d-x Hint"); return NULL; } else { return CCTransitionRadialCW::transitionWithDuration(t,s); } } break; case 28: return PageTransitionForward::transitionWithDuration(t, s); case 29: return PageTransitionBackward::transitionWithDuration(t, s); case 30: return CCTransitionFadeTR::transitionWithDuration(t, s); case 31: return CCTransitionFadeBL::transitionWithDuration(t, s); case 32: return CCTransitionFadeUp::transitionWithDuration(t, s); case 33: return CCTransitionFadeDown::transitionWithDuration(t, s); case 34: return CCTransitionTurnOffTiles::transitionWithDuration(t, s); case 35: return CCTransitionSplitRows::transitionWithDuration(t, s); case 36: return CCTransitionSplitCols::transitionWithDuration(t, s); default: break; } return NULL; } void TransitionsTestScene::runThisTest() { CCLayer * pLayer = new TestLayer1(); addChild(pLayer); pLayer->release(); // fix bug #486, without setDepthTest(false), FlipX,Y will flickers CCDirector::sharedDirector()->setDepthTest(false); CCDirector::sharedDirector()->replaceScene(this); } TestLayer1::TestLayer1(void) { float x,y; CCSize size = CCDirector::sharedDirector()->getWinSize(); x = size.width; y = size.height; CCSprite* bg1 = CCSprite::spriteWithFile(s_back1); bg1->setPosition( CCPointMake(size.width/2, size.height/2) ); addChild(bg1, -1); CCLabelTTF* title = CCLabelTTF::labelWithString( (transitions[s_nSceneIdx]).c_str(), "Thonburi", 32 ); addChild(title); title->setColor( ccc3(255,32,32) ); title->setPosition( CCPointMake(x/2, y-100) ); CCLabelTTF* label = CCLabelTTF::labelWithString("SCENE 1", "Marker Felt", 38); label->setColor( ccc3(16,16,255)); label->setPosition( CCPointMake(x/2,y/2)); addChild( label); // menu CCMenuItemImage *item1 = CCMenuItemImage::itemFromNormalImage(s_pPathB1, s_pPathB2, this, menu_selector(TestLayer1::backCallback) ); CCMenuItemImage *item2 = CCMenuItemImage::itemFromNormalImage(s_pPathR1, s_pPathR2, this, menu_selector(TestLayer1::restartCallback) ); CCMenuItemImage *item3 = CCMenuItemImage::itemFromNormalImage(s_pPathF1, s_pPathF2, this, menu_selector(TestLayer1::nextCallback) ); CCMenu *menu = CCMenu::menuWithItems(item1, item2, item3, NULL); menu->setPosition( CCPointZero ); item1->setPosition( CCPointMake( size.width/2 - 100,30) ); item2->setPosition( CCPointMake( size.width/2, 30) ); item3->setPosition( CCPointMake( size.width/2 + 100,30) ); addChild(menu, 1); schedule( schedule_selector(TestLayer1::step), 1.0f); } TestLayer1::~TestLayer1(void) { } void TestLayer1::restartCallback(CCObject* pSender) { CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer2(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer1::nextCallback(CCObject* pSender) { s_nSceneIdx++; s_nSceneIdx = s_nSceneIdx % MAX_LAYER; CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer2(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer1::backCallback(CCObject* pSender) { s_nSceneIdx--; int total = MAX_LAYER; if( s_nSceneIdx < 0 ) s_nSceneIdx += total; CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer2(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer1::step(ccTime dt) { } TestLayer2::TestLayer2() { float x,y; CCSize size = CCDirector::sharedDirector()->getWinSize(); x = size.width; y = size.height; CCSprite* bg1 = CCSprite::spriteWithFile(s_back2); bg1->setPosition( CCPointMake(size.width/2, size.height/2) ); addChild(bg1, -1); CCLabelTTF* title = CCLabelTTF::labelWithString((transitions[s_nSceneIdx]).c_str(), "Thonburi", 32 ); addChild(title); title->setColor( ccc3(255,32,32) ); title->setPosition( CCPointMake(x/2, y-100) ); CCLabelTTF* label = CCLabelTTF::labelWithString("SCENE 2", "Marker Felt", 38); label->setColor( ccc3(16,16,255)); label->setPosition( CCPointMake(x/2,y/2)); addChild( label); // menu CCMenuItemImage *item1 = CCMenuItemImage::itemFromNormalImage(s_pPathB1, s_pPathB2, this, menu_selector(TestLayer2::backCallback) ); CCMenuItemImage *item2 = CCMenuItemImage::itemFromNormalImage(s_pPathR1, s_pPathR2, this, menu_selector(TestLayer2::restartCallback) ); CCMenuItemImage *item3 = CCMenuItemImage::itemFromNormalImage(s_pPathF1, s_pPathF2, this, menu_selector(TestLayer2::nextCallback) ); CCMenu *menu = CCMenu::menuWithItems(item1, item2, item3, NULL); menu->setPosition( CCPointZero ); item1->setPosition( CCPointMake( x/2 - 100,30) ); item2->setPosition( CCPointMake( x/2, 30) ); item3->setPosition( CCPointMake( x/2 + 100,30) ); addChild(menu, 1); schedule(schedule_selector(TestLayer2::step), 1.0f); } TestLayer2::~TestLayer2() { } void TestLayer2::restartCallback(CCObject* pSender) { CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer1(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer2::nextCallback(CCObject* pSender) { s_nSceneIdx++; s_nSceneIdx = s_nSceneIdx % MAX_LAYER; CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer1(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer2::backCallback(CCObject* pSender) { s_nSceneIdx--; int total = MAX_LAYER; if( s_nSceneIdx < 0 ) s_nSceneIdx += total; CCScene* s = new TransitionsTestScene(); CCLayer* pLayer = new TestLayer1(); s->addChild(pLayer); CCScene* pScene = createTransition(s_nSceneIdx, TRANSITION_DURATION, s); s->release(); pLayer->release(); if (pScene) { CCDirector::sharedDirector()->replaceScene(pScene); } } void TestLayer2::step(ccTime dt) { } Algo_Ds_Notes-master/Algo_Ds_Notes-master/Number_Of_Islands/Number_Of_Islands.cpp /* Number of Islands Problem is a problem to compute the count of number of disconnected islands present in the sea i.e Given an adjacency matrix, it is count of number of connected components in that graph. */ #include using namespace std; #define C 1000 // Function to perform DFS from a cell void dfs(int i, int j, int adj[][C], int N, int M, bool visited[][C]) { // perform DFS when all the values of i and j // fall within the matrix if (i >= 0 && i < N && j >= 0 && j < M) { /* Check for an edge of the current cell with all the neighbouring 8 cells in the matrix and it is not visited, perform DFS from that cell, and mark the cell as visited. */ if (adj[i][j] == 1 && !visited[i][j]) { visited[i][j] = true; // Cell to the upper left diagonal of current cell dfs(i - 1, j - 1, adj, N, M, visited); // Cell to the upper right diagonal of current cell dfs(i - 1, j + 1, adj, N, M, visited); // Cell to the up of current cell dfs(i - 1, j, adj, N, M, visited); // Cell to the down of current cell dfs(i + 1, j, adj, N, M, visited); // Cell to the left of current cell dfs(i, j - 1, adj, N, M, visited); // Cell to the right of current cell dfs(i, j + 1, adj, N, M, visited); // Cell to the lower left diagonal of current cell dfs(i + 1, j - 1, adj, N, M, visited); // Cell to the lower right diagonal of current cell dfs(i + 1, j + 1, adj, N, M, visited); } } } // Function to compute number of connected components // using Adjacency Matrix Representation of Graph int numberOfIslands(int adj[][C], int N, int M) { // A 2D Matrix to keep track of visited cells // Initialising all cells with false initially bool visited[N][C]; memset(visited, false, N * C * sizeof(visited[0][0])); // Variable for storing count of components of Graphs int components = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { /* if there is an edge between i - j and it is not visited, perform DFS from that cell, then increase the number of connected components by 1. */ if (adj[i][j] == 1 && !visited[i][j]) { dfs(i, j, adj, N, M, visited); components++; } } } return components; } // Driver function int main() { // N is the number of rows // M is the numbers of columns int N, M; cin >> N >> M; // Adjacency Matrix representation of Graph in adj int adj[N][C]; // Taking input of Graph for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) cin >> adj[i][j]; // Call to compute the number of Islands cout << "Number of Islands: "; cout << numberOfIslands(adj, N, M) << endl; return 0; } /* Input: 4 6 1 1 0 0 0 0 0 1 0 0 1 1 0 0 0 0 1 1 1 1 0 0 0 0 Output: Number of Islands: 3 */ cblauvelt/redis-client0 #include #include #include #include #include #include "cpool/awaitable_latch.hpp" #include "redis/client.hpp" #include "redis/command.hpp" #include "redis/commands-hash.hpp" #include "redis/commands-json.hpp" #include "redis/commands-list.hpp" #include "redis/commands-set.hpp" #include "redis/commands-ttl.hpp" #include "redis/commands.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using namespace redis; const std::string DEFAULT_REDIS_HOST = "host.docker.internal"; const std::string DEFAULT_REDIS_PORT = "6379"; std::optional get_env_var(std::string const& key) { char* val = getenv(key.c_str()); return (val == NULL) ? std::nullopt : std::optional(std::string(val)); } void testForError(std::string cmd, const redis::reply& reply) { EXPECT_FALSE(reply.error()) << cmd; if (reply.error() == client_error_code::error) { EXPECT_EQ(reply.value().as().value().what(), std::string()) << cmd; } } void testForValue(std::string cmd, redis::reply reply, redis::value expected) { testForError(cmd, reply); EXPECT_EQ(reply.value(), expected) << "Expected string: " << expected; } void testForValue(std::string cmd, redis::reply reply, const char* expected) { testForValue(cmd, reply, std::string(expected)); } void testForValue(std::string cmd, redis::reply reply, string expected) { testForError(cmd, reply); auto optString = reply.value().as(); EXPECT_TRUE(optString.has_value()) << "Expected string: " << expected; EXPECT_EQ(optString.value(), expected) << "Expected string: " << expected; } void testForValue(std::string cmd, redis::reply reply, int expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optInt = value.as(); EXPECT_TRUE(optInt.has_value()) << cmd; EXPECT_EQ(optInt.value(), expected) << cmd; } void testForValue(std::string cmd, redis::reply reply, float expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optFloat = value.as(); EXPECT_TRUE(optFloat.has_value()) << cmd; EXPECT_FLOAT_EQ(optFloat.value(), expected) << cmd; } void testForValue(std::string cmd, redis::reply reply, double expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optDouble = value.as(); EXPECT_TRUE(optDouble.has_value()) << cmd; EXPECT_DOUBLE_EQ(optDouble.value(), expected) << cmd; } void testForValue(std::string cmd, redis::reply reply, redis::hash expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optHash = value.as(); redis::hash hash; EXPECT_TRUE(optHash.has_value()); EXPECT_NO_THROW(hash = optHash.value()); EXPECT_EQ(hash.size(), expected.size()); for (auto [key, value] : hash) { EXPECT_EQ(value, expected[key]); } } void testForValue(std::string cmd, redis::reply reply, bool expected) { testForError(cmd, reply); redis::value value = reply.value(); EXPECT_EQ(value.as().value(), expected) << cmd; } void testForGE(std::string cmd, redis::reply reply, int expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optInt = value.as(); EXPECT_TRUE(optInt.has_value()) << cmd; EXPECT_GE(optInt.value(), expected) << cmd; } void testForGT(std::string cmd, redis::reply reply, int expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optInt = value.as(); EXPECT_TRUE(optInt.has_value()) << cmd; EXPECT_GT(optInt.value(), expected) << cmd; } void testForLE(std::string cmd, redis::reply reply, int expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optInt = value.as(); EXPECT_TRUE(optInt.has_value()) << cmd; EXPECT_LE(optInt.value(), expected) << cmd; } void testForLT(std::string cmd, redis::reply reply, int expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optInt = value.as(); EXPECT_TRUE(optInt.has_value()) << cmd; EXPECT_LT(optInt.value(), expected) << cmd; } template void testForArray(std::string cmd, redis::reply reply, T expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optArray = value.as(); redis::redis_array array; EXPECT_TRUE(optArray.has_value()) << cmd; EXPECT_NO_THROW(array = optArray.value()) << cmd; EXPECT_EQ(array.size(), expected.size()) << cmd; for (int i = 0; i < array.size(); i++) { // EXPECT_EQ(array[i].type(), expected[i].type()); EXPECT_EQ(array[i], expected[i]); } } template void testForSortedArray(std::string cmd, redis::reply reply, T expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optArray = value.as(); redis::redis_array array; EXPECT_TRUE(optArray.has_value()) << cmd; EXPECT_NO_THROW(array = optArray.value()) << cmd; EXPECT_EQ(array.size(), expected.size()) << cmd; std::sort(array.begin(), array.end()); for (int i = 0; i < array.size(); i++) { // EXPECT_EQ(array[i].type(), expected[i].type()); EXPECT_EQ(array[i], expected[i]); } } void testForArraySize(std::string cmd, redis::reply reply, size_t expected) { testForError(cmd, reply); redis::value value = reply.value(); auto optArray = value.as(); redis::redis_array array; EXPECT_TRUE(optArray.has_value()) << cmd; EXPECT_NO_THROW(array = optArray.value()) << cmd; EXPECT_EQ(array.size(), expected) << cmd; } void testForSuccess(std::string cmd, redis::reply reply) { testForError(cmd, reply); redis::value value = reply.value(); EXPECT_TRUE(value.as().value_or(false)) << cmd; } void testForType(std::string cmd, redis::reply reply, redis::redis_type type) { testForError(cmd, reply); EXPECT_EQ(reply.value().type(), type); } void logMessage(log_level level, string_view message) { cout << message << endl; } awaitable test_basic(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key1 = std::string("basic") + std::to_string(c) + std::string("_1"); string key2 = std::string("basic") + std::to_string(c) + std::string("_2"); string key3 = std::string("basic") + std::to_string(c) + std::string("_3"); redis::reply reply; for (int i = 0; i < 2; i++) { reply = co_await client.send(redis::set(key1, "42")); testForSuccess("SET", reply); reply = co_await client.send(redis::set(key2, "142")); testForSuccess("SET", reply); reply = co_await client.send(get(key1)); testForValue("GET", reply, 42); reply = co_await client.send(exists(key1, key2, key3)); testForValue("EXISTS", reply, 2); reply = co_await client.send(del(key1, key2)); testForValue("DEL", reply, 2); reply = co_await client.send(get(key1)); testForType("GET", reply, redis_type::nil); reply = co_await client.send(publish(key1, "stuff" + to_string(i))); testForType("PUBLISH", reply, redis_type::integer); } barrier.count_down(); co_return; } awaitable run_basic_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_basic(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_ttl(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key = std::string("ttl") + std::to_string(c); redis::reply reply; const auto time_delay_sec = 10s; reply = co_await client.send(redis::ttl(key)); testForValue("TTL", reply, -2); reply = co_await client.send(redis::expire(key, time_delay_sec)); testForValue("EXPIRE", reply, 0); reply = co_await client.send(redis::set(key, "42")); testForSuccess("SET", reply); reply = co_await client.send(redis::ttl(key)); testForValue("TTL", reply, -1); reply = co_await client.send(redis::expire(key, time_delay_sec)); testForValue("EXPIRE", reply, 1); reply = co_await client.send(redis::ttl(key)); testForLE("TTL", reply, time_delay_sec.count()); reply = co_await client.send(redis::persist(key)); testForValue("PERSIST", reply, 1); reply = co_await client.send(redis::persist(key)); testForValue("PERSIST", reply, 0); reply = co_await client.send(del(key)); testForSuccess("DEL", reply); reply = co_await client.send(redis::pexpire(key, time_delay_sec)); testForValue("PEXPIRE", reply, 0); reply = co_await client.send(redis::set(key, "42")); testForSuccess("SET", reply); reply = co_await client.send(redis::pexpire(key, time_delay_sec)); testForValue("PEXPIRE", reply, 1); reply = co_await client.send(redis::pttl(key)); testForLE("PTTL", reply, time_delay_sec.count() * 1000); reply = co_await client.send(del(key)); testForSuccess("DEL", reply); barrier.count_down(); co_return; } awaitable run_ttl_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_ttl(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_pipeline_basic(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key = std::string("foo") + std::to_string(c); redis::commands commands{redis::set(key, "255"), redis::incrby(key, 2), redis::get(key)}; redis::replies replies; for (int i = 0; i < 2; i++) { replies = co_await client.send(commands); EXPECT_EQ(commands.size(), replies.size()); auto reply1 = replies[0]; testForSuccess("SET", reply1); auto reply2 = replies[1]; testForValue("INCRBY", reply2, 257); auto reply3 = replies[2]; testForValue("GET", reply3, 257); } barrier.count_down(); co_return; } awaitable run_pipeline_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_pipeline_basic(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_list(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key = std::string("list") + std::to_string(c); redis::reply reply; auto test_arr = redis::redis_array{ redis::value("field1"), redis::value("42"), redis::value("field2"), redis::value(string_to_vector("Hello")), redis::value("field3"), redis::value(string_to_vector("World"))}; try { reply = co_await client.send(redis::del(key)); for (int i = 0; i < 2; i++) { reply = co_await client.send(redis::rpush(key, std::string("field1"))); testForValue("RPUSH", reply, 1); reply = co_await client.send(redis::rpush(key, test_arr)); testForValue("RPUSH", reply, 7); reply = co_await client.send(redis::lpush(key, std::string("field0"))); testForValue("LPUSH", reply, 8); auto new_arr = redis::redis_array{std::string("field0"), std::string("42")}; reply = co_await client.send(redis::lpush(key, new_arr)); testForValue("LPUSH", reply, 10); reply = co_await client.send(redis::llen(key)); testForValue("LLEN", reply, 10); reply = co_await client.send(redis::lrange(key, 0, 1)); testForArray("LRANGE", reply, std::views::reverse(new_arr)); reply = co_await client.send(redis::lpop(key, 2)); testForArray("LPOP", reply, std::views::reverse(new_arr)); reply = co_await client.send(redis::rpop(key)); testForValue("RPOP", reply, redis::value(string_to_vector("World"))); reply = co_await client.send(redis::blpop(key)); new_arr = redis::redis_array{redis::value(key), redis::value("field0")}; testForArray("BLPOP", reply, new_arr); reply = co_await client.send(redis::brpop(key, 1)); new_arr = redis::redis_array{redis::value(key), redis::value("field3")}; testForArray("RPOP", reply, new_arr); reply = co_await client.send(redis::del(key)); testForValue("DEL", reply, 1); } } catch (const std::exception& ex) { EXPECT_EQ(std::string(), ex.what()); } barrier.count_down(); co_return; } awaitable run_list_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_list(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_hash(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key = std::string("hash") + std::to_string(c); redis::reply reply; auto test_hash = redis::hash{{"field1", redis::value("42")}, {"field2", redis::value("Hello")}, {"field3", redis::value("World")}}; auto test_arr = redis::redis_array{ redis::value("field1"), redis::value("42"), redis::value("field2"), redis::value(string_to_vector("Hello")), redis::value("field3"), redis::value(string_to_vector("World"))}; auto test_keys = redis::redis_array{ redis::value("field1"), redis::value("field2"), redis::value("field3")}; auto test_vals = redis::redis_array{ redis::value("42"), redis::value(string_to_vector("Hello")), redis::value(string_to_vector("World"))}; try { for (int i = 0; i < 2; i++) { reply = co_await client.send( redis::hset(key, "field1", redis::value("42"))); testForValue("HSET", reply, 1); reply = co_await client.send(redis::hset(key, test_hash)); testForValue("HSET", reply, 2); reply = co_await client.send(redis::hget(key, "field2")); testForValue("HGET", reply, (string)test_hash["field2"]); reply = co_await client.send(redis::hgetall(key)); testForType("HGETALL", reply, redis_type::array); testForArray("HGETALL", reply, test_arr); testForValue("HGETALL", reply, test_hash); reply = co_await client.send(redis::hkeys(key)); testForArray("HKEYS", reply, test_keys); reply = co_await client.send(redis::hvals(key)); testForArray("HVALS", reply, test_vals); reply = co_await client.send(redis::hincrby(key, "field1", 1)); testForValue("HINCRBY", reply, 43); reply = co_await client.send(redis::hincrbyfloat(key, "field1", 2.3)); testForValue("HINCRBY", reply, 45.3); reply = co_await client.send(redis::hexists(key, "field1")); testForValue("HEXISTS", reply, true); reply = co_await client.send(redis::hlen(key)); testForValue("HLEN", reply, 3); reply = co_await client.send(redis::hdel(key, "field1")); testForValue("HDEL", reply, 1); reply = co_await client.send(redis::hexists(key, "field1")); testForValue("HEXISTS", reply, false); reply = co_await client.send(redis::hlen(key)); testForValue("HLEN", reply, 2); reply = co_await client.send(redis::del(key)); testForValue("DEL", reply, 1); } } catch (const std::exception& ex) { EXPECT_EQ(std::string(), ex.what()); } barrier.count_down(); co_return; } awaitable run_hash_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_hash(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_set(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key1 = std::string("set") + std::to_string(c) + std::string("1"); string key2 = std::string("set") + std::to_string(c) + std::string("2"); redis::reply reply; try { for (int i = 0; i < 2; i++) { auto newMembers = strings{"Big", "Hello", "World"}; auto testKeyList = strings{key1, key2}; reply = co_await client.send(redis::sadd(key1, "Hello", "World")); testForValue("SADD", reply, 2); reply = co_await client.send(redis::sadd(key1, newMembers)); testForValue("SADD", reply, 1); reply = co_await client.send(redis::smembers(key1)); testForSortedArray("SMEMBERS", reply, newMembers); reply = co_await client.send(redis::srem(key1, "Hello", "World")); testForValue("SADD", reply, 2); reply = co_await client.send(redis::smembers(key1)); testForSortedArray("SMEMBERS", reply, strings{"Big"}); reply = co_await client.send(redis::del(key1)); testForValue("DEL", reply, 1); reply = co_await client.send(redis::sadd(key1, "a", "b", "c")); testForValue("SADD", reply, 3); reply = co_await client.send(redis::sadd(key2, "c", "d", "e")); testForValue("SADD", reply, 3); reply = co_await client.send(redis::sdiff(key1, key2)); testForSortedArray("SDIFF", reply, strings{"a", "b"}); reply = co_await client.send(redis::sdiff(testKeyList)); testForSortedArray("SDIFF", reply, strings{"a", "b"}); reply = co_await client.send(redis::sinter(key1, key2)); testForSortedArray("SINTER", reply, strings{"c"}); reply = co_await client.send(redis::sinter(testKeyList)); testForSortedArray("SINTER", reply, strings{"c"}); reply = co_await client.send(redis::sunion(key1, key2)); testForSortedArray("SUNION ", reply, strings{"a", "b", "c", "d", "e"}); reply = co_await client.send(redis::sunion(testKeyList)); testForSortedArray("SUNION ", reply, strings{"a", "b", "c", "d", "e"}); reply = co_await client.send(redis::spop(key1)); testForType("SPOP", reply, redis_type::bulk_string); reply = co_await client.send(redis::spop(key2, 2)); testForArraySize("SPOP", reply, 2); reply = co_await client.send(redis::del(key1, key2)); testForValue("DEL", reply, 2); } } catch (const std::exception& ex) { EXPECT_EQ(std::string(), ex.what()); } barrier.count_down(); co_return; } awaitable run_set_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); logMessage(redis::log_level::info, host); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_set(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable run_password_tests(asio::io_context& ctx) { const int num_runners = 2; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_PASSWORD_HOST").value_or(DEFAULT_REDIS_HOST); auto portString = get_env_var("REDIS_PASSWORD_PORT").value_or(DEFAULT_REDIS_PORT); int port = std::stoi(portString); auto password = get_env_var("REDIS_PASSWORD").value_or(""); auto config = client_config{}.set_host(host).set_port(port).set_password(password); logMessage(redis::log_level::info, fmt::format("Logging into {}:{} with password {}", config.host, config.port, config.password)); client client(exec, config); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); auto reply = co_await client.ping(); testForValue("PING", reply, "PONG"); EXPECT_TRUE(client.running()); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_basic(client, i, barrier), cpool::detached); } co_await barrier.wait(); ctx.stop(); co_return; } awaitable test_json(client& client, int c, cpool::awaitable_latch& barrier) { auto exec = co_await cpool::net::this_coro::executor; string key1 = std::string("object") + std::to_string(c); string key2 = std::string("amoreinterestingexample") + std::to_string(c); string key3 = std::string("arr") + std::to_string(c); redis::reply reply; for (int i = 0; i < 2; i++) { reply = co_await client.send( json_set(key1, ".", "{\"foo\": \"bar\", \"ans\": 0}")); testForSuccess("JSON_SET", reply); reply = co_await client.send(json_get(key1, ".ans")); testForValue("JSON_GET", reply, 0); reply = co_await client.send(json_type(key1, ".foo")); testForValue("JSON_TYPE", reply, "string"); reply = co_await client.send(json_strlen(key1, ".foo")); testForValue("JSON_STRLEN", reply, 3); reply = co_await client.send(json_strappend(key1, ".foo", "\"baz\"")); testForValue("JSON_STRAPPEND", reply, 6); reply = co_await client.send(json_get(key1, ".foo")); testForValue("JSON_GET", reply, "\"barbaz\""); reply = co_await client.send(json_numincrby(key1, ".ans", "1")); testForValue("JSON_NUMINCRBY", reply, 1); reply = co_await client.send(json_numincrby(key1, ".ans", "1.5")); testForValue("JSON_NUMINCRBY", reply, 2.5F); testForValue("JSON_NUMINCRBY", reply, 2.5); reply = co_await client.send(json_numincrby(key1, ".ans", "-0.75")); testForValue("JSON_NUMINCRBY", reply, 1.75F); testForValue("JSON_NUMINCRBY", reply, 1.75); reply = co_await client.send(json_nummultby(key1, ".ans", "24")); testForValue("JSON_NUMMULRBY", reply, 42); reply = co_await client.send(json_del(key1, ".")); testForSuccess("JSON_DEL", reply); reply = co_await client.send( json_set(key2, ".", "[ true, { \"answer\": 42 }, null ]")); testForSuccess("JSON_SET", reply); reply = co_await client.send(json_get(key2, ".")); testForValue("JSON_GET", reply, "[true,{\"answer\":42},null]"); reply = co_await client.send(json_get(key2, "[1].answer")); testForValue("JSON_GET", reply, 42); reply = co_await client.send(json_del(key2, "[-1]")); testForSuccess("JSON_DEL", reply); reply = co_await client.send(json_get(key2, ".")); testForValue("JSON_GET", reply, "[true,{\"answer\":42}]"); reply = co_await client.send(json_del(key2, ".")); testForSuccess("JSON_DEL", reply); // Test array functions reply = co_await client.send(json_set(key3, ".", "[]")); testForSuccess("JSON_SET", reply); reply = co_await client.send(json_arrappend(key3, ".", "0")); testForValue("JSON.ARRAPPEND", reply, 1); reply = co_await client.send(json_get(key3, ".")); testForValue("JSON.GET", reply, "[0]"); std::vector values{"0", "-2", "-1"}; reply = co_await client.send(json_arrinsert(key3, ".", values)); testForValue("JSON.ARRINSERT", reply, 3); reply = co_await client.send(json_get(key3, ".")); testForValue("JSON.GET", reply, "[-2,-1,0]"); reply = co_await client.send(json_arrtrim(key3, ".", "1", "1")); testForValue("JSON.ARRTRIM", reply, 1); reply = co_await client.send(json_get(key3, ".")); testForValue("JSON.GET", reply, "[-1]"); reply = co_await client.send(json_arrpop(key3, ".")); testForValue("JSON.ARRPOP", reply, "-1"); reply = co_await client.send(json_arrpop(key3, ".")); testForType("JSON.ARRPOP", reply, redis_type::nil); reply = co_await client.send(json_del(key3, ".")); testForSuccess("JSON_DEL", reply); // JSON Object Commands // clang-format off reply = co_await client.send(json_set( key1, ".", "{\"name\":\"\",\"lastSeen\":1478476800,\"loggedOut\": true}")); // clang-format on testForSuccess("JSON.SET", reply); reply = co_await client.send(json_objlen(key1, ".")); testForValue("JSON.OBJLEN", reply, 3); reply = co_await client.send(json_objkeys(key1, ".")); redis_array array = redis_array{value(string_to_vector("name")), value(string_to_vector("lastSeen")), value(string_to_vector("loggedOut"))}; testForArray("JSON.OBJKEYS", reply, array); } barrier.count_down(); co_return; } awaitable run_json_tests(asio::io_context& ctx) { const int num_runners = 50; auto exec = co_await cpool::net::this_coro::executor; cpool::awaitable_latch barrier(exec, num_runners); auto host = get_env_var("REDIS_HOST").value_or(DEFAULT_REDIS_HOST); client client(exec, host, 6379); client.set_logging_handler( std::bind(logMessage, std::placeholders::_1, std::placeholders::_2)); for (int i = 0; i < num_runners; i++) { cpool::co_spawn(ctx, test_json(client, i, barrier), cpool::detached); } co_await barrier.wait(); auto reply = co_await client.send(flush_all()); testForSuccess("FLUSH_ALL", reply); ctx.stop(); co_return; } TEST(Redis, BasicTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_basic_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, TtlTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_ttl_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, PipelineTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_pipeline_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, ListTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_list_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, HashTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_hash_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, SetTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_set_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, PasswordClientTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_password_tests(std::ref(ctx)), cpool::detached); ctx.run(); } TEST(Redis, JsonTest) { asio::io_context ctx(1); cpool::co_spawn(ctx, run_json_tests(std::ref(ctx)), cpool::detached); ctx.run(); } } // namespaceclass Solution { public: vector singleNumber(vector nums) { int xor; vector result; for(int i = 0; i < nums.size(); i++) { xor = xor ^ nums[i]; } return result; } }; #ifndef SPRITE_HPP_ #define SPRITE_HPP_ #include "node2d.hpp" class Sprite: public Node2D { GLuint texture; public: int width, height, numComponents; enum { REPEAT = GL_REPEAT, MIRRORED_REPEAT = GL_MIRRORED_REPEAT, CLAMP_TO_EDGE = GL_CLAMP_TO_EDGE, CLAMP_TO_BORDER = GL_CLAMP_TO_BORDER }; Sprite(); virtual ~Sprite(); virtual void update(double); virtual void draw(); int loadTexture(const char *fileName, int mode); }; #endif 1000+ // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include #include using namespace std; atomic Atom(true); void Spin() { while (Atom) { } } struct Global { thread m_t; Global() : m_t(Spin) {} ~Global() { Atom = false; m_t.join(); } }; Global g; int main() { // runtime tests are in constructors and destructors of variables with static storage duration } // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "StreetMapImporting/StreetMapFactory.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeStreetMapFactory() {} // Cross Module References STREETMAPIMPORTING_API UClass* Z_Construct_UClass_UStreetMapFactory_NoRegister(); STREETMAPIMPORTING_API UClass* Z_Construct_UClass_UStreetMapFactory(); UNREALED_API UClass* Z_Construct_UClass_UFactory(); UPackage* Z_Construct_UPackage__Script_StreetMapImporting(); // End Cross Module References void UStreetMapFactory::StaticRegisterNativesUStreetMapFactory() { } UClass* Z_Construct_UClass_UStreetMapFactory_NoRegister() { return UStreetMapFactory::StaticClass(); } struct Z_Construct_UClass_UStreetMapFactory_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UStreetMapFactory_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UFactory, (UObject* (*)())Z_Construct_UPackage__Script_StreetMapImporting, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UStreetMapFactory_Statics::Class_MetaDataParams[] = { { "IncludePath", "StreetMapFactory.h" }, { "ModuleRelativePath", "StreetMapFactory.h" }, { "ObjectInitializerConstructorDeclared", "" }, { "ToolTip", "Import factory object for OpenStreetMap assets" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_UStreetMapFactory_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UStreetMapFactory_Statics::ClassParams = { &UStreetMapFactory::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x000000A0u, nullptr, 0, nullptr, 0, nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_UStreetMapFactory_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UStreetMapFactory_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UStreetMapFactory() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UStreetMapFactory_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UStreetMapFactory, 633534429); static FCompiledInDefer Z_CompiledInDefer_UClass_UStreetMapFactory(Z_Construct_UClass_UStreetMapFactory, &UStreetMapFactory::StaticClass, TEXT("/Script/StreetMapImporting"), TEXT("UStreetMapFactory"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UStreetMapFactory); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif #include "ConcreteProduct.h" #include void ConcreteProduct::Operation() { std::cout << __FUNCSIG__ << std::endl; } test/utils.hpp /** @file utils.hpp * @brief Unit-test utilities. * * @author t-kenji <> * @date 2019-02-03 newly created. */ #ifndef __ANTTQ_TEST_UTILS_H__ #define __ANTTQ_TEST_UTILS_H__ #define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0])) template constexpr std::string tags(const First first, const Rest ...rest) { const First args[] = {first, rest...}; std::string tag_str = ""; for (size_t i = 0; i < sizeof(args)/sizeof(args[0]); ++i) { tag_str += "[" + std::string(args[i]) + "]"; } return tag_str; } /** * @sa https://stackoverflow.com/a/33047781 */ struct Lambda { template static Tret lambda_ptr_exec(Targs... args) { return (Tret) (*(T *)fn())(args...); } template static Tfp cify(T& t) { fn(&t); return (Tfp) lambda_ptr_exec; } template static void *fn(void *new_fn = nullptr) { static void *fn; if (new_fn != nullptr) { fn = new_fn; } return fn; } }; /** * @sa https://github.com/dascandy/hippomocks/blob/master/HippoMocks/hippomocks.h */ #include #include template class ReplIt { private: typedef unsigned int e9ptrsize_t; template U horrible_cast(V v) { union { U u; V v; } un; un.v = v; return un.u; } class Unprotect { private: intptr_t location_; size_t count_; public: Unprotect(void *location, size_t count): location_((intptr_t)location & ~(0xFFF)), count_(count + ((intptr_t)location - location_)) { mprotect((void *)location_, count_, PROT_READ | PROT_WRITE | PROT_EXEC); } ~Unprotect() { mprotect((void *)location_, count_, PROT_READ | PROT_EXEC); } }; T original_; uint8_t backup[16]; // typical use is 5 for 32-bit and 14 for 64-bit code. public: ReplIt(T original, T replacement): original_(original) { #if defined(__x86_64__) if (llabs((int64_t)original_ - (int64_t)replacement) < (1LL << 31)) { Unprotect _((void *)original_, sizeof(backup)); memcpy(backup, horrible_cast(original_), sizeof(backup)); *(uint8_t *)original_ = 0xE9; *(e9ptrsize_t *)((intptr_t)(original_) + 1) = (e9ptrsize_t)((intptr_t)(replacement) - (intptr_t)(original_) - sizeof(e9ptrsize_t) - 1); } else { Unprotect _((void *)original_, sizeof(backup)); memcpy(backup, horrible_cast(original_), sizeof(backup)); uint8_t *ptr = (uint8_t *)original_; ptr[0] = 0xFF; // jmp (rip + imm32) ptr[1] = 0x25; ptr[2] = 0x00; // imm32 of 0, so immediately after the instruction ptr[3] = 0x00; ptr[4] = 0x00; ptr[5] = 0x00; *(intptr_t *)((intptr_t)original_ + 6) = (intptr_t)replacement; } #else #error "Archtecture is not supported" #endif } ~ReplIt() { Unprotect _((void *)original_, sizeof(backup)); memcpy(horrible_cast(original_), backup, sizeof(backup)); } }; /** * @sa https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509#c29 */ template inline T ignore_result(T x [[gnu::unused]]) { return x; } int msleep(long msec); int64_t getuptime(int64_t base); ssize_t file_read(const char *path, void *buf, size_t count); ssize_t file_read(std::string path, void *buf, size_t count); ssize_t file_write(const char *path, void *buf, size_t count); ssize_t file_write(std::string path, void *buf, size_t count); #endif // __ANTTQ_TEST_UTILS_H__ osprey/be/lno/call_info.cxx /* * Copyright 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ // -*-C++-*- /* ==================================================================== * ==================================================================== * * Module: call_info.cxx * $Revision: * $Date: * $Author: * $Source: * * Revision history: * 20-Nov-96 - Original Version * * Description: * * Basic call information required to analyze loops * * ==================================================================== * ==================================================================== */ #include #ifdef USE_PCH #include "lno_pch.h" #endif // USE_PCH #pragma hdrstop #include "call_info.h" #include "lwn_util.h" #include "targ_const.h" #include "opt_du.h" #include "debug.h" #include "tlog.h" #include "ipa_lno_read.h" extern MEM_POOL ARA_memory_pool; void CALL_INFO::Print(FILE *fp) { fprintf(fp, "CALL %s FROM %s AT 0x%p. ", WB_Whirl_Symbol(_wn_call), ST_name(WN_st(Current_Func_Node)), _wn_call); if (_needs_evaluation) fprintf(fp, "Needs evaluation. "); if (_needs_evaluation) { if (_is_evaluated) fprintf(fp, "Evaluated. "); else fprintf(fp, "Unevaluated. "); } fprintf(fp, "\n"); _ara_call->CI_Print(fp); if (_value != NULL) { for (INT i = 0; i <= _value->Lastidx(); i++) (*_value)[i].WB_Print(fp, i); } else { fprintf(fp, "NULL SUMMARY_VALUEs\n"); } if (_expr != NULL) { for (INT i = 0; i <= _expr->Lastidx(); i++) (*_expr)[i].WB_Print(fp, i); } else { fprintf(fp, "NULL SUMMARY_EXPRs\n"); } } void CALL_INFO::Tlog_Print() { char bf[MAX_TLOG_CHARS]; INT new_ccount = 0; new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, "CALL "); new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, (char*) WB_Whirl_Symbol(_wn_call)); new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, " FROM "); new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, ST_name(WN_st(Current_Func_Node))); new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, ". "); Generate_Tlog("LNO", "Call_Info", (SRCPOS) 0, "", "", "", bf); new_ccount = 0; if (_needs_evaluation) new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, "Needs evaluation. "); if (_needs_evaluation) { if (_is_evaluated) new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, "Evaluated. "); else new_ccount = snprintfs(bf, new_ccount, MAX_TLOG_CHARS, "Unevaluated. "); } if (new_ccount > 0) Generate_Tlog("LNO", "Call_Info", (SRCPOS) 0, "", "", "", bf); _ara_call->Tlog_CI_Print(); // Need to generate execution cost (value,expr) pairs at some point. } // Given a WN*, loop depth and loop stack, create an ACCESS_VECTOR static ACCESS_VECTOR *Wn_To_Access_Vector( WN* wn, INT16 loop_depth, DOLOOP_STACK *loop_stack) { ST* st=WN_st(wn); ACCESS_VECTOR* av= CXX_NEW(ACCESS_VECTOR((INT64)loop_depth,&ARA_memory_pool), &ARA_memory_pool); av->Too_Messy=FALSE; if (ST_class(st)==CLASS_CONST) { av->Const_Offset=Targ_To_Host(STC_val(st)); } else { SYMBOL sym(wn); av->Add_Symbol(1,sym,loop_stack,wn); } return av; } // Create an Access Array which has all 0s for enclosing loop coefficients static ACCESS_ARRAY *Create_Dummy_Access_Array(INT16 dim, INT16 loop_depth) { ACCESS_ARRAY* kernel= CXX_NEW(ACCESS_ARRAY(dim,loop_depth,&ARA_memory_pool), &ARA_memory_pool); for (INT i=0; iDim(i)->Set_Loop_Coeff(j,0); kernel->Dim(i)->Too_Messy=FALSE; } kernel->Too_Messy=FALSE; return kernel; } // Given lower bound, upper bound and stride WNs, construct an AXLE_NODE static void Prepare_Axle( WN* lb_wn, WN* ub_wn, WN* stride_wn, INT16 loop_depth, DOLOOP_STACK* loop_stack, REGION* array_reg, INT16 axle_id) { ST* stride_st=WN_st(stride_wn); ACCESS_VECTOR* lbav=Wn_To_Access_Vector(lb_wn,loop_depth,loop_stack); if (lbav->Has_Loop_Coeff()) { BOOL* is_independent=array_reg->_kernel->Get_Independent_Loops(); for (INT k=0; kLoop_Coeff(k)) is_independent[k]=FALSE; } CON_PAIR* lbcp=CXX_NEW(CON_PAIR(lbav),&ARA_memory_pool); ACCESS_VECTOR* ubav=Wn_To_Access_Vector(ub_wn,loop_depth,loop_stack); if (ubav->Has_Loop_Coeff()) { BOOL* is_independent=array_reg->_kernel->Get_Independent_Loops(); for (INT k=0; kLoop_Coeff(k)) is_independent[k]=FALSE; } CON_PAIR* ubcp=CXX_NEW(CON_PAIR(ubav),&ARA_memory_pool); INT stride=Targ_To_Host(STC_val(stride_st)); if (*lbav == *ubav) { array_reg->_axle[axle_id].Set_Axle(lbcp,0,stride,array_reg->Num_Dim()); } else { array_reg->_axle[axle_id].Set_Axle(lbcp,ubcp, stride,array_reg->Num_Dim()); } } // process each call and looks at the parameters to construct ARA_LOOP_INFO // each array region can be specified by a set (>=5) of consecutive parameters: // array name -- e.g. a // access kind -- e.g. 'r' or 'w' // for i in num_of_dim_of array a // WN* lower bound of i-th dim // WN* upper bound of i-th dim // int stride of i-th dim static void Scan_Parameters(WN* call_stmt, ARA_LOOP_INFO* ali) { INT16 loop_depth=Do_Loop_Depth(Enclosing_Do_Loop(call_stmt))+1; DOLOOP_STACK *loop_stack=CXX_NEW(DOLOOP_STACK(&ARA_memory_pool), &ARA_memory_pool); Build_Doloop_Stack(call_stmt, loop_stack); INT16 kidno=0; while (kidno+5_axle=CXX_NEW_ARRAY(AXLE_NODE,dim,&ARA_memory_pool); array_reg->_type=ARA_NORMAL; array_reg->_coupled=FALSE; array_reg->_wn_list.Push(call_stmt); ACCESS_ARRAY* kernel=Create_Dummy_Access_Array(dim,loop_depth); array_reg->_kernel=CXX_NEW(KERNEL_IMAGE(kernel), &ARA_memory_pool); for (INT16 i=0; i_kernel->Set_Region(new_region); ARA_REF* new_ref=CXX_NEW(ARA_REF(&array_sym, array_reg, ali, TRUE), &ARA_memory_pool); if (is_read) ali->Add_Use(new_ref); else ali->Add_Def(new_ref); } } // process calls to subroutines with special prefix "lno_test" // and generate CALL_INFO void Process_Call(WN* call_stmt) { char* name=ST_name(WN_st(call_stmt)); if (strncmp(name,"lno_test",8)) return; ARA_LOOP_INFO* ali=CXX_NEW(ARA_LOOP_INFO(call_stmt, NULL, TRUE), &ARA_memory_pool); Scan_Parameters(call_stmt,ali); ali->Print(stdout); CALL_INFO* call_info=CXX_NEW(CALL_INFO(ali, call_stmt, FALSE, &ARA_memory_pool), &ARA_memory_pool); Set_Call_Info(call_stmt, call_info); } extern void Call_Info_Walk(WN* root) { WN* call_stmt=root; while (call_stmt=LWN_Get_Next_Stmt_Node(call_stmt)) { //if (OPCODE_is_call(WN_opcode(call_stmt))) if (WN_operator(call_stmt)==OPR_CALL) Process_Call(call_stmt); } } //----------------------------------------------------------------------- // NAME: IPA_LNO_Evaluate_Scalar_Formals // FUNCTION: Evaluate the 'formal_number'th of the 'wn_call' node on the // stack 'st_scalar'. //----------------------------------------------------------------------- static void IPA_LNO_Evaluate_Scalar_Formals(WN* wn_call, INT formal_number, SCALAR_STACK* st_scalar) { WN* wn_symbol = NULL; WN* wn_parm = WN_kid(wn_call, formal_number); FmtAssert(WN_operator(wn_parm) == OPR_PARM, ("IPA_LNO_Evaluate_Scalar_Formals: Expecting PARM node")); WN* wn_lda = WN_kid0(wn_parm); if (WN_operator(wn_lda) == OPR_INTCONST) return; for (INT i = 0; i < st_scalar->Elements(); i++) { SCALAR_NODE* sn = st_scalar->Bottom_nth(i); DYN_ARRAY wn_list(&LNO_local_pool); DYN_ARRAY int_list(&LNO_local_pool); INT64 const_value = 0; if (sn->_scalar.Is_Formal() && sn->_scalar.Formal_Number() == formal_number) { if (WN_operator(wn_lda) == OPR_LDA || WN_operator(wn_lda) == OPR_LDID) { SYMBOL sym_lda(WN_st(wn_lda), WN_offset(wn_lda), sn->_scalar.Type); WN* wn_single = Single_Definition_Temp(wn_lda); if (wn_single != NULL && Scalar_Expr(wn_single)) Add_Scalars_In_Expr(wn_single, st_scalar); st_scalar->Add_Scalar(wn_lda, &sym_lda, 0); } else if (Scalar_Expr(wn_lda) && Linear_Expr(wn_lda, &wn_list, &int_list, &const_value)) { Add_Scalars_In_Expr(wn_lda, st_scalar); } else { FmtAssert(FALSE, ("IPA_LNO_Read_Formal: Expecting LDA, LDID, INTCONST, or S-LIN Exp")); } } st_scalar->Clear_Formal(formal_number); } } //----------------------------------------------------------------------- // NAME: IPA_LNO_Find_Formal_Value // FUNCTION: Return the node which defines the 'formal_number'th parameter // of 'wn_call' (assuming that it is a scalar formal). Return NULL if // it is not a scalar formal, or if it is difficult to find. //----------------------------------------------------------------------- static WN* IPA_LNO_Find_Formal_Value(WN* wn_call, INT formal_number) { WN* wn_use = WN_kid(wn_call, formal_number); FmtAssert(WN_operator(wn_use) == OPR_PARM, ("IPA_LNO_Find_Formal_Value: Expecting PARM node")); if (WN_Parm_By_Reference(wn_use)) { LWN_ITER* itr = LWN_WALK_TreeIter(wn_use); DEF_LIST *def_list = Du_Mgr->Ud_Get_Def(wn_use); if (def_list == NULL) return NULL; DEF_LIST_ITER iter(def_list); const DU_NODE* node = NULL; WN* wn_def = NULL; for (node = iter.First(); !iter.Is_Empty(); node = iter.Next()) { if (wn_def != NULL) return NULL; wn_def = node->Wn(); } if (wn_def == NULL) return NULL; wn_use = WN_kid0(wn_def); } else { wn_use = WN_kid0(wn_use); } return wn_use; } //----------------------------------------------------------------------- // NAME: IPA_LNO_Evaluate_Array_Formals // FUNCTION: Replace all references to the 'formal_number' in 'st' with the // access vector equivalent of 'wn_use'. The 'stack' is the stack of loops // enclosing 'wn_use'. //----------------------------------------------------------------------- static void IPA_LNO_Evaluate_Array_Formals(ARA_REF_ST* st, WN* wn_call, INT formal_number) { WN* wn_use = NULL; DOLOOP_STACK* stack = NULL; for (INT i = 0; i < st->Elements(); i++) { ARA_REF* ar = st->Bottom_nth(i); REGION_UN* rgun = &ar->Image(); if (rgun == NULL) continue; REGION_ITER iter(rgun); for (REGION* rg = iter.First(); !iter.Is_Empty(); iter.Next()) { if (rg->_type == ARA_TOP || rg->_type == ARA_BOTTOM || rg->_type == ARA_TOO_MESSY) continue; for (INT i = 0; i < rg->_dim; i++) { AXLE_NODE* ax = &rg->_axle[i]; CON_PAIR* cp_lo = ax->lo; // DevWarn("rcox: Ignoring WN_OFFSET and TYPE_ID for array formals"); if (cp_lo != NULL) { ACCESS_VECTOR* av_lo = cp_lo->_ac_v; if (av_lo != NULL) { if (wn_use == NULL) { wn_use = IPA_LNO_Find_Formal_Value(wn_call, formal_number); if (wn_use != NULL) { stack = CXX_NEW(DOLOOP_STACK(&LNO_local_pool),&LNO_local_pool); Build_Doloop_Stack(LWN_Get_Parent(wn_use), stack); LNO_Build_Access(wn_use, stack, &LNO_default_pool); } } av_lo->Substitute(formal_number, wn_use, stack, LNO_Allow_Nonlinear); } } CON_PAIR* cp_up = ax->up; if (cp_up != NULL) { ACCESS_VECTOR* av_up = cp_up->_ac_v; if (av_up != NULL) { if (wn_use == NULL) { wn_use = IPA_LNO_Find_Formal_Value(wn_call, formal_number); if (wn_use != NULL) { stack = CXX_NEW(DOLOOP_STACK(&LNO_local_pool), &LNO_local_pool); Build_Doloop_Stack(LWN_Get_Parent(wn_use), stack); LNO_Build_Access(wn_use, stack, &LNO_default_pool); } } av_up->Substitute(formal_number, wn_use, stack, LNO_Allow_Nonlinear); } } } } } } //----------------------------------------------------------------------- // NAME: IPA_LNO_Evaluate_Formal_Symbols // FUNCTION: Evaluate the formal symbols in the scalar stacks and access // vectors of 'wn_call'. //----------------------------------------------------------------------- static void IPA_LNO_Evaluate_Formal_Symbols(WN* wn_call) { if (!Has_Call_Info(wn_call)) return; CALL_INFO* ci = Get_Call_Info(wn_call); ARA_LOOP_INFO* ali = ci->Call_Ara_Info(); for (INT i = 0; i < WN_kid_count(wn_call); i++) { SCALAR_STACK* st_sdef = &ali->SCALAR_MAY_DEF(); IPA_LNO_Evaluate_Scalar_Formals(wn_call, i, st_sdef); SCALAR_STACK* st_suse = &ali->SCALAR_USE(); IPA_LNO_Evaluate_Scalar_Formals(wn_call, i, st_suse); ARA_REF_ST* st_def = &ali->MAY_DEF(); IPA_LNO_Evaluate_Array_Formals(st_def, wn_call, i); ARA_REF_ST* st_use = &ali->USE(); IPA_LNO_Evaluate_Array_Formals(st_use, wn_call, i); } if (Get_Trace(TP_LNOPT2, TT_CALL_INFO)) { fprintf(stdout, "==========\n"); fprintf(stdout, "EVALUATING %s AT 0x%p\n", WB_Whirl_Symbol(wn_call), wn_call); CALL_INFO* call_info = (CALL_INFO *) WN_MAP_Get(LNO_Info_Map, wn_call); call_info->Print(stdout); } } //----------------------------------------------------------------------- // NAME: CALL_INFO::Evaluate // FUNCTION: Evaluate the CALL_INFO's formal parameters. //----------------------------------------------------------------------- void CALL_INFO::Evaluate() { if (!_needs_evaluation) return; if (_is_evaluated) { DevWarn("CALL_INFO::Evaluate: Already evaluated"); return; } FmtAssert(_wn_call != NULL, ("CALL_INFO::Evaluate: Must be assigned to particular call")); // OUCH!! BOGUS ... UNTIL WE GET A TRUE CONSTRUCTOR _ara_call_save = CXX_NEW(ARA_LOOP_INFO(_ara_call), _pool); ARA_LOOP_INFO* ali = Call_Ara_Info(); for (INT i = 0; i < WN_kid_count(_wn_call); i++) { SCALAR_STACK* st_sdef = &ali->SCALAR_MAY_DEF(); IPA_LNO_Evaluate_Scalar_Formals(_wn_call, i, st_sdef); SCALAR_STACK* st_suse = &ali->SCALAR_USE(); IPA_LNO_Evaluate_Scalar_Formals(_wn_call, i, st_suse); ARA_REF_ST* st_def = &ali->MAY_DEF(); IPA_LNO_Evaluate_Array_Formals(st_def, _wn_call, i); ARA_REF_ST* st_use = &ali->USE(); IPA_LNO_Evaluate_Array_Formals(st_use, _wn_call, i); } _is_evaluated = TRUE; } //----------------------------------------------------------------------- // NAME: CALL_INFO::Unevaluate // FUNCTION: Evaluate the CALL_INFO's formal parameters. //----------------------------------------------------------------------- void CALL_INFO::Unevaluate() { if (!_needs_evaluation) return; if (!_is_evaluated) { DevWarn("CALL_INFO::Unevaluate: Already unevaluated"); return; } CXX_DELETE(_ara_call, _pool); _ara_call = _ara_call_save; _ara_call_save = NULL; _is_evaluated = FALSE; } //----------------------------------------------------------------------- // NAME: CALL_INFO::CALL_INFO // FUNCTION: Constructor for CALL_INFO. //----------------------------------------------------------------------- CALL_INFO::CALL_INFO(CALL_INFO* ci) { FmtAssert(ci != NULL, ("CALL_INFO constructor: Called with NULL pointer")); _is_evaluated = ci->_is_evaluated; _needs_evaluation = ci->_needs_evaluation; _wn_call = ci->_wn_call; _pool = ci->_pool; FmtAssert(_pool == &ARA_memory_pool, ("CALL_INFO::CALL_INFO: can only allocate from ARA_memory_pool")); if (_ara_call != NULL) _ara_call = CXX_NEW(ARA_LOOP_INFO(ci->_ara_call), _pool); if (_ara_call_save != NULL) _ara_call_save = CXX_NEW(ARA_LOOP_INFO(ci->_ara_call_save), _pool); _value = CXX_NEW(DYN_ARRAY(_pool), _pool); INT i; for (i = 0; i <= ci->_value->Lastidx(); i++) _value->AddElement((*(ci->_value))[i]); _expr = CXX_NEW(DYN_ARRAY(_pool), _pool); for (i = 0; i <= ci->_expr->Lastidx(); i++) _expr->AddElement((*(ci->_expr))[i]); } //----------------------------------------------------------------------- // NAME: CALL_INFO::Has_Formal_Parameter // FUNCTION: Returns TRUE if CALL_INFO has at least one SYMBOL with a // formal parameter (which will therefore require evaluation). // NOTE: This is not a search of all possible symbols. I'm assuming that // formal parameters are only going to appear in the "may_def" and "use" // in the CALL_INFO. //----------------------------------------------------------------------- BOOL CALL_INFO::Has_Formal_Parameter() { ARA_LOOP_INFO* ali = Call_Ara_Info(); if (ali == NULL) return FALSE; SCALAR_STACK* st_scalar = &ali->SCALAR_MAY_DEF(); INT i; for (i = 0; i < st_scalar->Elements(); i++) { SCALAR_NODE* sn = st_scalar->Bottom_nth(i); if (sn->_scalar.Is_Formal()) return TRUE; } st_scalar = &ali->SCALAR_USE(); for (i = 0; i < st_scalar->Elements(); i++) { SCALAR_NODE* sn = st_scalar->Bottom_nth(i); if (sn->_scalar.Is_Formal()) return TRUE; } for (i = 0; i < ali->MAY_DEF().Elements(); i++) { ARA_REF* ara_ref = ali->MAY_DEF().Bottom_nth(i); if (ara_ref->Has_Formal_Parameter()) return TRUE; } for (i = 0; i < ali->USE().Elements(); i++) { ARA_REF* ara_ref = ali->USE().Bottom_nth(i); if (ara_ref->Has_Formal_Parameter()) return TRUE; } return FALSE; } // 1、逻辑写起来复杂,就是人工计算序号的映射,但好处是计算速度快(常数倍时间),节省空间 T=O(n) S=O(1) class Solution { public: string convert(string s, int nRows) { int len = (int)s.length(); // 总字符数 if (len == 0 || nRows == 1) { return s; } int res = len % (2 * nRows - 2); // 最后一块中的字符数 int nBlock = len / (2 * nRows - 2); // 总块数(只计算完整的块) string result(s); for (int i = 0; i < len; i++) { int block = i / (2 * nRows - 2); // 当前字符所在块 int position = i % (2 * nRows - 2); // 当前字符在块中的位置 int row; // 当前字符所在行数 int col; // 当前字符在块中的列数(0或1) int j; // 当前字符在新字符串中的位置 if (position < nRows) { row = position; col = 0; } else { row = 2 * nRows - 2 - position; col = 1; } // 首先不考虑最右侧的残块 if (row == 0) { j = block; } else if (row == nRows - 1) { j = nBlock * ( 2 * nRows - 3) + block; } else { j = nBlock * ( 2 * row - 1) + 2 * block + col; } // 加入最对右侧的残块的考虑 if (res < row) { j += res; } else if (res <= nRows) { j += row; } else { int tmp = res - 2 * nRows + row + 1; // 此处很难计算 j += row + (tmp > 0 ? tmp : 0); } // 给新字符串对应位置赋值 result[j] = s[i]; } return result; } }; // 2、编程负担小,但耗时间: T=O(n) S=O(n) class Solution { public: string convert(string s, int nRows) { int len = (int)s.length(); if (len == 0 || nRows == 1) { // 注意空串、或单行的情况 return s; } string result(s); vector> container(nRows); // int groupLen = nRows == 2 ? 2 : 2 * nRows - 2; // 注意两行的情况 int groupLen = 2 * (nRows - 1); // 两行的情况并不特殊 for (int i = 0; i < len; i++) { int pos = i % groupLen; // int row = pos < nRows ? pos : nRows - (pos - nRows) - 2; int row = pos < nRows ? pos : groupLen - pos; // 更简洁的写法 container[row].push_back(s[i]); } for (int i = 0, j = 0; i < nRows; i++) { // i 指向行,j 指向结果result的下一个空位 int iLen = (int)container[i].size(); for (int k = 0; k < iLen; j++, k++) { result[j] = container[i][k]; } } return result; } }; // 3、网上的解法 T=O(n) S=O(n) string convert(string s, int nRows) { if (nRows <= 1) return s; const int len = (int)s.length(); string *str = new string[nRows]; // string 和 vector 是类似的 int row = 0, step = 1; for (int i = 0; i < len; ++i) { str[row].push_back(s[i]); if (row == 0) // 上转折点 step = 1; else if (row == nRows - 1) // 下转折点 step = -1; row += step; } s.clear(); for (int j = 0; j < nRows; ++j) { s.append(str[j]); } delete[] str; return s; } shreejitverma/GeeksforGeeks // { Driver Code Starts #include using namespace std; // } Driver Code Ends // Function to find the subarray with given sum k // arr: input array // n: size of array vector subarraySum(int arr[], int n, int s){ // Your code here int left = 0, right = 0, sum = 0; vector ans; ans.push_back(-1); for(int i=0; i s){ sum -= arr[left++] + arr[i--]; } } return ans; } // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; long long s; cin>>n>>s; int arr[n]; for(int i=0;i>arr[i]; vectorres; res = subarraySum(arr, n, s); for(int i = 0;i #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(HAVE_LINENOISE) #include #endif using libutil::Filesystem; using libutil::DefaultFilesystem; typedef struct { std::unique_ptr object; } RootObjectContainer; class Options { private: ext::optional _help; ext::optional _xml; private: ext::optional _command; private: std::string _input; public: Options(); ~Options(); public: bool help() const { return _help.value_or(false); } bool xml() const { return _xml.value_or(false); } public: ext::optional command() const { return _command; } public: std::string input() const { return _input; } private: friend class libutil::Options; std::pair parseArgument(std::vector const &args, std::vector::const_iterator *it); }; Options:: Options() { } Options:: ~Options() { } std::pair Options:: parseArgument(std::vector const &args, std::vector::const_iterator *it) { std::string const &arg = **it; if (arg == "-h") { return libutil::Options::Current(&_help, arg, it); } else if (arg == "-x") { return libutil::Options::Current(&_xml, arg, it); } else if (arg == "-c") { return libutil::Options::Next(&_command, args, it); } else if (!arg.empty() && arg[0] != '-') { _input = arg; return std::make_pair(true, std::string()); } else { return std::make_pair(false, "unknown argument " + arg); } } static plist::ObjectType ParseType(std::string const &typeString) { if (typeString == "string") { return plist::ObjectType::String; } else if (typeString == "dictionary") { return plist::ObjectType::Dictionary; } else if (typeString == "array") { return plist::ObjectType::Array; } else if (typeString == "bool") { return plist::ObjectType::Boolean; } else if (typeString == "real") { return plist::ObjectType::Real; } else if (typeString == "integer") { return plist::ObjectType::Integer; } else if (typeString == "date") { return plist::ObjectType::Date; } else if (typeString == "data") { return plist::ObjectType::Data; } else { return plist::ObjectType::None; } } static int Help(std::string const &error = std::string()) { if (!error.empty()) { fprintf(stderr, "error: %s\n", error.c_str()); fprintf(stderr, "\n"); } fprintf(stderr, "usage: PlistBuddy [options] \n"); #define INDENT " " fprintf(stderr, "\noptions:\n"); fprintf(stderr, INDENT "-c \"\" command to execute, otherwise run in interactive mode\n"); fprintf(stderr, INDENT "-x output will be in xml plist format\n"); fprintf(stderr, INDENT "-h print help including commands\n"); #undef INDENT return (error.empty() ? 0 : -1); } static void CommandHelp() { #define INDENT " " fprintf(stderr, "\nCommands help:\n"); fprintf(stderr, INDENT "Help - Print this information\n"); fprintf(stderr, INDENT "Exit - Exits this program\n"); fprintf(stderr, INDENT "Print [] - Print value at KeyPath. (default KeyPath = root)\n"); fprintf(stderr, INDENT "Save - Save the changed plist file\n"); fprintf(stderr, INDENT "Set - Set value at KeyPath to Value\n"); fprintf(stderr, INDENT "Add - Set value at KeyPath to Value\n"); fprintf(stderr, INDENT "Clear - Clears all data, and sets root to of the given type\n"); fprintf(stderr, INDENT "Delete - Removes entry at KeyPath\n"); fprintf(stderr, "\n\n"); fprintf(stderr, INDENT ":= \"\" => root object\n"); fprintf(stderr, INDENT ":= [:] => indexes into dictionary\n"); fprintf(stderr, INDENT ":= [:] => indexes into Array\n"); fprintf(stderr, "\n := (string|dictionary|array|bool|real|integer|date|data)\n\n"); #undef INDENT } static void ParseCommandKeyPathString(std::string const &keyPathString, std::queue *keyPath) { std::string::size_type prev = 0; do { std::string::size_type pos = keyPathString.find(':', prev); std::string::size_type end = (pos == std::string::npos ? pos : pos - prev); std::string key = keyPathString.substr(prev, end); if (!key.empty()) { keyPath->push(key); } prev = (pos == std::string::npos ? pos : pos + 1); } while (prev != std::string::npos); } static std::string ParseCommandValueString(std::vector::const_iterator begin, std::vector::const_iterator end) { if (begin == end) { return ""; } std::string value; for (auto it = begin; it != end; it++) { if (it != begin) { value += ' '; } value += it->c_str(); } /* Strip double quotes if necessary. */ if (value.front() == '\"' && value.back() == '\"') { value = value.substr(1, value.size() - 2); } return value; } static plist::Object * GetObjectAtKeyPath(plist::Object *object, std::queue *remainingKeys, bool leaveLastKey = true) { if (remainingKeys->empty() || (leaveLastKey && remainingKeys->size() == 1)) { return object; } else if (!object) { fprintf(stderr, "Invalid key path (indexing into null object)\n"); return nullptr; } std::string currentKey = remainingKeys->front(); plist::Object *subObject = nullptr; switch (object->type()) { case plist::ObjectType::Dictionary: subObject = plist::CastTo(object)->value(currentKey); break; case plist::ObjectType::Array: { char *end = NULL; long long index = std::strtoll(currentKey.c_str(), &end, 0); if (end == currentKey.c_str() || index < 0) { fprintf(stderr, "Invalid array index\n"); return nullptr; } subObject = plist::CastTo(object)->value(index); break; } default: /* Reached a non-collection object with remaining key path, error. */ fprintf(stderr, "Invalid key path (indexing into non-collection object)\n"); return nullptr; } if (!subObject) { return object; } else { remainingKeys->pop(); return GetObjectAtKeyPath(subObject, remainingKeys, leaveLastKey); } } static bool Print(plist::Object *object, std::queue &keyPath, bool xml, Filesystem *filesystem = nullptr, std::string path = "-") { plist::Object *target = GetObjectAtKeyPath(object, &keyPath, false); if (!keyPath.empty() || target == nullptr) { fprintf(stderr, "Invalid key path (no object at key path)\n"); return false; } /* * Determine output format. */ ext::optional out; if (xml) { plist::Format::XML xml = plist::Format::XML::Create(plist::Format::Encoding::UTF8); out = plist::Format::Any::Create(xml); } else { plist::Format::ASCII ascii = plist::Format::ASCII::Create(false, plist::Format::Encoding::UTF8); out = plist::Format::Any::Create(ascii); } auto serialize = plist::Format::Any::Serialize(target, *out); if (serialize.first == nullptr) { fprintf(stderr, "error: %s\n", serialize.second.c_str()); return false; } /* Print. */ if (filesystem != nullptr && path != "-") { filesystem->write(*serialize.first, path); } else { std::copy(serialize.first->begin(), serialize.first->end(), std::ostream_iterator(std::cout)); } return true; } static bool Set(plist::Object *object, std::queue &keyPath, plist::ObjectType type, const std::string &valueString, bool overwrite = true) { plist::Object *target = GetObjectAtKeyPath(object, &keyPath, true); if (!target || keyPath.size() != 1) { fprintf(stderr, "Invalid key path (target object not found)\n"); return false; } std::string targetKey = keyPath.front(); std::unique_ptr newObj; switch (type) { case plist::ObjectType::String: newObj = plist::String::New(valueString); break; case plist::ObjectType::Dictionary: newObj = plist::Dictionary::New(); break; case plist::ObjectType::Array: newObj = plist::Array::New(); break; case plist::ObjectType::Boolean: newObj = plist::Boolean::Coerce(new plist::String(valueString)); break; case plist::ObjectType::Real: newObj = plist::Real::Coerce(new plist::String(valueString)); break; case plist::ObjectType::Integer: newObj = plist::Integer::Coerce(new plist::String(valueString)); break; case plist::ObjectType::Date: newObj = plist::Date::New(valueString); break; case plist::ObjectType::Data: newObj = plist::Data::New(valueString); break; default: fprintf(stderr, "Not supported\n"); return false; } switch (target->type()) { case plist::ObjectType::Dictionary: { plist::Dictionary *dict = plist::CastTo(target); if (!overwrite && dict->value(targetKey)) { fprintf(stderr, "Cannot overwrite key path\n"); return false; } dict->set(targetKey, std::move(newObj)); return true; } case plist::ObjectType::Array: { char *end = NULL; long long index = std::strtoll(targetKey.c_str(), &end, 0); if (end == targetKey.c_str() || index < 0) { fprintf(stderr, "Invalid array index\n"); return false; } plist::Array *array = plist::CastTo(target); if (!overwrite && array->value(index)) { fprintf(stderr, "Cannot overwrite key path\n"); return false; } array->insert(index, std::move(newObj)); return true; } default: fprintf(stderr, "Invalid key path (setting value on non-collection object)\n"); return false; } } static bool Clear(RootObjectContainer *root, plist::ObjectType clearType) { switch (clearType) { case plist::ObjectType::String: root->object = plist::String::New(); break; case plist::ObjectType::Dictionary: root->object = plist::Dictionary::New(); break; case plist::ObjectType::Array: root->object = plist::Array::New(); break; case plist::ObjectType::Boolean: root->object = plist::Boolean::New(false); break; case plist::ObjectType::Real: root->object = plist::Real::New(); break; case plist::ObjectType::Integer: root->object = plist::Integer::New(); break; case plist::ObjectType::Date: root->object = plist::Date::New(); break; case plist::ObjectType::Data: root->object = plist::Data::New(); break; default: fprintf(stderr, "Unsupported type\n"); return false; } return true; } static bool Delete(plist::Object *object, std::queue *keyPath) { plist::Object *target = GetObjectAtKeyPath(object, keyPath, true); if (!target || keyPath->size() != 1) { fprintf(stderr, "Invalid key path (target object not found)\n"); return false; } std::string targetKey = keyPath->front(); switch (target->type()) { case plist::ObjectType::Dictionary: { plist::Dictionary *dict = plist::CastTo(target); dict->remove(targetKey); return true; } case plist::ObjectType::Array: { char *end = NULL; long long index = std::strtoll(targetKey.c_str(), &end, 0); if (end == targetKey.c_str() || index < 0) { fprintf(stderr, "Invalid array index\n"); return false; } plist::Array *array = plist::CastTo(target); array->remove(index); return true; } default: fprintf(stderr, "Invalid key path (removing value on non-collection object)\n"); return false; } } static bool ProcessCommand(Filesystem *filesystem, std::string const &path, bool xml, RootObjectContainer &root, std::string const &input, bool *mutated) { std::vector tokens; std::stringstream sstream(input); std::copy(std::istream_iterator(sstream), std::istream_iterator(), std::back_inserter(tokens)); if (tokens.size() < 1) { return true; } std::string command = tokens[0]; if (command == "Print") { std::queue keyPath; if (tokens.size() > 1) { ParseCommandKeyPathString(tokens[1], &keyPath); } Print(root.object.get(), keyPath, xml); } else if (command == "Save") { std::queue keyPath; Print(root.object.get(), keyPath, xml, filesystem, path); } else if (command == "Exit") { return false; } else if (command == "Set") { if (tokens.size() < 2) { fprintf(stderr, "Set command requires KeyPath\n"); return true; } else { std::queue keyPath; ParseCommandKeyPathString(tokens[1], &keyPath); Set(root.object.get(), keyPath, plist::ObjectType::String, ParseCommandValueString(tokens.begin() + 2, tokens.end())); *mutated = true; } } else if (command == "Add") { if (tokens.size() < 3) { fprintf(stderr, "Add command requires KeyPath and Type\n"); return true; } else { std::queue keyPath; ParseCommandKeyPathString(tokens[1], &keyPath); plist::ObjectType type = ParseType(tokens[2]); Set(root.object.get(), keyPath, type, ParseCommandValueString(tokens.begin() + 3, tokens.end()), false); *mutated = true; } } else if (command == "Clear") { plist::ObjectType clearType; if (tokens.size() < 2) { clearType = plist::ObjectType::Dictionary; } else { clearType = ParseType(tokens[1]); } Clear(&root, clearType); *mutated = true; } else if (command == "Delete") { if (tokens.size() < 2) { fprintf(stderr, "Add command requires KeyPath\n"); return true; } std::queue keyPath; ParseCommandKeyPathString(tokens[1], &keyPath); Delete(root.object.get(), &keyPath); *mutated = true; } else if (command == "Help") { CommandHelp(); } else { fprintf(stderr, "Unrecognized command\n"); } return true; } int main(int argc, char **argv) { std::vector args = std::vector(argv + 1, argv + argc); DefaultFilesystem filesystem = DefaultFilesystem(); Options options; std::pair result = libutil::Options::Parse(&options, args); if (!result.first) { return Help(result.second); } if (options.help()) { Help(); CommandHelp(); return 0; } if (options.input().empty()) { return Help("no input specified"); } if (!filesystem.exists(options.input())) { fprintf(stderr, "File does not exist, will be created: %s\n", options.input().c_str()); } std::vector contents; if (!filesystem.read(&contents, options.input())) { fprintf(stderr, "error: unable to read %s\n", options.input().c_str()); return 1; } auto format = plist::Format::Any::Identify(contents); if (format == nullptr) { fprintf(stderr, "error: input %s not a plist\n", options.input().c_str()); return 1; } auto deserialize = plist::Format::Any::Deserialize(contents, *format); if (!deserialize.first) { fprintf(stderr, "error: %s\n", deserialize.second.c_str()); return 1; } RootObjectContainer root; root.object = std::move(deserialize.first); if (options.command()) { bool mutated = false; ProcessCommand(&filesystem, options.input(), options.xml(), root, *options.command(), &mutated); if (mutated) { /* Save result. */ std::queue keyPath; Print(root.object.get(), keyPath, options.xml(), &filesystem, options.input()); } } else { char *line; bool keepReading = true; while (keepReading) { #if defined(HAVE_LINENOISE) line = linenoise("Command: "); if (line[0] != '\0') { linenoiseHistoryAdd(line); #else fprintf(stdout, "Command: "); size_t size = 1024; line = static_cast(malloc(size)); if (fgets(line, size, stdin) == line) { #endif bool mutated = false; keepReading = ProcessCommand(&filesystem, options.input(), options.xml(), root, std::string(line), &mutated); } else { keepReading = false; } #if defined(HAVE_LINENOISE) linenoiseFree(static_cast(line)); #else free(static_cast(line)); #endif } } return 0; } // Fill out your copyright notice in the Description page of Project Settings. #include "PlayTile.h" #include "ConnectFourCharacter.h" #include "Kismet/GameplayStatics.h" #include "Materials/MaterialInstanceDynamic.h" #include "Net/UnrealNetwork.h" APlayTile::APlayTile() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SetReplicates(true); OrangeMaterial = CreateDefaultSubobject(TEXT("Player Orange Material")); BlueMaterial = CreateDefaultSubobject(TEXT("Player Blue Material")); Player = Cast(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0)); } void APlayTile::BeginPlay() { Super::BeginPlay(); //Default to empty tile as none is occupying TileType = ETileTypes::EMPTYTILE; AlreadyChecked = false; } void APlayTile::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void APlayTile::SetAlreadyChecked(bool Checked) { AlreadyChecked = Checked; } bool APlayTile::GetAlreadyChecked() { return AlreadyChecked; } void APlayTile::ServerChangeColour_Implementation() { if (Player->CurrentPlayerIndex == 0) { //Server's turn TileMesh->SetMaterial(0, OrangeMaterial); Occupied = true; Player->CurrentPlayerIndex = 1; TileType = ETileTypes::PLAYER1; SetAlreadyChecked(true); } else { //Client's turn TileMesh->SetMaterial(0, BlueMaterial); Occupied = true; Player->CurrentPlayerIndex = 0; TileType = ETileTypes::PLAYER2; SetAlreadyChecked(true); } } void APlayTile::ChangeColour() { if (HasAuthority()) { ServerChangeColour(); } } /** Name: CLOSURE_1 (Lambda introduction) Exercise: Prepare mutable and non-mutable functors and use them with algorithm Description: This exercise is an introductory exercise with Lambda function in C++11. BOOST library offers similar functionality in boost::lambda module. */ #include #include #include #include #include #include #include "utest.h" using namespace std; namespace { // Used to compare results vector VEC_ORIGINAL = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; vector VEC_INC = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; string STR_ORIGINAL = "ARM Holdings plc (ARM) is a British multinational semiconductor and software design company."; } int main(int argc, char *argv[]) { // Variables used for operations in tasks vector vec(VEC_ORIGINAL); // = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; string str(STR_ORIGINAL); //"ARM Holdings plc (ARM) is a British multinational semiconductor and software design company."; // ### Task 1 ### // Use lambda to print out each element // of vector vec 'and' each character in string 'str' /** UNCOMMENT TASK 1 cout << "============================================================================================" << endl; cout << "vec: "; for_each(begin(vec), end(vec), lambda ); // TODO: lambda cout << endl; cout << "str: "; for_each(begin(str), end(str), lambda ); // TODO: lambda cout << endl << "============================================================================================" << endl; CHECK_EQUAL("Task 1a :", vec, VEC_ORIGINAL); CHECK_EQUAL("Task 1b :", str, STR_ORIGINAL); UNCOMMENT */ // ############################################################################################ // ### Task 2 ### // Use lambda to convert each lowercase letter in 'str' to uppercase /** UNCOMMENT TASK 2 for_each(begin(str), end(str), lambda ); // TODO: lanmbda CHECK_EQUAL("Task 2 :", str, string("ARM HOLDINGS PLC (ARM) IS A BRITISH MULTINATIONAL SEMICONDUCTOR AND SOFTWARE DESIGN COMPANY.")); UNCOMMENT */ // ############################################################################################ // ### Task 3 ### // Use lambda to increment / decrement vector 'vec' values /** UNCOMMENT TASK 3 for_each(begin(vec), end(vec), lambda ); // TODO: lambda CHECK_EQUAL("Task 3 :", vec, VEC_INC); UNCOMMENT */ // ############################################################################################ // ### Task 4 ### // Use lambda to sum each element in vector 'vec' /** UNCOMMENT TASK 4 int sum = 0; for_each(begin(vec), end(vec), lambda ); // TODO: lambda CHECK_EQUAL("Task 4 :", sum, 65); UNCOMMENT */ return 0; } // MIT Licensed (see LICENSE.md). #pragma once namespace Plasma { /// Generates an orthonormal basis from the facing vector. Mat3 GenerateRotationMatrix(Vec3Param facing); void GenerateRotationMatrix(Vec3Param facing, Mat3Ptr matrix); /// Generates a rotation matrix from the given facing and up vectors. Mat3 GenerateRotationMatrix(Vec3Param facing, Vec3Param up); void GenerateRotationMatrix(Vec3Param facing, Vec3Param up, Mat3Ptr matrix); /// Generates a rotation matrix from the given bases. Mat3 GenerateRotationMatrix(Vec3Param facing, Vec3Param up, Vec3Param right); void GenerateRotationMatrix(Vec3Param facing, Vec3Param up, Vec3Param right, Mat3Ptr matrix); /// Generates a rotation matrix from the given Euler angles. Mat3 GenerateRotationMatrix(Math::real x, Math::real y, Math::real z); void GenerateRotationMatrix(Math::real x, Math::real y, Math::real z, Mat3Ptr matrix); Mat3 GenerateRotationMatrix(EulerAnglesParam eulerAngles); void GenerateRotationMatrix(EulerAnglesParam eulerAngles, Mat3Ptr matrix); } // namespace Plasma readdle/mailcore2 #include "CIMAPFolderInfoOperation.h" #include "CBase+Private.h" #include #define nativeType mailcore::IMAPFolderInfoOperation #define structName CIMAPFolderInfoOperation C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() C_SYNTHESIZE_FUNC_WITH_OBJ(CIMAPFolderInfo, info) SamWindell/AudioUtils10-100 #include "test_helpers.h" #include "common.h" namespace TestHelpers { AudioData CreateSingleOscillationSineWave(const unsigned num_channels, const unsigned sample_rate, const size_t num_frames) { AudioData buf; buf.num_channels = num_channels; buf.sample_rate = sample_rate; buf.interleaved_samples.resize(num_frames * num_channels); for (size_t frame = 0; frame < num_frames; ++frame) { for (unsigned channel = 0; channel < num_channels; ++channel) { constexpr double two_pi = 6.28318530718; buf.GetSample(channel, frame) = std::sin(frame * (two_pi / num_frames)); } } return buf; } AudioData CreateSineWaveAtFrequency(const unsigned num_channels, const unsigned sample_rate, const double length_seconds, const double frequency_hz) { const auto num_frames = (size_t)(length_seconds * sample_rate); const auto oscillations_per_sec = frequency_hz; const auto oscillations_in_whole = oscillations_per_sec * length_seconds; const auto taus_in_whole = oscillations_in_whole * 2 * pi; const auto taus_per_sample = taus_in_whole / num_frames; AudioData buf; buf.num_channels = num_channels; buf.sample_rate = sample_rate; buf.interleaved_samples.resize(num_frames * num_channels); double phase = -pi * 2; for (size_t frame = 0; frame < num_frames; ++frame) { const double value = (double)std::sin(phase); phase += taus_per_sample; for (unsigned channel = 0; channel < num_channels; ++channel) { buf.GetSample(channel, frame) = value; } } return buf; } AudioData CreateSquareWaveAtFrequency(const unsigned num_channels, const unsigned sample_rate, const double length_seconds, const double frequency_hz) { auto result = CreateSineWaveAtFrequency(num_channels, sample_rate, length_seconds, frequency_hz); for (auto &s : result.interleaved_samples) { if (s < 0) s = -1; else s = 1; } return result; } } // namespace TestHelpers 100-1000 // https://www.urionlinejudge.com.br/judge/en/problems/view/1960 #include #include #include using namespace std; int main() { int n, remainder, integer; string c[] = { "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; string d[] = { "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; string u[] = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; cin >> n; integer = n / 100; remainder = n % 100; switch(integer) { case 1: cout << c[0]; break; case 2: cout << c[1]; break; case 3: cout << c[2]; break; case 4: cout << c[3]; break; case 5: cout << c[4]; break; case 6: cout << c[5]; break; case 7: cout << c[6]; break; case 8: cout << c[7]; break; case 9: cout << c[8]; break; } integer = remainder / 10; remainder = remainder % 10; switch(integer) { case 1: cout << d[0]; break; case 2: cout << d[1]; break; case 3: cout << d[2]; break; case 4: cout << d[3]; break; case 5: cout << d[4]; break; case 6: cout << d[5]; break; case 7: cout << d[6]; break; case 8: cout << d[7]; break; case 9: cout << d[8]; break; } integer = remainder / 1; switch(integer) { case 1: cout << u[0]; break; case 2: cout << u[1]; break; case 3: cout << u[2]; break; case 4: cout << u[3]; break; case 5: cout << u[4]; break; case 6: cout << u[5]; break; case 7: cout << u[6]; break; case 8: cout << u[7]; break; case 9: cout << u[8]; break; } return 0; } 0 /** * This file contains basic streams pipeline and interface for Unity scene called "Streams" * Main goal is to show basic streams of OAK Device: color camera, mono right and left cameras, depth and disparity */ #pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" #pragma GCC diagnostic ignored "-Wdouble-promotion" #if _MSC_VER // this is defined when compiling with Visual Studio #define EXPORT_API __declspec(dllexport) // Visual Studio needs annotating exported functions with this #else #define EXPORT_API // XCode does not need annotating exported functions, so define is empty #endif // ------------------------------------------------------------------------ // Plugin itself #include #include #include #include "../utility.hpp" // Common necessary includes for development using depthai library #include "depthai/depthai.hpp" #include "depthai/device/Device.hpp" #include "depthai-unity/device/Streams.hpp" #include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/spdlog.h" #include "nlohmann/json.hpp" float maxDisparity; /** * Pipeline creation based on streams template * * @param config pipeline configuration * @returns pipeline */ dai::Pipeline createStreamsPipeline(PipelineConfig *config) { dai::Pipeline pipeline; std::shared_ptr xlinkOut; auto colorCam = pipeline.create(); // Color camera preview if (config->previewSizeWidth > 0 && config->previewSizeHeight > 0) { xlinkOut = pipeline.create(); xlinkOut->setStreamName("preview"); colorCam->setPreviewSize(config->previewSizeWidth, config->previewSizeHeight); colorCam->preview.link(xlinkOut->input); } // Color camera properties colorCam->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P); if (config->colorCameraResolution == 1) colorCam->setResolution(dai::ColorCameraProperties::SensorResolution::THE_4_K); if (config->colorCameraResolution == 2) colorCam->setResolution(dai::ColorCameraProperties::SensorResolution::THE_12_MP); if (config->colorCameraResolution == 3) colorCam->setResolution(dai::ColorCameraProperties::SensorResolution::THE_13_MP); colorCam->setInterleaved(config->colorCameraInterleaved); colorCam->setColorOrder(dai::ColorCameraProperties::ColorOrder::BGR); if (config->colorCameraColorOrder == 1) colorCam->setColorOrder(dai::ColorCameraProperties::ColorOrder::RGB); colorCam->setFps(config->colorCameraFPS); // Depth if (config->confidenceThreshold > 0) { auto left = pipeline.create(); auto right = pipeline.create(); auto stereo = pipeline.create(); // For RGB-Depth align if (config->ispScaleF1 > 0 && config->ispScaleF2 > 0) colorCam->setIspScale(config->ispScaleF1, config->ispScaleF2); if (config->manualFocus > 0) colorCam->initialControl.setManualFocus(config->manualFocus); // Mono camera properties left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P); if (config->monoLCameraResolution == 1) left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_720_P); if (config->monoLCameraResolution == 2) left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_800_P); if (config->monoLCameraResolution == 3) left->setResolution(dai::MonoCameraProperties::SensorResolution::THE_480_P); left->setBoardSocket(dai::CameraBoardSocket::LEFT); right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_400_P); if (config->monoRCameraResolution == 1) right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_720_P); if (config->monoRCameraResolution == 2) right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_800_P); if (config->monoRCameraResolution == 3) right->setResolution(dai::MonoCameraProperties::SensorResolution::THE_480_P); right->setBoardSocket(dai::CameraBoardSocket::RIGHT); // Stereo properties stereo->setConfidenceThreshold(config->confidenceThreshold); // LR-check is required for depth alignment stereo->setLeftRightCheck(config->leftRightCheck); //stereo->setDepthAlign(dai::CameraBoardSocket::RGB); stereo->setSubpixel(config->subpixel); stereo->initialConfig.setMedianFilter(dai::MedianFilter::MEDIAN_OFF); if (config->medianFilter == 1) stereo->initialConfig.setMedianFilter(dai::MedianFilter::KERNEL_3x3); if (config->medianFilter == 2) stereo->initialConfig.setMedianFilter(dai::MedianFilter::KERNEL_5x5); if (config->medianFilter == 3) stereo->initialConfig.setMedianFilter(dai::MedianFilter::KERNEL_7x7); // Linking left->out.link(stereo->left); right->out.link(stereo->right); auto xoutDepth = pipeline.create(); xoutDepth->setStreamName("depth"); stereo->depth.link(xoutDepth->input); auto xoutDisp = pipeline.create(); xoutDisp->setStreamName("disparity"); stereo->disparity.link(xoutDisp->input); auto xoutMonoR = pipeline.create(); xoutMonoR->setStreamName("monoR"); stereo->rectifiedRight.link(xoutMonoR->input); auto xoutMonoL = pipeline.create(); xoutMonoL->setStreamName("monoL"); stereo->rectifiedLeft.link(xoutMonoL->input); maxDisparity = stereo->initialConfig.getMaxDisparity(); } // SYSTEM INFORMATION if (config->rate > 0.0f) { // Define source and output auto sysLog = pipeline.create(); auto xout = pipeline.create(); xout->setStreamName("sysinfo"); // Properties sysLog->setRate(config->rate); // 1 hz updates // Linking sysLog->out.link(xout->input); } // IMU if (config->freq > 0) { auto imu = pipeline.create(); auto xlinkOutImu = pipeline.create(); xlinkOutImu->setStreamName("imu"); // enable ROTATION_VECTOR at 400 hz rate imu->enableIMUSensor(dai::IMUSensor::ROTATION_VECTOR, config->freq); // above this threshold packets will be sent in batch of X, if the host is not blocked and USB bandwidth is available imu->setBatchReportThreshold(config->batchReportThreshold); // maximum number of IMU packets in a batch, if it's reached device will block sending until host can receive it // if lower or equal to batchReportThreshold then the sending is always blocking on device // useful to reduce device's CPU load and number of lost packets, if CPU load is high on device side due to multiple nodes imu->setMaxBatchReports(config->maxBatchReports); // Link plugins IMU -> XLINK imu->out.link(xlinkOutImu->input); } return pipeline; } extern "C" { /** * Pipeline creation based on streams template * * @param config pipeline configuration * @returns pipeline */ EXPORT_API bool InitStreams(PipelineConfig *config) { dai::Pipeline pipeline = createStreamsPipeline(config); // If deviceId is empty .. just pick first available device bool res = false; if (strcmp(config->deviceId,"NONE")==0 || strcmp(config->deviceId,"")==0) res = DAIStartPipeline(pipeline,config->deviceNum,NULL); else res = DAIStartPipeline(pipeline,config->deviceNum,config->deviceId); return res; } /** * Pipeline results * * @param frameInfo camera images pointers * @param getPreview True if color preview image is requested, False otherwise. Requires previewSize in pipeline creation. * @param useDepth True if depth information is requested, False otherwise. Requires confidenceThreshold in pipeline creation. * @param retrieveInformation True if system information is requested, False otherwise. Requires rate in pipeline creation. * @param useIMU True if IMU information is requested, False otherwise. Requires freq in pipeline creation. * @param deviceNum Device selection on unity dropdown * @returns Json with results or information about device availability. */ EXPORT_API const char* StreamsResults(FrameInfo *frameInfo, bool getPreview, bool useDepth, bool retrieveInformation, bool useIMU, int deviceNum) { using namespace std; using namespace std::chrono; // Get device deviceNum std::shared_ptr device = GetDevice(deviceNum); // Device no available if (device == NULL) { char* ret = (char*)::malloc(strlen("{\"error\":\"NO_DEVICE\"}")); ::memcpy(ret, "{\"error\":\"NO_DEVICE\"}",strlen("{\"error\":\"NO_DEVICE\"}")); ret[strlen("{\"error\":\"NO_DEVICE\"}")] = 0; return ret; } // If device deviceNum is running pipeline if (IsDeviceRunning(deviceNum)) { // preview image cv::Mat frame; std::shared_ptr imgFrame; // other images cv::Mat depthFrame, depthFrameOrig, dispFrameOrig, dispFrame, monoRFrameOrig, monoRFrame, monoLFrameOrig, monoLFrame; // no specific information need it nlohmann::json streamsJson = {}; std::shared_ptr preview; std::shared_ptr depthQueue; std::shared_ptr dispQueue; std::shared_ptr monoRQueue; std::shared_ptr monoLQueue; // if preview image is requested. True in this case. if (getPreview) preview = device->getOutputQueue("preview",1,false); // if depth images are requested. All images. if (useDepth) { depthQueue = device->getOutputQueue("depth", 1, false); dispQueue = device->getOutputQueue("disparity", 1, false); monoRQueue = device->getOutputQueue("monoR", 1, false); monoLQueue = device->getOutputQueue("monoL", 1, false); } if (getPreview) { auto imgFrames = preview->tryGetAll(); auto countd = imgFrames.size(); if (countd > 0) { auto imgFrame = imgFrames[countd-1]; if(imgFrame){ //printf("Frame - w: %d, h: %d\n", imgFrame->getWidth(), imgFrame->getHeight()); frame = toMat(imgFrame->getData(), imgFrame->getWidth(), imgFrame->getHeight(), 3, 1); toARGB(frame,frameInfo->colorPreviewData); } } } vector> imgDepthFrames,imgDispFrames,imgMonoRFrames,imgMonoLFrames; std::shared_ptr imgDepthFrame,imgDispFrame,imgMonoRFrame,imgMonoLFrame; // In this case we allocate before Texture2D (ARGB32) and memcpy pointer data if (useDepth) { // Depth imgDepthFrames = depthQueue->tryGetAll(); int count = imgDepthFrames.size(); if (count > 0) { imgDepthFrame = imgDepthFrames[count-1]; depthFrameOrig = imgDepthFrame->getFrame(); cv::normalize(depthFrameOrig, depthFrame, 255, 0, cv::NORM_INF, CV_8UC1); cv::equalizeHist(depthFrame, depthFrame); cv::cvtColor(depthFrame, depthFrame, cv::COLOR_GRAY2BGR); toARGB(depthFrame,frameInfo->depthData); } // Disparity imgDispFrames = dispQueue->tryGetAll(); int countd = imgDispFrames.size(); if (countd > 0) { imgDispFrame = imgDispFrames[countd-1]; dispFrameOrig = imgDispFrame->getFrame(); dispFrameOrig.convertTo(dispFrame, CV_8UC1, 255 / maxDisparity); cv::applyColorMap(dispFrame, dispFrame, cv::COLORMAP_JET); toARGB(dispFrame,frameInfo->disparityData); } // Mono R imgMonoRFrames = monoRQueue->tryGetAll(); int countr = imgMonoRFrames.size(); if (countr > 0) { imgMonoRFrame = imgMonoRFrames[countr-1]; monoRFrameOrig = imgMonoRFrame->getFrame(); cv::cvtColor(monoRFrameOrig, monoRFrame, cv::COLOR_GRAY2BGR); toARGB(monoRFrame,frameInfo->rectifiedRData); } // Mono L imgMonoLFrames = monoLQueue->tryGetAll(); int countl = imgMonoLFrames.size(); if (countl > 0) { imgMonoLFrame = imgMonoLFrames[countl-1]; monoLFrameOrig = imgMonoLFrame->getFrame(); cv::cvtColor(monoLFrameOrig, monoLFrame, cv::COLOR_GRAY2BGR); toARGB(monoLFrame,frameInfo->rectifiedLData); } } // SYSTEM INFORMATION if (retrieveInformation) streamsJson["sysinfo"] = GetDeviceInfo(device); // IMU if (useIMU) streamsJson["imu"] = GetIMU(device); char* ret = (char*)::malloc(strlen(streamsJson.dump().c_str())+1); ::memcpy(ret, streamsJson.dump().c_str(),strlen(streamsJson.dump().c_str())); ret[strlen(streamsJson.dump().c_str())] = 0; return ret; } char* ret = (char*)::malloc(strlen("{\"error\":\"DEVICE_NOT_RUNNING\"}")); ::memcpy(ret, "{\"error\":\"DEVICE_NOT_RUNNING\"}",strlen("{\"error\":\"DEVICE_NOT_RUNNING\"}")); ret[strlen("{\"error\":\"DEVICE_NOT_RUNNING\"}")] = 0; return ret; } }// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include #include "openvino/opsets/opset6.hpp" #include "paddlepaddle_frontend/utility.hpp" namespace ov { namespace frontend { namespace pdpd { namespace op { NamedOutputs lstm(const NodeContext& node); NamedOutputs rnn(const NodeContext& node) { auto mode = node.get_attribute("mode"); PDPD_ASSERT(mode == "LSTM", "[Paddle Frontend]RNN Only Supports LSTM Ops Conversion now, don't " "support " + mode); return lstm(node); } } // namespace op } // namespace pdpd } // namespace frontend } // namespace ov zihadboss/UVA-Solutions #include using namespace std; int main() { int T; cin >> T; while (T--) { int sum = 0; for (int i = 0; i < 4; ++i) { int num; cin >> num; for (int j = 0; j < 2; ++j) { sum += num % 10; num /= 10; sum += num * 2 % 10; sum += (num % 10 * 2 / 10); num /= 10; } } if (sum % 10) cout << "Invalid\n"; else cout << "Valid\n"; } }1-10 #include "catch.hpp" #include "symcxx/core.hpp" TEST_CASE( "homogenous ordering", "[symcxx::Symbol]" ) { auto ns = symcxx::NameSpace(); auto s0_id = ns.make_symbol(0); auto s1_id = ns.make_symbol(1); auto& s0 = ns.instances[s0_id]; auto& s1 = ns.instances[s1_id]; REQUIRE( s0.data.idx_pair.first == 0 ); REQUIRE( s1.data.idx_pair.first == 1 ); REQUIRE( s0 < s1 ); REQUIRE( not (s1 < s0) ); REQUIRE( s0 <= s1 ); REQUIRE( not (s1 <= s0) ); REQUIRE( s0 <= s0 ); REQUIRE( s0 == s0 ); REQUIRE( not (s1 == s0) ); REQUIRE( s0 != s1 ); REQUIRE( not (s1 != s1) ); REQUIRE( s1 >= s0 ); REQUIRE( not (s0 >= s1) ); REQUIRE( s1 >= s1 ); REQUIRE( s1 > s0 ); REQUIRE( not (s0 > s1) ); } TEST_CASE( "heterogeneous ordering", "[symcxx::Basic]" ) { auto ns = symcxx::NameSpace(); auto idx_i = ns.make_integer(0); auto idx_s = ns.make_symbol(0); auto& s = ns.instances[idx_s]; auto& i = ns.instances[idx_i]; REQUIRE( s < i ); REQUIRE( not (i < s) ); REQUIRE( s <= i ); REQUIRE( not (i <= s) ); REQUIRE( i <= i ); REQUIRE( i == i ); REQUIRE( not (s == i) ); REQUIRE( s != i ); REQUIRE( not (i != i) ); REQUIRE( i >= s ); REQUIRE( not (s >= i) ); REQUIRE( i >= i ); REQUIRE( i > s ); REQUIRE( not (s > i) ); } TEST_CASE( "evalb", "[symcxx::Basic]" ) { std::cout << "evalb" << std::endl; auto ns = symcxx::NameSpace(); auto idx_i = ns.make_integer(0); auto idx_i2 = ns.make_integer(0); REQUIRE( idx_i == idx_i2 ); auto idx_s = ns.make_symbol(0); auto idx_lt = ns.lt(idx_s, idx_i); auto idx_le = ns.le(idx_s, idx_i); auto idx_eq = ns.eq(idx_s, idx_i); auto idx_ne = ns.ne(idx_s, idx_i); auto idx_ge = ns.ge(idx_s, idx_i); auto idx_gt = ns.gt(idx_s, idx_i); auto& s = ns.instances[idx_s]; REQUIRE( s.data.idx_pair.first == 0 ); auto& i = ns.instances[idx_i]; REQUIRE( i.data.intgr == 0 ); auto& lt = ns.instances[idx_lt]; auto& le = ns.instances[idx_le]; auto& eq = ns.instances[idx_eq]; auto& ne = ns.instances[idx_ne]; auto& ge = ns.instances[idx_ge]; auto& gt = ns.instances[idx_gt]; const double x1 = 1.0; const double xm1 = -1.0; const double x0 = 0.0; const double s_eval = s.evalf(&x1); REQUIRE( (s_eval - 1.0) == 0 ); REQUIRE( not lt.evalb(&x1) ); REQUIRE( not lt.evalb(&x0) ); REQUIRE( lt.evalb(&xm1) ); REQUIRE( not le.evalb(&x1) ); REQUIRE( le.evalb(&xm1) ); REQUIRE( le.evalb(&x0) ); REQUIRE( not eq.evalb(&x1) ); REQUIRE( eq.evalb(&x0) ); REQUIRE( not ne.evalb(&x0) ); REQUIRE( ne.evalb(&x1) ); REQUIRE( not ge.evalb(&xm1) ); REQUIRE( ge.evalb(&x1) ); REQUIRE( ge.evalb(&x0) ); REQUIRE( not gt.evalb(&xm1) ); REQUIRE( not gt.evalb(&x0) ); REQUIRE( gt.evalb(&x1) ); } TEST_CASE( "add_ordering", "[symcxx::Basic]" ) { auto ns = symcxx::NameSpace(); auto idx_i = ns.make_integer(0); auto idx_s = ns.make_symbol(0); auto& s = ns.instances[idx_s]; auto& i = ns.instances[idx_i]; REQUIRE( s < i ); REQUIRE( not (i < s) ); REQUIRE( s <= i ); REQUIRE( not (i <= s) ); REQUIRE( i <= i ); REQUIRE( i == i ); REQUIRE( not (s == i) ); REQUIRE( s != i ); REQUIRE( not (i != i) ); REQUIRE( i >= s ); REQUIRE( not (s >= i) ); REQUIRE( i >= i ); REQUIRE( i > s ); REQUIRE( not (s > i) ); } //Ctrl+k , Ctrl+c 전체 주석처리 //Ctrl+k , Ctrl+u 전체 주석해제 //3D gasket #include #include #include "InitShader.h" #include "math.h" #include "vec.h" #include #define BUFFER_OFFSET( offset ) ((GLvoid*) (offset)) int NumSubdivides; int NumTriangles; int NumVertices; vec3* points; vec3* colors; int index = 0; void init(); void display(); void idle(); void divide_triangle(vec3 a, vec3 b, vec3 c, unsigned int cnt,unsigned int coli); void triangle(vec3 a, vec3 b, vec3 c, unsigned int coli); void setGasketVertices(unsigned int col1, unsigned int col2, unsigned int col3, unsigned int col4); void gasketSetKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); void gasketSetMouseButtonCallback(GLFWwindow* window, int button, int action, int mods); vec3 baseVertices[] = { vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.942809f, -0.333333f), vec3(-0.816497f, -0.471405f, -0.333333f), vec3(0.816497f, -0.471405f, -0.333333f) }; vec3 baseColors[] = { vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f), vec3(1.0f, 0.0f, 1.0f) }; int main() { GLFWwindow* window; if (!glfwInit()) /* Initialize the library */ return -1; window = glfwCreateWindow(512, 512, "practice0507", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); /* Make the window's context current */ if (glewInit() != GLEW_OK) std::cout << "Error\n"; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// init(); glfwSetKeyCallback(window, gasketSetKeyCallback); glfwSetMouseButtonCallback(window, gasketSetMouseButtonCallback); /////////////////////////////////////////////////////////////////////////// /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { display(); idle(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); free(points); free(colors); return 0; } void init() { NumSubdivides=3; NumTriangles=4*pow(3.0f,NumSubdivides); NumVertices=3*NumTriangles; points = (vec3*)malloc(sizeof(vec3)*NumVertices); colors = (vec3*)malloc(sizeof(vec3)*NumVertices); // set gasket vertices divide_triangle(baseVertices[0],baseVertices[1], baseVertices[2], NumSubdivides, 0); divide_triangle(baseVertices[3],baseVertices[2], baseVertices[1], NumSubdivides, 1); divide_triangle(baseVertices[0],baseVertices[3], baseVertices[1], NumSubdivides, 2); divide_triangle(baseVertices[0],baseVertices[2], baseVertices[3], NumSubdivides, 3); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, 2*sizeof(vec3)*NumVertices, NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vec3)*NumVertices, points); glBufferSubData(GL_ARRAY_BUFFER, sizeof(vec3)*NumVertices, sizeof(vec3)*NumVertices, colors); // bufferdata GLuint simpleProgram = InitShader("vshader0507.glsl", "fshader0507.glsl"); glUseProgram(simpleProgram); GLuint vPosition = glGetAttribLocation(simpleProgram, "vPosition"); glEnableVertexAttribArray(vPosition); glVertexAttribPointer(vPosition, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); GLuint vColor = glGetAttribLocation(simpleProgram, "vColor"); glEnableVertexAttribArray(vColor); glVertexAttribPointer(vColor, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vec3)*NumVertices)); glEnable(GL_DEPTH_TEST); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, NumVertices); } void idle() { } void divide_triangle(vec3 a, vec3 b, vec3 c, unsigned int cnt, unsigned int coli) { if(cnt > 0) { vec3 ab = (a+b)/2.0f; vec3 ac = (a+c)/2.0f; vec3 bc = (b+c)/2.0f; divide_triangle(a, ab, ac, cnt-1, coli); divide_triangle(c, ac, bc, cnt-1, coli); divide_triangle(b, bc, ab, cnt-1, coli); } else { triangle(a,b, c, coli); } } void triangle(vec3 a, vec3 b, vec3 c, unsigned int coli) { points[index] = a; colors[index++] = baseColors[coli]; points[index] = b; colors[index++] = baseColors[coli]; points[index] = c; colors[index++] = baseColors[coli]; //coli++하면 색깔 이쁨 대신 면의 색상들을 구분할 수 없음. } void gasketSetKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_1 && action == GLFW_PRESS) { std::cout << "Key 1 is pressed\n"; } } void gasketSetMouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { std::cout << "Left button is pressed\n"; } } void setGasketVertices(unsigned int col1, unsigned int col2, unsigned int col3, unsigned int col4) { std::cout << "Left button is pressed\n"; } /* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #include "ShapedWeights.hpp" #include #include namespace onnx2trt { class TensorOrWeights { union { nvinfer1::ITensor* _tensor; ShapedWeights _weights; }; enum { NODE_TENSOR, NODE_WEIGHTS } _variant; public: TensorOrWeights() : _tensor(nullptr) , _variant(NODE_TENSOR) { } TensorOrWeights(nvinfer1::ITensor* tensor) : _tensor(tensor) , _variant(NODE_TENSOR) { } TensorOrWeights(ShapedWeights const& weights) : _weights(weights) , _variant(NODE_WEIGHTS) { } bool is_tensor() const { return _variant == NODE_TENSOR; } bool is_weights() const { return _variant == NODE_WEIGHTS; } bool isNullTensor() const { return is_tensor() && _tensor == nullptr; } nvinfer1::ITensor& tensor() { assert(!isNullTensor()); return *_tensor; } nvinfer1::ITensor const& tensor() const { assert(!isNullTensor()); return *_tensor; } ShapedWeights& weights() { assert(is_weights()); return _weights; } ShapedWeights const& weights() const { assert(is_weights()); return _weights; } nvinfer1::Dims shape() const { return is_tensor() ? _tensor->getDimensions() : _weights.shape; } explicit operator bool() const { return is_tensor() ? _tensor != nullptr : static_cast(_weights); } bool isInt32() const { return is_tensor() ? _tensor->getType() == nvinfer1::DataType::kINT32 : _weights.type == ::ONNX_NAMESPACE::TensorProto_DataType_INT32; } bool isBool() const { return is_tensor() ? _tensor->getType() == nvinfer1::DataType::kBOOL : _weights.type == ::ONNX_NAMESPACE::TensorProto_DataType_BOOL; } }; } // namespace onnx2trt third_party/skia_m63/third_party/externals/spirv-tools/test/hex_float_test.cpp // Copyright (c) 2015-2016 The Khronos Group 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. #include #include #include #include #include #include #include #include "source/util/hex_float.h" #include "unit_spirv.h" namespace { using ::testing::Eq; using spvutils::BitwiseCast; using spvutils::Float16; using spvutils::FloatProxy; using spvutils::HexFloat; using spvutils::ParseNormalFloat; // In this file "encode" means converting a number into a string, // and "decode" means converting a string into a number. using HexFloatTest = ::testing::TestWithParam, std::string>>; using DecodeHexFloatTest = ::testing::TestWithParam>>; using HexDoubleTest = ::testing::TestWithParam, std::string>>; using DecodeHexDoubleTest = ::testing::TestWithParam>>; // Hex-encodes a float value. template std::string EncodeViaHexFloat(const T& value) { std::stringstream ss; ss << spvutils::HexFloat(value); return ss.str(); } // The following two tests can't be DRY because they take different parameter // types. TEST_P(HexFloatTest, EncodeCorrectly) { EXPECT_THAT(EncodeViaHexFloat(GetParam().first), Eq(GetParam().second)); } TEST_P(HexDoubleTest, EncodeCorrectly) { EXPECT_THAT(EncodeViaHexFloat(GetParam().first), Eq(GetParam().second)); } // Decodes a hex-float string. template FloatProxy Decode(const std::string& str) { spvutils::HexFloat> decoded(0.f); EXPECT_TRUE((std::stringstream(str) >> decoded).eof()); return decoded.value(); } TEST_P(HexFloatTest, DecodeCorrectly) { EXPECT_THAT(Decode(GetParam().second), Eq(GetParam().first)); } TEST_P(HexDoubleTest, DecodeCorrectly) { EXPECT_THAT(Decode(GetParam().second), Eq(GetParam().first)); } INSTANTIATE_TEST_CASE_P( Float32Tests, HexFloatTest, ::testing::ValuesIn(std::vector, std::string>>({ {0.f, "0x0p+0"}, {1.f, "0x1p+0"}, {2.f, "0x1p+1"}, {3.f, "0x1.8p+1"}, {0.5f, "0x1p-1"}, {0.25f, "0x1p-2"}, {0.75f, "0x1.8p-1"}, {-0.f, "-0x0p+0"}, {-1.f, "-0x1p+0"}, {-0.5f, "-0x1p-1"}, {-0.25f, "-0x1p-2"}, {-0.75f, "-0x1.8p-1"}, // Larger numbers {512.f, "0x1p+9"}, {-512.f, "-0x1p+9"}, {1024.f, "0x1p+10"}, {-1024.f, "-0x1p+10"}, {1024.f + 8.f, "0x1.02p+10"}, {-1024.f - 8.f, "-0x1.02p+10"}, // Small numbers {1.0f / 512.f, "0x1p-9"}, {1.0f / -512.f, "-0x1p-9"}, {1.0f / 1024.f, "0x1p-10"}, {1.0f / -1024.f, "-0x1p-10"}, {1.0f / 1024.f + 1.0f / 8.f, "0x1.02p-3"}, {1.0f / -1024.f - 1.0f / 8.f, "-0x1.02p-3"}, // lowest non-denorm {float(ldexp(1.0f, -126)), "0x1p-126"}, {float(ldexp(-1.0f, -126)), "-0x1p-126"}, // Denormalized values {float(ldexp(1.0f, -127)), "0x1p-127"}, {float(ldexp(1.0f, -127) / 2.0f), "0x1p-128"}, {float(ldexp(1.0f, -127) / 4.0f), "0x1p-129"}, {float(ldexp(1.0f, -127) / 8.0f), "0x1p-130"}, {float(ldexp(-1.0f, -127)), "-0x1p-127"}, {float(ldexp(-1.0f, -127) / 2.0f), "-0x1p-128"}, {float(ldexp(-1.0f, -127) / 4.0f), "-0x1p-129"}, {float(ldexp(-1.0f, -127) / 8.0f), "-0x1p-130"}, {float(ldexp(1.0, -127) + (ldexp(1.0, -127) / 2.0f)), "0x1.8p-127"}, {float(ldexp(1.0, -127) / 2.0 + (ldexp(1.0, -127) / 4.0f)), "0x1.8p-128"}, })),); INSTANTIATE_TEST_CASE_P( Float32NanTests, HexFloatTest, ::testing::ValuesIn(std::vector, std::string>>({ // Various NAN and INF cases {uint32_t(0xFF800000), "-0x1p+128"}, // -inf {uint32_t(0x7F800000), "0x1p+128"}, // inf {uint32_t(0xFFC00000), "-0x1.8p+128"}, // -nan {uint32_t(0xFF800100), "-0x1.0002p+128"}, // -nan {uint32_t(0xFF800c00), "-0x1.0018p+128"}, // -nan {uint32_t(0xFF80F000), "-0x1.01ep+128"}, // -nan {uint32_t(0xFFFFFFFF), "-0x1.fffffep+128"}, // -nan {uint32_t(0x7FC00000), "0x1.8p+128"}, // +nan {uint32_t(0x7F800100), "0x1.0002p+128"}, // +nan {uint32_t(0x7f800c00), "0x1.0018p+128"}, // +nan {uint32_t(0x7F80F000), "0x1.01ep+128"}, // +nan {uint32_t(0x7FFFFFFF), "0x1.fffffep+128"}, // +nan })),); INSTANTIATE_TEST_CASE_P( Float64Tests, HexDoubleTest, ::testing::ValuesIn( std::vector, std::string>>({ {0., "0x0p+0"}, {1., "0x1p+0"}, {2., "0x1p+1"}, {3., "0x1.8p+1"}, {0.5, "0x1p-1"}, {0.25, "0x1p-2"}, {0.75, "0x1.8p-1"}, {-0., "-0x0p+0"}, {-1., "-0x1p+0"}, {-0.5, "-0x1p-1"}, {-0.25, "-0x1p-2"}, {-0.75, "-0x1.8p-1"}, // Larger numbers {512., "0x1p+9"}, {-512., "-0x1p+9"}, {1024., "0x1p+10"}, {-1024., "-0x1p+10"}, {1024. + 8., "0x1.02p+10"}, {-1024. - 8., "-0x1.02p+10"}, // Large outside the range of normal floats {ldexp(1.0, 128), "0x1p+128"}, {ldexp(1.0, 129), "0x1p+129"}, {ldexp(-1.0, 128), "-0x1p+128"}, {ldexp(-1.0, 129), "-0x1p+129"}, {ldexp(1.0, 128) + ldexp(1.0, 90), "0x1.0000000004p+128"}, {ldexp(1.0, 129) + ldexp(1.0, 120), "0x1.008p+129"}, {ldexp(-1.0, 128) + ldexp(1.0, 90), "-0x1.fffffffff8p+127"}, {ldexp(-1.0, 129) + ldexp(1.0, 120), "-0x1.ffp+128"}, // Small numbers {1.0 / 512., "0x1p-9"}, {1.0 / -512., "-0x1p-9"}, {1.0 / 1024., "0x1p-10"}, {1.0 / -1024., "-0x1p-10"}, {1.0 / 1024. + 1.0 / 8., "0x1.02p-3"}, {1.0 / -1024. - 1.0 / 8., "-0x1.02p-3"}, // Small outside the range of normal floats {ldexp(1.0, -128), "0x1p-128"}, {ldexp(1.0, -129), "0x1p-129"}, {ldexp(-1.0, -128), "-0x1p-128"}, {ldexp(-1.0, -129), "-0x1p-129"}, {ldexp(1.0, -128) + ldexp(1.0, -90), "0x1.0000000004p-90"}, {ldexp(1.0, -129) + ldexp(1.0, -120), "0x1.008p-120"}, {ldexp(-1.0, -128) + ldexp(1.0, -90), "0x1.fffffffff8p-91"}, {ldexp(-1.0, -129) + ldexp(1.0, -120), "0x1.ffp-121"}, // lowest non-denorm {ldexp(1.0, -1022), "0x1p-1022"}, {ldexp(-1.0, -1022), "-0x1p-1022"}, // Denormalized values {ldexp(1.0, -1023), "0x1p-1023"}, {ldexp(1.0, -1023) / 2.0, "0x1p-1024"}, {ldexp(1.0, -1023) / 4.0, "0x1p-1025"}, {ldexp(1.0, -1023) / 8.0, "0x1p-1026"}, {ldexp(-1.0, -1024), "-0x1p-1024"}, {ldexp(-1.0, -1024) / 2.0, "-0x1p-1025"}, {ldexp(-1.0, -1024) / 4.0, "-0x1p-1026"}, {ldexp(-1.0, -1024) / 8.0, "-0x1p-1027"}, {ldexp(1.0, -1023) + (ldexp(1.0, -1023) / 2.0), "0x1.8p-1023"}, {ldexp(1.0, -1023) / 2.0 + (ldexp(1.0, -1023) / 4.0), "0x1.8p-1024"}, })),); INSTANTIATE_TEST_CASE_P( Float64NanTests, HexDoubleTest, ::testing::ValuesIn(std::vector< std::pair, std::string>>({ // Various NAN and INF cases {uint64_t(0xFFF0000000000000LL), "-0x1p+1024"}, //-inf {uint64_t(0x7FF0000000000000LL), "0x1p+1024"}, //+inf {uint64_t(0xFFF8000000000000LL), "-0x1.8p+1024"}, // -nan {uint64_t(0xFFF0F00000000000LL), "-0x1.0fp+1024"}, // -nan {uint64_t(0xFFF0000000000001LL), "-0x1.0000000000001p+1024"}, // -nan {uint64_t(0xFFF0000300000000LL), "-0x1.00003p+1024"}, // -nan {uint64_t(0xFFFFFFFFFFFFFFFFLL), "-0x1.fffffffffffffp+1024"}, // -nan {uint64_t(0x7FF8000000000000LL), "0x1.8p+1024"}, // +nan {uint64_t(0x7FF0F00000000000LL), "0x1.0fp+1024"}, // +nan {uint64_t(0x7FF0000000000001LL), "0x1.0000000000001p+1024"}, // -nan {uint64_t(0x7FF0000300000000LL), "0x1.00003p+1024"}, // -nan {uint64_t(0x7FFFFFFFFFFFFFFFLL), "0x1.fffffffffffffp+1024"}, // -nan })),); TEST(HexFloatStreamTest, OperatorLeftShiftPreservesFloatAndFill) { std::stringstream s; s << std::setw(4) << std::oct << std::setfill('x') << 8 << " " << FloatProxy(uint32_t(0xFF800100)) << " " << std::setw(4) << 9; EXPECT_THAT(s.str(), Eq(std::string("xx10 -0x1.0002p+128 xx11"))); } TEST(HexDoubleStreamTest, OperatorLeftShiftPreservesFloatAndFill) { std::stringstream s; s << std::setw(4) << std::oct << std::setfill('x') << 8 << " " << FloatProxy(uint64_t(0x7FF0F00000000000LL)) << " " << std::setw(4) << 9; EXPECT_THAT(s.str(), Eq(std::string("xx10 0x1.0fp+1024 xx11"))); } TEST_P(DecodeHexFloatTest, DecodeCorrectly) { EXPECT_THAT(Decode(GetParam().first), Eq(GetParam().second)); } TEST_P(DecodeHexDoubleTest, DecodeCorrectly) { EXPECT_THAT(Decode(GetParam().first), Eq(GetParam().second)); } INSTANTIATE_TEST_CASE_P( Float32DecodeTests, DecodeHexFloatTest, ::testing::ValuesIn(std::vector>>({ {"0x0p+000", 0.f}, {"0x0p0", 0.f}, {"0x0p-0", 0.f}, // flush to zero cases {"0x1p-500", 0.f}, // Exponent underflows. {"-0x1p-500", -0.f}, {"0x0.00000000001p-126", 0.f}, // Fraction causes underflow. {"-0x0.0000000001p-127", -0.f}, {"-0x0.01p-142", -0.f}, // Fraction causes additional underflow. {"0x0.01p-142", 0.f}, // Some floats that do not encode the same way as they decode. {"0x2p+0", 2.f}, {"0xFFp+0", 255.f}, {"0x0.8p+0", 0.5f}, {"0x0.4p+0", 0.25f}, })),); INSTANTIATE_TEST_CASE_P( Float32DecodeInfTests, DecodeHexFloatTest, ::testing::ValuesIn(std::vector>>({ // inf cases {"-0x1p+128", uint32_t(0xFF800000)}, // -inf {"0x32p+127", uint32_t(0x7F800000)}, // inf {"0x32p+500", uint32_t(0x7F800000)}, // inf {"-0x32p+127", uint32_t(0xFF800000)}, // -inf })),); INSTANTIATE_TEST_CASE_P( Float64DecodeTests, DecodeHexDoubleTest, ::testing::ValuesIn( std::vector>>({ {"0x0p+000", 0.}, {"0x0p0", 0.}, {"0x0p-0", 0.}, // flush to zero cases {"0x1p-5000", 0.}, // Exponent underflows. {"-0x1p-5000", -0.}, {"0x0.0000000000000001p-1023", 0.}, // Fraction causes underflow. {"-0x0.000000000000001p-1024", -0.}, {"-0x0.01p-1090", -0.f}, // Fraction causes additional underflow. {"0x0.01p-1090", 0.}, // Some floats that do not encode the same way as they decode. {"0x2p+0", 2.}, {"0xFFp+0", 255.}, {"0x0.8p+0", 0.5}, {"0x0.4p+0", 0.25}, })),); INSTANTIATE_TEST_CASE_P( Float64DecodeInfTests, DecodeHexDoubleTest, ::testing::ValuesIn( std::vector>>({ // inf cases {"-0x1p+1024", uint64_t(0xFFF0000000000000)}, // -inf {"0x32p+1023", uint64_t(0x7FF0000000000000)}, // inf {"0x32p+5000", uint64_t(0x7FF0000000000000)}, // inf {"-0x32p+1023", uint64_t(0xFFF0000000000000)}, // -inf })),); TEST(FloatProxy, ValidConversion) { EXPECT_THAT(FloatProxy(1.f).getAsFloat(), Eq(1.0f)); EXPECT_THAT(FloatProxy(32.f).getAsFloat(), Eq(32.0f)); EXPECT_THAT(FloatProxy(-1.f).getAsFloat(), Eq(-1.0f)); EXPECT_THAT(FloatProxy(0.f).getAsFloat(), Eq(0.0f)); EXPECT_THAT(FloatProxy(-0.f).getAsFloat(), Eq(-0.0f)); EXPECT_THAT(FloatProxy(1.2e32f).getAsFloat(), Eq(1.2e32f)); EXPECT_TRUE(std::isinf(FloatProxy(uint32_t(0xFF800000)).getAsFloat())); EXPECT_TRUE(std::isinf(FloatProxy(uint32_t(0x7F800000)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0xFFC00000)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0xFF800100)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0xFF800c00)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0xFF80F000)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0xFFFFFFFF)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0x7FC00000)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0x7F800100)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0x7f800c00)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0x7F80F000)).getAsFloat())); EXPECT_TRUE(std::isnan(FloatProxy(uint32_t(0x7FFFFFFF)).getAsFloat())); EXPECT_THAT(FloatProxy(uint32_t(0xFF800000)).data(), Eq(0xFF800000u)); EXPECT_THAT(FloatProxy(uint32_t(0x7F800000)).data(), Eq(0x7F800000u)); EXPECT_THAT(FloatProxy(uint32_t(0xFFC00000)).data(), Eq(0xFFC00000u)); EXPECT_THAT(FloatProxy(uint32_t(0xFF800100)).data(), Eq(0xFF800100u)); EXPECT_THAT(FloatProxy(uint32_t(0xFF800c00)).data(), Eq(0xFF800c00u)); EXPECT_THAT(FloatProxy(uint32_t(0xFF80F000)).data(), Eq(0xFF80F000u)); EXPECT_THAT(FloatProxy(uint32_t(0xFFFFFFFF)).data(), Eq(0xFFFFFFFFu)); EXPECT_THAT(FloatProxy(uint32_t(0x7FC00000)).data(), Eq(0x7FC00000u)); EXPECT_THAT(FloatProxy(uint32_t(0x7F800100)).data(), Eq(0x7F800100u)); EXPECT_THAT(FloatProxy(uint32_t(0x7f800c00)).data(), Eq(0x7f800c00u)); EXPECT_THAT(FloatProxy(uint32_t(0x7F80F000)).data(), Eq(0x7F80F000u)); EXPECT_THAT(FloatProxy(uint32_t(0x7FFFFFFF)).data(), Eq(0x7FFFFFFFu)); } TEST(FloatProxy, Nan) { EXPECT_TRUE(FloatProxy(uint32_t(0xFFC00000)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0xFF800100)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0xFF800c00)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0xFF80F000)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0xFFFFFFFF)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0x7FC00000)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0x7F800100)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0x7f800c00)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0x7F80F000)).isNan()); EXPECT_TRUE(FloatProxy(uint32_t(0x7FFFFFFF)).isNan()); } TEST(FloatProxy, Negation) { EXPECT_THAT((-FloatProxy(1.f)).getAsFloat(), Eq(-1.0f)); EXPECT_THAT((-FloatProxy(0.f)).getAsFloat(), Eq(-0.0f)); EXPECT_THAT((-FloatProxy(-1.f)).getAsFloat(), Eq(1.0f)); EXPECT_THAT((-FloatProxy(-0.f)).getAsFloat(), Eq(0.0f)); EXPECT_THAT((-FloatProxy(32.f)).getAsFloat(), Eq(-32.0f)); EXPECT_THAT((-FloatProxy(-32.f)).getAsFloat(), Eq(32.0f)); EXPECT_THAT((-FloatProxy(1.2e32f)).getAsFloat(), Eq(-1.2e32f)); EXPECT_THAT((-FloatProxy(-1.2e32f)).getAsFloat(), Eq(1.2e32f)); EXPECT_THAT( (-FloatProxy(std::numeric_limits::infinity())).getAsFloat(), Eq(-std::numeric_limits::infinity())); EXPECT_THAT((-FloatProxy(-std::numeric_limits::infinity())) .getAsFloat(), Eq(std::numeric_limits::infinity())); } // Test conversion of FloatProxy values to strings. // // In previous cases, we always wrapped the FloatProxy value in a HexFloat // before conversion to a string. In the following cases, the FloatProxy // decides for itself whether to print as a regular number or as a hex float. using FloatProxyFloatTest = ::testing::TestWithParam, std::string>>; using FloatProxyDoubleTest = ::testing::TestWithParam, std::string>>; // Converts a float value to a string via a FloatProxy. template std::string EncodeViaFloatProxy(const T& value) { std::stringstream ss; ss << value; return ss.str(); } // Converts a floating point string so that the exponent prefix // is 'e', and the exponent value does not have leading zeros. // The Microsoft runtime library likes to write things like "2.5E+010". // Convert that to "2.5e+10". // We don't care what happens to strings that are not floating point // strings. std::string NormalizeExponentInFloatString(std::string in) { std::string result; // Reserve one spot for the terminating null, even when the sscanf fails. std::vector prefix(in.size() + 1); char e; char plus_or_minus; int exponent; // in base 10 if ((4 == std::sscanf(in.c_str(), "%[-+.0123456789]%c%c%d", prefix.data(), &e, &plus_or_minus, &exponent)) && (e == 'e' || e == 'E') && (plus_or_minus == '-' || plus_or_minus == '+')) { // It looks like a floating point value with exponent. std::stringstream out; out << prefix.data() << 'e' << plus_or_minus << exponent; result = out.str(); } else { result = in; } return result; } TEST(NormalizeFloat, Sample) { EXPECT_THAT(NormalizeExponentInFloatString(""), Eq("")); EXPECT_THAT(NormalizeExponentInFloatString("1e-12"), Eq("1e-12")); EXPECT_THAT(NormalizeExponentInFloatString("1E+14"), Eq("1e+14")); EXPECT_THAT(NormalizeExponentInFloatString("1e-0012"), Eq("1e-12")); EXPECT_THAT(NormalizeExponentInFloatString("1.263E+014"), Eq("1.263e+14")); } // The following two tests can't be DRY because they take different parameter // types. TEST_P(FloatProxyFloatTest, EncodeCorrectly) { EXPECT_THAT( NormalizeExponentInFloatString(EncodeViaFloatProxy(GetParam().first)), Eq(GetParam().second)); } TEST_P(FloatProxyDoubleTest, EncodeCorrectly) { EXPECT_THAT( NormalizeExponentInFloatString(EncodeViaFloatProxy(GetParam().first)), Eq(GetParam().second)); } INSTANTIATE_TEST_CASE_P( Float32Tests, FloatProxyFloatTest, ::testing::ValuesIn(std::vector, std::string>>({ // Zero {0.f, "0"}, // Normal numbers {1.f, "1"}, {-0.25f, "-0.25"}, {1000.0f, "1000"}, // Still normal numbers, but with large magnitude exponents. {float(ldexp(1.f, 126)), "8.50706e+37"}, {float(ldexp(-1.f, -126)), "-1.17549e-38"}, // denormalized values are printed as hex floats. {float(ldexp(1.0f, -127)), "0x1p-127"}, {float(ldexp(1.5f, -128)), "0x1.8p-128"}, {float(ldexp(1.25, -129)), "0x1.4p-129"}, {float(ldexp(1.125, -130)), "0x1.2p-130"}, {float(ldexp(-1.0f, -127)), "-0x1p-127"}, {float(ldexp(-1.0f, -128)), "-0x1p-128"}, {float(ldexp(-1.0f, -129)), "-0x1p-129"}, {float(ldexp(-1.5f, -130)), "-0x1.8p-130"}, // NaNs {FloatProxy(uint32_t(0xFFC00000)), "-0x1.8p+128"}, {FloatProxy(uint32_t(0xFF800100)), "-0x1.0002p+128"}, {std::numeric_limits::infinity(), "0x1p+128"}, {-std::numeric_limits::infinity(), "-0x1p+128"}, })),); INSTANTIATE_TEST_CASE_P( Float64Tests, FloatProxyDoubleTest, ::testing::ValuesIn( std::vector, std::string>>({ {0., "0"}, {1., "1"}, {-0.25, "-0.25"}, {1000.0, "1000"}, // Large outside the range of normal floats {ldexp(1.0, 128), "3.40282366920938e+38"}, {ldexp(1.5, 129), "1.02084710076282e+39"}, {ldexp(-1.0, 128), "-3.40282366920938e+38"}, {ldexp(-1.5, 129), "-1.02084710076282e+39"}, // Small outside the range of normal floats {ldexp(1.5, -129), "2.20405190779179e-39"}, {ldexp(-1.5, -129), "-2.20405190779179e-39"}, // lowest non-denorm {ldexp(1.0, -1022), "2.2250738585072e-308"}, {ldexp(-1.0, -1022), "-2.2250738585072e-308"}, // Denormalized values {ldexp(1.125, -1023), "0x1.2p-1023"}, {ldexp(-1.375, -1024), "-0x1.6p-1024"}, // NaNs {uint64_t(0x7FF8000000000000LL), "0x1.8p+1024"}, {uint64_t(0xFFF0F00000000000LL), "-0x1.0fp+1024"}, // Infinity {std::numeric_limits::infinity(), "0x1p+1024"}, {-std::numeric_limits::infinity(), "-0x1p+1024"}, })),); // double is used so that unbiased_exponent can be used with the output // of ldexp directly. int32_t unbiased_exponent(double f) { return spvutils::HexFloat>( static_cast(f)).getUnbiasedNormalizedExponent(); } int16_t unbiased_half_exponent(uint16_t f) { return spvutils::HexFloat>(f) .getUnbiasedNormalizedExponent(); } TEST(HexFloatOperationTest, UnbiasedExponent) { // Float cases EXPECT_EQ(0, unbiased_exponent(ldexp(1.0f, 0))); EXPECT_EQ(-32, unbiased_exponent(ldexp(1.0f, -32))); EXPECT_EQ(42, unbiased_exponent(ldexp(1.0f, 42))); EXPECT_EQ(125, unbiased_exponent(ldexp(1.0f, 125))); // Saturates to 128 EXPECT_EQ(128, unbiased_exponent(ldexp(1.0f, 256))); EXPECT_EQ(-100, unbiased_exponent(ldexp(1.0f, -100))); EXPECT_EQ(-127, unbiased_exponent(ldexp(1.0f, -127))); // First denorm EXPECT_EQ(-128, unbiased_exponent(ldexp(1.0f, -128))); EXPECT_EQ(-129, unbiased_exponent(ldexp(1.0f, -129))); EXPECT_EQ(-140, unbiased_exponent(ldexp(1.0f, -140))); // Smallest representable number EXPECT_EQ(-126 - 23, unbiased_exponent(ldexp(1.0f, -126 - 23))); // Should get rounded to 0 first. EXPECT_EQ(0, unbiased_exponent(ldexp(1.0f, -127 - 23))); // Float16 cases // The exponent is represented in the bits 0x7C00 // The offset is -15 EXPECT_EQ(0, unbiased_half_exponent(0x3C00)); EXPECT_EQ(3, unbiased_half_exponent(0x4800)); EXPECT_EQ(-1, unbiased_half_exponent(0x3800)); EXPECT_EQ(-14, unbiased_half_exponent(0x0400)); EXPECT_EQ(16, unbiased_half_exponent(0x7C00)); EXPECT_EQ(10, unbiased_half_exponent(0x6400)); // Smallest representable number EXPECT_EQ(-24, unbiased_half_exponent(0x0001)); } // Creates a float that is the sum of 1/(2 ^ fractions[i]) for i in factions float float_fractions(const std::vector& fractions) { float f = 0; for(int32_t i: fractions) { f += std::ldexp(1.0f, -i); } return f; } // Returns the normalized significand of a HexFloat> // that was created by calling float_fractions with the input fractions, // raised to the power of exp. uint32_t normalized_significand(const std::vector& fractions, uint32_t exp) { return spvutils::HexFloat>( static_cast(ldexp(float_fractions(fractions), exp))) .getNormalizedSignificand(); } // Sets the bits from MSB to LSB of the significand part of a float. // For example 0 would set the bit 23 (counting from LSB to MSB), // and 1 would set the 22nd bit. uint32_t bits_set(const std::vector& bits) { const uint32_t top_bit = 1u << 22u; uint32_t val= 0; for(uint32_t i: bits) { val |= top_bit >> i; } return val; } // The same as bits_set but for a Float16 value instead of 32-bit floating // point. uint16_t half_bits_set(const std::vector& bits) { const uint32_t top_bit = 1u << 9u; uint32_t val= 0; for(uint32_t i: bits) { val |= top_bit >> i; } return static_cast(val); } TEST(HexFloatOperationTest, NormalizedSignificand) { // For normalized numbers (the following) it should be a simple matter // of getting rid of the top implicit bit EXPECT_EQ(bits_set({}), normalized_significand({0}, 0)); EXPECT_EQ(bits_set({0}), normalized_significand({0, 1}, 0)); EXPECT_EQ(bits_set({0, 1}), normalized_significand({0, 1, 2}, 0)); EXPECT_EQ(bits_set({1}), normalized_significand({0, 2}, 0)); EXPECT_EQ(bits_set({1}), normalized_significand({0, 2}, 32)); EXPECT_EQ(bits_set({1}), normalized_significand({0, 2}, 126)); // For denormalized numbers we expect the normalized significand to // shift as if it were normalized. This means, in practice that the // top_most set bit will be cut off. Looks very similar to above (on purpose) EXPECT_EQ(bits_set({}), normalized_significand({0}, -127)); EXPECT_EQ(bits_set({3}), normalized_significand({0, 4}, -128)); EXPECT_EQ(bits_set({3}), normalized_significand({0, 4}, -127)); EXPECT_EQ(bits_set({}), normalized_significand({22}, -127)); EXPECT_EQ(bits_set({0}), normalized_significand({21, 22}, -127)); } // Returns the 32-bit floating point value created by // calling setFromSignUnbiasedExponentAndNormalizedSignificand // on a HexFloat> float set_from_sign(bool negative, int32_t unbiased_exponent, uint32_t significand, bool round_denorm_up) { spvutils::HexFloat> f(0.f); f.setFromSignUnbiasedExponentAndNormalizedSignificand( negative, unbiased_exponent, significand, round_denorm_up); return f.value().getAsFloat(); } TEST(HexFloatOperationTests, SetFromSignUnbiasedExponentAndNormalizedSignificand) { EXPECT_EQ(1.f, set_from_sign(false, 0, 0, false)); // Tests insertion of various denormalized numbers with and without round up. EXPECT_EQ(static_cast(ldexp(1.f, -149)), set_from_sign(false, -149, 0, false)); EXPECT_EQ(static_cast(ldexp(1.f, -149)), set_from_sign(false, -149, 0, true)); EXPECT_EQ(0.f, set_from_sign(false, -150, 1, false)); EXPECT_EQ(static_cast(ldexp(1.f, -149)), set_from_sign(false, -150, 1, true)); EXPECT_EQ(ldexp(1.0f, -127), set_from_sign(false, -127, 0, false)); EXPECT_EQ(ldexp(1.0f, -128), set_from_sign(false, -128, 0, false)); EXPECT_EQ(float_fractions({0, 1, 2, 5}), set_from_sign(false, 0, bits_set({0, 1, 4}), false)); EXPECT_EQ(ldexp(float_fractions({0, 1, 2, 5}), -32), set_from_sign(false, -32, bits_set({0, 1, 4}), false)); EXPECT_EQ(ldexp(float_fractions({0, 1, 2, 5}), -128), set_from_sign(false, -128, bits_set({0, 1, 4}), false)); // The negative cases from above. EXPECT_EQ(-1.f, set_from_sign(true, 0, 0, false)); EXPECT_EQ(-ldexp(1.0, -127), set_from_sign(true, -127, 0, false)); EXPECT_EQ(-ldexp(1.0, -128), set_from_sign(true, -128, 0, false)); EXPECT_EQ(-float_fractions({0, 1, 2, 5}), set_from_sign(true, 0, bits_set({0, 1, 4}), false)); EXPECT_EQ(-ldexp(float_fractions({0, 1, 2, 5}), -32), set_from_sign(true, -32, bits_set({0, 1, 4}), false)); EXPECT_EQ(-ldexp(float_fractions({0, 1, 2, 5}), -128), set_from_sign(true, -128, bits_set({0, 1, 4}), false)); } TEST(HexFloatOperationTests, NonRounding) { // Rounding from 32-bit hex-float to 32-bit hex-float should be trivial, // except in the denorm case which is a bit more complex. using HF = spvutils::HexFloat>; bool carry_bit = false; spvutils::round_direction rounding[] = { spvutils::round_direction::kToZero, spvutils::round_direction::kToNearestEven, spvutils::round_direction::kToPositiveInfinity, spvutils::round_direction::kToNegativeInfinity}; // Everything fits, so this should be straight-forward for (spvutils::round_direction round : rounding) { EXPECT_EQ(bits_set({}), HF(0.f).getRoundedNormalizedSignificand( round, &carry_bit)); EXPECT_FALSE(carry_bit); EXPECT_EQ(bits_set({0}), HF(float_fractions({0, 1})) .getRoundedNormalizedSignificand(round, &carry_bit)); EXPECT_FALSE(carry_bit); EXPECT_EQ(bits_set({1, 3}), HF(float_fractions({0, 2, 4})) .getRoundedNormalizedSignificand(round, &carry_bit)); EXPECT_FALSE(carry_bit); EXPECT_EQ( bits_set({0, 1, 4}), HF(static_cast(-ldexp(float_fractions({0, 1, 2, 5}), -128))) .getRoundedNormalizedSignificand(round, &carry_bit)); EXPECT_FALSE(carry_bit); EXPECT_EQ( bits_set({0, 1, 4, 22}), HF(static_cast(float_fractions({0, 1, 2, 5, 23}))) .getRoundedNormalizedSignificand(round, &carry_bit)); EXPECT_FALSE(carry_bit); } } using RD = spvutils::round_direction; struct RoundSignificandCase { float source_float; std::pair expected_results; spvutils::round_direction round; }; using HexFloatRoundTest = ::testing::TestWithParam; TEST_P(HexFloatRoundTest, RoundDownToFP16) { using HF = spvutils::HexFloat>; using HF16 = spvutils::HexFloat>; HF input_value(GetParam().source_float); bool carry_bit = false; EXPECT_EQ(GetParam().expected_results.first, input_value.getRoundedNormalizedSignificand( GetParam().round, &carry_bit)); EXPECT_EQ(carry_bit, GetParam().expected_results.second); } // clang-format off INSTANTIATE_TEST_CASE_P(F32ToF16, HexFloatRoundTest, ::testing::ValuesIn(std::vector( { {float_fractions({0}), std::make_pair(half_bits_set({}), false), RD::kToZero}, {float_fractions({0}), std::make_pair(half_bits_set({}), false), RD::kToNearestEven}, {float_fractions({0}), std::make_pair(half_bits_set({}), false), RD::kToPositiveInfinity}, {float_fractions({0}), std::make_pair(half_bits_set({}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1}), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {float_fractions({0, 1, 11}), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {float_fractions({0, 1, 11}), std::make_pair(half_bits_set({0, 9}), false), RD::kToPositiveInfinity}, {float_fractions({0, 1, 11}), std::make_pair(half_bits_set({0}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1, 11}), std::make_pair(half_bits_set({0}), false), RD::kToNearestEven}, {float_fractions({0, 1, 10, 11}), std::make_pair(half_bits_set({0, 9}), false), RD::kToZero}, {float_fractions({0, 1, 10, 11}), std::make_pair(half_bits_set({0, 8}), false), RD::kToPositiveInfinity}, {float_fractions({0, 1, 10, 11}), std::make_pair(half_bits_set({0, 9}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1, 10, 11}), std::make_pair(half_bits_set({0, 8}), false), RD::kToNearestEven}, {float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0, 9}), false), RD::kToPositiveInfinity}, {float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0, 9}), false), RD::kToNearestEven}, {-float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {-float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0}), false), RD::kToPositiveInfinity}, {-float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0, 9}), false), RD::kToNegativeInfinity}, {-float_fractions({0, 1, 11, 12}), std::make_pair(half_bits_set({0, 9}), false), RD::kToNearestEven}, {float_fractions({0, 1, 11, 22}), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {float_fractions({0, 1, 11, 22}), std::make_pair(half_bits_set({0, 9}), false), RD::kToPositiveInfinity}, {float_fractions({0, 1, 11, 22}), std::make_pair(half_bits_set({0}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1, 11, 22}), std::make_pair(half_bits_set({0, 9}), false), RD::kToNearestEven}, // Carries {float_fractions({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}), std::make_pair(half_bits_set({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}), false), RD::kToZero}, {float_fractions({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}), std::make_pair(half_bits_set({}), true), RD::kToPositiveInfinity}, {float_fractions({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}), std::make_pair(half_bits_set({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}), false), RD::kToNegativeInfinity}, {float_fractions({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}), std::make_pair(half_bits_set({}), true), RD::kToNearestEven}, // Cases where original number was denorm. Note: this should have no effect // the number is pre-normalized. {static_cast(ldexp(float_fractions({0, 1, 11, 13}), -128)), std::make_pair(half_bits_set({0}), false), RD::kToZero}, {static_cast(ldexp(float_fractions({0, 1, 11, 13}), -129)), std::make_pair(half_bits_set({0, 9}), false), RD::kToPositiveInfinity}, {static_cast(ldexp(float_fractions({0, 1, 11, 13}), -131)), std::make_pair(half_bits_set({0}), false), RD::kToNegativeInfinity}, {static_cast(ldexp(float_fractions({0, 1, 11, 13}), -130)), std::make_pair(half_bits_set({0, 9}), false), RD::kToNearestEven}, })),); // clang-format on struct UpCastSignificandCase { uint16_t source_half; uint32_t expected_result; }; using HexFloatRoundUpSignificandTest = ::testing::TestWithParam; TEST_P(HexFloatRoundUpSignificandTest, Widening) { using HF = spvutils::HexFloat>; using HF16 = spvutils::HexFloat>; bool carry_bit = false; spvutils::round_direction rounding[] = { spvutils::round_direction::kToZero, spvutils::round_direction::kToNearestEven, spvutils::round_direction::kToPositiveInfinity, spvutils::round_direction::kToNegativeInfinity}; // Everything fits, so everything should just be bit-shifts. for (spvutils::round_direction round : rounding) { carry_bit = false; HF16 input_value(GetParam().source_half); EXPECT_EQ( GetParam().expected_result, input_value.getRoundedNormalizedSignificand(round, &carry_bit)) << std::hex << "0x" << input_value.getRoundedNormalizedSignificand(round, &carry_bit) << " 0x" << GetParam().expected_result; EXPECT_FALSE(carry_bit); } } INSTANTIATE_TEST_CASE_P(F16toF32, HexFloatRoundUpSignificandTest, // 0xFC00 of the source 16-bit hex value cover the sign and the exponent. // They are ignored for this test. ::testing::ValuesIn(std::vector( { {0x3F00, 0x600000}, {0x0F00, 0x600000}, {0x0F01, 0x602000}, {0x0FFF, 0x7FE000}, })),); struct DownCastTest { float source_float; uint16_t expected_half; std::vector directions; }; std::string get_round_text(spvutils::round_direction direction) { #define CASE(round_direction) \ case round_direction: \ return #round_direction switch (direction) { CASE(spvutils::round_direction::kToZero); CASE(spvutils::round_direction::kToPositiveInfinity); CASE(spvutils::round_direction::kToNegativeInfinity); CASE(spvutils::round_direction::kToNearestEven); } #undef CASE return ""; } using HexFloatFP32To16Tests = ::testing::TestWithParam; TEST_P(HexFloatFP32To16Tests, NarrowingCasts) { using HF = spvutils::HexFloat>; using HF16 = spvutils::HexFloat>; HF f(GetParam().source_float); for (auto round : GetParam().directions) { HF16 half(0); f.castTo(half, round); EXPECT_EQ(GetParam().expected_half, half.value().getAsFloat().get_value()) << get_round_text(round) << " " << std::hex << spvutils::BitwiseCast(GetParam().source_float) << " cast to: " << half.value().getAsFloat().get_value(); } } const uint16_t positive_infinity = 0x7C00; const uint16_t negative_infinity = 0xFC00; INSTANTIATE_TEST_CASE_P(F32ToF16, HexFloatFP32To16Tests, ::testing::ValuesIn(std::vector( { // Exactly representable as half. {0.f, 0x0, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {-0.f, 0x8000, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {1.0f, 0x3C00, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {-1.0f, 0xBC00, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {float_fractions({0, 1, 10}) , 0x3E01, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {-float_fractions({0, 1, 10}) , 0xBE01, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(ldexp(float_fractions({0, 1, 10}), 3)), 0x4A01, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(-ldexp(float_fractions({0, 1, 10}), 3)), 0xCA01, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, // Underflow {static_cast(ldexp(1.0f, -25)), 0x0, {RD::kToZero, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(ldexp(1.0f, -25)), 0x1, {RD::kToPositiveInfinity}}, {static_cast(-ldexp(1.0f, -25)), 0x8000, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNearestEven}}, {static_cast(-ldexp(1.0f, -25)), 0x8001, {RD::kToNegativeInfinity}}, {static_cast(ldexp(1.0f, -24)), 0x1, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, // Overflow {static_cast(ldexp(1.0f, 16)), positive_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(ldexp(1.0f, 18)), positive_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(ldexp(1.3f, 16)), positive_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(-ldexp(1.0f, 16)), negative_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(-ldexp(1.0f, 18)), negative_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {static_cast(-ldexp(1.3f, 16)), negative_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, // Transfer of Infinities {std::numeric_limits::infinity(), positive_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, {-std::numeric_limits::infinity(), negative_infinity, {RD::kToZero, RD::kToPositiveInfinity, RD::kToNegativeInfinity, RD::kToNearestEven}}, // Nans are below because we cannot test for equality. })),); struct UpCastCase{ uint16_t source_half; float expected_float; }; using HexFloatFP16To32Tests = ::testing::TestWithParam; TEST_P(HexFloatFP16To32Tests, WideningCasts) { using HF = spvutils::HexFloat>; using HF16 = spvutils::HexFloat>; HF16 f(GetParam().source_half); spvutils::round_direction rounding[] = { spvutils::round_direction::kToZero, spvutils::round_direction::kToNearestEven, spvutils::round_direction::kToPositiveInfinity, spvutils::round_direction::kToNegativeInfinity}; // Everything fits, so everything should just be bit-shifts. for (spvutils::round_direction round : rounding) { HF flt(0.f); f.castTo(flt, round); EXPECT_EQ(GetParam().expected_float, flt.value().getAsFloat()) << get_round_text(round) << " " << std::hex << spvutils::BitwiseCast(GetParam().source_half) << " cast to: " << flt.value().getAsFloat(); } } INSTANTIATE_TEST_CASE_P(F16ToF32, HexFloatFP16To32Tests, ::testing::ValuesIn(std::vector( { {0x0000, 0.f}, {0x8000, -0.f}, {0x3C00, 1.0f}, {0xBC00, -1.0f}, {0x3F00, float_fractions({0, 1, 2})}, {0xBF00, -float_fractions({0, 1, 2})}, {0x3F01, float_fractions({0, 1, 2, 10})}, {0xBF01, -float_fractions({0, 1, 2, 10})}, // denorm {0x0001, static_cast(ldexp(1.0, -24))}, {0x0002, static_cast(ldexp(1.0, -23))}, {0x8001, static_cast(-ldexp(1.0, -24))}, {0x8011, static_cast(-ldexp(1.0, -20) + -ldexp(1.0, -24))}, // inf {0x7C00, std::numeric_limits::infinity()}, {0xFC00, -std::numeric_limits::infinity()}, })),); TEST(HexFloatOperationTests, NanTests) { using HF = spvutils::HexFloat>; using HF16 = spvutils::HexFloat>; spvutils::round_direction rounding[] = { spvutils::round_direction::kToZero, spvutils::round_direction::kToNearestEven, spvutils::round_direction::kToPositiveInfinity, spvutils::round_direction::kToNegativeInfinity}; // Everything fits, so everything should just be bit-shifts. for (spvutils::round_direction round : rounding) { HF16 f16(0); HF f(0.f); HF(std::numeric_limits::quiet_NaN()).castTo(f16, round); EXPECT_TRUE(f16.value().isNan()); HF(std::numeric_limits::signaling_NaN()).castTo(f16, round); EXPECT_TRUE(f16.value().isNan()); HF16(0x7C01).castTo(f, round); EXPECT_TRUE(f.value().isNan()); HF16(0x7C11).castTo(f, round); EXPECT_TRUE(f.value().isNan()); HF16(0xFC01).castTo(f, round); EXPECT_TRUE(f.value().isNan()); HF16(0x7C10).castTo(f, round); EXPECT_TRUE(f.value().isNan()); HF16(0xFF00).castTo(f, round); EXPECT_TRUE(f.value().isNan()); } } // A test case for parsing good and bad HexFloat> literals. template struct FloatParseCase { std::string literal; bool negate_value; bool expect_success; HexFloat> expected_value; }; using ParseNormalFloatTest = ::testing::TestWithParam>; TEST_P(ParseNormalFloatTest, Samples) { std::stringstream input(GetParam().literal); HexFloat> parsed_value(0.0f); ParseNormalFloat(input, GetParam().negate_value, parsed_value); EXPECT_NE(GetParam().expect_success, input.fail()) << " literal: " << GetParam().literal << " negate: " << GetParam().negate_value; if (GetParam().expect_success) { EXPECT_THAT(parsed_value.value(), Eq(GetParam().expected_value.value())) << " literal: " << GetParam().literal << " negate: " << GetParam().negate_value; } } // Returns a FloatParseCase with expected failure. template FloatParseCase BadFloatParseCase(std::string literal, bool negate_value, T expected_value) { HexFloat> proxy_expected_value(expected_value); return FloatParseCase{literal, negate_value, false, proxy_expected_value}; } // Returns a FloatParseCase that should successfully parse to a given value. template FloatParseCase GoodFloatParseCase(std::string literal, bool negate_value, T expected_value) { HexFloat> proxy_expected_value(expected_value); return FloatParseCase{literal, negate_value, true, proxy_expected_value}; } INSTANTIATE_TEST_CASE_P( FloatParse, ParseNormalFloatTest, ::testing::ValuesIn(std::vector>{ // Failing cases due to trivially incorrect syntax. BadFloatParseCase("abc", false, 0.0f), BadFloatParseCase("abc", true, 0.0f), // Valid cases. GoodFloatParseCase("0", false, 0.0f), GoodFloatParseCase("0.0", false, 0.0f), GoodFloatParseCase("-0.0", false, -0.0f), GoodFloatParseCase("2.0", false, 2.0f), GoodFloatParseCase("-2.0", false, -2.0f), GoodFloatParseCase("+2.0", false, 2.0f), // Cases with negate_value being true. GoodFloatParseCase("0.0", true, -0.0f), GoodFloatParseCase("2.0", true, -2.0f), // When negate_value is true, we should not accept a // leading minus or plus. BadFloatParseCase("-0.0", true, 0.0f), BadFloatParseCase("-2.0", true, 0.0f), BadFloatParseCase("+0.0", true, 0.0f), BadFloatParseCase("+2.0", true, 0.0f), // Overflow is an error for 32-bit float parsing. BadFloatParseCase("1e40", false, FLT_MAX), BadFloatParseCase("1e40", true, -FLT_MAX), BadFloatParseCase("-1e40", false, -FLT_MAX), // We can't have -1e40 and negate_value == true since // that represents an original case of "--1e40" which // is invalid. }),); using ParseNormalFloat16Test = ::testing::TestWithParam>; TEST_P(ParseNormalFloat16Test, Samples) { std::stringstream input(GetParam().literal); HexFloat> parsed_value(0); ParseNormalFloat(input, GetParam().negate_value, parsed_value); EXPECT_NE(GetParam().expect_success, input.fail()) << " literal: " << GetParam().literal << " negate: " << GetParam().negate_value; if (GetParam().expect_success) { EXPECT_THAT(parsed_value.value(), Eq(GetParam().expected_value.value())) << " literal: " << GetParam().literal << " negate: " << GetParam().negate_value; } } INSTANTIATE_TEST_CASE_P( Float16Parse, ParseNormalFloat16Test, ::testing::ValuesIn(std::vector>{ // Failing cases due to trivially incorrect syntax. BadFloatParseCase("abc", false, uint16_t{0}), BadFloatParseCase("abc", true, uint16_t{0}), // Valid cases. GoodFloatParseCase("0", false, uint16_t{0}), GoodFloatParseCase("0.0", false, uint16_t{0}), GoodFloatParseCase("-0.0", false, uint16_t{0x8000}), GoodFloatParseCase("2.0", false, uint16_t{0x4000}), GoodFloatParseCase("-2.0", false, uint16_t{0xc000}), GoodFloatParseCase("+2.0", false, uint16_t{0x4000}), // Cases with negate_value being true. GoodFloatParseCase("0.0", true, uint16_t{0x8000}), GoodFloatParseCase("2.0", true, uint16_t{0xc000}), // When negate_value is true, we should not accept a leading minus or // plus. BadFloatParseCase("-0.0", true, uint16_t{0}), BadFloatParseCase("-2.0", true, uint16_t{0}), BadFloatParseCase("+0.0", true, uint16_t{0}), BadFloatParseCase("+2.0", true, uint16_t{0}), }),); // A test case for detecting infinities. template struct OverflowParseCase { std::string input; bool expect_success; T expected_value; }; using FloatProxyParseOverflowFloatTest = ::testing::TestWithParam>; TEST_P(FloatProxyParseOverflowFloatTest, Sample) { std::istringstream input(GetParam().input); HexFloat> value(0.0f); input >> value; EXPECT_NE(GetParam().expect_success, input.fail()); if (GetParam().expect_success) { EXPECT_THAT(value.value().getAsFloat(), GetParam().expected_value); } } INSTANTIATE_TEST_CASE_P( FloatOverflow, FloatProxyParseOverflowFloatTest, ::testing::ValuesIn(std::vector>({ {"0", true, 0.0f}, {"0.0", true, 0.0f}, {"1.0", true, 1.0f}, {"1e38", true, 1e38f}, {"-1e38", true, -1e38f}, {"1e40", false, FLT_MAX}, {"-1e40", false, -FLT_MAX}, {"1e400", false, FLT_MAX}, {"-1e400", false, -FLT_MAX}, })),); using FloatProxyParseOverflowDoubleTest = ::testing::TestWithParam>; TEST_P(FloatProxyParseOverflowDoubleTest, Sample) { std::istringstream input(GetParam().input); HexFloat> value(0.0); input >> value; EXPECT_NE(GetParam().expect_success, input.fail()); if (GetParam().expect_success) { EXPECT_THAT(value.value().getAsFloat(), Eq(GetParam().expected_value)); } } INSTANTIATE_TEST_CASE_P( DoubleOverflow, FloatProxyParseOverflowDoubleTest, ::testing::ValuesIn(std::vector>({ {"0", true, 0.0}, {"0.0", true, 0.0}, {"1.0", true, 1.0}, {"1e38", true, 1e38}, {"-1e38", true, -1e38}, {"1e40", true, 1e40}, {"-1e40", true, -1e40}, {"1e400", false, DBL_MAX}, {"-1e400", false, -DBL_MAX}, })),); using FloatProxyParseOverflowFloat16Test = ::testing::TestWithParam>; TEST_P(FloatProxyParseOverflowFloat16Test, Sample) { std::istringstream input(GetParam().input); HexFloat> value(0); input >> value; EXPECT_NE(GetParam().expect_success, input.fail()) << " literal: " << GetParam().input; if (GetParam().expect_success) { EXPECT_THAT(value.value().data(), Eq(GetParam().expected_value)) << " literal: " << GetParam().input; } } INSTANTIATE_TEST_CASE_P( Float16Overflow, FloatProxyParseOverflowFloat16Test, ::testing::ValuesIn(std::vector>({ {"0", true, uint16_t{0}}, {"0.0", true, uint16_t{0}}, {"1.0", true, uint16_t{0x3c00}}, // Overflow for 16-bit float is an error, and returns max or // lowest value. {"1e38", false, uint16_t{0x7bff}}, {"1e40", false, uint16_t{0x7bff}}, {"1e400", false, uint16_t{0x7bff}}, {"-1e38", false, uint16_t{0xfbff}}, {"-1e40", false, uint16_t{0xfbff}}, {"-1e400", false, uint16_t{0xfbff}}, })),); TEST(FloatProxy, Max) { EXPECT_THAT(FloatProxy::max().getAsFloat().get_value(), Eq(uint16_t{0x7bff})); EXPECT_THAT(FloatProxy::max().getAsFloat(), Eq(std::numeric_limits::max())); EXPECT_THAT(FloatProxy::max().getAsFloat(), Eq(std::numeric_limits::max())); } TEST(FloatProxy, Lowest) { EXPECT_THAT(FloatProxy::lowest().getAsFloat().get_value(), Eq(uint16_t{0xfbff})); EXPECT_THAT(FloatProxy::lowest().getAsFloat(), Eq(std::numeric_limits::lowest())); EXPECT_THAT(FloatProxy::lowest().getAsFloat(), Eq(std::numeric_limits::lowest())); } // TODO(awoloszyn): Add fp16 tests and HexFloatTraits. } // anonymous namespace dacap/aseprite-interprocessing-demo1-10 /* * Sync aseprite image via websocket - server */ #include "tigr/tigr.h" #include "ixwebsocket/IXWebSocketServer.h" #include "ixwebsocket/IXWebSocketMessageType.h" #include TPixel* pixels; unsigned long w, h; bool update = false; void tigrResize(Tigr* bmp, int w, int h) { TPixel* newpix = (TPixel*)calloc(w * h, sizeof(TPixel)); free(bmp->pix); bmp->pix = newpix; bmp->w = w; bmp->h = h; } // async callback void handleMessage(std::shared_ptr connectionState, ix::WebSocket& webSocket, const ix::WebSocketMessagePtr& msg) { if (msg->type == ix::WebSocketMessageType::Message && msg->binary) { unsigned long* hdr = (unsigned long*)msg->str.c_str(); unsigned char* data = (unsigned char*)msg->str.c_str() + 3 * sizeof(unsigned long); if (hdr[0] == 'I') { w = hdr[1]; h = hdr[2]; pixels = (TPixel*)realloc(pixels, w * h * 4); memcpy(pixels, data, w * h * 4); update = true; } } } int main() { // init ix::initNetSystem(); Tigr* screen = tigrWindow(320, 240, "Rawr", 0); Tigr* bmp = tigrBitmap(1, 1); pixels = (TPixel*)malloc(1); tigrSetPostFX(screen, 1.0, 1.0, 0.4, 1.4); // zoomer scanlines ix::WebSocketServer serv(34613); serv.disablePerMessageDeflate(); serv.setOnClientMessageCallback(&handleMessage); serv.listenAndStart(); // main loop while (!tigrClosed(screen)) { if (update) { tigrResize(bmp, w, h); screen->w = bmp->w; screen->h = bmp->h; memcpy(bmp->pix, pixels, w * h * sizeof(TPixel)); update = false; } tigrClear(screen, tigrRGB(0x80, 0x80, 0x80)); tigrBlitAlpha(screen, bmp, 0, 0, 0, 0, bmp->w, bmp->h, 1.0); tigrUpdate(screen); } // clean up tigrFree(screen); tigrFree(bmp); serv.stop(); ix::uninitNetSystem(); return 0; }1-10 // System includes #include #include // OpenCL includes #include // Project includes // Constants, globals const int ELEMENTS = 2048; // elements in each vector // Signatures char* readSource(const char *sourceFilename); int main(int argc, char ** argv) { printf("Detecting Platform and Devices..\n\n"); size_t datasize = sizeof(int)*ELEMENTS; int *A, *B; // Input arrays int *C; // Output array // Allocate space for input/output data A = (int*)malloc(datasize); B = (int*)malloc(datasize); C = (int*)malloc(datasize); if(A == NULL || B == NULL || C == NULL) { perror("malloc"); exit(-1); } // Initialize the input data for(int i = 0; i < ELEMENTS; i++) { A[i] = i; B[i] = i; } cl_int status; // use as return value for most OpenCL functions cl_uint numPlatforms = 0; cl_platform_id *platforms; // Query for the number of recongnized platforms status = clGetPlatformIDs(0, NULL, &numPlatforms); if(status != CL_SUCCESS) { printf("clGetPlatformIDs failed\n"); exit(-1); } // Make sure some platforms were found if(numPlatforms == 0) { printf("No platforms detected.\n"); exit(-1); } // Allocate enough space for each platform platforms = (cl_platform_id*)malloc(numPlatforms*sizeof(cl_platform_id)); if(platforms == NULL) { perror("malloc"); exit(-1); } // Fill in platforms clGetPlatformIDs(numPlatforms, platforms, NULL); if(status != CL_SUCCESS) { printf("clGetPlatformIDs failed\n"); exit(-1); } // Print out some basic information about each platform printf("%u platforms detected\n", numPlatforms); for(unsigned int i = 0; i < numPlatforms; i++) { char buf[100]; printf("Platform %u: \n", i); status = clGetPlatformInfo(platforms[i], CL_PLATFORM_VENDOR, sizeof(buf), buf, NULL); printf("\tVendor: %s\n", buf); status |= clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, sizeof(buf), buf, NULL); printf("\tName: %s\n", buf); if(status != CL_SUCCESS) { printf("clGetPlatformInfo failed\n"); exit(-1); } } printf("\n"); cl_uint numDevices = 0; cl_device_id *devices; // Retrive the number of devices present status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices); if(status != CL_SUCCESS) { printf("clGetDeviceIDs failed\n"); exit(-1); } // Make sure some devices were found if(numDevices == 0) { printf("No devices detected.\n"); exit(-1); } // Allocate enough space for each device devices = (cl_device_id*)malloc(numDevices*sizeof(cl_device_id)); if(devices == NULL) { perror("malloc"); exit(-1); } // Fill in devices status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, numDevices, devices, NULL); if(status != CL_SUCCESS) { printf("clGetDeviceIDs failed\n"); exit(-1); } // Print out some basic information about each device printf("%u devices detected\n", numDevices); for(unsigned int i = 0; i < numDevices; i++) { char buf[100]; printf("Device %u: \n", i); status = clGetDeviceInfo(devices[i], CL_DEVICE_VENDOR, sizeof(buf), buf, NULL); printf("\tDevice: %s\n", buf); status |= clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(buf), buf, NULL); printf("\tName: %s\n", buf); if(status != CL_SUCCESS) { printf("clGetDeviceInfo failed\n"); exit(-1); } } printf("\n"); cl_context context; // Create a context and associate it with the devices context = clCreateContext(NULL, numDevices, devices, NULL, NULL, &status); if(status != CL_SUCCESS || context == NULL) { printf("clCreateContext failed\n"); exit(-1); } cl_command_queue cmdQueue; // Create a command queue and associate it with the device you // want to execute on cmdQueue = clCreateCommandQueue(context, devices[0], 0, &status); if(status != CL_SUCCESS || cmdQueue == NULL) { printf("clCreateCommandQueue failed\n"); exit(-1); } cl_mem d_A, d_B; // Input buffers on device cl_mem d_C; // Output buffer on device // Create a buffer object (d_A) that contains the data from the host ptr A d_A = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, datasize, A, &status); if(status != CL_SUCCESS || d_A == NULL) { printf("clCreateBuffer failed\n"); exit(-1); } // Create a buffer object (d_B) that contains the data from the host ptr B d_B = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, datasize, B, &status); if(status != CL_SUCCESS || d_B == NULL) { printf("clCreateBuffer failed\n"); exit(-1); } // Create a buffer object (d_C) with enough space to hold the output data d_C = clCreateBuffer(context, CL_MEM_READ_WRITE, datasize, NULL, &status); if(status != CL_SUCCESS || d_C == NULL) { printf("clCreateBuffer failed\n"); exit(-1); } cl_program program; char *source; const char *sourceFile = "vectoradd.cl"; // This function reads in the source code of the program source = readSource(sourceFile); //printf("Program source is:\n%s\n", source); // Create a program. The 'source' string is the code from the // vectoradd.cl file. program = clCreateProgramWithSource(context, 1, (const char**)&source, NULL, &status); if(status != CL_SUCCESS) { printf("clCreateProgramWithSource failed\n"); exit(-1); } cl_int buildErr; // Build (compile & link) the program for the devices. // Save the return value in 'buildErr' (the following // code will print any compilation errors to the screen) buildErr = clBuildProgram(program, numDevices, devices, NULL, NULL, NULL); // If there are build errors, print them to the screen if(buildErr != CL_SUCCESS) { printf("Program failed to build.\n"); cl_build_status buildStatus; for(unsigned int i = 0; i < numDevices; i++) { clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &buildStatus, NULL); if(buildStatus == CL_SUCCESS) { continue; } char *buildLog; size_t buildLogSize; clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_LOG, 0, NULL, &buildLogSize); buildLog = (char*)malloc(buildLogSize); if(buildLog == NULL) { perror("malloc"); exit(-1); } clGetProgramBuildInfo(program, devices[i], CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, NULL); buildLog[buildLogSize-1] = '\0'; printf("Device %u Build Log:\n%s\n", i, buildLog); free(buildLog); } exit(0); } else { printf("No build errors\n"); } cl_kernel kernel; // Create a kernel from the vector addition function (named "vecadd") kernel = clCreateKernel(program, "vecadd", &status); if(status != CL_SUCCESS) { printf("clCreateKernel failed\n"); exit(-1); } // Associate the input and output buffers with the kernel status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &d_A); status |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &d_B); status |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &d_C); if(status != CL_SUCCESS) { printf("clSetKernelArg failed\n"); exit(-1); } // Define an index space (global work size) of threads for execution. // A workgroup size (local work size) is not required, but can be used. size_t globalWorkSize[1]; // There are ELEMENTS threads globalWorkSize[0] = ELEMENTS; // Execute the kernel. // 'globalWorkSize' is the 1D dimension of the work-items status = clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL, globalWorkSize, NULL, 0, NULL, NULL); if(status != CL_SUCCESS) { printf("clEnqueueNDRangeKernel failed\n"); exit(-1); } // Read the OpenCL output buffer (d_C) to the host output array (C) clEnqueueReadBuffer(cmdQueue, d_C, CL_TRUE, 0, datasize, C, 0, NULL, NULL); // Verify correctness bool result = true; for(int i = 0; i < ELEMENTS; i++) { if(C[i] != i+i) { result = false; break; } } if(result) { printf("Output is correct\n"); } else { printf("Output is incorrect\n"); } clReleaseKernel(kernel); clReleaseProgram(program); clReleaseCommandQueue(cmdQueue); clReleaseMemObject(d_A); clReleaseMemObject(d_B); clReleaseMemObject(d_C); clReleaseContext(context); free(A); free(B); free(C); free(source); free(platforms); free(devices); } char* readSource(const char *sourceFilename) { FILE *fp; int err; int size; char *source; fp = fopen(sourceFilename, "rb"); if(fp == NULL) { printf("Could not open kernel file: %s\n", sourceFilename); exit(-1); } err = fseek(fp, 0, SEEK_END); if(err != 0) { printf("Error seeking to end of file\n"); exit(-1); } size = ftell(fp); if(size < 0) { printf("Error getting file position\n"); exit(-1); } err = fseek(fp, 0, SEEK_SET); if(err != 0) { printf("Error seeking to start of file\n"); exit(-1); } source = (char*)malloc(size+1); if(source == NULL) { printf("Error allocating %d bytes for the program source\n", size+1); exit(-1); } err = fread(source, 1, size, fp); if(err != size) { printf("only read %d bytes\n", err); exit(0); } source[size] = '\0'; return source; } leighgarbs/toolbox #include "ConfigurationParameterBase.hpp" //============================================================================================= Configuration::ParameterBase::ParameterBase() : set(false) { } //============================================================================================= Configuration::ParameterBase::~ParameterBase() { } mushroom-x/Misc3D #include #include "property_path.hpp" #include "core_variant/collection.hpp" #include "wg_types/hash_utilities.hpp" namespace wgt { BasePropertyPath::BasePropertyPath( IPropertyPath::ConstPtr & parent, const char * path ) : parent_(parent) , path_( path ? path : "" ) , hash_( 0 ) , recursiveHash_( parent ? parent->getRecursiveHash() : 0 ) //Do deep copy , recursivePath_( parent ? parent->getRecursivePath().str() : "" ) { } void BasePropertyPath::postConstruct() { auto path = generateDecoratedPath(); hash_ = HashUtilities::compute(path); HashUtilities::directCombine(recursiveHash_, hash_); recursivePath_ += path; } IPropertyPath::ConstPtr & BasePropertyPath::getParent() const { return parent_; } uint64_t BasePropertyPath::getHash() const { return hash_; } uint64_t BasePropertyPath::getRecursiveHash() const { return recursiveHash_; } const std::string & BasePropertyPath::getPath() const { return path_.str(); } const SharedString & BasePropertyPath::getRecursivePath() const { return recursivePath_; } IPropertyPath::ConstPtr BasePropertyPath::generateChildPath(IPropertyPath::ConstPtr & self, Variant & key) const { TF_ASSERT(self.get() == this); IPropertyPath::ConstPtr ptr(new CollectionChildPath(self, key)); return ptr; } bool BasePropertyPath::operator==(const char * name) const { return recursivePath_.str() == name; } bool BasePropertyPath::operator==(const std::string & name) const { return recursivePath_.str() == name; } PropertyPath::PropertyPath( IPropertyPath::ConstPtr & parent, const char * path) : BasePropertyPath(parent, path ) { postConstruct(); } std::string PropertyPath::generateDecoratedPath() const { if (parent_ == nullptr) { return path_.str(); } return "." + path_.str(); } IPropertyPath::Type PropertyPath::getType() const { return IPropertyPath::TYPE_PROPERTY; } CollectionPath::CollectionPath( IPropertyPath::ConstPtr & parent, const char * path) : PropertyPath( parent, path ) { } IPropertyPath::ConstPtr CollectionPath::generateChildPath(IPropertyPath::ConstPtr & self, Variant & key) const { TF_ASSERT(self.get() == this); IPropertyPath::ConstPtr ptr( new CollectionChildPath(self, key)); return ptr; } IPropertyPath::Type CollectionPath::getType() const { return IPropertyPath::TYPE_COLLECTION; } CollectionChildPath::CollectionChildPath( IPropertyPath::ConstPtr & parent, Variant & key) : BasePropertyPath( parent ) { size_t indexKey = 0; if (key.tryCast(indexKey)) { path_ += std::to_string(indexKey); } else { key.tryCast(path_); } postConstruct(); } std::string CollectionChildPath::generateDecoratedPath() const { return Collection::getIndexOpen() + path_.str() + Collection::getIndexClose(); } IPropertyPath::Type CollectionChildPath::getType() const { return IPropertyPath::TYPE_COLLECTION_ITEM; } } #include using namespace std; typedef long long ll; #define all(c) (c).begin(), (c).end() #define FOR(i,a,b) for (int i = (a); i < (b); i++) int D; vector v; vector > ids; vector > dp[2]; void update(int id, int pn){ dp[pn][0][id] = 1; FOR(d,1,D){ int m = id >> d; FOR(x,0,2){ int l1 = dp[x][d-1][m*2]; int l = l1 + dp[x^(l1&1)][d-1][m*2+1]; dp[x][d][m] = l; } } } int main(){ int N; ll fake, chatuser; cin >> N >> fake >> chatuser; v = vector(N); ids = vector > (N); FOR(i,0,N)cin >> v[i]; FOR(i,0,N)ids[i] = make_pair(abs(v[i]) + 1, i); D = 0; while((1<((N >> D)+4,0)); ++D; } FOR(i,0,N){ if(v[i] > 0)update(i,1); if(v[i] < 0)update(i,0); } ll res = (N - max(dp[0][D-1][0], dp[1][D-1][0])) * chatuser; sort(all(ids)); for(auto it: ids){ int i = it.second; if(v[i] <= 0)update(i,1); if(v[i] >= 0)update(i,0); res = min(res, (N - max(dp[0][D-1][0], dp[1][D-1][0])) * chatuser + it.first * fake); } cout << res << endl; return 0; } #include "testcases_electron.h" namespace hydra::testcases::electron { std::tuple get_linear_chain(int n_sites, double t, double U) { // Create model BondList bondlist; for (int s = 0; s < n_sites; ++s) bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites}); Couplings couplings; couplings["T"] = t; couplings["U"] = U; return {bondlist, couplings}; } std::tuple get_linear_chain_hb(int n_sites, double t, double U, double J) { // Create model BondList bondlist; // for (int s = 0; s < n_sites; ++s) // bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites}); for (int s = 0; s < n_sites; ++s) bondlist << Bond("EXCHANGE", "J", {s, (s + 1) % n_sites}); Couplings couplings; // couplings["T"] = t; // couplings["U"] = U; couplings["J"] = J; return {bondlist, couplings}; } std::tuple> get_cyclic_group_irreps(int n_sites) { // Create cyclic group as space group std::vector> permutations; for (int sym = 0; sym < n_sites; ++sym) { std::vector permutation; for (int site = 0; site < n_sites; ++site) { int newsite = (site + sym) % n_sites; permutation.push_back(newsite); } permutations.push_back(permutation); } auto space_group = PermutationGroup(permutations); // Create irreducible representations std::vector irreps; for (int k = 0; k < n_sites; ++k) { std::vector chis; for (int l = 0; l < n_sites; ++l) chis.push_back({std::cos(2 * M_PI * l * k / n_sites), std::sin(2 * M_PI * l * k / n_sites)}); auto irrep = Representation(chis); irreps.push_back(irrep); } return {space_group, irreps}; } std::tuple, std::vector> get_cyclic_group_irreps_mult(int n_sites) { // Create cyclic group as space group std::vector> permutations; for (int sym = 0; sym < n_sites; ++sym) { std::vector permutation; for (int site = 0; site < n_sites; ++site) { int newsite = (site + sym) % n_sites; permutation.push_back(newsite); } permutations.push_back(permutation); } auto space_group = PermutationGroup(permutations); // Create irreducible representations std::vector irreps; std::vector multiplicities; for (int k = 0; k < n_sites; ++k) { std::vector chis; for (int l = 0; l < n_sites; ++l) chis.push_back({std::cos(2 * M_PI * l * k / n_sites), std::sin(2 * M_PI * l * k / n_sites)}); auto irrep = Representation(chis); irreps.push_back(irrep); multiplicities.push_back(1); } return {space_group, irreps, multiplicities}; } std::tuple heisenberg_triangle() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple heisenberg_alltoall(int n_sites) { std::default_random_engine generator; std::normal_distribution distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { std::stringstream ss; ss << "J" << s1 << "_" << s2; std::string name = ss.str(); double value = distribution(generator); bondlist << Bond("HEISENBERG", name, {s1, s2}); couplings[name] = value; } return std::make_tuple(bondlist, couplings); } std::tuple heisenberg_kagome15() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {0, 5}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {1, 6}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {2, 6}); bondlist << Bond("HEISENBERG", "J", {2, 10}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {3, 10}); bondlist << Bond("HEISENBERG", "J", {3, 14}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {4, 14}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {8, 9}); bondlist << Bond("HEISENBERG", "J", {9, 10}); bondlist << Bond("HEISENBERG", "J", {9, 11}); bondlist << Bond("HEISENBERG", "J", {10, 11}); bondlist << Bond("HEISENBERG", "J", {11, 12}); bondlist << Bond("HEISENBERG", "J", {12, 13}); bondlist << Bond("HEISENBERG", "J", {13, 14}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple heisenberg_kagome39() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {0, 5}); bondlist << Bond("HEISENBERG", "J", {0, 27}); bondlist << Bond("HEISENBERG", "J", {0, 28}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {1, 6}); bondlist << Bond("HEISENBERG", "J", {1, 28}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {2, 6}); bondlist << Bond("HEISENBERG", "J", {2, 10}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {3, 10}); bondlist << Bond("HEISENBERG", "J", {3, 14}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {4, 14}); bondlist << Bond("HEISENBERG", "J", {4, 38}); bondlist << Bond("HEISENBERG", "J", {5, 27}); bondlist << Bond("HEISENBERG", "J", {5, 38}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {6, 29}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {7, 19}); bondlist << Bond("HEISENBERG", "J", {7, 29}); bondlist << Bond("HEISENBERG", "J", {8, 9}); bondlist << Bond("HEISENBERG", "J", {8, 15}); bondlist << Bond("HEISENBERG", "J", {8, 19}); bondlist << Bond("HEISENBERG", "J", {9, 10}); bondlist << Bond("HEISENBERG", "J", {9, 11}); bondlist << Bond("HEISENBERG", "J", {9, 15}); bondlist << Bond("HEISENBERG", "J", {10, 11}); bondlist << Bond("HEISENBERG", "J", {11, 12}); bondlist << Bond("HEISENBERG", "J", {11, 18}); bondlist << Bond("HEISENBERG", "J", {12, 13}); bondlist << Bond("HEISENBERG", "J", {12, 18}); bondlist << Bond("HEISENBERG", "J", {12, 26}); bondlist << Bond("HEISENBERG", "J", {13, 14}); bondlist << Bond("HEISENBERG", "J", {13, 26}); bondlist << Bond("HEISENBERG", "J", {13, 37}); bondlist << Bond("HEISENBERG", "J", {14, 37}); bondlist << Bond("HEISENBERG", "J", {15, 16}); bondlist << Bond("HEISENBERG", "J", {15, 22}); bondlist << Bond("HEISENBERG", "J", {16, 17}); bondlist << Bond("HEISENBERG", "J", {16, 22}); bondlist << Bond("HEISENBERG", "J", {16, 33}); bondlist << Bond("HEISENBERG", "J", {17, 18}); bondlist << Bond("HEISENBERG", "J", {17, 23}); bondlist << Bond("HEISENBERG", "J", {17, 33}); bondlist << Bond("HEISENBERG", "J", {18, 23}); bondlist << Bond("HEISENBERG", "J", {19, 20}); bondlist << Bond("HEISENBERG", "J", {19, 30}); bondlist << Bond("HEISENBERG", "J", {20, 21}); bondlist << Bond("HEISENBERG", "J", {20, 30}); bondlist << Bond("HEISENBERG", "J", {20, 31}); bondlist << Bond("HEISENBERG", "J", {21, 22}); bondlist << Bond("HEISENBERG", "J", {21, 31}); bondlist << Bond("HEISENBERG", "J", {21, 32}); bondlist << Bond("HEISENBERG", "J", {22, 32}); bondlist << Bond("HEISENBERG", "J", {23, 24}); bondlist << Bond("HEISENBERG", "J", {23, 34}); bondlist << Bond("HEISENBERG", "J", {24, 25}); bondlist << Bond("HEISENBERG", "J", {24, 34}); bondlist << Bond("HEISENBERG", "J", {24, 35}); bondlist << Bond("HEISENBERG", "J", {25, 26}); bondlist << Bond("HEISENBERG", "J", {25, 35}); bondlist << Bond("HEISENBERG", "J", {25, 36}); bondlist << Bond("HEISENBERG", "J", {26, 36}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple freefermion_alltoall(int n_sites) { std::default_random_engine generator; std::normal_distribution distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { std::stringstream ss; ss << "T" << s1 << "_" << s2; std::string name = ss.str(); double value = distribution(generator); bondlist << Bond("HOP", name, {s1, s2}); couplings[name] = value; } return std::make_tuple(bondlist, couplings); } std::tuple freefermion_alltoall_complex_updn(int n_sites) { std::default_random_engine generator; std::normal_distribution distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { // Hopping on upspins std::stringstream ss_up; ss_up << "TUP" << s1 << "_" << s2; std::string name_up = ss_up.str(); complex value_up = complex(distribution(generator), distribution(generator)); bondlist << Bond("HOPUP", name_up, {s1, s2}); couplings[name_up] = value_up; // Hopping on dnspins std::stringstream ss_dn; ss_dn << "TDN" << s1 << "_" << s2; std::string name_dn = ss_dn.str(); complex value_dn = complex(distribution(generator), distribution(generator)); bondlist << Bond("HOPDN", name_dn, {s1, s2}); couplings[name_dn] = value_dn; } return std::make_tuple(bondlist, couplings); } // std::tuple tJchain(int n_sites, double t, // double J) { // BondList bondlist; // Couplings couplings; // couplings["T"] = t; // couplings["J"] = J; // for (int s = 0; s < n_sites; ++s) { // bondlist << Bond("HUBBARDHOP", "T", {s, (s + 1) % n_sites}); // bondlist << Bond("HEISENBERG", "J", {s, (s + 1) % n_sites}); // } // return std::make_tuple(bondlist, couplings); // } std::tuple> randomAlltoAll4NoU() { BondList bondlist; Couplings couplings; // couplings["T01"] = 3; // couplings["J01"] = 1; // couplings["T02"] = 3; // couplings["J02"] = -3; // couplings["T03"] = 3; // couplings["J03"] = 5; // couplings["T12"] = 4; // couplings["J12"] = -5; // couplings["T13"] = -1; // couplings["J13"] = -1; // couplings["T23"] = 2; // couplings["J23"] = 1; couplings["T01"] = -3; couplings["J01"] = 1; couplings["T02"] = -3; couplings["J02"] = -3; couplings["T03"] = -3; couplings["J03"] = 5; couplings["T12"] = -4; couplings["J12"] = -5; couplings["T13"] = 1; couplings["J13"] = -1; couplings["T23"] = -2; couplings["J23"] = 1; bondlist << Bond("HOP", "T01", {0, 1}); bondlist << Bond("HOP", "T02", {0, 2}); bondlist << Bond("HOP", "T03", {0, 3}); bondlist << Bond("HOP", "T12", {1, 2}); bondlist << Bond("HOP", "T13", {1, 3}); bondlist << Bond("HOP", "T23", {2, 3}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J03", {0, 3}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); bondlist << Bond("HEISENBERG", "J13", {1, 3}); bondlist << Bond("HEISENBERG", "J23", {2, 3}); lila::Vector eigs = {-17.035603173216636, -16.054529653295518, -16.054529653295504, -14.839136196281768, -14.839136196281759, -14.479223672075845, -13.947060439818175, -13.681140962579473, -13.681140962579473, -13.681140962579470, -12.146019505147946, -12.146019505147938, -11.123249987689370, -11.083677166546861, -11.083677166546861, -10.361590604796385, -10.141075725997615, -10.141075725997606, -9.879061771701892, -9.879061771701885, -9.879061771701874, -9.720915055042584, -9.720915055042580, -9.300171000114572, -8.898903149068287, -8.898903149068287, -8.898903149068287, -8.587797030969547, -8.574093646826530, -8.574093646826528, -8.574093646826526, -8.567342877760581, -8.556463239828611, -8.556463239828611, -8.156431544113079, -8.156431544113071, -7.595003505113175, -7.595003505113174, -7.595003505113174, -7.595003505113171, -7.428914803058910, -7.428914803058910, -7.406132446925684, -7.406132446925682, -7.298052445959064, -7.298052445959062, -7.298052445959062, -6.776050147544091, -6.776050147544089, -6.597100597834562, -6.382421301285782, -6.382421301285780, -6.382421301285776, -5.914206919262412, -5.914206919262412, -5.914206919262412, -5.914206919262406, -5.898063094032344, -5.697730676986595, -5.652742708313134, -5.652742708313128, -5.382395669397896, -5.382395669397890, -4.827554533410211, -4.827554533410209, -4.827554533410208, -4.565866945456345, -4.392721098506336, -4.392721098506335, -4.392721098506333, -4.386896721326241, -4.386896721326240, -4.386896721326238, -4.287074157175168, -4.269109370889475, -4.269109370889474, -4.083758285516160, -3.784107949888678, -3.784107949888678, -3.230851175883084, -3.230851175883084, -3.166425888361765, -3.166425888361761, -3.060272421221770, -3.060272421221768, -3.060272421221768, -3.060272421221767, -2.846017856191310, -2.846017856191308, -2.826551366644327, -2.822163676323597, -2.822163676323595, -2.373593337341226, -2.304206358771344, -2.291423386597424, -2.291423386597422, -2.291423386597419, -2.258325746389715, -2.100087802223023, -2.100087802223022, -2.100087802223021, -2.002616246412348, -2.002616246412347, -2.002616246412346, -2.002616246412346, -1.653289828765464, -1.653289828765462, -1.653289828765460, -1.537108454167115, -1.537108454167113, -1.468496478890581, -1.184332042222068, -1.184332042222067, -1.183220245290653, -1.183220245290652, -1.183220245290647, -1.158824284368453, -1.158824284368453, -0.797210829513575, -0.797210829513574, -0.753299251580644, -0.500000000000001, -0.500000000000000, -0.500000000000000, -0.500000000000000, -0.499999999999998, -0.370985460263250, -0.370985460263249, -0.281075696274453, -0.230909105391692, -0.230909105391692, -0.230909105391689, 0, 0, 0.226914386262986, 0.226914386262986, 0.226914386262988, 0.339587764690138, 0.339587764690138, 0.339587764690140, 0.339587764690141, 0.864151894040242, 0.864151894040242, 0.977357729518521, 0.977357729518522, 0.982508508938287, 0.982508508938294, 1.184332042222068, 1.184332042222068, 1.286333102260671, 1.360519899915624, 1.360519899915626, 1.831699701973819, 1.831699701973819, 1.831699701973821, 2.168605503366585, 2.304759071083118, 2.305593972115476, 2.305593972115481, 2.305593972115481, 2.565136835120275, 2.565136835120277, 2.680716385503151, 2.680716385503155, 2.680716385503157, 2.859450072401542, 2.867740829382918, 2.867740829382918, 2.867740829382920, 2.867740829382922, 2.919012177817019, 2.919012177817021, 3.230851175883083, 3.230851175883084, 3.586647790757984, 3.586647790757985, 3.866685809727107, 3.866685809727108, 3.866685809727108, 3.962683310049183, 3.962683310049187, 3.983903797596342, 3.983903797596345, 3.983903797596353, 4.106914761573067, 4.258514587211152, 4.258514587211155, 4.258514587211158, 4.279939892091212, 4.647129236685327, 4.647129236685331, 4.730285398111332, 5.382395669397893, 5.382395669397895, 5.557913081969264, 5.729878922142601, 5.729878922142602, 5.729878922142604, 5.729878922142607, 5.854994021510809, 5.854994021510811, 6.026195725670756, 6.026195725670764, 6.112978522336865, 6.112978522336867, 6.112978522336871, 6.298578032819039, 6.627388000300686, 6.627388000300687, 6.638917394627725, 6.638917394627728, 6.638917394627730, 7.106988282706432, 7.261271812957728, 7.428914803058909, 7.428914803058913, 7.634891575794040, 7.634891575794041, 7.634891575794042, 7.634891575794042, 8.034109956056216, 8.034109956056225, 8.433501672445885, 8.437627423133117, 8.437627423133124, 8.437627423133126, 8.487415286599031, 8.740704187459059, 8.740704187459061, 8.740704187459061, 8.758701982332155, 9.740946203547077, 9.740946203547077, 10.075541640416940, 10.075541640416946, 10.365553083134904, 10.365553083134905, 10.898695460947337, 10.898695460947337, 10.898695460947343, 11.368060459508595, 11.880069395522252, 12.081391252276028, 12.081391252276036, 12.355338794669144, 12.355338794669148, 12.833107262067776, 14.296824370037875, 14.296824370037879, 14.296824370037887, 15.091839736118505, 15.091839736118507, 15.880746138642490, 17.166681362460483, 17.166681362460491, 18.194539570876405}; return std::make_tuple(bondlist, couplings, eigs); } std::tuple> randomAlltoAll4() { BondList bondlist; Couplings couplings; // couplings["U"] = 5; // couplings["T01"] = 3; // couplings["J01"] = -1; // couplings["T02"] = -3; // couplings["J02"] = -5; // couplings["T03"] = 3; // couplings["J03"] = -3; // couplings["T12"] = -1; // couplings["J12"] = 1; // couplings["T13"] = -3; // couplings["J13"] = 2; // couplings["T23"] = 0; // couplings["J23"] = -4; couplings["U"] = 5; couplings["T01"] = -3; couplings["J01"] = -1; couplings["T02"] = 3; couplings["J02"] = -5; couplings["T03"] = -3; couplings["J03"] = -3; couplings["T12"] = 1; couplings["J12"] = 1; couplings["T13"] = 3; couplings["J13"] = 2; couplings["T23"] = 0; couplings["J23"] = -4; bondlist << Bond("HOP", "T01", {0, 1}); bondlist << Bond("HOP", "T02", {0, 2}); bondlist << Bond("HOP", "T03", {0, 3}); bondlist << Bond("HOP", "T12", {1, 2}); bondlist << Bond("HOP", "T13", {1, 3}); bondlist << Bond("HOP", "T23", {2, 3}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J03", {0, 3}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); bondlist << Bond("HEISENBERG", "J13", {1, 3}); bondlist << Bond("HEISENBERG", "J23", {2, 3}); lila::Vector eigs = { -12.270231830055396, -12.270231830055389, -10.733666336755952, -10.069390063366962, -9.060858377591751, -9.060858377591751, -9.060858377591751, -8.419560252873284, -8.419560252873282, -8.419560252873278, -6.383158148575644, -6.383158148575637, -6.383158148575632, -6.352277902330186, -6.352277902330185, -6.273324224596429, -6.273324224596422, -6.250906641891413, -6.250906641891411, -6.164309032262214, -6.164309032262212, -6.164309032262212, -6.164309032262211, -5.730618769293929, -5.448935789669534, -5.448935789669532, -5.038951239070341, -4.949876862328434, -4.949876862328423, -4.532986251596143, -4.532986251596141, -4.532986251596141, -4.532986251596141, -3.353197524407229, -3.353197524407228, -3.353197524407226, -3.273406176414287, -3.002245918852136, -3.002245918852133, -2.753141709527037, -2.753141709527034, -2.753141709527034, -2.753141709527031, -2.646622091502864, -2.646622091502863, -2.646622091502862, -2.500000000000006, -2.500000000000000, -2.500000000000000, -2.500000000000000, -2.499999999999995, -2.002043720414641, -2.002043720414640, -2.002043720414639, -1.825844696317418, -1.825844696317417, -1.587175599207617, -1.587175599207614, -1.332228906443854, -1.332228906443853, -0.953827936085984, -0.635382900549627, -0.635382900549625, -0.635382900549624, -0.397581339114120, -0.397581339114115, -0.302660107585638, -0.302660107585633, -0.302660107585631, -0.080803683543577, -0.080803683543570, 0, 0.216457675593863, 0.256166291525251, 0.601566977837033, 0.601566977837038, 0.601566977837038, 0.601566977837040, 0.975606313924293, 0.975606313924297, 1.014605271271656, 1.014605271271658, 1.015859809070357, 1.015859809070358, 1.015859809070360, 1.020308313587130, 1.114881844698814, 1.791357286454801, 1.791357286454802, 1.791357286454810, 1.812876191672553, 2.051032557261542, 2.051032557261543, 2.054529439890590, 2.054529439890591, 2.054529439890594, 2.464728271742040, 2.464728271742042, 2.464728271742044, 2.464728271742044, 2.561461716067067, 2.599451504679192, 2.710382274715613, 2.710382274715615, 2.710382274715616, 2.999999999999997, 3.000000000000001, 3.165957899766594, 3.165957899766600, 3.217491411604103, 3.217491411604104, 3.217491411604105, 3.264426167093818, 3.264426167093818, 3.275854965551124, 3.873065426792698, 3.930285431436003, 3.930285431436005, 4.357654287008264, 4.373227423701834, 4.373227423701834, 4.373227423701836, 4.744551703509988, 4.744551703509988, 4.764857447396031, 4.764857447396040, 4.764857447396043, 4.838082241099029, 4.838082241099031, 5.078388983561651, 5.078388983561652, 5.095728306021306, 5.095728306021313, 5.095728306021315, 5.095728306021317, 5.270280349321774, 5.629364135391933, 5.629364135391936, 5.732050357363664, 5.732050357363669, 5.732050357363673, 5.902527336054253, 5.997898395939853, 5.997898395939854, 5.997898395939856, 6.168989353312808, 6.168989353312815, 6.168989353312816, 6.168989353312816, 6.251638235870590, 6.251638235870590, 6.639239164264768, 6.871779959503020, 6.871779959503024, 6.913606012729136, 7.197663951269839, 7.197663951269844, 7.241663577600812, 7.241663577600815, 7.548559413909176, 7.548559413909178, 7.548559413909183, 7.889853801872584, 8.012439704238972, 8.012439704238977, 8.048368645785640, 8.048368645785644, 8.195982486905091, 8.195982486905091, 8.195982486905095, 8.291793376177347, 8.291793376177351, 8.291793376177356, 8.468003039901994, 8.884687492644268, 8.929394188779456, 8.929394188779456, 9.084392860883399, 9.084392860883403, 9.084392860883410, 9.119424084472175, 9.119424084472177, 9.119424084472177, 9.119424084472181, 9.374280903298303, 9.374280903298303, 9.470513926885971, 9.470513926885971, 9.807459688038790, 9.894356293199492, 10.161917758900962, 10.161917758900971, 10.343135676951986, 10.647301560880138, 10.647301560880139, 10.781521078539114, 10.816967757221121, 10.816967757221125, 10.816967757221128, 10.989949094629180, 10.989949094629189, 10.989949094629189, 11.783921524648289, 11.862403712063079, 11.862403712063086, 11.999999999999995, 11.999999999999995, 12.122579175754746, 12.122579175754746, 12.422108994367830, 12.422108994367832, 12.660280744665648, 12.660280744665650, 12.660280744665654, 12.782275159258591, 13.142554967689829, 13.262004386769918, 13.262004386769929, 13.262004386769933, 13.345289206597041, 13.345289206597041, 13.920776472179945, 14.125358959870058, 14.125358959870061, 14.245875071040452, 14.245875071040452, 14.710043063865781, 14.821095142124749, 15.455920358765942, 15.455920358765947, 15.455920358765953, 15.977688392619838, 15.977688392619839, 16.548872176333433, 16.587175599207608, 16.587175599207615, 16.668859213157941, 16.668859213157944, 16.859992272946350, 17.289815197741845, 17.339978797436935, 17.339978797436938, 17.339978797436956, 18.075989445512761, 18.075989445512761, 18.524216278708529, 18.776715574088868, 18.776715574088868, 20.000000000000000, 20.972807969213903, 21.250906641891415, 21.250906641891415, 22.411220290848199, 22.411220290848210, 22.508215798228996, 25.052426347353144}; return std::make_tuple(bondlist, couplings, eigs); } std::tuple randomAlltoAll3() { BondList bondlist; Couplings couplings; couplings["T01"] = 1; couplings["J01"] = -2; couplings["T02"] = 0; couplings["J02"] = -1; couplings["T12"] = -5; couplings["J12"] = -3; bondlist << Bond("HUBBARDHOP", "T01", {0, 1}); bondlist << Bond("HUBBARDHOP", "T02", {0, 2}); bondlist << Bond("HUBBARDHOP", "T12", {1, 2}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); return std::make_tuple(bondlist, couplings); } std::tuple square2x2(double t, double J) { BondList bondlist; Couplings couplings; couplings["T"] = t; couplings["J"] = J; bondlist << Bond("HUBBARDHOP", "T", {0, 1}); bondlist << Bond("HUBBARDHOP", "T", {1, 0}); bondlist << Bond("HUBBARDHOP", "T", {2, 3}); bondlist << Bond("HUBBARDHOP", "T", {3, 2}); bondlist << Bond("HUBBARDHOP", "T", {0, 2}); bondlist << Bond("HUBBARDHOP", "T", {2, 0}); bondlist << Bond("HUBBARDHOP", "T", {1, 3}); bondlist << Bond("HUBBARDHOP", "T", {3, 1}); bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 0}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {3, 2}); bondlist << Bond("HEISENBERG", "J", {0, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); bondlist << Bond("HEISENBERG", "J", {1, 3}); bondlist << Bond("HEISENBERG", "J", {3, 1}); return std::make_tuple(bondlist, couplings); } std::tuple square3x3(double t, double J) { BondList bondlist; Couplings couplings; couplings["T"] = t; couplings["J"] = J; bondlist << Bond("HOP", "T", {0, 1}); bondlist << Bond("HOP", "T", {1, 2}); bondlist << Bond("HOP", "T", {2, 0}); bondlist << Bond("HOP", "T", {3, 4}); bondlist << Bond("HOP", "T", {4, 5}); bondlist << Bond("HOP", "T", {5, 3}); bondlist << Bond("HOP", "T", {6, 7}); bondlist << Bond("HOP", "T", {7, 8}); bondlist << Bond("HOP", "T", {8, 6}); bondlist << Bond("HOP", "T", {0, 3}); bondlist << Bond("HOP", "T", {3, 6}); bondlist << Bond("HOP", "T", {6, 0}); bondlist << Bond("HOP", "T", {1, 4}); bondlist << Bond("HOP", "T", {4, 7}); bondlist << Bond("HOP", "T", {7, 1}); bondlist << Bond("HOP", "T", {2, 5}); bondlist << Bond("HOP", "T", {5, 8}); bondlist << Bond("HOP", "T", {8, 2}); bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {5, 3}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {8, 6}); bondlist << Bond("HEISENBERG", "J", {0, 3}); bondlist << Bond("HEISENBERG", "J", {3, 6}); bondlist << Bond("HEISENBERG", "J", {6, 0}); bondlist << Bond("HEISENBERG", "J", {1, 4}); bondlist << Bond("HEISENBERG", "J", {4, 7}); bondlist << Bond("HEISENBERG", "J", {7, 1}); bondlist << Bond("HEISENBERG", "J", {2, 5}); bondlist << Bond("HEISENBERG", "J", {5, 8}); bondlist << Bond("HEISENBERG", "J", {8, 2}); return std::make_tuple(bondlist, couplings); } } // namespace hydra::testcases::electron sudiptog81/ducscode /** * Create the Person class. Create some objects of this * class (by taking information from the user). Inherit * the class Person to create two classes Teacher and * Student class. Maintain respective information in the * classes and create, display and delete objects of these * two classes. (Use Run Time Polymorphism). * * Written by: for University of Delhi * Date: 28 - 09 - 2019 */ #include #include using namespace std; class Person { private: int age; char name[255]; public: Person(); virtual ~Person(); virtual void get(); virtual void put(); }; Person::Person() { cout << "Constructor of Person called...\n"; strcpy(name, ""); age = 0; } Person::~Person() { cout << "Destructor of Person called...\n"; } void Person::get() { cout << "Enter name: "; cin >> name; cout << "Enter age: "; cin >> age; return; } void Person::put() { cout << "Name: " << name << "\n"; cout << "Age: " << age << "\n"; return; } class Teacher : public Person { private: int facultyId; char department[255]; public: Teacher(); ~Teacher(); void get(); void put(); }; Teacher::Teacher() { cout << "Constructor of Teacher called...\n"; facultyId = 0; strcpy(department, ""); } Teacher::~Teacher() { cout << "Destructor of Teacher called...\n"; } void Teacher::get() { Person::get(); cout << "Enter faculty ID: "; cin >> facultyId; cout << "Enter department: "; cin >> department; return; } void Teacher::put() { Person::put(); cout << "Faculty ID: " << facultyId << "\n"; cout << "Department: " << department << "\n"; return; } class Student : public Person { private: int rollNo; float marks; public: Student(); ~Student(); void get(); void put(); }; Student::Student() { cout << "Constructor of Student called...\n"; rollNo = 0; marks = 0; } Student::~Student() { cout << "Destructor of Student called...\n"; } void Student::get() { Person::get(); cout << "Enter roll no: "; cin >> rollNo; cout << "Enter marks: "; cin >> marks; return; } void Student::put() { Person::put(); cout << "Roll No: " << rollNo << "\n"; cout << "Marks: " << marks << "\n"; return; } int main() { Person *person1, *person2; cout << "Initializing two instances of Person...\n"; person1 = new Person(); person2 = new Person(); cout << endl; cout << "Enter details for Person 1: \n"; person1->get(); cout << endl; cout << "Enter details for Person 2: \n"; person2->get(); cout << endl; cout << "Person 1\n--------\n"; person1->put(); cout << endl; cout << "Person 2\n--------\n"; person2->put(); cout << endl; cout << "Changing Person 1 to Teacher...\n"; person1 = new Teacher(); cout << "Person 1 is now a Teacher...\n"; cout << "Enter new details for Person 1:\n"; person1->get(); cout << endl; cout << "Changing Person 2 to Student...\n"; person2 = new Student(); cout << "Person 2 is now a Student...\n"; cout << "Enter new details for Person 2:\n"; person2->get(); cout << endl; cout << "Person 1\n--------\n"; person1->put(); cout << endl; cout << "Person 2\n--------\n"; person2->put(); cout << endl; cout << "Deleting Person 1...\n"; delete person1; cout << endl; cout << "Deleting Person 2...\n"; delete person2; cout << endl; return 0; } #pragma once #include namespace gasp::torricelly { enum class torricelly_inst_code : unsigned short { NOOP = 0x0001, DUP, POP_BYTE, POP_SHORT, POP_INTEGER, POP_LONG, POP_BOOLEAN, POP_CHAR, POP_FLOAT, POP_DOUBLE, LOAD_BYTE, LOAD_SHORT, LOAD_INTEGER, LOAD_LONG, LOAD_BOOLEAN, LOAD_CHAR, LOAD_FLOAT, LOAD_DOUBLE, LOAD_ARRAY, LOAD_ARRAY_BYTE, LOAD_ARRAY_SHORT, LOAD_ARRAY_INTEGER, LOAD_ARRAY_LONG, LOAD_ARRAY_BOOLEAN, LOAD_ARRAY_CHAR, LOAD_ARRAY_FLOAT, LOAD_ARRAY_DOUBLE, STORE_BYTE, STORE_SHORT, STORE_INTEGER, STORE_LONG, STORE_BOOLEAN, STORE_CHAR, STORE_FLOAT, STORE_DOUBLE, STORE_ARRAY, STORE_ARRAY_BYTE, STORE_ARRAY_SHORT, STORE_ARRAY_INTEGER, STORE_ARRAY_LONG, STORE_ARRAY_BOOLEAN, STORE_ARRAY_CHAR, STORE_ARRAY_FLOAT, STORE_ARRAY_DOUBLE, ADD_BYTE, ADD_SHORT, ADD_INTEGER, ADD_LONG, ADD_FLOAT, ADD_DOUBLE, SUBTRACT_BYTE, SUBTRACT_SHORT, SUBTRACT_INTEGER, SUBTRACT_LONG, SUBTRACT_FLOAT, SUBTRACT_DOUBLE, MULTIPLY_BYTE, MULTIPLY_SHORT, MULTIPLY_INTEGER, MULTIPLY_LONG, MULTIPLY_FLOAT, MULTIPLY_DOUBLE, DIVIDE_BYTE, DIVIDE_SHORT, DIVIDE_INTEGER, DIVIDE_LONG, DIVIDE_FLOAT, DIVIDE_DOUBLE, REMINDER_BYTE, REMINDER_SHORT, REMINDER_INTEGER, REMINDER_LONG, NEGATE_BYTE, NEGATE_SHORT, NEGATE_INTEGER, NEGATE_LONG, NEGATE_FLOAT, NEGATE_DOUBLE, CMP_BYTE, CMP_SHORT, CMP_INTEGER, CMP_LONG, CMP_BOOLEAN, CMP_CHAR, CMP_FLOAT, CMP_DOUBLE, JUMP, JUMP_EQ_ZERO, JUMP_LT_ZERO, JUMP_LTE_ZERO, JUMP_GT_ZERO, JUMP_GTE_ZERO, JUMP_NOT_ZERO, CAST_BYTE_SHORT, CAST_BYTE_INT, CAST_BYTE_LONG, CAST_BYTE_FLOAT, CAST_BYTE_DOUBLE, CAST_BYTE_BOOLEAN, CAST_BYTE_CHAR, CAST_SHORT_BYTE, CAST_SHORT_INT, CAST_SHORT_LONG, CAST_SHORT_FLOAT, CAST_SHORT_DOUBLE, CAST_SHORT_BOOLEAN, CAST_SHORT_CHAR, CAST_INT_BYTE, CAST_INT_SHORT, CAST_INT_LONG, CAST_INT_FLOAT, CAST_INT_DOUBLE, CAST_INT_BOOLEAN, CAST_INT_CHAR, CAST_LONG_BYTE, CAST_LONG_SHORT, CAST_LONG_INT, CAST_LONG_FLOAT, CAST_LONG_DOUBLE, CAST_LONG_BOOLEAN, CAST_LONG_CHAR, CAST_BOOLEAN_BYTE, CAST_BOOLEAN_SHORT, CAST_BOOLEAN_INT, CAST_CHAR_BYTE, CAST_CHAR_SHORT, CAST_CHAR_INT, CAST_FLOAT_BYTE, CAST_FLOAT_SHORT, CAST_FLOAT_INT, CAST_FLOAT_LONG, CAST_FLOAT_DOUBLE, CAST_DOUBLE_BYTE, CAST_DOUBLE_SHORT, CAST_DOUBLE_INT, CAST_DOUBLE_LONG, CAST_DOUBLE_FLOAT, NOT, AND, OR, STATIC_INVOKE, NATIVE_INVOKE, VIRTUAL_INVOKE, DYNAMIC_INVOKE, RET, HALT, ALLOCATE_BYTE_ARRAY, ALLOCATE_SHORT_ARRAY, ALLOCATE_INT_ARRAY, ALLOCATE_LONG_ARRAY, ALLOCATE_CHAR_ARRAY, ALLOCATE_FLOAT_ARRAY, ALLOCATE_DOUBLE_ARRAY, ALLOCATE_BOOLEAN_ARRAY, FREE_ARRAY }; class torricelly_inst_code_helper { public: static bool accept_parameter(torricelly_inst_code code); static bool accept_reference(torricelly_inst_code code); static bool accept_label(torricelly_inst_code code); }; const char *to_string(torricelly_inst_code code); std::ostream &operator<<(std::ostream &os, torricelly_inst_code code); } // namespace gasp::torricellysrc/graphics/glfw/pch.hpp #pragma once // C library #include #include #include #include #include // C++ library #include #include #include #include #include #include #include #include #include #include #include #include // #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // External library #include #include "GLFW/glfw3.h" #include "spdlog/spdlog.h" #include "gsl/gsl" #include "range/v3/all.hpp" WebCacheTests/HttpClientTests.cpp #include #include using namespace Panda; TEST(HttpClientTests, get_a_file) { BasicHttpClient c; auto ret = c.get("http://whenwillyoulose.com"); EXPECT_EQ(200, ret.code); EXPECT_EQ(9169, ret.message.size()); } TEST(HttpClientTests, fail_a_connection) //this test requires to run on a machine with no http server on 666 { BasicHttpClient c; ASSERT_THROW(c.get("http://localhost:666"), HttpClientException); } 0 #include #include #include "sparse.h" using std::string; using std::cin; using std::cout; using std::endl; Parser ab = ETA(unit | ('a'_P & ab & 'b'_P & ab) | ('b'_P & ab & 'a'_P & ab)); int main() { string l; while (cin >> l) { if (valid(ab, l)) cout << "ACCEPTED" << endl; else cout << "REJECTED" << endl; } return 0; } Dani-24/RPG #include "FadeToBlack.h" #include "Window.h" #include "Render.h" #include "Camera.h" #include "ModuleQFonts.h" #include "SDL/include/SDL_render.h" #include "Logo.h" FadeToBlack::FadeToBlack(App* application, bool start_enabled) : Module(application, start_enabled) { name.Create("fade"); } FadeToBlack::~FadeToBlack() { } bool FadeToBlack::Start() { LOG("Preparing Fade Screen"); screenRect = { 0,0, app->win->GetWidth() * (int)app->win->GetScale(), app->win->GetHeight() * (int)app->win->GetScale() }; SDL_SetRenderDrawBlendMode(app->render->renderer, SDL_BLENDMODE_BLEND); fading = changeStage = false; return true; } bool FadeToBlack::Update(float dt) { if (currentStep == Fade_Step::NONE) { return true; } if (currentStep == Fade_Step::TO_BLACK) { ++frameCount; if (frameCount >= maxFadeFrames) { if (moduleToDisable != nullptr) { moduleToDisable->Disable(); moduleToEnable->Enable(); } if (changeStage == true) { app->stages->ChangeStage(stageToChange); changeStage = false; } currentStep = Fade_Step::FROM_BLACK; } } else { --frameCount; if (frameCount <= 0) { fading = false; currentStep = Fade_Step::NONE; } } return true; } bool FadeToBlack::PostUpdate() { if (currentStep == Fade_Step::NONE) { return true; } float fadeRatio = (float)frameCount / (float)maxFadeFrames; SDL_SetRenderDrawColor(app->render->renderer, 0, 0, 0, (Uint8)(fadeRatio * 255.0f)); SDL_RenderFillRect(app->render->renderer, &screenRect); // Draw Loading text if (app->logoScene->isEnabled() == false) { // Desactivado en el logo pa q quede bonico app->font->DrawText("Loading . . .", -app->camera->GetPos().x / app->win->GetScale() + app->win->GetWidth() / 2 - 110, -app->camera->GetPos().y / app->win->GetScale() + app->win->GetHeight() / 2 - 25); } return true; } bool FadeToBlack::DoFadeToBlack(Module* moduleToDisable, Module* moduleToEnable, float frames) { bool ret = false; if (currentStep == Fade_Step::NONE) { currentStep = Fade_Step::TO_BLACK; frameCount = 0; maxFadeFrames = frames; this->moduleToDisable = moduleToDisable; this->moduleToEnable = moduleToEnable; fading = true; ret = true; } return ret; } bool FadeToBlack::DoFadeToBlack(float frames) { bool ret = false; if (currentStep == Fade_Step::NONE) { currentStep = Fade_Step::TO_BLACK; frameCount = 0; maxFadeFrames = frames; this->moduleToDisable = nullptr; this->moduleToEnable = nullptr; fading = true; ret = true; } return ret; } bool FadeToBlack::DoFadeToBlack(StageIndex stage, float frames) { bool ret = false; if (currentStep == Fade_Step::NONE) { currentStep = Fade_Step::TO_BLACK; frameCount = 0; maxFadeFrames = frames; this->moduleToDisable = nullptr; this->moduleToEnable = nullptr; fading = true; changeStage = true; stageToChange = stage; ret = true; } return ret; }0 #include "adm/parse.hpp" #include #include #include "adm/private/xml_parser.hpp" namespace adm { std::shared_ptr parseXml(const std::string& filename, xml::ParserOptions options) { xml::XmlParser parser(filename, options); return parser.parse(); } std::shared_ptr parseXml(std::istream& stream, xml::ParserOptions options) { xml::XmlParser parser(stream, options); return parser.parse(); } } // namespace adm 0 // TO BE WRITTEN#ifndef SPARSE_KERNEL_HPP #define SPARSE_KERNEL_HPP #include #include #include "cfs_config.hpp" #include "matrix/sparse_matrix.hpp" namespace cfs { using namespace matrix::sparse; namespace kernel { namespace sparse { template struct SpDMV { public: SpDMV() = delete; // Any preprocessing happens here SpDMV(SparseMatrix *A, Tuning t = Tuning::Aggressive); void operator()(ValueType *__restrict y, const int M, const ValueType *__restrict x, const int N); private: SparseMatrix *A_; }; } // end of namespace sparse } // end of namespace kernel } // end of namespace cfs #endif #include "log.hpp" namespace clover { namespace debug { Log::Log(){ file.open("debuglog.txt"); } Log::~Log(){ file.close(); } void Log::operator()(const char8 * msg){ if (file.good()){ file << msg << "\n"; file.flush(); } } } // debug } // clover 10-100 #include using namespace std; int main() { int n; cout<<"which fibonacci number do you want?"; cout<>n; int p=0; int q=1; if(n==0) { cout<<0< #include #include #include TEST(ErrorHandlingMat, isMatFinite_Matrix) { using stan::math::is_mat_finite; Eigen::Matrix x; x.resize(3); x << -1, 0, 1; EXPECT_TRUE(is_mat_finite(x)); x.resize(3); x << -1, 0, std::numeric_limits::infinity(); EXPECT_FALSE(is_mat_finite(x)); x.resize(3); x << -1, 0, -std::numeric_limits::infinity(); EXPECT_FALSE(is_mat_finite(x)); x.resize(3); x << -1, 0, std::numeric_limits::quiet_NaN(); EXPECT_FALSE(is_mat_finite(x)); } TEST(ErrorHandlingMat, isMatFinite_nan) { using stan::math::is_mat_finite; double nan = std::numeric_limits::quiet_NaN(); Eigen::Matrix x_mat(3); x_mat << nan, 0, 1; EXPECT_FALSE(is_mat_finite(x_mat)); x_mat << 1, nan, 1; EXPECT_FALSE(is_mat_finite(x_mat)); x_mat << 1, 0, nan; EXPECT_FALSE(is_mat_finite(x_mat)); } /*************************************************************************** * * * Copyright (C) Chaos Group & Golaem S.A. - All Rights Reserved. * * * ***************************************************************************/ #include "glmCrowdIO.h" #include "glmSimulationData.h" #include "glmFrameData.h" #include "vraygolaem.h" #include "instance.h" #include "resource.h" #pragma warning(push) #pragma warning(disable : 4456) #include "vrayver.h" #pragma warning(pop) #pragma warning(push) #pragma warning(disable : 4535) #include "maxscript/maxscript.h" #pragma warning(pop) // V-Ray plugin ID for the 3ds Max material wrapper #define GLM_MTL_WRAPPER_VRAY_ID LARGE_CONST(0x2015080783) #include // std::ofstream #include // std::stringstream #if GET_MAX_RELEASE(VERSION_3DSMAX) >= 9000 #include "IPathConfigMgr.h" #endif #if GET_MAX_RELEASE(VERSION_3DSMAX) >= 11900 #include "IFileResolutionManager.h" #pragma comment(lib, "assetmanagement.lib") #endif // no param block script access for VRay free #ifdef _FREE_ #define _FT(X) _T("") #define IS_PUBLIC 0 #else #define _FT(X) _T(X) #define IS_PUBLIC 1 #endif // _FREE_ //************************************************************ // Class descriptor //************************************************************ class VRayGolaemClassDesc : public ClassDesc2 { public: int IsPublic(void) { return IS_PUBLIC; } void* Create(BOOL /*loading*/) { return new VRayGolaem; } const TCHAR* ClassName(void) { return STR_CLASSNAME; } SClass_ID SuperClassID(void) { return GEOMOBJECT_CLASS_ID; } Class_ID ClassID(void) { return PLUGIN_CLASSID; } const TCHAR* Category(void) { return _T("VRay"); } // Hardwired name, used by MAX Script as unique identifier const TCHAR* InternalName(void) { return STR_INTERNALNAME; } HINSTANCE HInstance(void) { return hInstance; } }; //************************************************************ // Static / Define variables //************************************************************ #define BIGFLOAT float(999999) // from bendmod sample #define BIGINT int(999999) #define ICON_RADIUS 2 #define CROWDVRAYPLUGINID PluginID(LARGE_CONST(2011070866)) // from glmCrowdVRayPlugin.h TCHAR* iconText = _T("VRayGolaem"); static VRayGolaemClassDesc vrayGolaemClassDesc; // The names of the node user properties that V-Ray uses for reflection/refraction visibility. // V-Ray doesn't publish the header with their definitions so I copy them here. #define PROP_GI_VISIBLETOREFL _T("VRay_GI_VisibleToReflections") #define PROP_GI_VISIBLETOREFR _T("VRay_GI_VisibleToRefractions") #define PROP_MOBLUR_USEDEFAULTGEOMSAMPLES _T("VRay_MoBlur_DefaultGeomSamples") #define PROP_MOBLUR_GEOMSAMPLES _T("VRay_MoBlur_GeomSamples") #define PROP_MOBLUR_OVERRIDEDURATION _T("VRay_MoBlur_Override") #define PROP_MOBLUR_DURATION _T("VRay_MoBlur_Override_Duration") //************************************************************ // DLL stuff //************************************************************ HINSTANCE hInstance; int controlsInit = FALSE; BOOL WINAPI DllMain(HINSTANCE hinstDLL, ULONG /*fdwReason*/, LPVOID /*lpvReserved*/) { hInstance = hinstDLL; if (!controlsInit) { controlsInit = TRUE; #if MAX_RELEASE < 13900 InitCustomControls(hInstance); #endif InitCommonControls(); } return (TRUE); } __declspec(dllexport) const TCHAR* LibDescription(void) { return STR_LIBDESC; } __declspec(dllexport) int LibNumberClasses(void) { return 1; } __declspec(dllexport) ClassDesc* LibClassDesc(int i) { switch (i) { case 0: return &vrayGolaemClassDesc; } return NULL; } __declspec(dllexport) ULONG LibVersion(void) { return VERSION_3DSMAX; } __declspec(dllexport) int LibInitialize(void) { return TRUE; } __declspec(dllexport) int LibShutdown(void) { return TRUE; } class VRayGolaemDlgProc : public ParamMap2UserDlgProc { void chooseFileName(IParamBlock2* pblock2, ParamID paramID, const TCHAR* title); public: VRayGolaemDlgProc() { } INT_PTR DlgProc(TimeValue t, IParamMap2* map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); void DeleteThis() { } void SetThing(ReferenceTarget* /*m*/) { } }; static VRayGolaemDlgProc vrayGolaemDlgProc; // Find the node that references this Golaem object. If the Golaem object is instanced, // it is not defined which node is returned. INode* getNode(VRayGolaem* golaem) { ULONG handle = 0; golaem->NotifyDependents(FOREVER, (PartID)&handle, REFMSG_GET_NODE_HANDLE); INode* node = GetCOREInterface()->GetINodeByHandle(handle); return node; } //------------------------------------------------------------ bool fileExists(const CStr& pathname) { return (_waccess(pathname.ToWStr(), 0) == 0); } CStr getEnvironmentVariable(const CStr& envVarName) { CStr envVarValue(""); #ifdef _MSC_VER size_t requiredSize; getenv_s(&requiredSize, NULL, 0, envVarName.data()); if (requiredSize != 0) { char* envVariable(new char[requiredSize]); getenv_s(&requiredSize, envVariable, requiredSize, envVarName.data()); envVarValue = CStr(envVariable); delete[] envVariable; } #else char* envVariable(getenv(envVarName.c_str())); if (envVariable != NULL) { envVarValue = (*envVariable); } #endif return envVarValue; } double getCrowdUnitScale() { double maxUnitsInMeter = GetMasterScale(UNITS_METERS); double glmUnitsInMeter(0.01); //default is centimeters CStr glmcrowd_unit_Str(getEnvironmentVariable("GLMCROWD_UNIT")); int glmcrowd_unit = atoi(glmcrowd_unit_Str.data()); switch(glmcrowd_unit) { case 0: //millimeters { glmUnitsInMeter = 0.001; } break; case 1: //centimeters { glmUnitsInMeter = 0.01; } break; case 2: //decimeters { glmUnitsInMeter = 0.1; } break; case 3: //meters { glmUnitsInMeter = 1; } break; case 4: //inches { glmUnitsInMeter = 0.0254; //http://en.wikipedia.org/wiki/Inch } break; case 5: //feet { glmUnitsInMeter = 0.3048; //http://en.wikipedia.org/wiki/Foot_%28length%29 } break; case 6: //yards { glmUnitsInMeter = 0.9144; //http://en.wikipedia.org/wiki/Yard } break; } return glmUnitsInMeter / maxUnitsInMeter; } //************************************************************ // Parameter block //************************************************************ // Paramblock2 name enum { params, }; static ParamBlockDesc2 param_blk( params, STR_DLGTITLE, 0, &vrayGolaemClassDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, REFNO_PBLOCK, IDD_VRAYGOLAEM, IDS_VRAYGOLAEM_PARAMS, 0, 0, &vrayGolaemDlgProc, // Params pb_file, _T("cache_file"), TYPE_FILENAME, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_GOLAEMVRSCENE, #if GET_MAX_RELEASE(VERSION_3DSMAX) >= 11900 p_assetTypeID, MaxSDK::AssetManagement::AssetType::kExternalLink, #endif PB_END, pb_shaders_file, _T("shaders_file"), TYPE_FILENAME, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_SHADERSVRSCENE, #if GET_MAX_RELEASE(VERSION_3DSMAX) >= 11900 p_assetTypeID, MaxSDK::AssetManagement::AssetType::kExternalLink, #endif PB_END, // display attributes pb_enable_display, _T("enable_display"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, ED_DISPLAYENABLE, PB_END, pb_display_percentage, _T("display_percentage"), TYPE_FLOAT, P_RESET_DEFAULT, 0, p_default, 100.f, p_range, 0.f, 100.f, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, ED_DISPLAYPERCENT, ED_DISPLAYPERCENTSPIN, 1.f, PB_END, pb_display_entity_ids, _T("display_entity_ids"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, ED_DISPLAYENTITYIDS, PB_END, // cache attributes pb_crowd_fields, _T("crowd_fields"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_CROWDFIELDS, PB_END, pb_cache_name, _T("cache_name"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_CACHENAME, PB_END, pb_cache_dir, _T("cache_dir"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_CACHEDIR, PB_END, pb_character_files, _T("character_files"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_CHARACTERFILES, PB_END, // layout attributes pb_layout_enable, _T("layout_enable"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, ED_LAYOUTENABLE, PB_END, pb_layout_file, _T("layout_file"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_LAYOUTFILE, PB_END, pb_terrain_file, _T("terrain_file"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_TERRAINFILE, PB_END, // culling attributes pb_lod_enable, _T("lod_enable"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, ED_LODENABLE, PB_END, pb_frustum_enable, _T("frustum_enable"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, ED_FRUSTUMENABLE, PB_END, pb_frustum_margin, _T("frustum_margin"), TYPE_FLOAT, P_RESET_DEFAULT, 0, p_default, 10.f, p_range, -BIGFLOAT, BIGFLOAT, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, ED_FRUSTUMMARGIN, ED_FRUSTUMMARGINSPIN, 1.f, PB_END, pb_camera_margin, _T("camera_margin"), TYPE_FLOAT, P_RESET_DEFAULT, 0, p_default, 10.f, p_range, -BIGFLOAT, BIGFLOAT, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, ED_CAMERAMARGIN, ED_CAMERAMARGINSPIN, 1.f, PB_END, // vray attributes pb_fframe_offset, _T("fframe_offset"), TYPE_FLOAT, P_RESET_DEFAULT, 0.f, p_default, 0.f, p_range, -BIGFLOAT, BIGFLOAT, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, ED_FFRAMEOFFSET, ED_FFRAMEOFFSETSPIN, 1.f, PB_END, pb_object_id_mode, _T("objectId_mode"), TYPE_INT, P_RESET_DEFAULT, 0, p_ui, TYPE_INT_COMBOBOX, CB_OBJECTIDMODE, 8, CB_OBJECTIDMODE_ITEM1, CB_OBJECTIDMODE_ITEM2, CB_OBJECTIDMODE_ITEM3, CB_OBJECTIDMODE_ITEM4, CB_OBJECTIDMODE_ITEM5, CB_OBJECTIDMODE_ITEM6, CB_OBJECTIDMODE_ITEM7, CB_OBJECTIDMODE_ITEM8, p_vals, 0, 1, 2, 3, 4, 5, 6, 7, p_default, 0, PB_END, pb_geometry_tag, _T("geometry_tag"), TYPE_INT, P_RESET_DEFAULT, 0, p_default, 0, p_range, 0, 9, p_ui, TYPE_SPINNER, EDITTYPE_INT, ED_GEOMETRYTAG, ED_GEOMETRYTAGSPIN, 1, PB_END, pb_default_material, _T("default_material"), TYPE_STRING, P_RESET_DEFAULT, 0, p_ui, TYPE_EDITBOX, ED_DEFAULTMATERIAL, PB_END, pb_temp_vrscene_file_dir, _T("temp_vrscene_file_dir"), TYPE_STRING, P_RESET_DEFAULT, 0, p_default, _T("TEMP"), p_ui, TYPE_EDITBOX, ED_TEMPVRSCENEFILEDIR, PB_END, pb_instancing_enable, _T("instancing_enable"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, ED_INSTANCINGENABLE, PB_END, pb_log_level, _T("log_level"), TYPE_INT, P_RESET_DEFAULT, 0, p_ui, TYPE_INT_COMBOBOX, CB_LOGLEVEL, 4, CB_LOGLEVEL_ITEM1, CB_LOGLEVEL_ITEM2, CB_LOGLEVEL_ITEM3, CB_LOGLEVEL_ITEM4, p_vals, 0, 1, 2, 3, p_default, 1, PB_END, // time override attributes pb_frame_override_enable, _T("frame_override_enable"), TYPE_BOOL, P_RESET_DEFAULT, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, ED_FRAMEOVERRIDEENABLE, PB_END, pb_frame_override, _T("frame_override"), TYPE_FLOAT, P_RESET_DEFAULT + P_ANIMATABLE, 0, p_default, 0.f, p_range, -BIGFLOAT, BIGFLOAT, p_ui, TYPE_SPINNER, EDITTYPE_FLOAT, ED_FRAMEOVERRIDE, ED_FRAMEOVERRIDESPIN, 1.f, PB_END, // not used anymore but kept for retrocomp pb_frame_offset, _T(""), TYPE_INT, 0, 0, PB_END, pb_display_percent, _T(""), TYPE_INT, 0, 0, PB_END, pb_use_node_attributes, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_motion_blur_enable, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_motion_blur_start, _T(""), TYPE_FLOAT, 0, 0, PB_END, pb_motion_blur_window_size, _T(""), TYPE_FLOAT, 0, 0, PB_END, pb_motion_blur_samples, _T(""), TYPE_INT, 0, 0, PB_END, pb_scale_transform, _T(""), TYPE_FLOAT, 0, 0, PB_END, pb_object_id_base, _T(""), TYPE_INT, 0, 0, PB_END, pb_primary_visibility, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_casts_shadows, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_visible_in_reflections, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_visible_in_refractions, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_override_node_properties, _T(""), TYPE_BOOL, 0, 0, PB_END, pb_excluded_entities, _T(""), TYPE_STRING, 0, 0, PB_END, pb_layout_name, _T(""), TYPE_STRING, 0, 0, PB_END, pb_layout_dir, _T(""), TYPE_STRING, 0, 0, PB_END, PB_END); //************************************************************ // VRayGolaem implementation //************************************************************ //------------------------------------------------------------ // VRayGolaem //------------------------------------------------------------ VRayGolaem::VRayGolaem() : _simDataToDraw(NULL) , _frameDataToDraw(NULL) , _updateCacheData(true) { static int pblockDesc_inited = false; if (!pblockDesc_inited) { initPBlockDesc(param_blk); pblockDesc_inited = true; } pblock2 = NULL; vrayGolaemClassDesc.MakeAutoParamBlocks(this); assert(pblock2); suspendSnap = FALSE; VrayGolaemContext::getVrayGolaemContext(); _cacheFactory = new glm::crowdio::SimulationCacheFactory(); } VRayGolaem::~VRayGolaem() { GLM_SAFE_DELETE(_cacheFactory); } //------------------------------------------------------------ // Misc //------------------------------------------------------------ void VRayGolaem::InvalidateUI() { param_blk.InvalidateUI(pblock2->LastNotifyParamID()); } static Pb2TemplateGenerator templateGenerator; void VRayGolaem::BeginEditParams(IObjParam* ip, ULONG uflags, Animatable* prev) { vrayGolaemClassDesc.BeginEditParams(ip, this, uflags, prev); } void VRayGolaem::EndEditParams(IObjParam* ip, ULONG uflags, Animatable* next) { vrayGolaemClassDesc.EndEditParams(ip, this, uflags, next); } RefTargetHandle VRayGolaem::Clone() { #if GET_MAX_RELEASE(VERSION_3DSMAX) < 8900 NoRemap defaultRemap; #else DefaultRemapDir defaultRemap; #endif RemapDir& remap = defaultRemap; return Clone(remap); } RefTargetHandle VRayGolaem::Clone(RemapDir& remap) { VRayGolaem* newob = new VRayGolaem(); BaseClone(this, newob, remap); newob->ReplaceReference(0, pblock2->Clone(remap)); return newob; } Animatable* VRayGolaem::SubAnim(int i) { switch (i) { case 0: return pblock2; default: return NULL; } } TSTR VRayGolaem::SubAnimName(int i) { switch (i) { case 0: return STR_DLGTITLE; default: return _T(""); } } RefTargetHandle VRayGolaem::GetReference(int i) { switch (i) { case REFNO_PBLOCK: return pblock2; default: return NULL; } } void VRayGolaem::SetReference(int i, RefTargetHandle rtarg) { switch (i) { case REFNO_PBLOCK: pblock2 = (IParamBlock2*)rtarg; break; } } RefResult VRayGolaem::NotifyRefChanged(NOTIFY_REF_CHANGED_ARGS) { (void)changeInt; (void)partID; (void)propagate; switch (message) { case REFMSG_CHANGE: if (hTarget == pblock2) { ParamID paramID = pblock2->LastNotifyParamID(); switch (paramID) { case pb_frustum_enable: case pb_frame_override_enable: grayDlgControls(); break; } param_blk.InvalidateUI(); } break; } return REF_SUCCEED; } Interval VRayGolaem::ObjectValidity(TimeValue t) { return Interval(t, t); } //------------------------------------------------------------ // proc //------------------------------------------------------------ int VRayGolaemCreateCallBack::proc(ViewExp* vpt, int msg, int point, int /*flags*/, IPoint2 m, Matrix3& mat) { if (!sphere) return CREATE_ABORT; Point3 np = vpt->SnapPoint(m, m, NULL, SNAP_IN_PLANE); switch (msg) { case MOUSE_POINT: switch (point) { case 0: sphere->suspendSnap = TRUE; sp0 = m; p0 = vpt->SnapPoint(m, m, NULL, SNAP_IN_3D); mat.SetTrans(p0); case 1: return CREATE_STOP; } return CREATE_CONTINUE; case MOUSE_MOVE: return CREATE_CONTINUE; case MOUSE_ABORT: return CREATE_ABORT; } return CREATE_CONTINUE; } static VRayGolaemCreateCallBack createCB; CreateMouseCallBack* VRayGolaem::GetCreateMouseCallBack() { createCB.SetObj(this); return &createCB; } void VRayGolaem::SetExtendedDisplay(int /*flags*/) { } void VRayGolaem::GetLocalBoundBox(TimeValue /*t*/, INode* /*inode*/, ViewExp* /*vpt*/, Box3& box) { float radius = ICON_RADIUS; _nodeBbox += Point3(-radius, -radius, -radius); _nodeBbox += Point3(radius, radius, radius); box = _nodeBbox; } void VRayGolaem::GetWorldBoundBox(TimeValue t, INode* inode, ViewExp* vpt, Box3& box) { if (!inode) return; Box3 localBox; GetLocalBoundBox(t, inode, vpt, localBox); box = localBox * (inode->GetObjectTM(t)); } void VRayGolaem::GetDeformBBox(TimeValue t, Box3& b, Matrix3* tm, BOOL /*useSel*/) { if (!tm) GetLocalBoundBox(t, NULL, NULL, b); else { Box3 bbox; GetLocalBoundBox(t, NULL, NULL, bbox); b.Init(); for (int i = 0; i < 8; i++) b += (*tm) * bbox[i]; } } int VRayGolaem::HitTest(TimeValue t, INode* inode, int type, int crossing, int /*flags*/, IPoint2* p, ViewExp* vpt) { static HitRegion hitRegion; DWORD savedLimits; GraphicsWindow* gw = vpt->getGW(); //Material *mtl=gw->getMaterial(); MakeHitRegion(hitRegion, type, crossing, 4, p); gw->setRndLimits(((savedLimits = gw->getRndLimits()) | GW_PICK) & ~GW_ILLUM); gw->setHitRegion(&hitRegion); gw->clearHitCode(); draw(t, inode, vpt); gw->setRndLimits(savedLimits); if ((hitRegion.type != POINT_RGN) && !hitRegion.crossing) return TRUE; return gw->checkHitCode(); } void VRayGolaem::Snap(TimeValue /*t*/, INode* /*inode*/, SnapInfo* /*snap*/, IPoint2* /*p*/, ViewExp* /*vpt*/) { if (suspendSnap) return; } //------------------------------------------------------------ // Display //------------------------------------------------------------ int VRayGolaem::Display(TimeValue t, INode* inode, ViewExp* vpt, int /*flags*/) { draw(t, inode, vpt); return 0; } ObjectState VRayGolaem::Eval(TimeValue /*time*/) { _updateCacheData = true; // time has changed, we should re-read the cache return ObjectState(this); } void* VRayGolaem::GetInterface(ULONG id) { if (id == I_VRAYGEOMETRY) return (VR::VRenderObject*)this; return GeomObject::GetInterface(id); } void VRayGolaem::ReleaseInterface(ULONG id, void* ip) { if (id == I_VRAYGEOMETRY) return; GeomObject::ReleaseInterface(id, ip); } int VRayGolaem::RenderBegin(TimeValue t, ULONG /*flags*/) { // This is called at the start of the rendering before the render instances are created and the scene is built; // we must make sure the parameters are cached before newRenderInstance() is called. updateVRayParams(t); return TRUE; } Mesh* VRayGolaem::GetRenderMesh(TimeValue /*t*/, INode* /*inode*/, View& /*view*/, BOOL& needDelete) { needDelete = false; return &_mesh; } INT_PTR VRayGolaemDlgProc::DlgProc(TimeValue t, IParamMap2* map, HWND /*hWnd*/, UINT msg, WPARAM wParam, LPARAM /*lParam*/) { //int id=LOWORD(wParam); IParamBlock2* pblock = NULL; VRayGolaem* vrayGolaem = NULL; if (map) pblock = map->GetParamBlock(); if (pblock) vrayGolaem = static_cast(pblock->GetOwner()); switch (msg) { case WM_INITDIALOG: { if (vrayGolaem) vrayGolaem->grayDlgControls(); break; } case WM_DESTROY: break; case WM_COMMAND: { int ctrlID = LOWORD(wParam); int notifyCode = HIWORD(wParam); //HWND ctrlHWnd=(HWND) lParam; if (notifyCode == BN_CLICKED) { if (ctrlID == BN_GOLAEMBROWSE && vrayGolaem) { chooseFileName(pblock, pb_file, _T("Choose Golaem .vrscene file")); // if the vrscene has been loaded, fill the node attributes const TCHAR* fname_wstr = pblock->GetStr(pb_file, t); if (fname_wstr) { GET_MBCS(fname_wstr, fname_mbcs); vrayGolaem->readCrowdVRScene(fname_mbcs); } } if (ctrlID == BN_SHADERSBROWSE && vrayGolaem) { chooseFileName(pblock, pb_shaders_file, _T("Choose shaders .vrscene file")); } if (ctrlID == BN_MATERIALSCREATE && vrayGolaem) { // call post creation python script INode* node = getNode(vrayGolaem); if (node == NULL) { CStr logMessage = CStr("VRayGolaem: This object is an 3ds Max instance and is not supported. Please create a copy."); mprintf(logMessage.ToBSTR()); return FALSE; } GET_MBCS(node->GetName(), nodeName); CStr sourceCmd = CStr("python.ExecuteFile \"vraygolaem.py\""); ExecuteMAXScriptScript(sourceCmd.ToBSTR()); CStr callbackCmd = CStr("python.Execute \"glmVRayGolaemPostCreationCallback('") + CStr(nodeName) + CStr("')\""); ExecuteMAXScriptScript(callbackCmd.ToBSTR()); } } break; } } return FALSE; } void VRayGolaem::grayDlgControls(void) { IParamMap2* map = pblock2->GetMap(); if (!map) return; // If no UI - nothing to do HWND hWnd = map->GetHWnd(); // Frustum culling int fcull = pblock2->GetInt(pb_frustum_enable); map->Enable(pb_frustum_margin, fcull); map->Enable(pb_camera_margin, fcull); int foverride = pblock2->GetInt(pb_frame_override_enable); map->Enable(pb_frame_override, foverride); EnableWindow(GetDlgItem(hWnd, ST_CULLFRUSTUM), fcull); EnableWindow(GetDlgItem(hWnd, ST_CULLCAMERA), fcull); } //************************************************************ // Browse //************************************************************ static const TCHAR* vrsceneExtList = _T("V-Ray scene file (*.vrscene)\0*.vrscene\0All files(*.*)\0*.*\0\0"); static const TCHAR* vrsceneDefExt = _T("vrscene"); //------------------------------------------------------------ // chooseFileName //------------------------------------------------------------ void VRayGolaemDlgProc::chooseFileName(IParamBlock2* pblock2, ParamID paramID, const TCHAR* title) { TCHAR fname[512] = _T(""); fname[0] = '\0'; const TCHAR* storedName = pblock2->GetStr(paramID); if (storedName) vutils_strcpy_n(fname, storedName, COUNT_OF(fname)); OPENFILENAME fn; fn.lStructSize = sizeof(fn); fn.hwndOwner = GetCOREInterface()->GetMAXHWnd(); fn.hInstance = hInstance; fn.lpstrFilter = vrsceneExtList; fn.lpstrCustomFilter = NULL; fn.nMaxCustFilter = 0; fn.nFilterIndex = 1; fn.lpstrFile = fname; fn.nMaxFile = 512; fn.lpstrFileTitle = NULL; fn.nMaxFileTitle = 0; fn.lpstrInitialDir = NULL; fn.lpstrTitle = title; fn.Flags = 0; fn.lpstrDefExt = vrsceneDefExt; fn.lCustData = NULL; fn.lpfnHook = NULL; fn.lpTemplateName = NULL; BOOL res = GetOpenFileName(&fn); const TCHAR* fullFname = NULL; #if GET_MAX_RELEASE(VERSION_3DSMAX) >= 9000 MaxSDK::Util::Path fpath(fname); #if GET_MAX_RELEASE(VERSION_3DSMAX) < 11900 IPathConfigMgr::GetPathConfigMgr()->NormalizePathAccordingToSettings(fpath); fullFname = fpath.GetCStr(); #else TSTR mstrfname(fname); IFileResolutionManager::GetInstance()->DoGetUniversalFileName(mstrfname); fullFname = mstrfname.data(); #endif #else fullFname = fname; #endif if (res) { pblock2->SetValue(paramID, 0, const_cast(fullFname)); IParamMap2* map = pblock2->GetMap(); if (map) map->Invalidate(paramID); } } //************************************************************ // Time //************************************************************ //------------------------------------------------------------ // getCurrentFrame //------------------------------------------------------------ float VRayGolaem::getCurrentFrame(const TimeValue t) const { return ((float)t / (float)TIME_TICKSPERSEC * (float)GetFrameRate()); } //------------------------------------------------------------ // getCurrentFrameOffset //------------------------------------------------------------ float VRayGolaem::getCurrentFrameOffset(const TimeValue t) const { float frameOffset = _frameOffset; if (_frameOverrideEnable) frameOffset += _frameOverride - getCurrentFrame(t); return frameOffset; } //------------------------------------------------------------ // getNodeCurrentFrame //------------------------------------------------------------ void VRayGolaem::getNodeCurrentFrame(const TimeValue t, float& currentFrame, float& frameMin, float& frameMax, float& factor) const { currentFrame = getCurrentFrame(t) + getCurrentFrameOffset(t); frameMin = floor(currentFrame); frameMax = ceil(currentFrame); if (fabs(frameMin - currentFrame) <= 0.001f) { currentFrame = frameMin; frameMax = currentFrame; } else if (fabs(frameMax - currentFrame) <= 0.001f) { currentFrame = frameMax; frameMin = currentFrame; } factor = 0.f; if (frameMin != frameMax) { factor = static_cast((currentFrame - frameMin) / (frameMax - frameMin)); } } //------------------------------------------------------------ // readGolaemCache //------------------------------------------------------------ void VRayGolaem::readGolaemCache(const Matrix3& transform, TimeValue t) { if (!_updateCacheData) return; // clean previous data _simDataToDraw.removeAll(); _frameDataToDraw.removeAll(); _exclusionData.removeAll(); // update params updateVRayParams(t); _updateCacheData = false; // Proxy Matrix Matrix3 nodeTransformNoRot = transform * maxToGolaem(); float proxyArray[16]; float inverseProxyArray[16]; maxToGolaem(nodeTransformNoRot, proxyArray); maxToGolaem(Inverse(nodeTransformNoRot), inverseProxyArray); _cacheFactory->clear(glm::crowdio::FactoryClearMode::ALL); //is it necessary ?? Couldn't we keep the cache ? // load gscl first if (_layoutEnable) { // parse sparse array of layout files glm::GlmString layoutFiles = _layoutFile.data(); glm::Array layoutFilesArray; glm::split(layoutFiles, ";", layoutFilesArray); for (size_t iLayoutFile = 0; iLayoutFile < layoutFilesArray.size(); iLayoutFile++) { _cacheFactory->loadLayoutHistoryFile(iLayoutFile, layoutFilesArray[iLayoutFile].c_str()); } _cacheFactory->setSimulationProxyMatrix(proxyArray, inverseProxyArray); } // read caches MaxSDK::Array crowdFields; splitStr(_crowdFields, ';', crowdFields); if (_cacheName.length() != 0 && _cacheDir.length() != 0) { // find the current frame float currentFrame = getCurrentFrame(t) + getCurrentFrameOffset(t); // read caches for (size_t iCf = 0, nbCf = crowdFields.length(); iCf < nbCf; ++iCf) { glm::crowdio::crowdTerrain::TerrainMesh *terrainMeshSource(NULL), *terrainMeshDestination(NULL); // load gscl first if (_layoutEnable) { // Terrain CStr cachePrefix(_cacheDir + "/" + _cacheName + "." + crowdFields[iCf] + "."); CStr srcTerrainFile(cachePrefix + "terrain.gtg"); if (!fileExists(srcTerrainFile)) srcTerrainFile = cachePrefix + "terrain.fbx"; if (srcTerrainFile.Length()) terrainMeshSource = glm::crowdio::crowdTerrain::loadTerrainAsset(srcTerrainFile); if (_terrainFile.Length()) terrainMeshDestination = glm::crowdio::crowdTerrain::loadTerrainAsset(_terrainFile); if (terrainMeshDestination == NULL) terrainMeshDestination = terrainMeshSource; _cacheFactory->setTerrainMeshes(terrainMeshSource, terrainMeshDestination); } glm::crowdio::CachedSimulation& cachedSimulation = _cacheFactory->getCachedSimulation(_cacheDir, _cacheName, crowdFields[iCf]); const glm::crowdio::GlmSimulationData* simData = cachedSimulation.getFinalSimulationData(); if (!simData) { DebugPrint(_T("VRayGolaem: Error loading .gscs file\n")); return; } const glm::crowdio::GlmFrameData* frameData = cachedSimulation.getFinalFrameData(currentFrame, UINT32_MAX, true); // UINT32_MAX = output of layout after all nodes if (!frameData) { DebugPrint(_T("VRayGolaem: Error loading .gscf file(s) for frame \"%f\"\n"), currentFrame); return; } glm::PODArray killList; glm::Array historyRuntimes; cachedSimulation.getHistoryRuntimeStructures(historyRuntimes); createEntityExclusionList(killList, cachedSimulation.getSrcSimulationData(), _cacheFactory->getLayoutHistories(), historyRuntimes); for (size_t iExcluded = 0; iExcluded < killList.size(); ++iExcluded) { _exclusionData.append(killList[iExcluded]); } _simDataToDraw.append(simData); _frameDataToDraw.append(frameData); //clear terrain _cacheFactory->setTerrainMeshes(NULL, NULL); if (terrainMeshDestination && terrainMeshDestination != terrainMeshSource) glm::crowdio::crowdTerrain::closeTerrainAsset(terrainMeshDestination); if (terrainMeshSource) glm::crowdio::crowdTerrain::closeTerrainAsset(terrainMeshSource); } } } //------------------------------------------------------------ // drawEntities //------------------------------------------------------------ void VRayGolaem::drawEntities(GraphicsWindow* gw, const Matrix3& transform, TimeValue t) { // get display attributes bool displayEnable = pblock2->GetInt(pb_enable_display, t) == 1; float displayPercent = pblock2->GetFloat(pb_display_percentage, t); bool displayEntityIds = pblock2->GetInt(pb_display_entity_ids, t) == 1; if (!displayEnable) return; // update cache if required readGolaemCache(transform, t); if (_simDataToDraw.length() == 0 || _frameDataToDraw.length() == 0 || _simDataToDraw.length() != _frameDataToDraw.length()) return; // draw _nodeBbox.Init(); // rescale the display according to unit because cache is in golaem units double unitScale = getCrowdUnitScale(); Matrix3 displayTransform = transform; displayTransform.Scale(Point3(unitScale, unitScale, unitScale), TRUE); float transformScale(displayTransform.GetRow(0).Length()); for (size_t iData = 0, nbData = _simDataToDraw.length(); iData < nbData; ++iData) { int maxDisplayedEntity = (int)(_simDataToDraw[iData]->_entityCount * displayPercent / 100.f); for (size_t iEntity = 0, entityCount = maxDisplayedEntity; iEntity < entityCount; ++iEntity) { int64_t entityId = _simDataToDraw[iData]->_entityIds[iEntity]; if (entityId == -1) continue; if (_exclusionData.contains(entityId)) continue; unsigned int entityType = _simDataToDraw[iData]->_entityTypes[iEntity]; if (_simDataToDraw[iData]->_boneCount[entityType] > 0) { float entityRadius = _simDataToDraw[iData]->_entityRadius[iEntity] * transformScale; float entityHeight = _simDataToDraw[iData]->_entityHeight[iEntity] * transformScale; // draw bbox unsigned int iBoneIndex = _simDataToDraw[iData]->_iBoneOffsetPerEntityType[entityType] + _simDataToDraw[iData]->_indexInEntityType[iEntity] * _simDataToDraw[iData]->_boneCount[entityType]; Point3 entityPosition(_frameDataToDraw[iData]->_bonePositions[iBoneIndex][0], _frameDataToDraw[iData]->_bonePositions[iBoneIndex][1], _frameDataToDraw[iData]->_bonePositions[iBoneIndex][2]); // axis transformation for max entityPosition = entityPosition * displayTransform; Box3 entityBbox(Point3(entityPosition[0] - entityRadius, entityPosition[1] - entityRadius, entityPosition[2]), Point3(entityPosition[0] + entityRadius, entityPosition[1] + entityRadius, entityPosition[2] + entityHeight)); drawBBox(gw, entityBbox); // update node bbox _nodeBbox += entityBbox; // draw EntityID if (displayEntityIds) { CStr entityIdStrs; entityIdStrs.printf("%i", entityId); drawText(gw, entityIdStrs.ToMCHAR(), entityPosition); } } } } } //------------------------------------------------------------ // draw //------------------------------------------------------------ void VRayGolaem::draw(TimeValue t, INode* inode, ViewExp* vpt) { GraphicsWindow* gw = vpt->getGW(); Matrix3 tm = inode->GetObjectTM(t); gw->setTransform(tm); Color color = Color(inode->GetWireColor()); if (inode->IsFrozen()) color = GetUIColor(COLOR_FREEZE); else if (inode->Selected()) color = GetUIColor(COLOR_SELECTION); gw->setColor(LINE_COLOR, color); // locator drawSphere(gw, Point3::Origin, ICON_RADIUS, 30); // entities drawEntities(gw, tm, t); // text tm.NoScale(); float scaleFactor = vpt->NonScalingObjectSize() * vpt->GetVPWorldWidth(tm.GetTrans()) / (float)360.0; tm.Scale(Point3(scaleFactor, scaleFactor, scaleFactor)); gw->setTransform(tm); drawText(gw, iconText, Point3::Origin); } //************************************************************ // VRenderObject //************************************************************ int VRayGolaem::init(const ObjectState& os, INode* inode, VR::VRayCore* vray) { VRenderObject::init(os, inode, vray); return true; } CStr getStrParam(IParamBlock2* block, ParamID id, TimeValue t, const CStr& defaultStr = "") { CStr returnedString = defaultStr; const TCHAR* param_wstr = block->GetStr(id, t); if (param_wstr) { GET_MBCS(param_wstr, param_mbcs); returnedString = param_mbcs; } return returnedString; } //------------------------------------------------------------ // updateVRayParams //------------------------------------------------------------ void VRayGolaem::updateVRayParams(TimeValue t) { // check if this object is not an instance (then it has no max node to query) INode* inode = getNode(this); if (inode == NULL) { CStr logMessage = CStr("VRayGolaem: This object is an 3ds Max instance and is not supported. Please create a copy."); mprintf(logMessage.ToBSTR()); return; } // vrscene attributes _vrsceneFile = getStrParam(pblock2, pb_file, t); _shadersFile = getStrParam(pblock2, pb_shaders_file, t); // cache attributes _crowdFields = getStrParam(pblock2, pb_crowd_fields, t); _cacheName = getStrParam(pblock2, pb_cache_name, t); _cacheDir = getStrParam(pblock2, pb_cache_dir, t); _characterFiles = getStrParam(pblock2, pb_character_files, t); // layout attributes _layoutEnable = pblock2->GetInt(pb_layout_enable, t) == 1; _layoutFile = getStrParam(pblock2, pb_layout_file, t); _terrainFile = getStrParam(pblock2, pb_terrain_file, t); // motion blur attributes BOOL overrideValue; inode->GetUserPropBool(PROP_MOBLUR_OVERRIDEDURATION, overrideValue); _overMBlurWindowSize = overrideValue == 1; inode->GetUserPropFloat(PROP_MOBLUR_DURATION, _mBlurWindowSize); inode->GetUserPropBool(PROP_MOBLUR_USEDEFAULTGEOMSAMPLES, overrideValue); _overMBlurSamples = overrideValue == 0; inode->GetUserPropInt(PROP_MOBLUR_GEOMSAMPLES, _mBlurSamples); _mBlurEnable = !(_overMBlurSamples && _mBlurSamples == 1); // moblur is disabled if the object geo samples == 1 // culling attributes _lodEnable = pblock2->GetInt(pb_lod_enable, t) == 1; _frustumEnable = pblock2->GetInt(pb_frustum_enable, t) == 1; _frustumMargin = pblock2->GetFloat(pb_frustum_margin, t); _cameraMargin = pblock2->GetFloat(pb_camera_margin, t); // transform _geoScale = (float)getCrowdUnitScale(); // vray _frameOffset = pblock2->GetFloat(pb_fframe_offset, t); _frameOverrideEnable = pblock2->GetInt(pb_frame_override_enable, t) == 1; _frameOverride = pblock2->GetFloat(pb_frame_override, t); _defaultMaterial = getStrParam(pblock2, pb_default_material, t); _displayPercent = pblock2->GetFloat(pb_display_percentage, t); _geometryTag = pblock2->GetInt(pb_geometry_tag, t); _instancingEnable = pblock2->GetInt(pb_instancing_enable, t) == 1; _logLevel = (short)pblock2->GetInt(pb_log_level, t); // object properties _objectIDBase = inode->GetGBufID(); _objectIDMode = (short)pblock2->GetInt(pb_object_id_mode, t); _primaryVisibility = inode->GetPrimaryVisibility() == 1; _castsShadows = inode->CastShadows() == 1; // Get secondary visibility from the 3ds Max object properties _visibleInReflections = true; _visibleInRefractions = true; int nodeSecondaryVisibility = inode->GetSecondaryVisibility(); if (0 == nodeSecondaryVisibility) _visibleInReflections = false; if (0 == nodeSecondaryVisibility) _visibleInRefractions = false; // Check secondary visibility in the V-Ray object properties int vrayReflVisibility = true, vrayRefrVisibility = true; inode->GetUserPropBool(PROP_GI_VISIBLETOREFL, vrayReflVisibility); inode->GetUserPropBool(PROP_GI_VISIBLETOREFR, vrayRefrVisibility); if (!vrayReflVisibility) _visibleInReflections = false; if (!vrayRefrVisibility) _visibleInRefractions = false; } void VRayGolaem::wrapMaterial(VUtils::VRayCore* vrayCore, Mtl* mtl) { if (!mtl) return; VR::VRayRenderer* vray = static_cast(vrayCore); VR::VRenderMtl* vrenderMtl = VR::getVRenderMtl(mtl, vray); if (!vrenderMtl) return; // Material is not V-Ray compatible, can't do anything. GolaemBRDFWrapper* wrapper = static_cast(_vrayScene->newPluginWithoutParams(GLM_MTL_WRAPPER_VRAY_ID, NULL)); if (!wrapper) return; wrapper->setMaxMtl(mtl, vrenderMtl, this); } void VRayGolaem::enumMaterials(VUtils::VRayCore* vray, Mtl* mtl) { if (!mtl || mtl->SuperClassID() != MATERIAL_CLASS_ID) return; wrapMaterial(vray, mtl); int numMtls = mtl->NumSubMtls(); for (int i = 0; i < numMtls; i++) { Mtl* sub = mtl->GetSubMtl(i); if (sub && sub->SuperClassID() == MATERIAL_CLASS_ID) { wrapMaterial(vray, sub); } } } void VRayGolaem::createMaterials(VR::VRayCore* vray) { const VR::VRaySequenceData& sdata = vray->getSequenceData(); INode* inode = getNode(this); const TCHAR* name_wstr = GetObjectName(); if (!inode) { if (sdata.progress) { GET_MBCS(name_wstr, name_mbcs); sdata.progress->warning("No node found for Golaem object \"%s\"; can't create materials", name_mbcs ? name_mbcs : ""); } return; } if (sdata.progress) { GET_MBCS(node->GetName(), nodeName); sdata.progress->info("VRayGolaem: Create materials attached to the VRayGolaem node %s", nodeName); } enumMaterials(vray, inode->GetMtl()); } class GolaemBRDFMaterialDesc : public PluginDesc { public: PluginID getPluginID(void) VRAY_OVERRIDE { return GLM_MTL_WRAPPER_VRAY_ID; } Plugin* newPlugin(PluginHost*) VRAY_OVERRIDE { return new GolaemBRDFWrapper; } void deletePlugin(Plugin* plugin) { delete static_cast(plugin); } bool supportsInterface(InterfaceID id) { if (id == EXT_MATERIAL) return true; else if (id == EXT_BSDF) return true; else return false; } /// Returns the name of the plugin class (human readable name). virtual VRAY3_CONST_COMPAT tchar* getName(void) VRAY_OVERRIDE { return "GolaemMtlMaxWrapper"; } /// Returns a brief explanation of the purpose of the plugin virtual const tchar* getDescription() const VRAY_OVERRIDE { return "Golaem material 3dsMax Wrapper"; } }; static GolaemBRDFMaterialDesc golaemWrapperMaterialDesc; //------------------------------------------------------------ // renderBegin / renderEnd //------------------------------------------------------------ void VRayGolaem::renderBegin(TimeValue t, VR::VRayCore* vrayCore) { VR::VRayRenderer* vray = static_cast(vrayCore); VRenderObject::renderBegin(t, vray); const VR::VRaySequenceData& sdata = vray->getSequenceData(); VRenderPluginRendererInterface* pluginRenderer = queryInterface(vray, EXT_VRENDER_PLUGIN_RENDERER); vassert(pluginRenderer); pluginRenderer->registerPlugin(wrapperMaterialDesc); pluginRenderer->registerPlugin(golaemWrapperMaterialDesc); updateVRayParams(t); // Load the .vrscene into the plugin manager PluginManager* plugMan = pluginRenderer->getPluginManager(); vassert(plugMan); _vrayScene = new VR::VRayScene(plugMan); #if 1 GET_MBCS(node->GetName(), nodeName); int prevNbPlugins(plugMan->enumPlugins(NULL)); int newNbPlugins = prevNbPlugins; // Create wrapper plugins for all 3ds Max materials in the scene, // so that the Golaem plugin can use them, if needed. createMaterials(vray); newNbPlugins = plugMan->enumPlugins(NULL); if (newNbPlugins != prevNbPlugins) { sdata.progress->info("VRayGolaem: Materials created successfully, %i materials created for node %s", newNbPlugins - prevNbPlugins, nodeName); prevNbPlugins = newNbPlugins; } if (_shadersFile.empty()) { if (sdata.progress) { sdata.progress->warning("VRayGolaem: No shaders .vrscene file specified for node %s", nodeName); } } else { const VR::ErrorCode errCode = _vrayScene->readFile(_shadersFile.ptr()); newNbPlugins = plugMan->enumPlugins(NULL); if (errCode.error()) { if (sdata.progress) { const VR::CharString errMsg = errCode.getErrorString(); sdata.progress->warning("VRayGolaem: Error loading shaders .vrscene file \"%s\": %s", _shadersFile.ptr(), errMsg.ptr()); } } else { if (sdata.progress) { sdata.progress->info("VRayGolaem: Shaders file \"%s\" loaded successfully, %i materials loaded", _shadersFile.ptr(), newNbPlugins - prevNbPlugins); } } } #else PluginManager* plugMan = pluginRenderer->getPluginManager(); vassert(plugMan); // Creates the crowd .vrscene file on the fly if required VR::CharString vrSceneFileToLoad(_vrsceneFile); CStr outputDir(getEnvironmentVariable(_tempVRSceneFileDir)); if (outputDir != NULL) { if (outputDir.Length() != 0 && _cacheName.Length() != 0 && _crowdFields.length() != 0) { GET_MBCS(node->GetName(), nodeName); CStr outputPathStr(outputDir + "/" + _cacheName + "." + nodeName + ".vrscene"); VR::CharString vrSceneExportPath(outputPathStr); // TODO if (!writeCrowdVRScene(t, vrSceneExportPath)) { sdata.progress->warning("VRayGolaem: Error writing .vrscene file \"%s\"", vrSceneExportPath.ptr()); } else { sdata.progress->info("VRayGolaem: Writing .vrscene file \"%s\"", vrSceneExportPath.ptr()); vrSceneFileToLoad = vrSceneExportPath; } } else { sdata.progress->warning("VRayGolaem: Node attributes invalid (CrowdFields, Cache Name or Cache Dir is empty)"); } } else { sdata.progress->warning("VRayGolaem: Error finding environment variable for .vrscene output \"%s\"", _tempVRSceneFileDir.data()); } // Load the .vrscene into the plugin manager _vrayScene = new VR::VRayScene(plugMan); int prevNbPlugins(plugMan->enumPlugins(NULL)); int newNbPlugins(prevNbPlugins); newNbPlugins = plugMan->enumPlugins(NULL); sdata.progress->info("VRayGolaem: Materials created successfully, %i materials created", newNbPlugins - prevNbPlugins); prevNbPlugins = newNbPlugins; if (vrSceneFileToLoad.empty()) { sdata.progress->warning("VRayGolaem: No .vrscene file specified"); } else { VR::ErrorCode errCode = _vrayScene->readFile(vrSceneFileToLoad.ptr()); newNbPlugins = plugMan->enumPlugins(NULL); if (errCode.error()) { VR::CharString errMsg = errCode.getErrorString(); sdata.progress->warning("VRayGolaem: Error loading .vrscene file \"%s\": %s", vrSceneFileToLoad.ptr(), errMsg.ptr()); } else { sdata.progress->info("VRayGolaem: Scene file \"%s\" loaded successfully, %i nodes loaded", vrSceneFileToLoad.ptr(), newNbPlugins - prevNbPlugins); } prevNbPlugins = newNbPlugins; } if (_shadersFile.empty()) { sdata.progress->warning("VRayGolaem: No shaders .vrscene file specified"); } else { VR::ErrorCode errCode = _vrayScene->readFile(_shadersFile.ptr()); newNbPlugins = plugMan->enumPlugins(NULL); if (errCode.error()) { VR::CharString errMsg = errCode.getErrorString(); sdata.progress->warning("VRayGolaem: Error loading shaders .vrscene file \"%s\": %s", _shadersFile.ptr(), errMsg.ptr()); } else { sdata.progress->info("VRayGolaem: Shaders file \"%s\" loaded successfully, %i materials loaded", _shadersFile.ptr(), newNbPlugins - prevNbPlugins); } prevNbPlugins = newNbPlugins; } // check dependency files float currentFrame, frameMin, frameMax, interpolateFactor; getNodeCurrentFrame(t, currentFrame, frameMin, frameMax, interpolateFactor); FindPluginOfTypeCallback pluginCallback(CROWDVRAYPLUGINID); _vrayScene->enumPlugins(&pluginCallback); if (pluginCallback._foundPlugins.length()) { // per crowdField VR::VRayPluginParameter* currentParam = NULL; CStr crowdField, cacheName, cacheDir, characterFiles; for (size_t iPlugin = 0; iPlugin < pluginCallback._foundPlugins.length(); ++iPlugin) { VR::VRayPlugin* plugin(pluginCallback._foundPlugins[iPlugin]); currentParam = plugin->getParameter("crowdField"); if (currentParam) crowdField = currentParam->getString(); currentParam = plugin->getParameter("cacheName"); if (currentParam) cacheName = currentParam->getString(); currentParam = plugin->getParameter("cacheFileDir"); if (currentParam) cacheDir = currentParam->getString(); currentParam = pluginCallback._foundPlugins[0]->getParameter("characterFiles"); if (currentParam) characterFiles = currentParam->getString(); MaxSDK::Array crowdFields; splitStr(crowdField, ';', crowdFields); for (size_t iCf = 0, nbCf = crowdFields.length(); iCf < nbCf; ++iCf) { // caa CStr caaName(cacheDir + "/" + cacheName + "." + crowdFields[iCf] + ".caa"); if (!fileExists(caaName)) sdata.progress->warning("VRayGolaem: Error loading Crowd Assets Association file \"%s\"", caaName.data()); else sdata.progress->info("VRayGolaem: Crowd Assets Association file \"%s\" loaded successfully.", caaName.data()); // gscs CStr gscsName(cacheDir + "/" + cacheName + "." + crowdFields[iCf] + ".gscs"); if (!fileExists(gscsName)) sdata.progress->warning("VRayGolaem: Error loading Simulation Cache file \"%s\"", gscsName.data()); else sdata.progress->info("VRayGolaem: Simulation Cache file \"%s\" loaded successfully.", gscsName.data()); // gscf if (frameMin == frameMax) { CStr currentFrameStr; currentFrameStr.printf("%i", (int)currentFrame); CStr gscfName(cacheDir + "/" + cacheName + "." + crowdFields[iCf] + "." + currentFrameStr + ".gscf"); if (!fileExists(gscfName)) sdata.progress->warning("VRayGolaem: Error loading Simulation Cache file \"%s\"", gscfName.data()); else sdata.progress->info("VRayGolaem: Simulation Cache file \"%s\" loaded successfully.", gscfName.data()); } else { CStr currentFrameStr; currentFrameStr.printf("%i", (int)frameMin); CStr gscfName(cacheDir + "/" + cacheName + "." + crowdFields[iCf] + "." + currentFrameStr + ".gscf"); if (!fileExists(gscfName)) sdata.progress->warning("VRayGolaem: Error loading Simulation Cache file \"%s\"", gscfName.data()); else sdata.progress->info("VRayGolaem: Simulation Cache file \"%s\" loaded successfully.", gscfName.data()); currentFrameStr.printf("%i", (int)frameMin); gscfName = (cacheDir + "/" + cacheName + "." + crowdFields[iCf] + "." + currentFrameStr + ".gscf"); if (!fileExists(gscfName)) sdata.progress->warning("VRayGolaem: Error loading Simulation Cache file \"%s\"", gscfName.data()); else sdata.progress->info("VRayGolaem: Simulation Cache file \"%s\" loaded successfully.", gscfName.data()); } } // character files MaxSDK::Array characters; splitStr(characterFiles, ';', characters); for (size_t iCh = 0, nbCh = characters.length(); iCh < nbCh; ++iCh) { if (!fileExists(characters[iCh])) sdata.progress->warning("VRayGolaem: Error loading Character file \"%s\"", characters[iCh].data()); else sdata.progress->info("VRayGolaem: Character file file \"%s\" loaded successfully.", characters[iCh].data()); } } } else { sdata.progress->warning("VRayGolaem: No GolaemCrowd node found in the current scene"); } #endif } void VRayGolaem::renderEnd(VR::VRayCore* _vray) { VR::VRayRenderer* vray = static_cast(_vray); VRenderObject::renderEnd(vray); if (_vrayScene) { delete _vrayScene; _vrayScene = NULL; } } //------------------------------------------------------------ // frameBegin / frameEnd //------------------------------------------------------------ void VRayGolaem::frameBegin(TimeValue t, VR::VRayCore* _vray) { VR::VRayRenderer* vray = static_cast(_vray); VRenderObject::frameBegin(t, vray); } void VRayGolaem::frameEnd(VR::VRayCore* _vray) { VR::VRayRenderer* vray = static_cast(_vray); VRenderObject::frameEnd(vray); } //------------------------------------------------------------ // newRenderInstance / deleteRenderInstance //------------------------------------------------------------ VR::VRenderInstance* VRayGolaem::newRenderInstance(INode* inode, VR::VRayCore* vray, int renderID) { vassert(vray); const VR::VRaySequenceData& sdata = vray->getSequenceData(); if (sdata.progress) { const TCHAR* nodeName = inode ? inode->GetName() : _T(""); GET_MBCS(nodeName, nodeName_mbcs); sdata.progress->debug("VRayGolaem: newRenderInstance() for node \"%s\"", nodeName_mbcs); } VRayGolaemInstance* golaemInstance = new VRayGolaemInstance(*this, inode, vray, renderID); golaemInstance->newVRayPlugin(*vray); return golaemInstance; } void VRayGolaem::deleteRenderInstance(VR::VRenderInstance* ri) { delete static_cast(ri); } //************************************************************ // Read / Write VRScene //************************************************************ //------------------------------------------------------------ // readCrowdVRScene: parse the imported crowd .vrscene to fill the node attributes //------------------------------------------------------------ bool VRayGolaem::readCrowdVRScene(const VR::CharString& file) { // check if this object is not an instance (then it has no max node to query) INode* inode = getNode(this); if (inode == NULL) { CStr logMessage = CStr("VRayGolaem: This object is an 3ds Max instance and is not supported. Please create a copy."); mprintf(logMessage.ToBSTR()); return false; } PluginManager* tempPlugMan = newDefaultPluginManager(); const VUtils::CharString& vrayPluginPath = getVRayPluginsPath(); tempPlugMan->loadLibraryFromPathCollection(vrayPluginPath.ptr(), "/vray_*.dll", NULL, NULL); VR::VRayScene* tmpVrayScene = new VR::VRayScene(tempPlugMan); VR::ErrorCode errCode = tmpVrayScene->readFile(file.ptr()); if (!errCode.error()) { // find the nodes FindPluginOfTypeCallback pluginCallback(CROWDVRAYPLUGINID); tmpVrayScene->enumPlugins(&pluginCallback); // read attributes if (pluginCallback._foundPlugins.length()) { VR::VRayPlugin* plugin(pluginCallback._foundPlugins[0]); VR::VRayPluginParameter* currentParam = NULL; CStr crowdFields; // transform currentParam = plugin->getParameter("proxyMatrix"); if (currentParam) { VR::TraceTransform t = currentParam->getTransform(); Matrix3 transform(Point3(1, 0, 0), Point3(0, 1, 0), Point3(0, 0, 1), Point3(t.offs[0], t.offs[1], t.offs[2])); // axis change between max and maya transform = transform * golaemToMax(); inode->SetNodeTM(0, transform); } // cache attributes currentParam = plugin->getParameter("crowdField"); if (currentParam) { crowdFields = currentParam->getString(); } currentParam = plugin->getParameter("cacheName"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_cache_name, 0, currentParamMbcs, 0); } currentParam = plugin->getParameter("cacheFileDir"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_cache_dir, 0, currentParamMbcs, 0); } currentParam = plugin->getParameter("characterFiles"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_character_files, 0, currentParamMbcs, 0); } // layout currentParam = plugin->getParameter("layoutEnable"); if (currentParam) pblock2->SetValue(pb_layout_enable, 0, currentParam->getBool() == 1); currentParam = plugin->getParameter("layoutFile"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_layout_file, 0, currentParamMbcs, 0); } currentParam = plugin->getParameter("terrainFile"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_terrain_file, 0, currentParamMbcs, 0); } // motion blur currentParam = plugin->getParameter("motionBlurWindowSize"); if (currentParam) { inode->SetUserPropBool(PROP_MOBLUR_OVERRIDEDURATION, true); inode->SetUserPropFloat(PROP_MOBLUR_DURATION, currentParam->getFloat()); } currentParam = plugin->getParameter("motionBlurSamples"); if (currentParam) { inode->SetUserPropBool(PROP_MOBLUR_USEDEFAULTGEOMSAMPLES, false); inode->SetUserPropInt(PROP_MOBLUR_GEOMSAMPLES, currentParam->getInt()); } // if motion blur is off, override geometry samples value with 1 currentParam = plugin->getParameter("motionBlurEnable"); if (currentParam) { if (currentParam->getInt() == 0) { inode->SetUserPropBool(PROP_MOBLUR_USEDEFAULTGEOMSAMPLES, false); inode->SetUserPropInt(PROP_MOBLUR_GEOMSAMPLES, 1); } } // frustum culling currentParam = plugin->getParameter("LODEnable"); if (currentParam) pblock2->SetValue(pb_lod_enable, 0, currentParam->getBool() == 1); currentParam = plugin->getParameter("frustumCullingEnable"); if (currentParam) pblock2->SetValue(pb_frustum_enable, 0, currentParam->getBool() == 1); currentParam = plugin->getParameter("frustumMargin"); if (currentParam) pblock2->SetValue(pb_frustum_margin, 0, (float)currentParam->getDouble()); currentParam = plugin->getParameter("cameraMargin"); if (currentParam) pblock2->SetValue(pb_camera_margin, 0, (float)currentParam->getDouble()); // vray currentParam = plugin->getParameter("renderPercent"); if (currentParam) pblock2->SetValue(pb_display_percentage, 0, currentParam->getFloat()); currentParam = plugin->getParameter("geometryTag"); if (currentParam) pblock2->SetValue(pb_geometry_tag, 0, currentParam->getInt()); currentParam = plugin->getParameter("frameOffset"); if (currentParam) pblock2->SetValue(pb_fframe_offset, 0, currentParam->getFloat()); currentParam = plugin->getParameter("defaultMaterial"); if (currentParam) { GET_WSTR(currentParam->getString(), currentParamMbcs) pblock2->SetValue(pb_default_material, 0, currentParamMbcs, 0); } currentParam = plugin->getParameter("instancingEnable"); if (currentParam) pblock2->SetValue(pb_instancing_enable, 0, currentParam->getBool() == 1); currentParam = plugin->getParameter("logLevel"); if (currentParam) pblock2->SetValue(pb_log_level, 0, currentParam->getInt()); // properties (copy them in the max node as well if it exists) int objectIDBase(0); bool primaryVisibility(true), castShadows(true), inReflections(true), inRefractions(true); currentParam = plugin->getParameter("objectIdBase"); if (currentParam) objectIDBase = currentParam->getInt(); currentParam = plugin->getParameter("objectIdMode"); if (currentParam) pblock2->SetValue(pb_object_id_mode, 0, currentParam->getInt()); currentParam = plugin->getParameter("cameraVisibility"); if (currentParam) primaryVisibility = currentParam->getBool() == 1; currentParam = plugin->getParameter("shadowsVisibility"); if (currentParam) castShadows = currentParam->getBool() == 1; currentParam = plugin->getParameter("reflectionsVisibility"); if (currentParam) inReflections = currentParam->getBool() == 1; currentParam = plugin->getParameter("refractionsVisibility"); if (currentParam) inRefractions = currentParam->getBool() == 1; inode->SetGBufID(objectIDBase); inode->SetPrimaryVisibility(primaryVisibility); inode->SetCastShadows(castShadows); inode->SetSecondaryVisibility(inReflections && inRefractions); int visibleInRefl((int)inReflections), visibleInRefr((int)inRefractions); inode->SetUserPropBool(PROP_GI_VISIBLETOREFL, visibleInRefl); inode->SetUserPropBool(PROP_GI_VISIBLETOREFR, visibleInRefr); // other crowdFields? for (size_t iPlugin = 1; iPlugin < pluginCallback._foundPlugins.length(); ++iPlugin) { plugin = pluginCallback._foundPlugins[iPlugin]; currentParam = plugin->getParameter("crowdField"); if (currentParam) crowdFields += (CStr(";") + CStr(currentParam->getString())); } GET_WSTR(crowdFields, currentParamMbcs) pblock2->SetValue(pb_crowd_fields, 0, currentParamMbcs, 0); // ok, vray_glmCrowdVRayPlugin.dll is loaded and all params are filled CStr logMessage = CStr("VRayGolaem: Success loading .vrscene file \"") + CStr(file.ptr()) + CStr("\" \n"); mprintf(logMessage.ToBSTR()); } else { // CROWDVRAYPLUGINID not found = not loaded or env not configured CStr vrayEnvVar = CStr(VRAYSTD_PLUGINS); CStr logMessage = CStr("VRayGolaem: Error loading .vrscene file \"") + CStr(file.ptr()) + CStr("\". vray_glmCrowdVRayPlugin.dll plugin was not found in environment variable \"") + vrayEnvVar + CStr("\" (") + CStr(getVRayPluginsPath().ptr()) + CStr(").\n"); mprintf(logMessage.ToBSTR()); } } else { CStr logMessage = CStr("VRayGolaem: Success loading .vrscene file \"") + CStr(file.ptr()) + CStr("\". Vrscene file is invalid.\n"); mprintf(logMessage.ToBSTR()); } delete tmpVrayScene; delete tempPlugMan; return true; } //************************************************************ // Inline utility functions //************************************************************ //------------------------------------------------------------ // isCharInvalidVrscene //------------------------------------------------------------ bool isCharInvalidVrscene(char c) { if (c == '|' || c == '@') return false; if (c >= 'a' && c <= 'z') return false; if (c >= 'A' && c <= 'Z') return false; if (c >= '0' && c <= '9') return false; return true; } //------------------------------------------------------------ // convertToValidVrsceneName //------------------------------------------------------------ void convertToValidVrsceneName(const CStr& strIn, CStr& strOut) { int strSize = int(strIn.length()); if (strSize == 0) { strOut.Resize(0); return; } strOut.Resize(strSize * 2); // If the first character is a digit, convert that to a letter int pos(0), i(0); strOut.dataForWrite()[0] = strIn[0]; if (strIn[0] >= '0' && strIn[0] <= '9') { strOut.dataForWrite()[0] = 'a' + (strIn[0] - '0'); pos++; i++; } while (i < strSize) { if (isCharInvalidVrscene(strIn[i])) { strOut.dataForWrite()[pos++] = '_'; if (strIn[i] == ':') { strOut.dataForWrite()[pos++] = '_'; } } else strOut.dataForWrite()[pos++] = strIn[i]; i++; } strOut.Resize(pos); } void splitStr(const CStr& input, char delim, MaxSDK::Array& result) { int startPos(0); if (input.length() == 0) return; // first character is delim if (input[0] == delim) { result.append(""); startPos = 1; } for (int iChar = 1, nbChars = input.length(); iChar < nbChars; ++iChar) { if (input[iChar] == delim) { CStr tmpStr = input.Substr(startPos, iChar - startPos); result.append(tmpStr); startPos = iChar + 1; } } if (startPos != input.length()) { CStr tmpStr = input.Substr(startPos, input.length() - startPos); result.append(tmpStr); } } //************************************************************ // Accessors draw functions //************************************************************ inline void drawLine(GraphicsWindow* gw, const Point3& p0, const Point3& p1) { Point3 p[3] = {p0, p1}; gw->segment(p, TRUE); } inline void drawBBox(GraphicsWindow* gw, const Box3& b) { gw->setTransform(Matrix3(1)); Point3 p[8]; for (int i = 0; i < 8; i++) p[i] = b[i]; gw->startSegments(); drawLine(gw, p[0], p[1]); drawLine(gw, p[0], p[2]); drawLine(gw, p[3], p[1]); drawLine(gw, p[3], p[2]); drawLine(gw, p[7], p[6]); drawLine(gw, p[7], p[5]); drawLine(gw, p[4], p[5]); drawLine(gw, p[4], p[6]); drawLine(gw, p[0], p[4]); drawLine(gw, p[1], p[5]); drawLine(gw, p[2], p[6]); drawLine(gw, p[3], p[7]); gw->endSegments(); } inline void drawSphere(GraphicsWindow* gw, const Point3& pos, float radius, int nsegs) { float u0 = radius, v0 = 0.0f; Point3 pt[3]; // draw locator sphere gw->startSegments(); for (int i = 0; i < nsegs; i++) { float a = 2.0f * (float)pi * float(i + 1) / float(nsegs); float u1 = radius * cosf(a); float v1 = radius * sinf(a); pt[0] = Point3(u0, v0, 0.0f) + pos; pt[1] = Point3(u1, v1, 0.0f) + pos; gw->segment(pt, true); pt[0] = Point3(0.0f, u0, v0) + pos; pt[1] = Point3(0.0f, u1, v1) + pos; gw->segment(pt, true); pt[0] = Point3(u0, 0.0f, v0) + pos; pt[1] = Point3(u1, 0.0f, v1) + pos; gw->segment(pt, true); u0 = u1; v0 = v1; } gw->endSegments(); } inline void drawText(GraphicsWindow* gw, const MCHAR* text, const Point3& pos) { IPoint3 ipt; gw->wTransPoint(&pos, &ipt); // text position SIZE sp; gw->getTextExtents(text, &sp); // draw shadow text ipt.x -= sp.cx / 2; ipt.y -= sp.cy / 2; gw->setColor(TEXT_COLOR, 0.0f, 0.0f, 0.0f); gw->wText(&ipt, text); // draw white text ipt.x--; ipt.y--; gw->setColor(TEXT_COLOR, 1.0f, 1.0f, 1.0f); gw->wText(&ipt, text); } // V-Ray materials expect rc.rayresult.sd to derive from VR::ShadeData, but this is not true for // the geometry from Standalone plugins, so wrap the original shade data with this class. This also // allows us to remap the texture mapping channels on the fly (in 3ds Max, they start from 1, but // in the standalone plugins, they start from 0). struct MtlShadeData : VR::ShadeData { MtlShadeData(VR::VRayContext& rc, VR::SurfaceProperties* surfaceProps, int mtlID, int rID, int objID) { renderID = rID; gbufID = mtlID; objectID = objID; orig_rc = &rc; orig_sd = rc.rayresult.sd; orig_sp = rc.rayresult.surfaceProps; rc.rayresult.sd = static_cast(this); rc.rayresult.surfaceProps = surfaceProps; lastMapChannelIndex = -3; } ~MtlShadeData(void) { orig_rc->rayresult.sd = orig_sd; orig_rc->rayresult.surfaceProps = orig_sp; } VR::ShadeVec getUVWcoords(const VR::VRayContext& rc, int channel) VRAY_OVERRIDE { VR::ShadeVec result(0.0f, 0.0f, 0.0f); if (initMapChannel(rc, channel)) { result = lastMapChannelTransform.offs; } return result; } #ifdef GLM_USE_VRAY50 void getUVWderivs(const VR::VRayContext& rc, int channel, VR::ShadeVec derivs[2], const VR::UVWFlags /*uvwFlags*/) VRAY_OVERRIDE #else void getUVWderivs(const VR::VRayContext& rc, int channel, VR::ShadeVec derivs[2]) VRAY_OVERRIDE #endif { if (!initMapChannel(rc, channel)) { derivs[0].makeZero(); derivs[1].makeZero(); } else { derivs[0] = rc.rayresult.dPdx * lastMapChannelTransform.m; derivs[1] = rc.rayresult.dPdy * lastMapChannelTransform.m; } } #ifdef GLM_USE_VRAY50 void getUVWbases(const VR::VRayContext& rc, int channel, VR::ShadeVec bases[3], const VR::UVWFlags /*uvwFlags*/) VRAY_OVERRIDE #else void getUVWbases(const VR::VRayContext& rc, int channel, VR::ShadeVec bases[3]) VRAY_OVERRIDE #endif { if (!initMapChannel(rc, channel)) { bases[0].makeZero(); bases[1].makeZero(); bases[2].makeZero(); } else { bases[0] = lastMapChannelTransform.m[0]; bases[1] = lastMapChannelTransform.m[1]; bases[2] = lastMapChannelTransform.m[2]; } } VR::ShadeVec getUVWnormal(const VR::VRayContext& rc, int channel) VRAY_OVERRIDE { if (!initMapChannel(rc, channel)) { return VR::ShadeVec(0.0f, 0.0f, 1.0f); } else { return VR::simd::crossf(lastMapChannelTransform.m[0], lastMapChannelTransform.m[1]); } } int getMtlID(const VR::VRayContext& rc) VRAY_OVERRIDE { VR::SurfaceInfoInterface* surfaceInfo = static_cast(GET_INTERFACE(orig_sd, EXT_SURFACE_INFO)); if (surfaceInfo) return surfaceInfo->getFaceID(rc); return 0; } int getGBufID(void) VRAY_OVERRIDE { return objectID; } int getSmoothingGroup(const VR::VRayContext&) VRAY_OVERRIDE { return 0; } int getEdgeVisibility(const VR::VRayContext&) VRAY_OVERRIDE { return 7; } int getSurfaceRenderID(const VR::VRayContext&) VRAY_OVERRIDE { return renderID; } int getMaterialRenderID(const VR::VRayContext&) VRAY_OVERRIDE { return gbufID; } PluginInterface* newInterface(InterfaceID id) VRAY_OVERRIDE { PluginInterface* res = orig_sd->newInterface(id); if (res) return res; return VR::ShadeData::newInterface(id); } protected: int initMapChannel(const VR::VRayContext& rc, int channelIndex) { if (lastMapChannelIndex == channelIndex) return true; if (-2 == lastMapChannelIndex) return false; VR::MappedSurface* mappedSurface = static_cast(GET_INTERFACE(orig_sd, EXT_MAPPED_SURFACE)); if (!mappedSurface) { lastMapChannelIndex = -2; return false; } // In 3ds Max, mapping channels start from 1, so that's why we subtract 1 from the channelIndex here. #ifdef GLM_USE_VRAY50 mappedSurface->getLocalUVWTransform(rc, channelIndex - 1, lastMapChannelTransform, VR::UVWFlags::uvwFlags_default); #else mappedSurface->getLocalUVWTransform(rc, channelIndex - 1, lastMapChannelTransform); #endif lastMapChannelIndex = channelIndex; return true; } VR::VRayContext* orig_rc; VR::VRayShadeData* orig_sd; VR::VRaySurfaceProperties* orig_sp; int lastMapChannelIndex; VR::ShadeTransform lastMapChannelTransform; int gbufID, renderID, objectID; }; void GolaemBRDFWrapper::shade(VR::VRayContext& rc) { // 3ds Max materials for V-Ray expect rc.rayresult.sd to be ShadeData, so create a wrapper here MtlShadeData shadeData(rc, NULL, _mtlID, 0 /* renderID */, _golaemInstance->getObjectID()); VR::VRayInterface& vri = static_cast(rc); // Just call the original 3ds Max material to shade itself. _vrayMtl->shade(vri, _mtlID); // Handle alpha contribution - there's no one to do it for us since we don't go through VRayInstance::fullShade(). if (rc.rayresult.surfaceProps && 0 != (rc.rayparams.localRayType & VR::RT_GBUFFER)) { float alphaContrib = static_cast(rc.rayresult.surfaceProps)->alphaContribution; if (alphaContrib >= 0.0f) { rc.mtlresult.alpha *= alphaContrib; rc.mtlresult.alphaTransp = VR::ShadeCol(1.0f, 1.0f, 1.0f) * (1.0f - alphaContrib) + rc.mtlresult.alphaTransp * alphaContrib; } else { rc.mtlresult.alpha.makeZero(); rc.mtlresult.alphaTransp = VR::ShadeCol(1.0f, 1.0f, 1.0f) * (1.0f + alphaContrib) - rc.mtlresult.alphaTransp * alphaContrib; } } } int GolaemBRDFWrapper::getMaterialRenderID(const VR::VRayContext&) { return _mtlID; } int GolaemBRDFWrapper::getBSDFFlags(void) { int res = 0; if (isOpaqueForShadows()) res |= VUtils::bsdfFlag_opaqueForShadows; if (needs2SidedLighting()) res |= VUtils::bsdfFlag_cantUsePremultLightCache; return res; } VR::BSDFSampler* GolaemBRDFWrapper::newBSDF(const VR::VRayContext& rc, VR::BSDFFlags flags) { if (!_vrayMtl) return NULL; VR::VRenderMtlFlags mtlFlags; mtlFlags.force1sided = flags.force1sided; return _vrayMtl->newBSDF(rc, mtlFlags); } void GolaemBRDFWrapper::deleteBSDF(const VR::VRayContext& rc, VR::BSDFSampler* bsdf) { if (!bsdf) return; _vrayMtl->deleteBSDF(rc, bsdf); } void GolaemBRDFWrapper::setMaxMtl(Mtl* maxMtl, VR::VRenderMtl* vrayMtl, VRayGolaem* golaem) { this->_maxMtl = maxMtl; this->_vrayMtl = vrayMtl; this->_golaemInstance = golaem; GET_MBCS(maxMtl->GetName(), mtlName); setPluginName(mtlName); // Set the name to be the same as the Max name, so that the Golaem plugin can find it. _maxMtlFlags = maxMtl->Requirements(-1); _mtlID = maxMtl->gbufID; } GolaemBRDFWrapper::GolaemBRDFWrapper(void) : _maxMtl(NULL) , _vrayMtl(NULL) , _maxMtlFlags(0) , _mtlID(0) , _golaemInstance(NULL) { } //----------------------------------------------------------------------------- VrayGolaemContext::VrayGolaemContext() { glm::crowdio::init(); } //----------------------------------------------------------------------------- VrayGolaemContext::~VrayGolaemContext() { glm::crowdio::finish(); } //----------------------------------------------------------------------------- VrayGolaemContext& VrayGolaemContext::getVrayGolaemContext() { static VrayGolaemContext vrayGolaemContext; return vrayGolaemContext; } #include #include #include #include #include #include #include struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; struct NodeWrapper { TreeNode* node; int deep; }; class Solution { public: std::vector largestValues(TreeNode* root) { std::vector res; if (root == nullptr) { return res; } int current_deep = -1; int max_size = 0; std::queue qu; { NodeWrapper w; w.node = root; w.deep = 0; qu.push(w); } while (!qu.empty()) { NodeWrapper node = qu.front(); qu.pop(); if (current_deep != node.deep) { if (current_deep == -1) { current_deep = node.deep; max_size = node.node->val; } else { res.push_back(max_size); current_deep = node.deep; max_size = node.node->val; } } max_size = std::max(max_size, node.node->val); if (node.node->left != nullptr) { NodeWrapper w; w.node = node.node->left; w.deep = current_deep + 1; qu.push(w); } if (node.node->right != nullptr) { NodeWrapper w; w.node = node.node->right; w.deep = current_deep + 1; qu.push(w); } } return res; } }; int main() { TreeNode* root = new TreeNode(1); TreeNode* left = new TreeNode(2); TreeNode* right = new TreeNode(3); root->left = left; root->right = right; Solution solution; auto res = solution.largestValues(root); for (const auto& item : res) { std::cout << item << " "; } std::cout << std::endl; } eWert-Online/esy-cmakeTests/VSWinStorePhone/CxxDLL/cxxdll.cpp #include "cxxdll.h" #include void CxxDllClass::SomeMethod() { std::cout << "CxxDllClass::SomeMethod\n"; } // Created on: 1993-01-11 // Created by: CKY / Contract Toubro-Larsen ( ) // Copyright (c) 1993-1999 // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESAppli_LevelToPWBLayerMap_HeaderFile #define _IGESAppli_LevelToPWBLayerMap_HeaderFile #include #include #include #include #include #include class Standard_DimensionMismatch; class Standard_OutOfRange; class TCollection_HAsciiString; class IGESAppli_LevelToPWBLayerMap; DEFINE_STANDARD_HANDLE(IGESAppli_LevelToPWBLayerMap, IGESData_IGESEntity) //! defines LevelToPWBLayerMap, Type <406> Form <24> //! in package IGESAppli //! Used to correlate an exchange file level number with //! its corresponding native level identifier, physical PWB //! layer number and predefined functional level //! identification class IGESAppli_LevelToPWBLayerMap : public IGESData_IGESEntity { public: Standard_EXPORT IGESAppli_LevelToPWBLayerMap(); //! This method is used to set the fields of the class //! LevelToPWBLayerMap //! - nbPropVal : Number of property values //! - allExchLevels : Exchange File Level Numbers //! - allNativeLevels : Native Level Identifications //! - allPhysLevels : Physical Layer Numbers //! - allExchIdents : Exchange File Level Identifications //! raises exception if allExchLevels, allNativeLevels, allPhysLevels //! and all ExchIdents are not of same dimensions Standard_EXPORT void Init (const Standard_Integer nbPropVal, const Handle(TColStd_HArray1OfInteger)& allExchLevels, const Handle(Interface_HArray1OfHAsciiString)& allNativeLevels, const Handle(TColStd_HArray1OfInteger)& allPhysLevels, const Handle(Interface_HArray1OfHAsciiString)& allExchIdents); //! returns number of property values Standard_EXPORT Standard_Integer NbPropertyValues() const; //! returns number of level to layer definitions Standard_EXPORT Standard_Integer NbLevelToLayerDefs() const; //! returns Exchange File Level Number //! raises exception if Index <= 0 or Index > NbLevelToLayerDefs Standard_EXPORT Standard_Integer ExchangeFileLevelNumber (const Standard_Integer Index) const; //! returns Native Level Identification //! raises exception if Index <= 0 or Index > NbLevelToLayerDefs Standard_EXPORT Handle(TCollection_HAsciiString) NativeLevel (const Standard_Integer Index) const; //! returns Physical Layer Number //! raises exception if Index <= 0 or Index > NbLevelToLayerDefs Standard_EXPORT Standard_Integer PhysicalLayerNumber (const Standard_Integer Index) const; Standard_EXPORT Handle(TCollection_HAsciiString) ExchangeFileLevelIdent (const Standard_Integer Index) const; DEFINE_STANDARD_RTTIEXT(IGESAppli_LevelToPWBLayerMap,IGESData_IGESEntity) protected: private: Standard_Integer theNbPropertyValues; Handle(TColStd_HArray1OfInteger) theExchangeFileLevelNumber; Handle(Interface_HArray1OfHAsciiString) theNativeLevel; Handle(TColStd_HArray1OfInteger) thePhysicalLayerNumber; Handle(Interface_HArray1OfHAsciiString) theExchangeFileLevelIdent; }; #endif // _IGESAppli_LevelToPWBLayerMap_HeaderFile 10-100 #pragma once #include namespace glpp::test { struct offscreen_driver_t { system::windowless_context_t m_context { system::driver_t::mesa }; }; }AnthonyDas/Cpp_Data_Structures_And_Algorithms #include #include std::string DecimalToBinaryString(int decimalNumber) { // Initial result std::string binaryString = "0"; // Only perform this procedure // if decimalNumber is greater than 0 if (decimalNumber > 0) { // Reset result binaryString.clear(); while (decimalNumber) { std::ostringstream ss{ decimalNumber % 2 }; binaryString = ss.str() + binaryString; decimalNumber /= 2; } } // return the binary string return binaryString; } main.cpp0 #include "pico_explorer.hpp" using namespace pimoroni; uint16_t buffer[PicoExplorer::WIDTH * PicoExplorer::HEIGHT]; PicoExplorer pico_explorer(buffer); int main() { pico_explorer.init(); // set the backlight to a value between 0 and 255 // the backlight is driven via PWM and is gamma corrected by our // library to give a gorgeous linear brightness range. pico_explorer.set_backlight(100); pico_explorer.set_pen(255, 0, 0); while(true) { pico_explorer.pixel(point(0, 0)); // now we've done our drawing let's update the screen pico_explorer.update(); } }/******************************************************************************* * tlx/string/union_words.hpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2016-2017 <> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #ifndef TLX_STRING_UNION_WORDS_HEADER #define TLX_STRING_UNION_WORDS_HEADER #include namespace tlx { //! \addtogroup string //! \{ /*! * Return union of two keyword sets. */ std::string union_words(const std::string& wordsA, const std::string& wordsB); //! \} } // namespace tlx #endif // !TLX_STRING_UNION_WORDS_HEADER /******************************************************************************/ project3D/Point.cpp #include "Point.h" #include #include "Body.h" void Physics::Point::DrawGizmo(const Body * const _body, const glm::vec4 & _colour) const { aie::Gizmos::addSphere(_body->GetPosition(), 0.1f, 12, 12, _colour); } Char-Aznable/kokkoscore/src/impl/Kokkos_Atomic_Compare_Exchange_Weak.hpp /* //@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact () // // ************************************************************************ //@HEADER */ #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) #include #endif #include #include #ifndef KOKKOS_ATOMIC_COMPARE_EXCHANGE_WEAK_HPP #define KOKKOS_ATOMIC_COMPARE_EXCHANGE_WEAK_HPP #if defined(KOKKOS_ENABLE_CUDA) #include #endif namespace Kokkos { //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Cuda sm_70 or greater supports C++-like semantics directly #if defined( KOKKOS_ENABLE_CUDA ) #if defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND) #if __CUDA_ARCH__ >= 700 // See: https://github.com/ogiroux/freestanding # define kokkos_cuda_internal_cas_release_32(ptr, old, expected, desired) \ asm volatile("atom.cas.release.sys.b32 %0, [%1], %2, %3;" : "=r"(old) : "l"(ptr), "r"(expected), "r"(desired) : "memory") # define kokkos_cuda_internal_cas_acquire_32(ptr, old, expected, desired) \ asm volatile("atom.cas.acquire.sys.b32 %0, [%1], %2, %3;" : "=r"(old) : "l"(ptr), "r"(expected), "r"(desired) : "memory") # define kokkos_cuda_internal_cas_acq_rel_32(ptr, old, expected, desired) \ asm volatile("atom.cas.acq_rel.sys.b32 %0, [%1], %2, %3;" : "=r"(old) : "l"(ptr), "r"(expected), "r"(desired) : "memory") # define kokkos_cuda_internal_cas_relaxed_32(ptr, old, expected, desired) \ asm volatile("atom.cas.relaxed.sys.b32 %0, [%1], %2, %3;" : "=r"(old) : "l"(ptr), "r"(expected), "r"(desired) : "memory") # define kokkos_cuda_internal_fence_seq_cst() asm volatile("fence.sc.sys;" : : : "memory") # define kokkos_cuda_internal_fence_acq_rel() asm volatile("fence.acq_rel.sys;" : : : "memory") #else # define kokkos_cuda_internal_fence_acq_rel() asm volatile("membar.sys;" : : : "memory") # define kokkos_cuda_internal_fence_seq_cst() asm volatile("membar.sys;" : : : "memory") #endif // 32-bit version template ::type = 0 > __inline__ __device__ bool atomic_compare_exchange_weak( T volatile* const dest, T* const expected, T const desired, std::memory_order success_order = std::memory_order_seq_cst, std::memory_order failure_order = std::memory_order_seq_cst ) { // TODO assert that success_order >= failure_order // See: https://github.com/ogiroux/freestanding int32_t tmp = 0; int32_t old = 0; memcpy(&tmp, &desired, sizeof(T)); memcpy(&old, expected, sizeof(T)); int32_t old_tmp = old; #if __CUDA_ARCH__ >= 700 switch(success_order) { case std::memory_order_seq_cst: // sequentially consistent is just an acquire with a seq_cst fence kokkos_cuda_internal_fence_seq_cst(); kokkos_cuda_internal_cas_acquire_32((T*)dest, old, old_tmp, tmp); break; case std::memory_order_acquire: kokkos_cuda_internal_cas_acquire_32((T*)dest, old, old_tmp, tmp); break; case std::memory_order_consume: // same as acquire on PTX compatible platforms kokkos_cuda_internal_cas_acquire_32((T*)dest, old, old_tmp, tmp); break; case std::memory_order_acq_rel: kokkos_cuda_internal_cas_acq_rel_32((T*)dest, old, old_tmp, tmp); break; case std::memory_order_release: kokkos_cuda_internal_cas_release_32((T*)dest, old, old_tmp, tmp); break; case std::memory_order_relaxed: kokkos_cuda_internal_cas_relaxed_32((T*)dest, old, old_tmp, tmp); break; }; #else // All of the orders that require a fence before the relaxed atomic operation: if( success_order == std::memory_order_release || success_order == std::memory_order_acq_rel ) { kokkos_cuda_internal_fence_acq_rel(); } else if(success_order == std::memory_order_seq_cst) { kokkos_cuda_internal_fence_seq_cst(); } // This is relaxed: // Cuda API requires casting away volatile atomicCAS((T*)dest, old_tmp, tmp); #endif bool const rv = (old == old_tmp); #if __CUDA_ARCH__ < 700 if(rv) { if( success_order == std::memory_order_acquire || success_order == std::memory_order_consume || success_order == std::memory_order_acq_rel ) { kokkos_cuda_internal_fence_acq_rel(); } else if(success_order == std::memory_order_seq_cst) { kokkos_cuda_internal_fence_seq_cst(); } } else { if( failure_order == std::memory_order_acquire || failure_order == std::memory_order_consume || failure_order == std::memory_order_acq_rel ) { kokkos_cuda_internal_fence_acq_rel(); } else if(failure_order == std::memory_order_seq_cst) { kokkos_cuda_internal_fence_seq_cst(); } } #endif memcpy(expected, &old, sizeof(T)); return rv; } // 64-bit version template ::type = 0 > bool atomic_compare_exchange_weak( T volatile* const dest, T* const expected, T const desired, std::memory_order success_order = std::memory_order_seq_cst, std::memory_order failure_order = std::memory_order_seq_cst ) { // TODO assert that success_order >= failure_order // See: https://github.com/ogiroux/freestanding int64_t tmp = 0; int64_t old = 0; memcpy(&tmp, &desired, sizeof(T)); memcpy(&old, expected, sizeof(T)); int64_t old_tmp = old; #if __CUDA_ARCH__ >= 700 switch(success_order) { case std::memory_order_seq_cst: // sequentially consistent is just an acquire with a seq_cst fence kokkos_cuda_internal_fence_seq_cst(); kokkos_cuda_internal_cas_acquire_64((T*)dest, old, old_tmp, tmp); break; case std::memory_order_acquire: kokkos_cuda_internal_cas_acquire_64((T*)dest, old, old_tmp, tmp); break; case std::memory_order_consume: // same as acquire on PTX compatible platforms kokkos_cuda_internal_cas_acquire_64((T*)dest, old, old_tmp, tmp); break; case std::memory_order_acq_rel: kokkos_cuda_internal_cas_acq_rel_64((T*)dest, old, old_tmp, tmp); break; case std::memory_order_release: kokkos_cuda_internal_cas_release_64((T*)dest, old, old_tmp, tmp); break; case std::memory_order_relaxed: kokkos_cuda_internal_cas_relaxed_64((T*)dest, old, old_tmp, tmp); break; }; #else // Cuda API requires casting away volatile atomicCAS((T*)dest, old_tmp, tmp); #endif bool const rv = (old == old_tmp); memcpy(expected, &old, sizeof(T)); return rv; } #endif // defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND) #endif // defined( KOKKOS_ENABLE_CUDA ) //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // GCC native CAS supports int, long, unsigned int, unsigned long. // Intel native CAS support int and long with the same interface as GCC. #if !defined(KOKKOS_ENABLE_ROCM_ATOMICS) #if !defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND) #if defined(KOKKOS_ENABLE_GNU_ATOMICS) || defined(KOKKOS_ENABLE_INTEL_ATOMICS) inline int atomic_compare_exchange( volatile int * const dest, const int compare, const int val) { #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif return __sync_val_compare_and_swap(dest,compare,val); } inline long atomic_compare_exchange( volatile long * const dest, const long compare, const long val ) { #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif return __sync_val_compare_and_swap(dest,compare,val); } #if defined( KOKKOS_ENABLE_GNU_ATOMICS ) // GCC supports unsigned inline unsigned int atomic_compare_exchange( volatile unsigned int * const dest, const unsigned int compare, const unsigned int val ) { return __sync_val_compare_and_swap(dest,compare,val); } inline unsigned long atomic_compare_exchange( volatile unsigned long * const dest , const unsigned long compare , const unsigned long val ) { return __sync_val_compare_and_swap(dest,compare,val); } #endif template < typename T > inline T atomic_compare_exchange( volatile T * const dest, const T & compare, typename Kokkos::Impl::enable_if< sizeof(T) == sizeof(int) , const T & >::type val ) { union U { int i ; T t ; KOKKOS_INLINE_FUNCTION U() {}; } tmp ; #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif tmp.i = __sync_val_compare_and_swap( (int*) dest , *((int*)&compare) , *((int*)&val) ); return tmp.t ; } template < typename T > inline T atomic_compare_exchange( volatile T * const dest, const T & compare, typename Kokkos::Impl::enable_if< sizeof(T) != sizeof(int) && sizeof(T) == sizeof(long) , const T & >::type val ) { union U { long i ; T t ; KOKKOS_INLINE_FUNCTION U() {}; } tmp ; #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif tmp.i = __sync_val_compare_and_swap( (long*) dest , *((long*)&compare) , *((long*)&val) ); return tmp.t ; } #if defined( KOKKOS_ENABLE_ASM) && defined ( KOKKOS_ENABLE_ISA_X86_64 ) template < typename T > inline T atomic_compare_exchange( volatile T * const dest, const T & compare, typename Kokkos::Impl::enable_if< sizeof(T) != sizeof(int) && sizeof(T) != sizeof(long) && sizeof(T) == sizeof(Impl::cas128_t), const T & >::type val ) { union U { Impl::cas128_t i ; T t ; KOKKOS_INLINE_FUNCTION U() {}; } tmp ; #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif tmp.i = Impl::cas128( (Impl::cas128_t*) dest , *((Impl::cas128_t*)&compare) , *((Impl::cas128_t*)&val) ); return tmp.t ; } #endif template < typename T > inline T atomic_compare_exchange( volatile T * const dest , const T compare , typename Kokkos::Impl::enable_if< ( sizeof(T) != 4 ) && ( sizeof(T) != 8 ) #if defined(KOKKOS_ENABLE_ASM) && defined ( KOKKOS_ENABLE_ISA_X86_64 ) && ( sizeof(T) != 16 ) #endif , const T >::type& val ) { #if defined( KOKKOS_ENABLE_RFO_PREFETCH ) _mm_prefetch( (const char*) dest, _MM_HINT_ET0 ); #endif while( !Impl::lock_address_host_space( (void*) dest ) ); T return_val = *dest; if( return_val == compare ) { // Don't use the following line of code here: // //const T tmp = *dest = val; // // Instead, put each assignment in its own statement. This is // because the overload of T::operator= for volatile *this should // return void, not volatile T&. See Kokkos #177: // // https://github.com/kokkos/kokkos/issues/177 *dest = val; const T tmp = *dest; #ifndef KOKKOS_COMPILER_CLANG (void) tmp; #endif } Impl::unlock_address_host_space( (void*) dest ); return return_val; } //---------------------------------------------------------------------------- #elif defined( KOKKOS_ENABLE_OPENMP_ATOMICS ) template< typename T > KOKKOS_INLINE_FUNCTION T atomic_compare_exchange( volatile T * const dest, const T compare, const T val ) { T retval; #pragma omp critical { retval = dest[0]; if ( retval == compare ) dest[0] = val; } return retval; } #elif defined( KOKKOS_ENABLE_SERIAL_ATOMICS ) template< typename T > KOKKOS_INLINE_FUNCTION T atomic_compare_exchange( volatile T * const dest_v, const T compare, const T val ) { T* dest = const_cast(dest_v); T retval = *dest; if (retval == compare) *dest = val; return retval; } #endif #endif #endif // !defined ROCM_ATOMICS template KOKKOS_INLINE_FUNCTION bool atomic_compare_exchange_strong(volatile T* const dest, const T compare, const T val) { return compare == atomic_compare_exchange(dest, compare, val); } //---------------------------------------------------------------------------- } // namespace Kokkos #endif zipated/srccomponents/previews/core/previews_amp_converter.cc // Copyright 2017 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 "components/previews/core/previews_amp_converter.h" #include #include "base/feature_list.h" #include "base/json/json_reader.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/values.h" #include "components/previews/core/previews_features.h" #include "components/variations/variations_associated_data.h" #include "third_party/re2/src/re2/re2.h" #include "url/url_constants.h" namespace previews { namespace { const char kAMPRedirectionConfig[] = "config"; // Allowed URL schemes to match. enum MatchingScheme { HTTP, HTTPS, BOTH }; } // namespace struct AMPConverterEntry { AMPConverterEntry(MatchingScheme matching_scheme, std::unique_ptr matching_path_pattern, const std::string& hostname_amp, const std::string& scheme_amp, const std::string& prefix, const std::string& suffix, const std::string& suffix_html) : matching_scheme(matching_scheme), matching_path_pattern(std::move(matching_path_pattern)), hostname_amp(hostname_amp), scheme_amp(scheme_amp), prefix(prefix), suffix(suffix), suffix_html(suffix_html) {} ~AMPConverterEntry() {} // URL scheme to match. const MatchingScheme matching_scheme; // RE2 pattern the URL path should match. const std::unique_ptr matching_path_pattern; // New AMP hostname for the URL, if any. const std::string hostname_amp; // New scheme for the AMP URL, if any. const std::string scheme_amp; // String to be prefixed to the URL path, if any. const std::string prefix; // String to be suffixed to the URL path, before query string and named // anchor, if any. const std::string suffix; // String to be suffixed to the URL path, before the .html extension, if // any. const std::string suffix_html; }; PreviewsAMPConverter::PreviewsAMPConverter() { std::string config_text = GetFieldTrialParamValueByFeature( features::kAMPRedirection, kAMPRedirectionConfig); if (config_text.empty()) return; std::unique_ptr value = base::JSONReader::Read(config_text); const base::ListValue* entries = nullptr; if (!value || !value->GetAsList(&entries)) return; re2::RE2::Options options(re2::RE2::DefaultOptions); options.set_case_sensitive(true); for (const auto& entry : *entries) { const base::DictionaryValue* dict = nullptr; if (!entry.GetAsDictionary(&dict)) continue; std::string host, matching_scheme_str, matching_path_pattern_str, host_amp, scheme_amp, prefix, suffix, suffix_html; dict->GetString("host", &host); dict->GetString("scheme", &matching_scheme_str); dict->GetString("pattern", &matching_path_pattern_str); dict->GetString("hostamp", &host_amp); dict->GetString("schemeamp", &scheme_amp); dict->GetString("prefix", &prefix); dict->GetString("suffix", &suffix); dict->GetString("suffixhtml", &suffix_html); MatchingScheme matching_scheme = matching_scheme_str == url::kHttpScheme ? MatchingScheme::HTTP : matching_scheme_str == url::kHttpsScheme ? MatchingScheme::HTTPS : MatchingScheme::BOTH; // If matching scheme is HTTPS or BOTH, then AMP scheme should not be http, // which will redirect https to http. DCHECK(matching_scheme == MatchingScheme::HTTP || scheme_amp != url::kHttpScheme); std::unique_ptr matching_path_pattern_re2( std::make_unique(matching_path_pattern_str, options)); if (host.empty() || !matching_path_pattern_re2->ok() || (scheme_amp != "" && scheme_amp != url::kHttpScheme && scheme_amp != url::kHttpsScheme)) { continue; } amp_converter_.insert(std::make_pair( host, std::make_unique( matching_scheme, std::move(matching_path_pattern_re2), host_amp, scheme_amp, prefix, suffix, suffix_html))); } } PreviewsAMPConverter::~PreviewsAMPConverter() {} bool PreviewsAMPConverter::GetAMPURL(const GURL& url, GURL* new_amp_url) const { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS()) { return false; } const auto amp_converter_iter = amp_converter_.find(url.host()); if (amp_converter_iter == amp_converter_.end() || !re2::RE2::FullMatch( url.path(), *amp_converter_iter->second->matching_path_pattern)) { return false; } const auto& entry = *amp_converter_iter->second; // Check for allowed URL schemes. if (entry.matching_scheme != MatchingScheme::BOTH && (entry.matching_scheme == MatchingScheme::HTTP) != url.SchemeIs(url::kHttpScheme)) { return false; } GURL amp_url(url); GURL::Replacements url_replacements; if (!entry.hostname_amp.empty()) url_replacements.SetHostStr(entry.hostname_amp); if (!entry.scheme_amp.empty()) { // Avoid https to http redirection. if (url.scheme() == url::kHttpsScheme && entry.scheme_amp == url::kHttpScheme) { return false; } url_replacements.SetSchemeStr(entry.scheme_amp); } std::string path; if (!entry.prefix.empty() || !entry.suffix.empty() || !entry.suffix_html.empty()) { DCHECK(entry.prefix.empty() || entry.prefix[0] == '/'); path = base::StrCat({entry.prefix, url.path(), entry.suffix}); if (!entry.suffix_html.empty() && base::EndsWith(path, ".html", base::CompareCase::SENSITIVE)) { // Insert suffix_html before the .html extension. path.insert(path.length() - 5, entry.suffix_html); } url_replacements.SetPathStr(path); } amp_url = amp_url.ReplaceComponents(url_replacements); if (!amp_url.is_valid()) return false; new_amp_url->Swap(&_url); return true; } } // namespace previews bigov/daft-lib //// // Базовые библиотеки для всех компонентов приложения // #ifndef __LIB_H__ #define __LIB_H__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // add libs on the path ../libs #include #include #include #include #include namespace lib { //// file: io.cpp"|------------------------------------ extern void show_error (const std::string &); extern void show_message (const std::string &); extern void write_log (const std::string &); extern void set_log_fname (const std::string &); extern void out_debug_file (const std::string &); extern void msg_out_console(const std::string &); extern bool filepath_ok (const std::string &); extern bool sdl_file_exist(const char* file_pathname); extern char* sdl_file_read(const char* file_pathname); // ----------------------------------------------------| struct defShader { GLenum id; std::string name; }; } //namespace lib #endif // __LIB_H__ // ====================================================================== // \title NORFlashMgrWorker.hpp // \author ciankc // \brief cpp file for NORFlashMgrWorker test harness implementation class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #include "Tester.hpp" #define INSTANCE 0 #define MAX_HISTORY_SIZE 1000 #define QUEUE_DEPTH 10 namespace Drv { // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- Tester :: Tester(void) : #if FW_OBJECT_NAMES == 1 NORFlashMgrWorkerGTestBase("Tester", MAX_HISTORY_SIZE), component("NORFlashMgrWorker") #else NORFlashMgrWorkerGTestBase(MAX_HISTORY_SIZE), component() #endif { this->initComponents(); this->connectPorts(); } Tester :: ~Tester(void) { } // ---------------------------------------------------------------------- // Tests // ---------------------------------------------------------------------- void Tester :: toDo(void) { // TODO } // ---------------------------------------------------------------------- // Handlers for typed from ports // ---------------------------------------------------------------------- I8 Tester :: from_read_handler( const NATIVE_INT_TYPE portNum, U32 dest, U8 *data ) { U32 diff = dest % 0x4; U32 addr = dest - diff; U32 val = readReg(addr); U32 mask = 0xff000000 >> (diff*8); U32 res = (val & mask) >> ((3-diff)*8); *data = (U8) res; this->pushFromPortEntry_read(dest, data); if(dest > 0x10000000) { return 1; } return 0; } void Tester :: from_statusOut_handler( const NATIVE_INT_TYPE portNum, I8 done, U32 context1, U32 context2 ) { if(context2 == 0) { ASSERT_TRUE(done == NORMGR_FAILED_TO_READ | done == NORMGR_SUCCESSFUL_ERASE | done == NORMGR_OK); } else if(context2 == 8) { ASSERT_EQ(done, NORMGR_OK); } else if(context2 == 0xC) { ASSERT_EQ(done, NORMGR_FAILED_TO_UNLOCK_PROGRAM); } this->pushFromPortEntry_statusOut(done, context1, context2); } I8 Tester :: from_write_handler( const NATIVE_INT_TYPE portNum, U32 dest_addr, U8 src ) { U32 diff = dest_addr % 0x4; U32 addr = dest_addr - diff; U32 val = src << ((3-diff)*8); U32 prev = readReg(addr); writeReg(addr, val | prev); this->pushFromPortEntry_write(addr, src); if(dest_addr > 0x10000000) { return 1; } return 0; } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- void Tester :: connectPorts(void) { // cancel this->connect_to_cancel( 0, this->component.get_cancel_InputPort(0) ); // erase this->connect_to_erase( 0, this->component.get_erase_InputPort(0) ); // reset this->connect_to_reset( 0, this->component.get_reset_InputPort(0) ); // verify this->connect_to_verify( 0, this->component.get_verify_InputPort(0) ); // write_block this->connect_to_write_block( 0, this->component.get_write_block_InputPort(0) ); // read_block this->connect_to_read_block( 0, this->component.get_read_block_InputPort(0) ); // read this->component.set_read_OutputPort( 0, this->get_from_read(0) ); // statusOut this->component.set_statusOut_OutputPort( 0, this->get_from_statusOut(0) ); // write this->component.set_write_OutputPort( 0, this->get_from_write(0) ); } void Tester :: initComponents(void) { this->init(); this->component.init( QUEUE_DEPTH, INSTANCE ); } } // end namespace Drv // 3.1.3 #include #include #include #include using namespace std; int main() { int t[] = {10, 2, 4, 3, 5, 6, 10, 8, 9, 10,}; deque d1(t, t+10); cout<<"Look for the first even element in the container:\n"; deque::iterator found = find(d1.begin(), d1.end(), 10); if (found!=d1.end()) { cout<<"Value 10 found at position : "<1-10 uint64_t x86_bfs(const uint64_t* data, size_t n) { uint64_t ptr = 0; uint64_t res = 0; asm volatile ( "mov %[data], %[ptr] \n" "sub $8, %[ptr] \n" "0:\n" // main loop "add $8, %[ptr] \n" "cmp %[ptr], %[end] \n" "je 2f \n" "tzcnt (%[ptr]), %[res] \n" "jz 0b \n" // goto main loop "sub %[data], %[ptr] \n" // ptr -= data "lea (%[res], %[ptr], 8), %[res] \n" // return ptr*8 + bfs "jmp 3f \n" "2:\n" // end of the loop "mov $-1, %[res] \n" "3:\n" : [ptr] "+r" (ptr) , [res] "+r" (res) : [data] "r" (data) , [end] "r" (data + n) : "cc" ); return res; } ppearson/ImaginePartial /* Imagine Copyright 2013-2014 . 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 "image_reader_tiff.h" #include #include "image/image_1f.h" #include "image/image_1b.h" #include "image/image_colour3f.h" #include "image/image_colour3h.h" #include "image/image_colour3b.h" #include "colour/colour_space.h" #include "global_context.h" #include "utils/file_helpers.h" namespace Imagine { // TODO: there's a fair bit of duplicate code here and it could be re-written in a more compact way, but it's written // with as few branches as possible (i.e. not within loops) in the hope compilers might be able to vectorise it more easily ImageReaderTIFF::ImageReaderTIFF() { } bool ImageReaderTIFF::readInfo(TIFF* pTiff, TiffInfo& tiffInfo) { TIFFGetField(pTiff, TIFFTAG_IMAGELENGTH, &tiffInfo.imageHeight); TIFFGetField(pTiff, TIFFTAG_IMAGEWIDTH, &tiffInfo.imageWidth); TIFFGetField(pTiff, TIFFTAG_IMAGEDEPTH, &tiffInfo.imageDepth); if (tiffInfo.imageHeight == 0 || tiffInfo.imageWidth == 0) return false; TIFFGetField(pTiff, TIFFTAG_XPOSITION, &tiffInfo.xPos); TIFFGetField(pTiff, TIFFTAG_YPOSITION, &tiffInfo.yPos); TIFFGetField(pTiff, TIFFTAG_BITSPERSAMPLE, &tiffInfo.bitDepth); TIFFGetField(pTiff, TIFFTAG_SAMPLESPERPIXEL, &tiffInfo.channelCount); TIFFGetField(pTiff, TIFFTAG_ROWSPERSTRIP, &tiffInfo.rowsPerStrip); TIFFGetFieldDefaulted(pTiff, TIFFTAG_SAMPLEFORMAT, &tiffInfo.sampleFormat); uint16_t planarConfig = 0; TIFFGetFieldDefaulted(pTiff, TIFFTAG_PLANARCONFIG, &planarConfig); if (planarConfig == PLANARCONFIG_SEPARATE && tiffInfo.channelCount > 1) { tiffInfo.separatePlanes = true; } TIFFGetField(pTiff, TIFFTAG_ORIENTATION, &tiffInfo.orientation); TIFFGetField(pTiff, TIFFTAG_COMPRESSION, &tiffInfo.compression); if (TIFFIsTiled(pTiff)) { tiffInfo.isTiled = true; TIFFGetField(pTiff, TIFFTAG_TILEWIDTH, &tiffInfo.tileWidth); TIFFGetField(pTiff, TIFFTAG_TILELENGTH, &tiffInfo.tileHeight); TIFFGetField(pTiff, TIFFTAG_TILEDEPTH, &tiffInfo.tileDepth); // get other stuff // if (TIFFGetField(pTiff, TIFFTAG_PIXAR_IMAGEFULLLENGTH, &tiffInfo.imageHeight) == 1) { } // if (TIFFGetField(pTiff, TIFFTAG_PIXAR_IMAGEFULLWIDTH, &tiffInfo.imageWidth) == 1) { } } return true; } Image* ImageReaderTIFF::readColourImage(const std::string& filePath, unsigned int requiredTypeFlags) { TIFF* pTiff = TIFFOpen(filePath.c_str(), "r"); if (!pTiff) { GlobalContext::instance().getLogger().error("Can't open file: %s", filePath.c_str()); return nullptr; } TiffInfo tiffInfo; if (!readInfo(pTiff, tiffInfo)) { GlobalContext::instance().getLogger().error("Invalid tiff file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (tiffInfo.bitDepth < 8) { GlobalContext::instance().getLogger().error("Unsupported TIFF format for file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (!tiffInfo.isTiled) { return readScanlineColourImage(filePath, pTiff, tiffInfo, requiredTypeFlags); } else { return readTiledColourImage(filePath, pTiff, tiffInfo, requiredTypeFlags); } } Image* ImageReaderTIFF::readScanlineColourImage(const std::string& filePath, TIFF* pTiff, TiffInfo& tiffInfo, unsigned int requiredTypeFlags) { ImageColour3f* pImage3f = nullptr; ImageColour3h* pImage3h = nullptr; ImageColour3b* pImage3b = nullptr; unsigned int bitDepthToCreate = tiffInfo.bitDepth; if (!(requiredTypeFlags & Image::IMAGE_FORMAT_NATIVE)) { bitDepthToCreate = 32; } if (bitDepthToCreate == 32) { pImage3f = new ImageColour3f(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } else if (bitDepthToCreate == 16) { pImage3h = new ImageColour3h(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } else if (bitDepthToCreate == 8) { pImage3b = new ImageColour3b(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } // if we didn't allocate any image, bail out if (!pImage3b && !pImage3h && !pImage3f) { GlobalContext::instance().getLogger().error("Couldn't allocate memory for new image for file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (bitDepthToCreate == 8) { // allocate memory for image - do it the easy way for the moment - we can convert to scanline approach later... uint32_t totalImageSize = tiffInfo.imageHeight * tiffInfo.imageWidth; uint32_t* pRawBuffer = (uint32_t*)_TIFFmalloc(totalImageSize * sizeof(uint32_t)); // RGBA byte bool failed = false; if (!pRawBuffer) { GlobalContext::instance().getLogger().error("Couldn't allocate memory to read file: %s", filePath.c_str()); failed = true; } if (TIFFReadRGBAImage(pTiff, tiffInfo.imageWidth, tiffInfo.imageHeight, pRawBuffer, 0) == 0) { GlobalContext::instance().getLogger().error("Couldn't read image: %s", filePath.c_str()); failed = true; _TIFFfree(pRawBuffer); } if (failed) { if (pImage3b) { delete pImage3b; pImage3b = nullptr; } TIFFClose(pTiff); return nullptr; } unsigned int index = 0; for (unsigned int i = 0; i < tiffInfo.imageHeight; i++) { // we don't seem to need to reverse this for 8-bit... unsigned int y = i; Colour3b* pImageRow = pImage3b->colour3bRowPtr(y); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { unsigned char red = TIFFGetR(pRawBuffer[index]); unsigned char green = TIFFGetG(pRawBuffer[index]); unsigned char blue = TIFFGetB(pRawBuffer[index]); pImageRow->r = red; pImageRow->g = green; pImageRow->b = blue; pImageRow++; index ++; } } _TIFFfree(pRawBuffer); } else { // if we're not 8-bit, it's highly likely the image is compressed, so // we need to read images as strips, as TIFFReadScanline() cannot read // compressed images. unsigned int stripSize = TIFFStripSize(pTiff); unsigned int numStrips = TIFFNumberOfStrips(pTiff); tdata_t pRawBuffer = _TIFFmalloc(stripSize); if (!pRawBuffer) { GlobalContext::instance().getLogger().error("Couldn't allocate memory to read file: %s", filePath.c_str()); if (pImage3f) { delete pImage3f; pImage3f = nullptr; } if (pImage3h) { delete pImage3h; pImage3h = nullptr; } TIFFClose(pTiff); return nullptr; } const float invShortConvert = 1.0f / 65536.0f; unsigned int targetY = 0; for (unsigned int strip = 0; strip < numStrips; strip++) { TIFFReadEncodedStrip(pTiff, strip, pRawBuffer, (tsize_t)-1); for (unsigned int tY = 0; tY < tiffInfo.rowsPerStrip; tY++) { if (tiffInfo.bitDepth == 16 && bitDepthToCreate == 32) { // TODO: there's got to be a better way to handle this... Return value of TIFFReadEncodedStrip()? if (targetY >= tiffInfo.imageHeight) break; const uint16* pUShortLine = (uint16*)pRawBuffer + (tY * tiffInfo.imageWidth * tiffInfo.channelCount); // reverse Y unsigned int actualY = tiffInfo.imageHeight - targetY - 1; Colour3f* pImageRow = pImage3f->colourRowPtr(actualY); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { uint16_t red = *pUShortLine++; uint16_t green = *pUShortLine++; uint16_t blue = *pUShortLine++; // TODO: LUT for ushort format pImageRow->r = (float)red * invShortConvert; pImageRow->g = (float)green * invShortConvert; pImageRow->b = (float)blue * invShortConvert; // convert to linear ColourSpace::convertSRGBToLinearAccurate(*pImageRow); pImageRow++; } } else if (tiffInfo.bitDepth == 16 && bitDepthToCreate == 16) { // TODO: there's got to be a better way to handle this... Return value of TIFFReadEncodedStrip()? if (targetY >= tiffInfo.imageHeight) break; const uint16_t* pUShortLine = (uint16*)pRawBuffer + (tY * tiffInfo.imageWidth * tiffInfo.channelCount); // reverse Y unsigned int actualY = tiffInfo.imageHeight - targetY - 1; Colour3h* pImageRow = pImage3h->colour3hRowPtr(actualY); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { uint16_t red = *pUShortLine++; uint16_t green = *pUShortLine++; uint16_t blue = *pUShortLine++; // TODO: LUT for ushort format pImageRow->r = (float)red * invShortConvert; pImageRow->g = (float)green * invShortConvert; pImageRow->b = (float)blue * invShortConvert; // convert to linear ColourSpace::convertSRGBToLinearAccurate(*pImageRow); pImageRow++; } } else { if (targetY >= tiffInfo.imageHeight) break; const float* pFloatLine = (float*)pRawBuffer + (tY * tiffInfo.imageWidth * tiffInfo.channelCount); // reverse Y unsigned int actualY = tiffInfo.imageHeight - targetY - 1; Colour3f* pImageRow = pImage3f->colourRowPtr(actualY); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { pImageRow->r = *pFloatLine++; pImageRow->g = *pFloatLine++; pImageRow->b = *pFloatLine++; pImageRow++; } } targetY += 1; } } _TIFFfree(pRawBuffer); } TIFFClose(pTiff); if (pImage3f) return pImage3f; if (pImage3h) return pImage3h; if (pImage3b) return pImage3b; return nullptr; } Image* ImageReaderTIFF::readTiledColourImage(const std::string& filePath, TIFF* pTiff, TiffInfo& tiffInfo, unsigned int requiredTypeFlags) { ImageColour3f* pImage3f = nullptr; ImageColour3h* pImage3h = nullptr; ImageColour3b* pImage3b = nullptr; unsigned int bitDepthToCreate = tiffInfo.bitDepth; if (!(requiredTypeFlags & Image::IMAGE_FORMAT_NATIVE)) { bitDepthToCreate = 32; } unsigned int dirOffset = 0; if (requiredTypeFlags & Image::IMAGE_CONSTRAINTS_MIPMAP_LEVEL_MINUS1) { dirOffset = 1; } else if (requiredTypeFlags & Image::IMAGE_CONSTRAINTS_MIPMAP_LEVEL_MINUS2) { dirOffset = 2; } if (dirOffset) { TIFFSetDirectory(pTiff, dirOffset); // read the info again to get the correct image dimensions readInfo(pTiff, tiffInfo); } if (bitDepthToCreate == 32) { pImage3f = new ImageColour3f(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } else if (bitDepthToCreate == 16) { pImage3h = new ImageColour3h(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } else if (bitDepthToCreate == 8) { pImage3b = new ImageColour3b(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } // if we didn't allocate any image, bail out if (!pImage3b && !pImage3h && !pImage3f) { GlobalContext::instance().getLogger().error("Couldn't allocate memory for new image for file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } // allocate memory to store a single tile unsigned int tileLineSize = (bitDepthToCreate / 8) * tiffInfo.tileWidth * tiffInfo.channelCount; unsigned int tileByteSize = tileLineSize * tiffInfo.tileHeight; unsigned char* pTileBuffer = new unsigned char[tileByteSize]; // work out how many tiles we've got in each direction unsigned int tileCountX = tiffInfo.imageWidth / tiffInfo.tileWidth; unsigned int tileCountY = tiffInfo.imageHeight / tiffInfo.tileHeight; // see if there are any remainders, meaning non-complete tiles... bool remainderX = false; bool remainderY = false; if (tiffInfo.imageWidth % tiffInfo.tileWidth > 0) { remainderX = true; tileCountX += 1; } if (tiffInfo.imageHeight % tiffInfo.tileHeight > 0) { remainderY = true; tileCountY += 1; } const float invShortConvert = 1.0f / 65536.0f; // we need to read each tile individually and copy it into the destination image - this is not going to be too efficient... // TODO: need to work out if tile order makes a difference - rows first or columns? for (unsigned int tileX = 0; tileX < tileCountX; tileX++) { unsigned int tilePosX = tileX * tiffInfo.tileWidth; unsigned int localTileWidth = tiffInfo.tileWidth; if (remainderX && tileX == (tileCountX - 1)) { localTileWidth = tiffInfo.imageWidth - ((tileCountX - 1) * tiffInfo.tileWidth); } for (unsigned int tileY = 0; tileY < tileCountY; tileY++) { unsigned int tilePosY = tileY * tiffInfo.tileHeight; TIFFReadTile(pTiff, pTileBuffer, tilePosX, tilePosY, 0, 0); unsigned int localTileHeight = tiffInfo.tileHeight; if (remainderY && tileY == (tileCountY - 1)) { localTileHeight = tiffInfo.imageHeight - ((tileCountY - 1) * tiffInfo.tileHeight); } unsigned int localYStartPos = tileY * tiffInfo.tileHeight; // now copy the data into our image in the correct position... if (bitDepthToCreate == 32) { // cast to the type the data should be... const Colour3f* pSrcTileBuffer = (Colour3f*)pTileBuffer; unsigned int localLineSizeBytes = (bitDepthToCreate / 8) * localTileWidth * tiffInfo.channelCount; for (unsigned int localY = 0; localY < localTileHeight; localY++) { // reverse Y unsigned int actualY = tiffInfo.imageHeight - (localYStartPos + localY + 1); Colour3f* pDst = pImage3f->colourRowPtr(actualY); // offset to X pos pDst += tilePosX; memcpy(pDst, pSrcTileBuffer, localLineSizeBytes); // because we're of the correct type, we should be able to just increment // by the tile width to get to the next line... pSrcTileBuffer += tiffInfo.tileWidth; } } else if (bitDepthToCreate == 16) { // cast to the type the data should be... const uint16_t* pSrcTileBuffer = (uint16_t*)pTileBuffer; for (unsigned int localY = 0; localY < localTileHeight; localY++) { // reverse Y unsigned int actualY = tiffInfo.imageHeight - (localYStartPos + localY + 1); Colour3h* pDst = pImage3h->colour3hRowPtr(actualY); // offset to X pos pDst += tilePosX; const uint16_t* pLocalSrcTileBuffer = pSrcTileBuffer + (localY * tiffInfo.tileWidth * 3); // need to use tileWidth here for (unsigned int localX = 0; localX < localTileWidth; localX++) { uint16_t red = *pLocalSrcTileBuffer++; uint16_t green = *pLocalSrcTileBuffer++; uint16_t blue = *pLocalSrcTileBuffer++; pDst->r = (float)red * invShortConvert; pDst->g = (float)green * invShortConvert; pDst->b = (float)blue * invShortConvert; // convert to linear ColourSpace::convertSRGBToLinearAccurate(*pDst++); } } } else if (bitDepthToCreate == 8) { // cast to the type the data should be... const uint8_t* pSrcTileBuffer = (uint8_t*)pTileBuffer; for (unsigned int localY = 0; localY < localTileHeight; localY++) { // reverse Y unsigned int actualY = tiffInfo.imageHeight - (localYStartPos + localY + 1); Colour3b* pDst = pImage3b->colour3bRowPtr(actualY); // offset to X pos pDst += tilePosX; const uint8_t* pLocalSrcTileBuffer = pSrcTileBuffer + (localY * tiffInfo.tileWidth * 3); // need to use tileWidth here for (unsigned int localX = 0; localX < localTileWidth; localX++) { uint8_t red = *pLocalSrcTileBuffer++; uint8_t green = *pLocalSrcTileBuffer++; uint8_t blue = *pLocalSrcTileBuffer++; pDst->r = red; pDst->g = green; pDst->b = blue; pDst++; } } } } } if (pTileBuffer) { delete [] pTileBuffer; pTileBuffer = nullptr; } TIFFClose(pTiff); if (pImage3f) return pImage3f; if (pImage3h) return pImage3h; if (pImage3b) return pImage3b; return nullptr; } Image* ImageReaderTIFF::readGreyscaleImage(const std::string& filePath, unsigned int requiredTypeFlags) { TIFF* pTiff = TIFFOpen(filePath.c_str(), "r"); if (!pTiff) { GlobalContext::instance().getLogger().error("Error reading file: %s", filePath.c_str()); return nullptr; } TiffInfo tiffInfo; if (!readInfo(pTiff, tiffInfo)) { GlobalContext::instance().getLogger().error("Invalid tiff file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (tiffInfo.bitDepth < 8) { GlobalContext::instance().getLogger().error("Unsupported TIFF format for file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (!tiffInfo.isTiled) { return readScanlineGreyscaleImage(filePath, pTiff, tiffInfo, requiredTypeFlags); } else { return readTiledGreyscaleImage(filePath, pTiff, tiffInfo, requiredTypeFlags); } } Image* ImageReaderTIFF::readScanlineGreyscaleImage(const std::string& filePath, TIFF* pTiff, TiffInfo& tiffInfo, unsigned int requiredTypeFlags) { Image1f* pImage1f = nullptr; Image1b* pImage1b = nullptr; bool makeFloat = tiffInfo.bitDepth >= 16 || !(requiredTypeFlags & Image::IMAGE_FORMAT_NATIVE); if (makeFloat) { pImage1f = new Image1f(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } else { pImage1b = new Image1b(tiffInfo.imageWidth, tiffInfo.imageHeight, false); } // if we didn't allocate any image, bail out if (!pImage1b && !pImage1f) { GlobalContext::instance().getLogger().error("Couldn't allocate memory for new image for file: %s", filePath.c_str()); TIFFClose(pTiff); return nullptr; } if (!makeFloat) { // allocate memory for image - do it the easy way for the moment - we can convert to scanline approach later... uint32_t totalImageSize = tiffInfo.imageHeight * tiffInfo.imageWidth; uint32_t* pRawBuffer = (uint32_t*)_TIFFmalloc(totalImageSize * sizeof(uint32_t)); // RGBA byte bool failed = false; if (!pRawBuffer) { GlobalContext::instance().getLogger().error("Couldn't allocate memory to read file: %s", filePath.c_str()); failed = true; } if (TIFFReadRGBAImage(pTiff, tiffInfo.imageWidth, tiffInfo.imageHeight, pRawBuffer, 0) == 0) { GlobalContext::instance().getLogger().error("Couldn't read image: %s", filePath.c_str()); failed = true; _TIFFfree(pRawBuffer); } if (failed) { if (pImage1b) { delete pImage1b; pImage1b = nullptr; } TIFFClose(pTiff); return nullptr; } unsigned int index = 0; if (requiredTypeFlags & Image::IMAGE_FLAGS_ALPHA) { for (unsigned int i = 0; i < tiffInfo.imageHeight; i++) { // for 8-bit, we don't seem to need to flip Y unsigned int y = i; unsigned char* pUCharRow = pImage1b->uCharRowPtr(y); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { unsigned char alpha; if (tiffInfo.channelCount == 1 || tiffInfo.channelCount == 3) { // it's actually the red channel alpha = TIFFGetR(pRawBuffer[index]); } else { alpha = TIFFGetA(pRawBuffer[index]); } *pUCharRow = alpha; pUCharRow++; index ++; } } } else if (requiredTypeFlags & Image::IMAGE_FLAGS_BRIGHTNESS) { for (unsigned int i = 0; i < tiffInfo.imageHeight; i++) { // for 8-bit, we don't seem to need to flip Y unsigned int y = i; unsigned char* pUCharRow = pImage1b->uCharRowPtr(y); for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { unsigned char red = TIFFGetR(pRawBuffer[index]); unsigned char green = TIFFGetG(pRawBuffer[index]); unsigned char blue = TIFFGetB(pRawBuffer[index]); Colour3b finalColour(red, green, blue); *pUCharRow = finalColour.brightness(); pUCharRow++; index ++; } } } else { // exact for (unsigned int i = 0; i < tiffInfo.imageHeight; i++) { // for 8-bit, we don't seem to need to flip Y unsigned int y = i; unsigned char* pUCharRow = pImage1b->uCharRowPtr(y); if (tiffInfo.channelCount == 1) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { unsigned char red = TIFFGetR(pRawBuffer[index]); *pUCharRow = red; pUCharRow++; index ++; } } else { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { unsigned char red = TIFFGetR(pRawBuffer[index]); unsigned char green = TIFFGetG(pRawBuffer[index]); unsigned char blue = TIFFGetB(pRawBuffer[index]); float average = (float)red + (float)green + (float)blue; average *= 0.3333333333f; *pUCharRow = (unsigned char)average; pUCharRow++; index ++; } } } } _TIFFfree(pRawBuffer); } else { // if we're not 8-bit, it's highly likely the image is compressed, so // we need to read images as strips, as TIFFReadScanline() cannot read // compressed images. unsigned int stripSize = TIFFStripSize(pTiff); unsigned int numStrips = TIFFNumberOfStrips(pTiff); tdata_t pRawBuffer = _TIFFmalloc(stripSize); if (!pRawBuffer) { GlobalContext::instance().getLogger().error("Couldn't allocate memory to read file: %s", filePath.c_str()); if (pImage1f) { delete pImage1f; pImage1f = nullptr; } TIFFClose(pTiff); return nullptr; } const float invShortConvert = 1.0f / 65536.0f; unsigned int targetY = 0; for (unsigned int strip = 0; strip < numStrips; strip++) { TIFFReadEncodedStrip(pTiff, strip, pRawBuffer, (tsize_t)-1); for (unsigned int tY = 0; tY < tiffInfo.rowsPerStrip; tY++) { if (tiffInfo.bitDepth == 16) { // TODO: there's got to be a better way to handle this... Return value of TIFFReadEncodedStrip()? if (targetY >= tiffInfo.imageHeight) break; const uint16* pUShortLine = (uint16*)pRawBuffer + (tY * tiffInfo.imageWidth * tiffInfo.channelCount); // flip Y unsigned int actualY = tiffInfo.imageHeight - targetY - 1; float* pFloatRow = pImage1f->floatRowPtr(actualY); if (requiredTypeFlags & Image::IMAGE_FLAGS_ALPHA) { uint16_t alpha = 0; if (tiffInfo.channelCount == 1) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { alpha = *pUShortLine++; *pFloatRow++ = (float)alpha * invShortConvert; } } else if (tiffInfo.channelCount == 3) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { // get red one alpha = *pUShortLine++; pUShortLine++; pUShortLine++; *pFloatRow++ = (float)alpha * invShortConvert; } } else { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { // ignore first 3 pUShortLine++; pUShortLine++; pUShortLine++; alpha = *pUShortLine++; *pFloatRow++ = (float)alpha * invShortConvert; } } } else if (requiredTypeFlags & Image::IMAGE_FLAGS_BRIGHTNESS) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { float brightness = 0.0f; if (tiffInfo.channelCount == 1) { uint16_t rawValue = *pUShortLine++; brightness = (float)rawValue * invShortConvert; } else { uint16_t red = *pUShortLine++; uint16_t green = *pUShortLine++; uint16_t blue = *pUShortLine++; float fRed = (float)red * invShortConvert; float fGreen = (float)green * invShortConvert; float fBlue = (float)blue * invShortConvert; Colour3f colour(fRed, fGreen, fBlue); brightness = colour.brightness(); } *pFloatRow++ = brightness; } } else { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { // exact copy - assume 1 channel for the moment float value = 0.0f; if (tiffInfo.channelCount == 1) { uint16_t rawValue = *pUShortLine++; value = (float)rawValue * invShortConvert; } *pFloatRow++ = value; } } pFloatRow++; } else { // must be float if (targetY >= tiffInfo.imageHeight) break; const float* pFloatLine = (float*)pRawBuffer + (tY * tiffInfo.imageWidth * tiffInfo.channelCount); // flip Y unsigned int actualY = tiffInfo.imageHeight - targetY - 1; float* pFloatRow = pImage1f->floatRowPtr(actualY); if (tiffInfo.channelCount == 1) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { *pFloatRow = *pFloatLine++; pFloatRow++; } } else if (tiffInfo.channelCount == 3) { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { *pFloatRow = *pFloatLine++; pFloatLine++; pFloatLine++; } } else { for (unsigned int x = 0; x < tiffInfo.imageWidth; x++) { *pFloatRow = *pFloatLine++; pFloatLine++; pFloatLine++; pFloatRow++; } } } targetY += 1; } } _TIFFfree(pRawBuffer); } TIFFClose(pTiff); Image* pFinalImage = (makeFloat) ? static_cast(pImage1f) : static_cast(pImage1b); return pFinalImage; } Image* ImageReaderTIFF::readTiledGreyscaleImage(const std::string& filePath, TIFF* pTiff, TiffInfo& tiffInfo, unsigned int requiredTypeFlags) { return nullptr; } bool ImageReaderTIFF::readImageDetails(const std::string& filePath, ImageTextureDetails& textureDetails) const { TIFF* pTiff = TIFFOpen(filePath.c_str(), "r"); if (!pTiff) { GlobalContext::instance().getLogger().error("Error reading file: %s", filePath.c_str()); return false; } TiffInfo info; if (!readInfo(pTiff, info) || !info.isTiled) { TIFFClose(pTiff); return false; } textureDetails.setFullWidth(info.imageWidth); textureDetails.setFullHeight(info.imageHeight); if (info.separatePlanes) { TiffCustomData* pCustData = new TiffCustomData(); pCustData->separatePlanes = true; textureDetails.setCustomData(pCustData); } // TODO: technically, in TIFF all the below stuff can be completely different per subimage, so it's possible // there's a complete miss-match and this won't work... textureDetails.setChannelCount(info.channelCount); ImageTextureDetails::ImageDataType dataType = ImageTextureDetails::eUnknown; if (info.bitDepth == 8) { dataType = ImageTextureDetails::eUInt8; } else if (info.bitDepth == 16) { dataType = ImageTextureDetails::eUInt16; } else if (info.bitDepth == 32) { dataType = ImageTextureDetails::eFloat; } textureDetails.setDataType(dataType); textureDetails.setIsTiled(true); textureDetails.setMipmapped(true); // we're not going to support all the modes, just check for flip of Y... if (info.orientation == 1 || info.orientation == 2) { textureDetails.setFlipY(true); } std::vector& mipmaps = textureDetails.getMipmaps(); unsigned int imageWidth = info.imageWidth; unsigned int imageHeight = info.imageHeight; unsigned int tileWidth = info.tileWidth; unsigned int tileHeight = info.tileHeight; bool wasOkay = true; int mipmapLevel = 0; while (imageWidth > 1 || imageHeight > 1) { ImageTextureItemDetails mipmapDetails(imageWidth, imageHeight, tileWidth, tileHeight); mipmaps.emplace_back(mipmapDetails); mipmapLevel += 1; if (TIFFSetDirectory(pTiff, mipmapLevel) == 0) { // we don't seem to have this, so exit out... break; } // check the subimages have roughly the same data type uint16_t bitDepth; uint16_t channelCount; TIFFGetField(pTiff, TIFFTAG_BITSPERSAMPLE, &bitDepth); TIFFGetField(pTiff, TIFFTAG_SAMPLESPERPIXEL, &channelCount); // if not, exit out if (bitDepth != info.bitDepth || channelCount != info.channelCount) { GlobalContext::instance().getLogger().error("Error reading file - image subimage mismatch for file: %s", filePath.c_str()); wasOkay = false; break; } // now get the next info for the next level TIFFGetField(pTiff, TIFFTAG_IMAGELENGTH, &imageHeight); TIFFGetField(pTiff, TIFFTAG_IMAGEWIDTH, &imageWidth); TIFFGetField(pTiff, TIFFTAG_TILEWIDTH, &tileWidth); TIFFGetField(pTiff, TIFFTAG_TILELENGTH, &tileHeight); } TIFFClose(pTiff); return wasOkay; } bool ImageReaderTIFF::readImageTile(const ImageTextureTileReadParams& readParams, ImageTextureTileReadResults& readResults) const { const ImageTextureDetails& textureDetails = readParams.getImageDetails(); if (readParams.wantStats()) { readResults.getFileOpenTimer().start(); } TIFF* pTiff = TIFFOpen(textureDetails.getFilePath().c_str(), "r"); if (!pTiff) { if (readParams.wantStats()) { readResults.getFileOpenTimer().stop(); } return false; } if (readParams.wantStats()) { readResults.getFileOpenTimer().stop(); } readResults.setFileOpenedThisRequest(); const ImageTextureItemDetails& mipmapInfo = textureDetails.getMipmaps()[readParams.mipmapLevel]; unsigned int tileWidth = mipmapInfo.getTileWidth(); unsigned int tileHeight = mipmapInfo.getTileHeight(); if (readParams.wantStats()) { readResults.getFileSeekTimer().start(); } // set mipmap level - this is expensive over NFS as it does a stat() internally... TIFFSetDirectory(pTiff, readParams.mipmapLevel); if (readParams.wantStats()) { readResults.getFileSeekTimer().stop(); } // work out the tile coords in image space - TIFF needs them as opposed to actual tile indices unsigned int tilePosX = readParams.tileX * tileWidth; unsigned int tilePosY = readParams.tileY * tileHeight; // should be okay with this, but MSVC used to be fussy about static_casting nullptr pointers... // seems to work on Linux/Mac anyway... const TiffCustomData* pCustData = static_cast(textureDetails.getCustomData()); // not great, but... if (readParams.wantStats()) { readResults.getFileReadTimer().start(); } if (pCustData && pCustData->separatePlanes) { // each channel is stored in separate planar planes in the image, so we can't just pull it out, we need to read each // plane seperately, then reorder into the destination buffer // TODO: ideally, we should expose some beeter stuff in ImageTextureDetails to do this... size_t tileSize = tileWidth * tileHeight * readParams.pixelSize; size_t tilePlaneSize = tileSize / textureDetails.getChannelCount(); size_t singleChannelPixelByte = readParams.pixelSize / textureDetails.getChannelCount(); unsigned char* pTempData = new unsigned char[tileSize]; if (!pTempData) { if (readParams.wantStats()) { readResults.getFileReadTimer().stop(); } TIFFClose(pTiff); return false; } // read each plane in separately into the temp buffer unsigned char* pTilePlaneData = pTempData; for (unsigned int i = 0; i < textureDetails.getChannelCount(); i++) { TIFFReadTile(pTiff, pTilePlaneData, tilePosX, tilePosY, 0, i); pTilePlaneData += tilePlaneSize; } unsigned char* __restrict pDst = readParams.pData; unsigned char* __restrict pSrc = pTempData; // now re-order the pixels in interleaved fashion // we're probably going to thrash the caches anyway, regardless of the order we do this... for (unsigned int y = 0; y < tileHeight; y++) { for (unsigned int x = 0; x < tileWidth; x++) { for (unsigned int c = 0; c < textureDetails.getChannelCount(); c++) { // we could cache some of this above in the individual loops... pSrc = pTempData + (tilePlaneSize * c) + (y * tileWidth * singleChannelPixelByte) + (x * singleChannelPixelByte); memcpy(pDst, pSrc, singleChannelPixelByte); pDst += singleChannelPixelByte; } } } if (pTempData) { delete [] pTempData; pTempData = nullptr; } } else { TIFFReadTile(pTiff, readParams.pData, tilePosX, tilePosY, 0, 0); } if (readParams.wantStats()) { readResults.getFileReadTimer().stop(); } TIFFClose(pTiff); return true; } } // namespace Imagine namespace { Imagine::ImageReader* createImageReaderTIFF() { return new ImageReaderTIFF(); } const bool registered = Imagine::FileIORegistry::instance().registerImageReaderMultipleExtensions("tif;tiff;tex;tx", createImageReaderTIFF, true); } #ifndef _GROUNG_RANSAC_SEGMENTER_HPP_ #define _GROUNG_RANSAC_SEGMENTER_HPP_ #include "./base_segmenter.hpp" #include /* pcl::SACSegmentation */ #include "common/types/type.h" using namespace autosense; namespace segmenter { class GroundRANSACSegmenter : public BaseSegmenter { public: GroundRANSACSegmenter(); explicit GroundRANSACSegmenter(const SegmenterParams& params); ~GroundRANSACSegmenter(); /// \brief Segment the point cloud. virtual void segment(const PointICloud& cloud_in, std::vector* cloud_clusters); virtual std::string name() const { return "GroundRANSACSegmenter"; } private: SegmenterParams params_; pcl::SACSegmentation sac_estimator_; }; /* class GroundRANSACSegmenter */ } // namespace segmenter #endif /* _GROUNG_RANSAC_SEGMENTER_HPP_ */ // PDI - RLE compressed DOS disk images. #include "SAMdisk.h" #include "types.h" struct PDI_HEADER { char sig[9]; // "PDITYPEx\0" char idata[5]; // "IDATA" uint8_t unknown[4]; // checksum perhaps? uint8_t unknown2; // zero char maindata[8]; // "MAINDATA" }; bool ReadPDI(MemFile& file, std::shared_ptr& disk) { PDI_HEADER ph{}; if (!file.rewind() || !file.read(&ph, sizeof(ph))) return false; else if (std::string(ph.sig, 7) != "PDITYPE") return false; if (ph.sig[7] != '1') throw util::exception("PDI version ", ph.sig[7], " files are not supported"); else if (std::string(ph.maindata, 8) != "MAINDATA") throw util::exception("missing main data header"); Data data; data.reserve(Format(RegularFormat::PC1440).disk_size()); int last_b = -1, last_last_b = -1; uint8_t b; while (file.read(b)) { data.push_back(b); if (b == last_b && last_b == last_last_b) { uint8_t count; if (!file.read(count)) throw util::exception("EOF in byte repeat count"); for (int i = 0; i < count; ++i) data.push_back(b); last_b = last_last_b = -1; continue; } last_last_b = last_b; last_b = b; } Data end_marker{ 0, 'E', 'N', 'D', 0 }; if (data.size() >= end_marker.size() && Data(data.end() - end_marker.size(), data.end()) == end_marker) data.resize(data.size() - end_marker.size()); Format fmt{}; if (!Format::FromSize(data.size(), fmt)) throw util::exception("unrecognised uncompressed size (", data.size(), ")"); disk->format(fmt, data); disk->strType = "PDI"; return true; } #pragma once #include "base/assert.hpp" #include "base/base.hpp" namespace my { namespace impl { // http://rsdn.ru/Forum/?mid=1025325 template char(&ArraySize(T(&)[N]))[N]; } } // Number of elements in array. Compilation error if the type passed is not an array. #define ARRAY_SIZE(X) sizeof(::my::impl::ArraySize(X)) #define DISALLOW_COPY(className) \ private: \ className(className const &) = delete; \ className & operator=(className const &) = delete #define DISALLOW_MOVE(className) \ private: \ className(className &&) = delete; \ className & operator=(className &&) = delete #define DISALLOW_COPY_AND_MOVE(className) \ DISALLOW_COPY(className); \ DISALLOW_MOVE(className) ///////////////////////////////////////////////////////////// #define TO_STRING_IMPL(x) #x #define TO_STRING(x) TO_STRING_IMPL(x) #define UNUSED_VALUE(x) static_cast(x) namespace my { namespace impl { template inline void ForceUseValue(T const & t) { volatile T dummy = t; UNUSED_VALUE(dummy); } } } // Prevent compiler optimization. #define FORCE_USE_VALUE(x) ::my::impl::ForceUseValue(x) #ifdef __GNUC__ #define PREDICT(x, prediction) __builtin_expect(x, prediction) #define PREDICT_TRUE(x) __builtin_expect((x) != 0, 1) #define PREDICT_FALSE(x) __builtin_expect((x) != 0, 0) #else #define PREDICT(x, prediction) (x) #define PREDICT_TRUE(x) (x) #define PREDICT_FALSE(x) (x) #endif #define UINT16_FROM_UINT8(hi, lo) ((static_cast(hi) << 8) | lo) #define UINT32_FROM_UINT16(hi, lo) ((static_cast(hi) << 16) | lo) #define UINT64_FROM_UINT32(hi, lo) ((static_cast(hi) << 32) | lo) #define UINT32_FROM_UINT8(u3, u2, u1, u0) \ UINT32_FROM_UINT16(UINT16_FROM_UINT8(u3, u2), UINT16_FROM_UINT8(u1, u0)) #define UINT64_FROM_UINT8(u7, u6, u5, u4, u3, u2, u1, u0) \ UINT64_FROM_UINT32(UINT32_FROM_UINT8(u7, u6, u5, u4), UINT32_FROM_UINT8(u3, u2, u1, u0)) #define UINT16_LO(x) (static_cast(x & 0xFF)) #define UINT16_HI(x) (static_cast(x >> 8)) #define UINT32_LO(x) (static_cast(x & 0xFFFF)) #define UINT32_HI(x) (static_cast(x >> 16)) #define UINT64_LO(x) (static_cast(x & 0xFFFFFFFF)) #define UINT64_HI(x) (static_cast(x >> 32)) #define NOTIMPLEMENTED() ASSERT(false, ("Function", __func__, "is not implemented!")); #if defined(__GNUC__) #define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else #define WARN_UNUSED_RESULT #endif // defined(__GNUC__) // Copyright 2016 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 #include #include const size_t kInitialPrintfBufferSize = 100; namespace google_smart_card { std::string FormatPrintfTemplate(const char* format, ...) { va_list var_args; va_start(var_args, format); const std::string result = FormatPrintfTemplate(format, var_args); va_end(var_args); return result; } std::string FormatPrintfTemplate(const char* format, va_list var_args) { std::vector buffer(kInitialPrintfBufferSize); for (;;) { va_list var_args_copy; va_copy(var_args_copy, var_args); const int result = std::vsnprintf( &buffer[0], buffer.size(), format, var_args_copy); va_end(var_args_copy); if (0 <= result && result < static_cast(buffer.size())) return std::string(buffer.begin(), buffer.begin() + result); const size_t new_size = result > 0 ? result + 1 : buffer.size() * 2; buffer.resize(new_size); } } } // namespace google_smart_card // Fill out your copyright notice in the Description page of Project Settings. #include "FootSyncMarkersTest.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, FootSyncMarkersTest, "FootSyncMarkersTest" ); 1-10 ///////////////////////////////////////////////////////////////////////////// // Name: wxjsontest.cpp // Purpose: Json using wxWidgets // Author: // Created: 25/03/2020 ///////////////////////////////////////////////////////////////////////////// #include "wx/wx.h" #include "wx/json_defs.h" #include "wx/jsonreader.h" #include "wx/jsonval.h" #include "wx/jsonwriter.h" class MyApp : public wxApp { public: virtual bool OnInit(); }; class MyFrame : public wxFrame { public: MyFrame(const wxString& title); void OnQuit(wxCommandEvent& event); wxString ReadJson(); wxTextCtrl *txt; private: wxDECLARE_EVENT_TABLE(); }; enum { Minimal_Quit = wxID_EXIT }; wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(Minimal_Quit, MyFrame::OnQuit) wxEND_EVENT_TABLE() IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; MyFrame *frame = new MyFrame("wxJson"); frame->Show(true); return true; } MyFrame::MyFrame(const wxString& title) : wxFrame(NULL, wxID_ANY, title) { wxMenu *fileMenu = new wxMenu; fileMenu->Append(Minimal_Quit, "E&xit\tAlt-X", "Quit this program"); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(fileMenu, "&File"); SetMenuBar(menuBar); wxString jresult = ReadJson(); txt = new wxTextCtrl(this,wxID_ANY, jresult, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_RICH , wxDefaultValidator, wxTextCtrlNameStr); } void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { Close(true); } wxString MyFrame::ReadJson() { // the JSON text, stored in a wxString object wxString document(("{\"Serial\" : {\"Baud\":9600, \"Parity\":\"Even\"}}")); wxString mes; // construct the JSON root object wxJSONValue root; // construct a JSON parser wxJSONReader reader; // now read the JSON text and store it in the 'root' structure // check for errors before retreiving values... int numErrors = reader.Parse(document, &root); if (numErrors > 0) { mes = "ERROR: the JSON document is not well-formed"; // const wxArrayString& errors = reader.GetErrors(); return mes; } else { mes = "OK: Reading the JSON document... \n"; } // get the values wxString v1 = root["Serial"]["Baud"].AsString(); wxString v2 = root["Serial"]["Parity"].AsString(); mes += "Serial: baudrate = "+ v1 + ", parity = " + v2; return mes; } //---------------------------------------------------------------------------// // Copyright (c) 2018-2021 <> // // MIT 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. //---------------------------------------------------------------------------// #pragma once #include #include #include #include #include namespace nil { namespace actor { /// A growable double-ended queue container that can be efficiently /// extended (and shrunk) from both ends. Implementation is a single /// storage vector. /// /// Similar to libstdc++'s std::deque, except that it uses a single /// level store, and so is more efficient for simple stored items. /// Similar to boost::circular_buffer_space_optimized, except it uses /// uninitialized storage for unoccupied elements (and thus move/copy /// constructors instead of move/copy assignments, which are less /// efficient). /// /// The storage of the circular_buffer is expanded automatically in /// exponential increments. /// When adding new elements: /// * if size + 1 > capacity: all iterators and references are /// invalidated, /// * otherwise only the begin() or end() iterator is invalidated: /// * push_front() and emplace_front() will invalidate begin() and /// * push_back() and emplace_back() will invalidate end(). /// /// Removing elements never invalidates any references and only /// invalidates begin() or end() iterators: /// * pop_front() will invalidate begin() and /// * pop_back() will invalidate end(). /// /// reserve() may also invalidate all iterators and references. template> class circular_buffer { struct impl : Alloc { T *storage = nullptr; // begin, end interpreted (mod capacity) size_t begin = 0; size_t end = 0; size_t capacity = 0; impl(Alloc a) noexcept : Alloc(std::move(a)) { } void reset() { storage = {}; begin = 0; end = 0; capacity = 0; } }; static_assert(!std::is_default_constructible_v || std::is_nothrow_default_constructible_v); static_assert(std::is_nothrow_move_constructible_v); impl _impl; public: using value_type = T; using size_type = size_t; using reference = T &; using pointer = T *; using const_reference = const T &; using const_pointer = const T *; public: #ifdef BOOST_HAS_CONCEPTS circular_buffer() noexcept requires std::default_initializable : circular_buffer(Alloc()) { } #else circular_buffer() noexcept : circular_buffer(Alloc()) { } #endif circular_buffer(Alloc alloc) noexcept; circular_buffer(circular_buffer &&X) noexcept; circular_buffer(const circular_buffer &X) = delete; ~circular_buffer(); circular_buffer &operator=(const circular_buffer &) = delete; circular_buffer &operator=(circular_buffer &&b) noexcept; void push_front(const T &data); void push_front(T &&data); template void emplace_front(A &&...args); void push_back(const T &data); void push_back(T &&data); template void emplace_back(A &&...args); T &front() noexcept; const T &front() const noexcept; T &back() noexcept; const T &back() const noexcept; void pop_front() noexcept; void pop_back() noexcept; bool empty() const; size_t size() const; size_t capacity() const; void reserve(size_t); void clear(); T &operator[](size_t idx) noexcept; const T &operator[](size_t idx) const noexcept; template void for_each(Func func); // access an element, may return wrong or destroyed element // only useful if you do not rely on data accuracy (e.g. prefetch) T &access_element_unsafe(size_t idx) noexcept; private: void expand(); void expand(size_t); void maybe_expand(size_t nr = 1); size_t mask(size_t idx) const; template struct cbiterator : std::iterator { typedef std::iterator super_t; ValueType &operator*() const noexcept { return cb->_impl.storage[cb->mask(idx)]; } ValueType *operator->() const noexcept { return &cb->_impl.storage[cb->mask(idx)]; } // prefix cbiterator &operator++() noexcept { idx++; return *this; } // postfix cbiterator operator++(int unused) noexcept { auto v = *this; idx++; return v; } // prefix cbiterator &operator--() noexcept { idx--; return *this; } // postfix cbiterator operator--(int unused) noexcept { auto v = *this; idx--; return v; } cbiterator operator+(typename super_t::difference_type n) const noexcept { return cbiterator(cb, idx + n); } cbiterator operator-(typename super_t::difference_type n) const noexcept { return cbiterator(cb, idx - n); } cbiterator &operator+=(typename super_t::difference_type n) noexcept { idx += n; return *this; } cbiterator &operator-=(typename super_t::difference_type n) noexcept { idx -= n; return *this; } bool operator==(const cbiterator &rhs) const noexcept { return idx == rhs.idx; } bool operator!=(const cbiterator &rhs) const noexcept { return idx != rhs.idx; } bool operator<(const cbiterator &rhs) const noexcept { return idx < rhs.idx; } bool operator>(const cbiterator &rhs) const noexcept { return idx > rhs.idx; } bool operator>=(const cbiterator &rhs) const noexcept { return idx >= rhs.idx; } bool operator<=(const cbiterator &rhs) const noexcept { return idx <= rhs.idx; } typename super_t::difference_type operator-(const cbiterator &rhs) const noexcept { return idx - rhs.idx; } private: CB *cb; size_t idx; cbiterator(CB *b, size_t i) noexcept : cb(b), idx(i) { } friend class circular_buffer; }; friend class iterator; public: typedef cbiterator iterator; typedef cbiterator const_iterator; iterator begin() noexcept { return iterator(this, _impl.begin); } const_iterator begin() const noexcept { return const_iterator(this, _impl.begin); } iterator end() noexcept { return iterator(this, _impl.end); } const_iterator end() const noexcept { return const_iterator(this, _impl.end); } const_iterator cbegin() const noexcept { return const_iterator(this, _impl.begin); } const_iterator cend() const noexcept { return const_iterator(this, _impl.end); } iterator erase(iterator first, iterator last) noexcept; }; template inline size_t circular_buffer::mask(size_t idx) const { return idx & (_impl.capacity - 1); } template inline bool circular_buffer::empty() const { return _impl.begin == _impl.end; } template inline size_t circular_buffer::size() const { return _impl.end - _impl.begin; } template inline size_t circular_buffer::capacity() const { return _impl.capacity; } template inline void circular_buffer::reserve(size_t size) { if (capacity() < size) { // Make sure that the new capacity is a power of two. expand(size_t(1) << log2ceil(size)); } } template inline void circular_buffer::clear() { erase(begin(), end()); } template inline circular_buffer::circular_buffer(Alloc alloc) noexcept : _impl(std::move(alloc)) { } template inline circular_buffer::circular_buffer(circular_buffer &&x) noexcept : _impl(std::move(x._impl)) { x._impl.reset(); } template inline circular_buffer &circular_buffer::operator=(circular_buffer &&x) noexcept { if (this != &x) { this->~circular_buffer(); new (this) circular_buffer(std::move(x)); } return *this; } template template inline void circular_buffer::for_each(Func func) { auto s = _impl.storage; auto m = _impl.capacity - 1; for (auto i = _impl.begin; i != _impl.end; ++i) { func(s[i & m]); } } template inline circular_buffer::~circular_buffer() { for_each([this](T &obj) { std::allocator_traits::destroy(_impl, &obj); }); _impl.deallocate(_impl.storage, _impl.capacity); } template void circular_buffer::expand() { expand(std::max(_impl.capacity * 2, 1)); } template void circular_buffer::expand(size_t new_cap) { auto new_storage = _impl.allocate(new_cap); auto p = new_storage; try { for_each([this, &p](T &obj) { transfer_pass1(_impl, &obj, p); p++; }); } catch (...) { while (p != new_storage) { std::allocator_traits::destroy(_impl, --p); } _impl.deallocate(new_storage, new_cap); throw; } p = new_storage; for_each([this, &p](T &obj) { transfer_pass2(_impl, &obj, p++); }); std::swap(_impl.storage, new_storage); std::swap(_impl.capacity, new_cap); _impl.begin = 0; _impl.end = p - _impl.storage; _impl.deallocate(new_storage, new_cap); } template inline void circular_buffer::maybe_expand(size_t nr) { if (_impl.end - _impl.begin + nr > _impl.capacity) { expand(); } } template inline void circular_buffer::push_front(const T &data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; std::allocator_traits::construct(_impl, p, data); --_impl.begin; } template inline void circular_buffer::push_front(T &&data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; std::allocator_traits::construct(_impl, p, std::move(data)); --_impl.begin; } template template inline void circular_buffer::emplace_front(Args &&...args) { maybe_expand(); auto p = &_impl.storage[mask(_impl.begin - 1)]; std::allocator_traits::construct(_impl, p, std::forward(args)...); --_impl.begin; } template inline void circular_buffer::push_back(const T &data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; std::allocator_traits::construct(_impl, p, data); ++_impl.end; } template inline void circular_buffer::push_back(T &&data) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; std::allocator_traits::construct(_impl, p, std::move(data)); ++_impl.end; } template template inline void circular_buffer::emplace_back(Args &&...args) { maybe_expand(); auto p = &_impl.storage[mask(_impl.end)]; std::allocator_traits::construct(_impl, p, std::forward(args)...); ++_impl.end; } template inline T &circular_buffer::front() noexcept { return _impl.storage[mask(_impl.begin)]; } template inline const T &circular_buffer::front() const noexcept { return _impl.storage[mask(_impl.begin)]; } template inline T &circular_buffer::back() noexcept { return _impl.storage[mask(_impl.end - 1)]; } template inline const T &circular_buffer::back() const noexcept { return _impl.storage[mask(_impl.end - 1)]; } template inline void circular_buffer::pop_front() noexcept { std::allocator_traits::destroy(_impl, &front()); ++_impl.begin; } template inline void circular_buffer::pop_back() noexcept { std::allocator_traits::destroy(_impl, &back()); --_impl.end; } template inline T &circular_buffer::operator[](size_t idx) noexcept { return _impl.storage[mask(_impl.begin + idx)]; } template inline const T &circular_buffer::operator[](size_t idx) const noexcept { return _impl.storage[mask(_impl.begin + idx)]; } template inline T &circular_buffer::access_element_unsafe(size_t idx) noexcept { return _impl.storage[mask(_impl.begin + idx)]; } template inline typename circular_buffer::iterator circular_buffer::erase(iterator first, iterator last) noexcept { static_assert(std::is_nothrow_move_assignable::value, "erase() assumes move assignment does not throw"); if (first == last) { return last; } // Move to the left or right depending on which would result in least amount of moves. // This also guarantees that iterators will be stable when removing from either front or back. if (std::distance(begin(), first) < std::distance(last, end())) { auto new_start = std::move_backward(begin(), first, last); auto i = begin(); while (i < new_start) { std::allocator_traits::destroy(_impl, &*i++); } _impl.begin = new_start.idx; return last; } else { auto new_end = std::move(last, end(), first); auto i = new_end; auto e = end(); while (i < e) { std::allocator_traits::destroy(_impl, &*i++); } _impl.end = new_end.idx; return first; } } } // namespace actor } // namespace nil #include "../content/Context.hpp" #include "../view/View.hpp" #include "../view/ViewGroup.hpp" #include "./Filter.hpp" #include "../../JString.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "./CursorTreeAdapter.hpp" namespace android::widget { // Fields // QJniObject forward CursorTreeAdapter::CursorTreeAdapter(QJniObject obj) : android::widget::BaseExpandableListAdapter(obj) {} // Constructors CursorTreeAdapter::CursorTreeAdapter(JObject arg0, android::content::Context arg1) : android::widget::BaseExpandableListAdapter( "android.widget.CursorTreeAdapter", "(Landroid/database/Cursor;Landroid/content/Context;)V", arg0.object(), arg1.object() ) {} CursorTreeAdapter::CursorTreeAdapter(JObject arg0, android::content::Context arg1, jboolean arg2) : android::widget::BaseExpandableListAdapter( "android.widget.CursorTreeAdapter", "(Landroid/database/Cursor;Landroid/content/Context;Z)V", arg0.object(), arg1.object(), arg2 ) {} // Methods void CursorTreeAdapter::changeCursor(JObject arg0) const { callMethod( "changeCursor", "(Landroid/database/Cursor;)V", arg0.object() ); } JString CursorTreeAdapter::convertToString(JObject arg0) const { return callObjectMethod( "convertToString", "(Landroid/database/Cursor;)Ljava/lang/String;", arg0.object() ); } JObject CursorTreeAdapter::getChild(jint arg0, jint arg1) const { return callObjectMethod( "getChild", "(II)Landroid/database/Cursor;", arg0, arg1 ); } jlong CursorTreeAdapter::getChildId(jint arg0, jint arg1) const { return callMethod( "getChildId", "(II)J", arg0, arg1 ); } android::view::View CursorTreeAdapter::getChildView(jint arg0, jint arg1, jboolean arg2, android::view::View arg3, android::view::ViewGroup arg4) const { return callObjectMethod( "getChildView", "(IIZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1, arg2, arg3.object(), arg4.object() ); } jint CursorTreeAdapter::getChildrenCount(jint arg0) const { return callMethod( "getChildrenCount", "(I)I", arg0 ); } JObject CursorTreeAdapter::getCursor() const { return callObjectMethod( "getCursor", "()Landroid/database/Cursor;" ); } android::widget::Filter CursorTreeAdapter::getFilter() const { return callObjectMethod( "getFilter", "()Landroid/widget/Filter;" ); } JObject CursorTreeAdapter::getFilterQueryProvider() const { return callObjectMethod( "getFilterQueryProvider", "()Landroid/widget/FilterQueryProvider;" ); } JObject CursorTreeAdapter::getGroup(jint arg0) const { return callObjectMethod( "getGroup", "(I)Landroid/database/Cursor;", arg0 ); } jint CursorTreeAdapter::getGroupCount() const { return callMethod( "getGroupCount", "()I" ); } jlong CursorTreeAdapter::getGroupId(jint arg0) const { return callMethod( "getGroupId", "(I)J", arg0 ); } android::view::View CursorTreeAdapter::getGroupView(jint arg0, jboolean arg1, android::view::View arg2, android::view::ViewGroup arg3) const { return callObjectMethod( "getGroupView", "(IZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1, arg2.object(), arg3.object() ); } jboolean CursorTreeAdapter::hasStableIds() const { return callMethod( "hasStableIds", "()Z" ); } jboolean CursorTreeAdapter::isChildSelectable(jint arg0, jint arg1) const { return callMethod( "isChildSelectable", "(II)Z", arg0, arg1 ); } void CursorTreeAdapter::notifyDataSetChanged() const { callMethod( "notifyDataSetChanged", "()V" ); } void CursorTreeAdapter::notifyDataSetChanged(jboolean arg0) const { callMethod( "notifyDataSetChanged", "(Z)V", arg0 ); } void CursorTreeAdapter::notifyDataSetInvalidated() const { callMethod( "notifyDataSetInvalidated", "()V" ); } void CursorTreeAdapter::onGroupCollapsed(jint arg0) const { callMethod( "onGroupCollapsed", "(I)V", arg0 ); } JObject CursorTreeAdapter::runQueryOnBackgroundThread(JString arg0) const { return callObjectMethod( "runQueryOnBackgroundThread", "(Ljava/lang/CharSequence;)Landroid/database/Cursor;", arg0.object() ); } void CursorTreeAdapter::setChildrenCursor(jint arg0, JObject arg1) const { callMethod( "setChildrenCursor", "(ILandroid/database/Cursor;)V", arg0, arg1.object() ); } void CursorTreeAdapter::setFilterQueryProvider(JObject arg0) const { callMethod( "setFilterQueryProvider", "(Landroid/widget/FilterQueryProvider;)V", arg0.object() ); } void CursorTreeAdapter::setGroupCursor(JObject arg0) const { callMethod( "setGroupCursor", "(Landroid/database/Cursor;)V", arg0.object() ); } } // namespace android::widget /* 09/23/2017 Copyright Tlera Corporation Created by Library may be used freely and without limit with attribution. */ #include "ICM42605.hpp" ICM42605::ICM42605(I2C_HandleTypeDef* i2c_bus) : _i2c_bus(i2c_bus) {} uint8_t ICM42605::getChipID() { return readByte(ICM42605_WHO_AM_I); } float ICM42605::getAres(uint8_t Ascale) { switch (Ascale) { // Possible accelerometer scales (and their register bit settings) are: // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11). case AFS_2G: _aRes = 2.0f / 32768.0f; return _aRes; case AFS_4G: _aRes = 4.0f / 32768.0f; return _aRes; case AFS_8G: _aRes = 8.0f / 32768.0f; return _aRes; case AFS_16G: _aRes = 16.0f / 32768.0f; return _aRes; default: return 0.0; } } float ICM42605::getGres(uint8_t Gscale) { switch (Gscale) { case GFS_15_125DPS: _gRes = 15.125f / 32768.0f; return _gRes; case GFS_31_25DPS: _gRes = 31.25f / 32768.0f; return _gRes; case GFS_62_5DPS: _gRes = 62.5f / 32768.0f; return _gRes; case GFS_125DPS: _gRes = 125.0f / 32768.0f; return _gRes; case GFS_250DPS: _gRes = 250.0f / 32768.0f; return _gRes; case GFS_500DPS: _gRes = 500.0f / 32768.0f; return _gRes; case GFS_1000DPS: _gRes = 1000.0f / 32768.0f; return _gRes; case GFS_2000DPS: _gRes = 2000.0f / 32768.0f; return _gRes; default: return 0.0; } } void ICM42605::init(uint8_t Ascale, uint8_t Gscale, uint8_t AODR, uint8_t GODR) { // enable gyro and accel in low noise mode // make sure not to disturb reserved bit values uint8_t temp = readByte(ICM42605_PWR_MGMT0); writeByte(ICM42605_PWR_MGMT0, temp | 0x0F); // gyro full scale and data rate temp = readByte(ICM42605_GYRO_CONFIG0); writeByte(ICM42605_GYRO_CONFIG0, temp | GODR | Gscale << 5); // set accel full scale and data rate temp = readByte(ICM42605_ACCEL_CONFIG0); writeByte(ICM42605_ACCEL_CONFIG0, temp | AODR | Ascale << 5); // set temperature sensor low pass filter to 5Hz, use first order gyro filter temp = readByte(ICM42605_GYRO_CONFIG1); writeByte(ICM42605_GYRO_CONFIG1, temp | 0xD0); } void ICM42605::readData(int16_t* destination) { uint8_t rawData[14]; // x/y/z accel register data stored here // Read the 14 raw data registers into data array readBytes(ICM42605_TEMP_DATA1, 14, &rawData[0]); // Turn the MSB and LSB into a signed 16-bit value destination[0] = ((int16_t)rawData[0] << 8) | rawData[1]; destination[1] = ((int16_t)rawData[2] << 8) | rawData[3]; destination[2] = ((int16_t)rawData[4] << 8) | rawData[5]; destination[3] = ((int16_t)rawData[6] << 8) | rawData[7]; destination[4] = ((int16_t)rawData[8] << 8) | rawData[9]; destination[5] = ((int16_t)rawData[10] << 8) | rawData[11]; destination[6] = ((int16_t)rawData[12] << 8) | rawData[13]; } uint8_t ICM42605::readByte(uint16_t address) { uint8_t temp; HAL_I2C_Mem_Read(_i2c_bus, ICM42605_ADDRESS, address, 1, &temp, 1, 5); return temp; } void ICM42605::writeByte(uint16_t address, uint8_t data) { HAL_I2C_Mem_Write(_i2c_bus, ICM42605_ADDRESS, address, 1, &data, 1, 5); } void ICM42605::readBytes(uint16_t addres, uint16_t size, uint8_t* data) { HAL_I2C_Mem_Read(_i2c_bus, ICM42605_ADDRESS, addres, 1, data, size, 50); } #pragma once /************************************************************************ * \file chatter/NEDistributedApp.hpp * \brief Configurations, settings, etc.. ************************************************************************/ #include "areg/base/GEGlobal.h" #include "areg/trace/GETrace.h" #include #include namespace NEDistributedApp { const char * const THREAD_DISTRIBUTED = "ThreadMessager"; typedef enum E_WndCommands { CmdFirst = WM_USER + 10 , CmdServiceStartup , CmdServiceNetwork , CmdServiceConnection , CmdClientConnection , CmdClientRegistration , CmdAddConnection , CmdRemoveConnection , CmdUpdateConnection , CmdDisconnectTriggered , CmdSendMessage , CmdTypeMessage , CmdSetDirectConnection , CmdDirectConnectionAdd , CmdDirectConnectionRemove , CmdDirectConnectionClose , CmdChatJoined , CmdChatMessage , CmdChatTyping , CmdChatClosed , CmdLast } eWndCommands; const char * const PREFIX_TRHEAD = "thread_"; const char * const PREFIX_MODEL = "model_"; const char * const PREFIX_INITIATOR = "init_"; const char * const PREFIX_PARTICIPANT = "part_"; String getDirectConnectionName( const String & nickName, uint32_t cookie, uint64_t session); String getConnectionServiceRole( const String & nickName, uint32_t cookie ); String getDirectMessagingRole( const String & nickName, uint32_t cookie, uint64_t session, bool isInitiator ); } #include #include #include #include #include #include #ifdef _WIN32 #include #else #include #endif #define IWQSORT_FO_IMPLEMENTATION 1 #include "Foundational/cmdline/cmdline.h" #include "Foundational/iwmisc/misc.h" #include "Foundational/iwmisc/sparse_fp_creator.h" #include "Foundational/iwqsort/iwqsort.h" #include "sparsefp.h" #include "dyfp.h" #include "various_distance_metrics.h" // Whether or not to issue a warning when an empty Sparse_Fingerprint is // built from a Daylight represetation. static int warn_empty_data = 0; void set_sparsefp_warn_empty_data(int s) { warn_empty_data = s; } static double continuous_tanimoto_exponent = 1.0; void set_continuous_tanimoto_exponent(double s) { continuous_tanimoto_exponent = s; } int Sparse_Fingerprint::check_sorted() const { unsigned int prev = _bit[0]; int need_to_die = 0; for (int i = 1; i < _nbits; i++) { if (_bit[i] <= prev) { cerr << "Out of order, i = " << i << " prev " << prev << " now " << _bit[i] << endl; need_to_die = 1; } prev = _bit[i]; } if (need_to_die) { cerr << "Sparse_Fingerprint::check_sorted: bits out of order\n"; debug_print(cerr); abort(); } return 1; } Sparse_Fingerprint::Sparse_Fingerprint() { _nbits = 0; _nset = 0; _bit = nullptr; _count = nullptr; _sum_squared = 0; _norm = 0.0; return; } Sparse_Fingerprint::Sparse_Fingerprint(const Sparse_Fingerprint & rhs) { _nbits = rhs._nbits; _nset = rhs._nset; _norm = rhs._norm; _sum_squared = rhs._sum_squared; if (nullptr == rhs._bit && nullptr == rhs._count) { _bit = nullptr; _count = nullptr; return; } assert(_nbits > 0); _bit = new unsigned int[_nbits]; _count = new int[_nbits]; copy_vector(_bit, rhs._bit, _nbits); copy_vector(_count, rhs._count, _nbits); return; } Sparse_Fingerprint::~Sparse_Fingerprint() { assert (-15 != _nbits); if (nullptr != _bit) delete [] _bit; if (nullptr != _count) delete [] _count; _nbits = -15; return; } // Recompute various aggregate variables. void Sparse_Fingerprint::_recompute_sums() { _nset = 0; _sum_squared = 0; for (int i = 0; i < _nbits; i++) { _nset += _count[i]; _sum_squared += _count[i] * _count[i]; } _norm = sqrt(static_cast(_sum_squared)); } int Sparse_Fingerprint::resize(int n) { if (nullptr != _bit) delete [] _bit; if (nullptr != _count) delete [] _count; if (0 == n) { _nbits = 0; _bit = nullptr; _nset = 0; _count = nullptr; _sum_squared = 0; return 1; } _bit = new unsigned int[n]; _count = new int[n]; if (nullptr == _count) { cerr << "Sparse_Fingerprint::resize: memory failure for " << n << " bits\n"; _nset = _nbits = 0; return 0; } _nbits = n; _nset = 0; _sum_squared = 0; return 1; } Sparse_Fingerprint & Sparse_Fingerprint::operator = (const Sparse_Fingerprint & rhs) { if (0 == rhs._nbits) { resize(0); return *this; } if (rhs._nbits != _nbits) resize(rhs._nbits); copy_vector(_bit, rhs._bit, _nbits); copy_vector(_count, rhs._count, _nbits); _nset = rhs._nset; _norm = rhs._norm; _sum_squared = rhs._sum_squared; return *this; } int Sparse_Fingerprint::construct_from_tdt_record(const const_IWSubstring & buffer) { const_IWSubstring daylight = buffer; //assert (buffer.ends_with ('>')); // new version may have newline daylight.remove_up_to_first('<'); daylight.chop(); if (0 == daylight.length()) { if (warn_empty_data) cerr << "Sparse_Fingerprint::construct_from_tdt_record: empty dataitem\n"; resize(0); return 1; } return construct_from_daylight_ascii_representation(daylight); } int Sparse_Fingerprint::debug_print(std::ostream & os) const { os << "Sparse fingerprint with " << _nbits << " bits, nset " << _nset << " sum_squared " << _sum_squared << '\n'; for (int i = 0; i < _nbits; i++) { os << ' ' << i << " bit " << _bit[i]; if (nullptr != _count) os << " hit " << _count[i] << " times"; os << endl; } return os.good(); } similarity_type_t Sparse_Fingerprint::tanimoto(const Sparse_Fingerprint & rhs) const { return _tanimoto_with_counts(rhs); } similarity_type_t Sparse_Fingerprint::distance(const Sparse_Fingerprint & rhs) const { return static_cast(1.0) - tanimoto(rhs); } similarity_type_t Sparse_Fingerprint::optimistic_distance(const Sparse_Fingerprint & rhs, const Tversky & tv) const { similarity_type_t d = distance(rhs); similarity_type_t tv1 = tversky_distance(rhs, tv); similarity_type_t tv2 = rhs.tversky_distance(*this, tv); if (d < tv1 && d < tv2) return d; if (tv1 < d && tv1 < tv2) return tv1; return tv2; } similarity_type_t Sparse_Fingerprint::tversky_distance(const Sparse_Fingerprint & rhs, const Tversky & tv) const { if (tv.treat_non_colliding_as_01()) return tversky_distance01(rhs, tv); return static_cast(1.0) - tversky(rhs, tv); } /* We don't take any advantage of the fact that we have counts */ similarity_type_t Sparse_Fingerprint::tversky_distance01(const Sparse_Fingerprint & rhs, const Tversky & tv) const { if (0 == _nbits || 0 == rhs._nbits) { if (_nbits == rhs._nbits) return static_cast(0.0); return static_cast(1.0); } const unsigned int * b1; int n1; const unsigned int * b2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; b1 = _bit; b2 = rhs._bit; } else { n1 = rhs._nbits; b1 = rhs._bit; b2 = _bit; } int bits_in_common = 0; for (int i = 0, j = 0; i < n1; i++) { unsigned int b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { bits_in_common++; j++; } } int just_a = _nbits - bits_in_common; int just_b = rhs._nbits - bits_in_common; similarity_type_t rc = static_cast(bits_in_common) / static_cast(tv.a() * just_a + tv.b() * just_b + bits_in_common); return static_cast(1.0) - rc; // convert to distance } similarity_type_t Sparse_Fingerprint::tversky(const Sparse_Fingerprint & rhs, const Tversky & tv) const { if (tv.treat_non_colliding_as_01()) return static_cast(1.0) - tversky_distance01(rhs, tv); if (0 == _nbits || 0 == rhs._nbits) { if (_nbits == rhs._nbits) // both 0 return static_cast(1.0); return static_cast(0.0); } const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 #ifdef DEBUG_SPARSE_TVERSKY cerr << "Lhs contains " << _nbits << " bits, last " << _bit[_nbits - 1] << " rhs contains " << rhs._nbits << " bits, last " << rhs._bit[rhs._nbits - 1] << endl; #endif if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; b1 = _bit; c1 = _count; b2 = rhs._bit; c2 = rhs._count; } else { n1 = rhs._nbits; b1 = rhs._bit; c1 = rhs._count; b2 = _bit; c2 = _count; } #ifdef DEBUG_SPARSE_TVERSKY cerr << "LHS\n"; for (int i = 0; i < _nbits; i++) { cerr << " i = " << i << " bit " << _bit[i] << " count " << _count[i] << endl; } cerr << "RHS\n"; for (int i = 0; i < rhs._nbits; i++) { cerr << " i = " << i << " bit " << rhs._bit[i] << " count " << rhs._count[i] << endl; } cerr << "Scanning " << n1 << " bits\n"; #endif int bits_in_common = 0; unsigned int b; // declare here for efficiency for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { // cerr << " skipping j = " << j << " bit " << b2[j] << " need " << b << endl; j++; } if (b2[j] == b) { if (c1[i] < c2[j]) bits_in_common += c1[i]; else bits_in_common += c2[j]; j++; } } int just_a = _nset - bits_in_common; int just_b = rhs._nset - bits_in_common; similarity_type_t rc = static_cast(bits_in_common) / static_cast(tv.a() * just_a + tv.b() * just_b + bits_in_common); return rc; } std::ostream & operator << (std::ostream & os, const Sparse_Fingerprint & sfp) { sfp.debug_print(os); return os; } int Sparse_Fingerprint::is_set(unsigned int b) const { #ifdef IS_SET_SLOW for (int i = 0; i < _nbits; i++) { if (b == _bit[i]) return 1; } return 0; #endif return std::binary_search(_bit, _bit + _nbits, b); } #ifdef SLOWER_VERSION_AA similarity_type_t Sparse_Fingerprint::_tanimoto_with_counts(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); //#define DEBUG_SPARSE_TANIMOTO_COUNT #ifdef DEBUG_SPARSE_TANIMOTO_COUNT cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set. RHS " << rhs._nbits << ' ' << rhs._nset << '\n'; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int bits_in_common = 0; unsigned int b; for (int i = 0, j = 0; i < n1;) { if (b1[i] < b2[j]) i++; else if (b1[i] > b2[j]) j++; else { bits_in_common += std::min(c1[i], c2[j]); i++; j++; } } similarity_type_t rc = static_cast(bits_in_common) / static_cast(_nset + rhs._nset - bits_in_common); #ifdef DEBUG_SPARSE_TANIMOTO_COUNT cerr << _nset << " bits and " << rhs._nset << " bits, " << bits_in_common << " bits_in_common, similarity " << rc << endl; #endif return rc; } #endif similarity_type_t Sparse_Fingerprint::_tanimoto_with_counts(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); //#define DEBUG_SPARSE_TANIMOTO_COUNT #ifdef DEBUG_SPARSE_TANIMOTO_COUNT cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set. RHS " << rhs._nbits << ' ' << rhs._nset << '\n'; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int bits_in_common = 0; unsigned int b; for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { if (c1[i] <= c2[j]) bits_in_common += c1[i]; else bits_in_common += c2[j]; j++; } } similarity_type_t rc = static_cast(bits_in_common) / static_cast(_nset + rhs._nset - bits_in_common); #ifdef DEBUG_SPARSE_TANIMOTO_COUNT cerr << _nset << " bits and " << rhs._nset << " bits, " << bits_in_common << " bits_in_common, similarity " << rc << endl; #endif return rc; } /* Version that does not depend on bic_table No longer needed, the default version does not use bic_table. */ similarity_type_t Sparse_Fingerprint::tanimoto_with_unlimited_counts(const Sparse_Fingerprint & rhs) const { return tanimoto(rhs); } similarity_type_t Sparse_Fingerprint::tanimoto_binary(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); //#define DEBUG_SPARSE_TANIMOTO_BINARY #ifdef DEBUG_SPARSE_TANIMOTO_BINARY cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set\n"; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; int n1; const unsigned int * b2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; b1 = _bit; b2 = rhs._bit; } else { n1 = rhs._nbits; b1 = rhs._bit; b2 = _bit; } int bits_in_common = 0; unsigned int b; for (int i = 0, j = 0; i < n1; ++i) { b = b1[i]; while (b2[j] < b) { ++j; } if (b2[j] == b) { bits_in_common++; ++j; } } similarity_type_t rc = static_cast(bits_in_common) / static_cast(_nbits + rhs._nbits - bits_in_common); #ifdef DEBUG_SPARSE_TANIMOTO_BINARY cerr << _nset << " bits and " << rhs._nset << " bits, " << bits_in_common << " bits_in_common, similarity " << rc << endl; #endif return rc; } /* At some stage, change this to just call dot_product and divide... */ similarity_type_t Sparse_Fingerprint::cosine_measure(const Sparse_Fingerprint & rhs) const { // Not sure why there were ever two variants of cosine. Consolidate. return cosine_coefficient(rhs); #ifdef NO_LONGER_NEEDED assert (nullptr != _count); //#define DEBUG_SPARSE_TANIMOTO_COUNT #ifdef DEBUG_SPARSE_TANIMOTO_COUNT cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set\n"; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int d1d2 = 0; unsigned int b; for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { d1d2 += c1[i] * c2[j]; j++; } } similarity_type_t rc = static_cast(d1d2) / (_norm * rhs._norm); return rc; #endif } uint32_t Sparse_Fingerprint::dot_product(const Sparse_Fingerprint & rhs) const { assert (nullptr != _count); const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } uint32_t d1d2 = 0; // To be returned. unsigned int b; for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { d1d2 += c1[i] * c2[j]; j++; } } return d1d2; } // Building a Sparse_Fingerprint from the Daylight form first involves forming // an IW_Bits_Base. std::optional FromDaylight(const const_IWSubstring& daylight) { if (daylight.empty()) { return std::nullopt; } IW_Bits_Base result; if (! result.construct_from_daylight_ascii_representation(daylight)) { cerr << "FromDaylight: cannot parse Daylight respresntation\n"; cerr << daylight << '\n'; return std::nullopt; } const int nbits = result.nbits(); if (0 != nbits % IW_BITS_PER_WORD) { cerr << "FromDaylight: must be a multiple of " << IW_BITS_PER_WORD << " bits, " << nbits << " is not\n"; return std::nullopt; } if (0 == nbits) { cerr << "FromDaylight:no bits present! '" << daylight << "'\n"; return std::nullopt; } int nwords = nbits / IW_BITS_PER_WORD; if (nbits % IW_BITS_PER_WORD != 0) { nwords++; } // Use old style cast since we change both the type and const. unsigned int * data = (unsigned int *) result.bits(); for (int i = 0; i < nwords; ++i) { data[i] = ntohl(data[i]); } return result; } /* Figuring out how many bits we have encoded is tricky. Here's a table of number of bits and number of words needed 1 2 2 3 3 4 4 5 5 7 6 8 7 9 8 10 9 12 10 13 11 14 12 15 13 17 14 18 15 19 16 20 17 22 */ int Sparse_Fingerprint::construct_from_daylight_ascii_representation(const const_IWSubstring & daylight) { if (0 == daylight.length()) return 1; IW_Bits_Base fp; if (! fp.construct_from_daylight_ascii_representation(daylight)) { cerr << "Sparse_Fingerprint::_counted_form_construct_from_daylight_ascii_representation: cannot parse\n"; cerr << daylight << endl; return 0; } int nb = fp.nbits(); if (0 != nb % IW_BITS_PER_WORD) { cerr << "Sparse_Fingerprint::construct_from_daylight_ascii_representation: must be a multiple of " << IW_BITS_PER_WORD << " bits, " << nb << " is not\n"; return 0; } if (0 == nb) { cerr << "Sparse_Fingerprint::construct_from_daylight_ascii_representation:no bits present! '" << daylight << "'\n"; return 0; } int nwords = nb / IW_BITS_PER_WORD; int number_bits = nwords / 5 * 4; // each 4 "bits" have a word with their counts int remainder = nwords % 5; if (0 != remainder) number_bits += remainder - 1; //cerr << "Reading " << nb << " bits, which is " << nwords << " words. nbits " << number_bits << endl; resize(number_bits); if (! iw_little_endian()) return _counted_form_construct_from_array_of_bits(fp.bits()); // need to do a byte swap. We only do byte swaps on the bit numbers, not the counts unsigned int * b = reinterpret_cast(const_cast(fp.bits())); unsigned int last_word = b[nwords - 1]; for (int i = 0; i < nwords; i++) { if (4 != i % 5) // swap words 0 1 2 3 5 6 7 8 10 11 12 13 15 16 ... b[i] = ntohl(b[i]); } b[nwords - 1] = last_word; return _counted_form_construct_from_array_of_bits(fp.bits()); // has been swapped } int Sparse_Fingerprint::_counted_form_construct_from_array_of_bits(const void * voidb) { assert (_nbits > 0); #ifdef __GNUG__ const unsigned int * b = static_cast(voidb); #else const unsigned int * b = reinterpret_cast(voidb); #endif union foo { unsigned int zbit; unsigned char count[IW_BYTES_PER_WORD]; }; #ifdef __GNUG__ const foo * fooptr = static_cast(voidb); #else const foo * fooptr = reinterpret_cast(voidb); #endif //cerr << "Reading " << _nbits << " bits\n"; // This constant will be used for checking whether or not we have 4 words + a count word int nbits_minus_5 = _nbits - IW_BYTES_PER_WORD - 1; for (int i = 0, j = 0; i < _nbits; i += IW_BYTES_PER_WORD, j += IW_BYTES_PER_WORD + 1) { if (i <= nbits_minus_5) // hopefully the most common case, we have 5 words to process { memcpy(_bit + i, b + j, IW_BYTES_PER_WORD * IW_BYTES_PER_WORD); const foo * c = fooptr + j + 4; _count[i] = c->count[0]; _count[i + 1] = c->count[1]; _count[i + 2] = c->count[2]; _count[i + 3] = c->count[3]; // cerr << "Read bits " << _bit[i] << ',' << _bit[i + 1] << ',' << _bit[i + 2] << ',' << _bit[i + 3] << endl; continue; } // We are at the end, we don't have a full set of words to process int extra_words = _nbits - i; memcpy(_bit + i, b + j, extra_words * IW_BYTES_PER_WORD); const foo * c = fooptr + j + extra_words; for (int k = 0; k < extra_words; k++) { _count[i + k] = c->count[k]; } break; } _recompute_sums(); check_sorted(); //#define ECHO_COUNTED_FINGERPRINTS #ifdef ECHO_COUNTED_FINGERPRINTS cerr << "Just read fingerprint\n"; debug_print(cerr); #endif return 1; } int Sparse_Fingerprint::construct_from_daylight_ascii_representation_uncounted(const const_IWSubstring& daylight) { std::optional bits = FromDaylight(daylight); if (! bits) { cerr << "Sparse_Fingerprint::construct_from_daylight_ascii_representation_uncounted:cannot intrepret input\n"; return 0; } const unsigned int * data = reinterpret_cast(bits->bits()); const int nbits = bits->nbits() / IW_BITS_PER_WORD; resize(nbits); // A little wasteful, perhaps add an option to resize to omit allocating the count array. delete [] _count; _count = nullptr; std::copy_n(data, nbits, _bit); return 1; } int Sparse_Fingerprint::next_bit_set(int & istart, unsigned int & zbit, int & hits) const { if (istart >= _nbits) return 0; zbit = _bit[istart]; hits = _count[istart]; istart++; return 1; } int Sparse_Fingerprint::_build_bit(int ndx, const const_IWSubstring & s) { const char sep = ':'; int i = 0; const_IWSubstring token; s.nextword(token, i, sep); unsigned int b; if (! token.numeric_value(b)) { cerr << "Sparse_Fingerprint::_build_bit:invalid bit '" << token << "'\n"; return 0; } _bit[ndx] = b; if (! s.nextword(token, i, sep)) { _count[ndx] = 1; return 1; } unsigned int c; if (! token.numeric_value(c)) { cerr << "Sparse_Fingerprint::_build_bit:invalid count '" << token << "'\n"; return 0; } _count[ndx] = c; return 1; } /* Somewhat hard to implement because we need to know the number of bits set up front. */ int Sparse_Fingerprint::construct_from_sparse_ascii_representation(const const_IWSubstring & fp) { if (0 == fp.length()) { _nbits = 0; return 1; } int n = fp.nwords(); if (! resize(n)) return 0; const_IWSubstring token; int i = 0; int ndx = 0; while (fp.nextword(token, i)) { if (! _build_bit(ndx, token)) { cerr << "Sparse_Fingerprint::construct_from_sparse_ascii_representation:invalid bit/count specification '" << token << "'\n"; return 0; } ndx++; } _recompute_sums(); assert (ndx == _nbits); if (! check_sorted()) { cerr << "Sparse_Fingerprint::construct_from_sparse_ascii_representation:not sorted\n"; return 0; } return 1; } /* This is incorrect. With sparse fingerprints, there really is no concept of number of bits not set by either entity. Also, doesn't look like I'm correctly counting the bits either - trailing bits from longer vector omitted. Don't use this. */ similarity_type_t Sparse_Fingerprint::fvb_modified_tanimoto(const Sparse_Fingerprint & rhs) const { //cerr << "NBITS " << _nbits << " nset " << _nset << " and rhs nbits " << rhs._nbits << " set " << rhs._nset << endl; if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } const unsigned int * b1; int n1; const int * c1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; b1 = _bit; c1 = _count; b2 = rhs._bit; c2 = rhs._count; } else { n1 = rhs._nbits; b1 = rhs._bit; c1 = rhs._count; b2 = _bit; c2 = _count; } int n11 = 0; int n00 = 0; for (int i = 0, j = 0; i < n1; i++) { unsigned int b = b1[i]; while (b2[j] < b) { j++; n00 += c2[j]; } if (b2[j] == b) { if (c1[i] > c2[j]) { n11 += c2[j]; } else // less than or equal { n11 += c1[i]; } j++; } } return fligner_verducci_blower(_nset + rhs._nset, _nset, rhs._nset, n00, n11); } /* */ similarity_type_t Sparse_Fingerprint::manhattan_distance(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); //#define DEBUG_MANHATTAN_MEASURE #ifdef DEBUG_MANHATTAN_MEASURE cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set\n"; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; int n2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; n2 = rhs._nbits; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; n2 = _nbits; c2 = _count; b2 = _bit; } unsigned int d = 0; unsigned int b; int j = 0; for (int i = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { d += c2[j]; j++; } if (b2[j] == b) // bit set in both { if (c1[i] > c2[j]) d += c1[i] - c2[j]; else d += c2[j] - c1[i]; j++; } else // bit not set in 2nd FP d += c1[i]; } // Remember, the *2 array is longer than the *1 array. Gather any // unused items from *2 while (j < n2) { d += c2[j]; j++; } #ifdef DEBUG_MANHATTAN_MEASURE cerr << "d = " << d << " becomes " << (1.0 /static_cast(1 + d) ) << endl; #endif return static_cast(1.0 / static_cast(1 + d)); } /* Had to make a decision about how to handle the case where a bit is missing in one of the molecules, but not in the other. Do we add 1.0 to the distance, or just ignore it. I get better looking distances when I ignore those bits... */ similarity_type_t Sparse_Fingerprint::soergel_variant_similarity(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); //#define DEBUG_SOERGEL_MEASURE #ifdef DEBUG_SOERGEL_MEASURE cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set\n"; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } double rc = 0.0; int p = 0; unsigned int b; int j = 0; for (int i = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { rc += 1.0; p++; j++; } if (b2[j] == b) // bit set in both { if (c1[i] > c2[j]) { rc += static_cast(c1[i] - c2[j]) / static_cast(c1[i]); p++; } else if (c1[i] == c2[j]) p++; else { rc += static_cast(c2[j] - c1[i]) / static_cast(c2[j]); p++; } j++; } else { rc += 1.0; p++; } } #ifdef DEBUG_SOERGEL_MEASURE cerr << "p = 0, must be identical\n"; #endif if (0 == p) return 1.0f; #ifdef DEBUG_SOERGEL_MEASURE cerr << "rc = " << rc << " across " << p << " bits, becomes " << (rc / static_cast(p)) << endl; #endif return 1.0f - static_cast(rc / static_cast(p)); } //#define DEBUG_SOERGEL_MEASURE similarity_type_t Sparse_Fingerprint::soergel_similarity(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) { if (0 == _nbits && 0 == rhs._nbits) return static_cast(1.0); return static_cast(0.0); } assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); #ifdef DEBUG_SOERGEL_MEASURE cerr << "Comparing non colliding counted fingerprint with " << _nbits << " bits " << _nset << " set\n"; int bic = 0; for (int i = 0; i < _nbits; i++) { unsigned int b = _bit[i]; cerr << ' ' << i << " bit " << b << " set " << _count[i] << " times"; if (rhs.is_set(b)) { bic++; cerr << " *"; } cerr << endl; } cerr << bic << " bits in common, and " << rhs; #endif const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int numerator = 0; int denominator = 0; unsigned int b; int j = 0; for (int i = 0; i < n1; i++) { b = b1[i]; #ifdef DEBUG_SOERGEL_MEASURE cerr << "B1 " << b << " (i = " << i << "), c = " << c1[i] << "\n"; #endif while (b2[j] < b) { numerator += c2[j]; denominator += c2[j]; #ifdef DEBUG_SOERGEL_MEASURE cerr << " incrementing second vector, b = " << b2[j] << " count " << c2[j] << endl; #endif j++; } if (b2[j] == b) // bit set in both { #ifdef DEBUG_SOERGEL_MEASURE cerr << " match for bit " << b << ", i = " << i << " c1 " << c1[i] << ", j = " << j << " c2 " << c2[j] << endl; #endif if (c1[i] > c2[j]) { numerator += c1[i] - c2[j]; denominator += c1[i]; } else { numerator += c2[j] - c1[i]; denominator += c2[j]; } j++; } else { numerator += c1[i]; denominator += c1[i]; #ifdef DEBUG_SOERGEL_MEASURE cerr << " bit 1 " << b << " ahead, c = " << c1[i] << endl; #endif } #ifdef DEBUG_SOERGEL_MEASURE cerr << " finished i = " << i << ", numerator " << numerator << " denominator " << denominator << endl; #endif } return static_cast(1.0f) - static_cast(numerator) / static_cast(denominator); } #ifdef MIGHT_BE_SLIGHTLY_SLOWER int Sparse_Fingerprint::bits_in_common(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) return 0; assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int bits_in_common = 0; unsigned int b; for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { bits_in_common += bic_table[c1[i] * 256 + c2[j]]; j++; } } return bits_in_common; } #endif int Sparse_Fingerprint::bits_in_common(const Sparse_Fingerprint & rhs) const { if (0 == _nbits || 0 == rhs._nbits) return 0; assert (nullptr != _count); assert (_nset > 0 && rhs._nset > 0); const unsigned int * b1; const int * c1; int n1; const unsigned int * b2; const int * c2; // Make sure the last item in b2 is greater than the last item in b1 if (_bit[_nbits - 1] < rhs._bit[rhs._nbits - 1]) { n1 = _nbits; c1 = _count; b1 = _bit; c2 = rhs._count; b2 = rhs._bit; } else { n1 = rhs._nbits; c1 = rhs._count; b1 = rhs._bit; c2 = _count; b2 = _bit; } int bits_in_common = 0; unsigned int b; for (int i = 0, j = 0; i < n1; i++) { b = b1[i]; while (b2[j] < b) { j++; } if (b2[j] == b) { if (c1[i] < c2[j]) bits_in_common += c1[i]; else bits_in_common += c2[j]; j++; } } return bits_in_common; } int Sparse_Fingerprint::truncate_counts_at(int c) { int rc = 0; _nset = 0; _sum_squared = 0; for (int i = 0; i < _nbits; i++) { if (_count[i] > c) { _count[i] = c; _nset += c; _sum_squared += c * c; rc++; } else { _nset += _count[i]; _sum_squared += _count[i] * _count[i]; } } _norm = sqrt(static_cast(_sum_squared)); return rc; } /* compute fp1 - fp2 */ void Sparse_Fingerprint::vector_difference(const Sparse_Fingerprint & fp1, const Sparse_Fingerprint & fp2) { resize(fp1._nbits + fp2._nbits); // worst case, no bits in common _nbits = 0; int i1 = 0; int i2 = 0; while (i1 < fp1._nbits && i2 < fp2._nbits) { if (fp2._bit[i2] < fp1._bit[i1]) { _bit[_nbits] = fp2._bit[i2]; _count[_nbits] = - fp2._count[i2]; i2++; } else if (fp1._bit[i1] == fp2._bit[i2]) { _bit[_nbits] = fp1._bit[i1]; _count[_nbits] = fp1._count[i1] - fp2._count[i2]; i1++; i2++; } else { _bit[_nbits] = fp1._bit[i1]; _count[_nbits] = fp1._count[i1]; i1++; } _nbits++; } while (i1 < fp1._nbits) { _bit[_nbits] = fp1._bit[i1]; _count[_nbits] = fp1._count[i1]; i1++; _nbits++; } while (i2 < fp2._nbits) { _bit[_nbits] = fp2._bit[i2]; _count[_nbits] = - fp2._count[i2]; i2++; _nbits++; } // we don't set _nset, not sure what it would mean _nset = 0; _sum_squared = 0; _norm = 0.0; return; } double Sparse_Fingerprint::cosine_coefficient(const Sparse_Fingerprint & rhs) const { if (0 == _sum_squared || 0 == rhs._sum_squared) return 0.0; int sum_product = 0; int i1 = 0; int i2 = 0; #ifdef DEBUG_COSINE_COEFFICIENT cerr << "Cosine between " << _nbits << " bits and " << rhs._nbits << endl; #endif while (i1 < _nbits && i2 < rhs._nbits) { #ifdef DEBUG_COSINE_COEFFICIENT cerr << " cmp " << i1 << ' ' << _bit[i1] << " and " << i2 << ' ' << rhs._bit[i2] << ", counts " << _count[i1] << " and " << rhs._count[i2] << endl; #endif if (_bit[i1] < rhs._bit[i2]) i1++; else if (_bit[i1] == rhs._bit[i2]) { sum_product += _count[i1] * rhs._count[i2]; i1++; i2++; } else i2++; } if (0 == sum_product) return 0.0; #ifdef DEBUG_COSINE_COEFFICIENT cerr << " sum_product " << sum_product << " sum2 " << _sum_squared << " sum2 " << rhs._sum_squared << endl; #endif return static_cast(sum_product) / sqrt(static_cast(_sum_squared) * static_cast(rhs._sum_squared)); // Original version, not sure where this came from. Prefer standard form above. //return (static_cast(sum_product) / // sqrt(static_cast(_sum_squared) * static_cast(rhs._sum_squared)) + 1.0) * 0.5; } similarity_type_t Sparse_Fingerprint::continuous_tanimoto(const Sparse_Fingerprint & rhs) const { if (0 == _sum_squared || 0 == rhs._sum_squared) return 0.0; int i1 = 0; int i2 = 0; int sum_product = 0; while (i1 < _nbits && i2 < rhs._nbits) { if (_bit[i1] < rhs._bit[i2]) i1++; else if (_bit[i1] == rhs._bit[i2]) { sum_product += _count[i1] * rhs._count[i2]; i1++; i2++; } else i2++; } //cerr << "continuous_tanimoto_exponent " << continuous_tanimoto_exponent << " sum_product " << sum_product << " sq " << _sum_squared << " rhs " << rhs._sum_squared << endl; //cerr << static_cast(sum_product) / static_cast(_sum_squared + rhs._sum_squared) << endl; // Because we deal with counts, we will never have negative values, so we do NOT do the scaling from the -1.33 to 1 range if (1.0 != continuous_tanimoto_exponent) return pow((static_cast(sum_product) / static_cast(_sum_squared + rhs._sum_squared - sum_product)), continuous_tanimoto_exponent); else return (static_cast(sum_product) / static_cast(_sum_squared + rhs._sum_squared - sum_product)); } int Sparse_Fingerprint::append_daylight_ascii_form_with_counts_encoded(IWString & s) const { if (0 == _nbits) return 1; int bytes_needed = _nbits * 5; // need 5 bytes per sparse bit if (0 != bytes_needed % 4) bytes_needed = (bytes_needed / 4 + 1) * 4; IW_Bits_Base b(bytes_needed * IW_BITS_PER_BYTE); unsigned int * y = (unsigned int *)(b.bits()); // dangerous C type cast union { unsigned int counts; unsigned char c[4]; } counts; int counts_ndx = 0; // index into union above int b_ndx = 0; // index into y array counts.counts = 0; for (int i = 0; i < _nbits; i++) { y[b_ndx] = htonl(_bit[i]); b_ndx++; counts.c[counts_ndx] = static_cast(_count[i]); counts_ndx++; if (4 == counts_ndx) { y[b_ndx] = counts.counts; b_ndx++; counts_ndx = 0; } } if (counts_ndx > 0) { y[b_ndx] = counts.counts; b_ndx++; } IWString tmp; b.daylight_ascii_representation(tmp); s << tmp; return 1; } int Sparse_Fingerprint::count_for_bit(unsigned int b) const { const auto iter = std::lower_bound(_bit, _bit + _nbits, b); // If bit not present, return 0; if (iter == (_bit + _nbits) || *iter != b) { // bit not present return 0; } const int ndx = iter - _bit; return _count[ndx]; #ifdef EQUIVALENT_VERSION for (int i = 0; i < _nbits; i++) { if (b == _bit[i]) return _count[i]; if (_bit[i] > b) { return 0; } } return 0; #endif } class UnsignedIntComparator { private: public: int operator () (unsigned int, unsigned int) const; }; int UnsignedIntComparator::operator () (unsigned int i1, unsigned int i2) const { if (i1 < i2) return -1; if (i1 > i2) return 1; return 0; } int Sparse_Fingerprint::build_from_sparse_fingerprint_creator(Sparse_Fingerprint_Creator & sfc) { int n = sfc.nbits(); if (! resize(n)) return 0; if (0 == n) return 1; int notused; sfc.copy_bits_to_unsigned_int_array(_bit, notused); assert (notused == _nbits); UnsignedIntComparator uic; iwqsort(_bit, _nbits, uic); sfc.fill_count_array(_bit, _count, n); _recompute_sums(); return 1; } #ifdef __GNUG__ template void iwqsort(unsigned*, int, UnsignedIntComparator&); template void iwqsort(unsigned*, int, UnsignedIntComparator&, void*); template void compare_two_items(unsigned*, UnsignedIntComparator&, void*); template void swap_elements(unsigned&, unsigned&, void*); template void move_in_from_right(unsigned*, int&, int&, UnsignedIntComparator&); template void move_in_from_left(unsigned*, int&, int&, int, UnsignedIntComparator&, void*); #endif void * Sparse_Fingerprint::copy_to_contiguous_storage(void * p) const { memcpy(p, this, sizeof(Sparse_Fingerprint)); p = reinterpret_cast(p) + 1; memcpy(p, _bit, _nbits * sizeof(int)); p = reinterpret_cast(p) + _nbits; memcpy(p, _count, _nbits * sizeof(int)); p = reinterpret_cast(p) + _nbits; return p; } void * Sparse_Fingerprint::copy_to_contiguous_storage_gpu(void * p) const { memcpy(p, &_nbits, sizeof(int)); p = reinterpret_cast(p) + 1; memcpy(p, &_nset, sizeof(int)); p = reinterpret_cast(p) + 1; memcpy(p, _bit, _nbits * sizeof(int)); p = reinterpret_cast(p) + _nbits; unsigned int terminate=std::numeric_limits::max(); memcpy(p, &terminate, sizeof(unsigned int)); p = reinterpret_cast(p) + 1; memcpy(p, _count, _nbits * sizeof(int)); p = reinterpret_cast(p) + _nbits; return p; } const void * Sparse_Fingerprint::build_from_contiguous_storage(const void * p, int allocate_arrays) { if (allocate_arrays && nullptr != _bit) { delete [] _bit; delete [] _count; } memcpy(this, p, sizeof(Sparse_Fingerprint)); p = reinterpret_cast(p) + 1; if (allocate_arrays) { resize(_nbits); memcpy(_bit, p, _nbits * sizeof(int)); } else _bit = (unsigned int *) p; p = reinterpret_cast(p) + _nbits; if (allocate_arrays) memcpy(_count, p, _nbits * sizeof(int)); else _count = (int *) p; p = reinterpret_cast(p) + _nbits; return p; } int Sparse_Fingerprint::remove_bit(unsigned int b) { auto f = std::lower_bound(_bit, _bit + _nbits, b); if (f == (_bit + _nbits) || *f != b) // bit not present to be removed return 0; _nset -= _count[f - _bit]; _sum_squared -= (_count[f - _bit] * _count[f - _bit]); _norm = sqrt(static_cast(_sum_squared)); _nbits--; for (auto i = f - _bit; i < _nbits; ++i) { _bit[i] = _bit[i+1]; _count[i] = _count[i+1]; } return 1; } int Sparse_Fingerprint::set_count(unsigned int b, int c) { auto f = std::lower_bound(_bit, _bit + _nbits, b); if (f == (_bit + _nbits) || *f != b) // bit not present. return 0; const auto ndx = f - _bit; int old_count = _count[ndx]; _count[ndx] = c; _nset += (c - old_count); _sum_squared = _sum_squared - (old_count * old_count) + (c * c); _norm = sqrt(static_cast(_sum_squared)); return 1; } alonmm/VCSamples //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" using namespace concurrency; using namespace Windows::Data::Xml::Dom; using namespace Windows::Storage; using namespace Windows::Storage::Streams; ImageFile::ImageFile() : m_refCount(0), m_offset(0), m_data(nullptr) { } // Asynchronously load image data from an image file // void ImageFile::LoadAsync( _In_ StorageFolder^ location, _In_ Platform::String^ fileName ) { task getFile(location->GetFileAsync(fileName)); getFile.then([=](StorageFile^ file) { return FileIO::ReadBufferAsync(file); }).then([=](IBuffer^ buffer) { m_data = ref new Platform::Array(buffer->Length); DataReader::FromBuffer(buffer)->ReadBytes(m_data); }); } HRESULT STDMETHODCALLTYPE ImageFile::QueryInterface( REFIID uuid, _Outptr_ void** object ) { *object = nullptr; if ( uuid == __uuidof(IUnknown) || uuid == __uuidof(IStream) || uuid == __uuidof(ISequentialStream) ) { *object = static_cast(this); AddRef(); return S_OK; } else { *object = nullptr; return E_NOINTERFACE; } } ULONG STDMETHODCALLTYPE ImageFile::AddRef() { return static_cast(InterlockedIncrement(&m_refCount)); } ULONG STDMETHODCALLTYPE ImageFile::Release() { ULONG newCount = static_cast(InterlockedDecrement(&m_refCount)); if (newCount == 0) delete this; return newCount; } HRESULT STDMETHODCALLTYPE ImageFile::Read( _Out_writes_bytes_(bytesToRead) void* outputBuffer, ULONG bytesToRead, _Out_ ULONG* bytesRead ) { HRESULT hr = S_OK; if (m_offset + bytesToRead > m_data->Length) { bytesToRead = m_data->Length - m_offset; hr = S_FALSE; } if (bytesToRead > 0) { memcpy(outputBuffer, m_data->Data + m_offset, bytesToRead); } *bytesRead = bytesToRead; m_offset += bytesToRead; return hr; } HRESULT STDMETHODCALLTYPE ImageFile::Seek( LARGE_INTEGER distance, DWORD origin, _Out_ ULARGE_INTEGER* newLocation ) { ULONG offset = 0; switch (origin) { case STREAM_SEEK_CUR: offset = m_offset; case STREAM_SEEK_SET: if ( distance.HighPart != 0 || distance.LowPart + offset > m_data->Length ) { return STG_E_INVALIDFUNCTION; } offset += distance.LowPart; break; case STREAM_SEEK_END: if ( distance.HighPart != 0 || distance.LowPart > m_data->Length ) { return STG_E_INVALIDFUNCTION; } offset = m_data->Length - distance.LowPart; break; default: return STG_E_INVALIDFUNCTION; } m_offset = offset; if (newLocation) { newLocation->HighPart = 0; newLocation->LowPart = m_offset; } return S_OK; } HRESULT STDMETHODCALLTYPE ImageFile::Write( _In_reads_bytes_(bytesToWrite) void const* inputBuffer, ULONG bytesToWrite, _Out_ ULONG* bytesWritten ) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::SetSize(ULARGE_INTEGER) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::CopyTo( _In_ IStream*, ULARGE_INTEGER, _Out_ ULARGE_INTEGER*, _Out_ ULARGE_INTEGER* ) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::Commit(DWORD) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::Revert() { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::LockRegion( ULARGE_INTEGER, ULARGE_INTEGER, DWORD ) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::UnlockRegion( ULARGE_INTEGER, ULARGE_INTEGER, DWORD ) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::Clone(_Outptr_ IStream **) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE ImageFile::Stat( _Out_ STATSTG* statistics, DWORD ) { memset(statistics, 0, sizeof(*statistics)); statistics->cbSize.LowPart = m_data->Length; statistics->cbSize.HighPart = 0; return S_OK; } maktheus/esbmc0 /*******************************************************************\ Module: C++ Language Type Checking Author: , \*******************************************************************/ #include #include #include void cpp_declaratort::output(std::ostream &out) const { out << " name: " << name().pretty() << std::endl; out << " type: " << type().pretty() << std::endl; out << " value: " << value().pretty() << std::endl; out << " init_args: " << init_args().pretty() << std::endl; out << " method_qualifier: " << method_qualifier().pretty() << std::endl; } typet cpp_declaratort::merge_type(const typet &declaration_type) const { typet dest_type = type(); if(declaration_type.id() == "cpp-cast-operator") return dest_type; typet *p = &dest_type; // walk down subtype until we hit nil while(true) { typet &t = *p; if(t.is_nil()) { t = declaration_type; break; } assert(t.id() != ""); p = &t.subtype(); } return dest_type; } 0 /***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr const char _loggerCat[] = "RenderableHabitableZone"; constexpr const std::array UniformNames = { "modelViewProjectionTransform", "opacity", "width", "transferFunctionTexture", "conservativeBounds", "showOptimistic" }; constexpr openspace::properties::Property::PropertyInfo EffectiveTemperatureInfo = { "EffectiveTemperature", "Effective Temperature", "The effective temperature of the corresponding star, in Kelvin. " "Used to compute the width and size of the disc." }; constexpr openspace::properties::Property::PropertyInfo LuminosityInfo = { "Luminosity", "Luminosity", "The luminosity of the corresponding star, in units of solar luminosities. " "Used to compute the width and size of the disc." }; constexpr openspace::properties::Property::PropertyInfo OptimisticInfo = { "Optimistic", "Optimistic" , "If true, the habitable zone disc is rendered with the optimistic boundaries " "rather than the conservative ones." }; constexpr openspace::properties::Property::PropertyInfo KopparapuTeffIntervalInfo = { "KopparapuTeffInterval", "Kopparapu TEFF" , "The effective temperature interval for which Kopparapu's formula is used for " "the habitable zone computation. For stars with temperatures outside the range, " "a simpler method by is used. This method only uses the star " "luminosity and does not include computation of the optimistic boundaries." }; struct [[codegen::Dictionary(RenderableHabitableZone)]] Parameters { // [[codegen::verbatim(EffectiveTemperatureInfo.description)]] float effectiveTemperature; // [[codegen::verbatim(LuminosityInfo.description)]] float luminosity; // [[codegen::verbatim(OptimisticInfo.description)]] std::optional optimistic; // [[codegen::verbatim(KopparapuTeffIntervalInfo.description)]] std::optional kopparapuTeffInterval; }; #include "renderablehabitablezone_codegen.cpp" } // namespace namespace openspace { documentation::Documentation RenderableHabitableZone::Documentation() { documentation::Documentation doc = codegen::doc(); doc.id = "space_renderablehabitablezone"; // @TODO cleanup // Insert the parents documentation entries until we have a verifier that can deal // with class hierarchy documentation::Documentation parentDoc = RenderableDisc::Documentation(); doc.entries.insert( doc.entries.end(), parentDoc.entries.begin(), parentDoc.entries.end() ); return doc; } RenderableHabitableZone::RenderableHabitableZone(const ghoul::Dictionary& dictionary) : RenderableDisc(dictionary) , _teff(EffectiveTemperatureInfo, 5780.f, 0.f, 7.5e4f) , _luminosity(LuminosityInfo, 1.f, 0.f, 1e8f) , _showOptimistic(OptimisticInfo, false) , _kopparapuTeffInterval(KopparapuTeffIntervalInfo, glm::vec2(1000.f, 10000.f)) { const Parameters p = codegen::bake(dictionary); _teff = p.effectiveTemperature; _teff.onChange([this]() { computeZone(); }); addProperty(_teff); _luminosity = p.luminosity; _luminosity.onChange([this]() { computeZone(); }); addProperty(_luminosity); _showOptimistic = p.optimistic.value_or(_showOptimistic); addProperty(_showOptimistic); // The user should not be able to change this property. It's just used to communicate // the different rendering that happens outside of this interval addProperty(_kopparapuTeffInterval); _kopparapuTeffInterval.setReadOnly(true); // Make parent's size related properties read only. We want to set them based on the // given temperature and luminosity _size.setReadOnly(true); _width.setReadOnly(true); computeZone(); setBoundingSphere(_size); } void RenderableHabitableZone::render(const RenderData& data, RendererTasks&) { _shader->activate(); glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)); glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; _shader->setUniform( _uniformCache.modelViewProjection, data.camera.projectionMatrix() * glm::mat4(modelViewTransform) ); _shader->setUniform(_uniformCache.width, _width); _shader->setUniform(_uniformCache.opacity, _opacity); _shader->setUniform(_uniformCache.conservativeBounds, _conservativeBounds); _shader->setUniform(_uniformCache.showOptimistic, _showOptimistic); ghoul::opengl::TextureUnit unit; unit.activate(); _texture->bind(); _shader->setUniform(_uniformCache.texture, unit); glEnablei(GL_BLEND, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(false); glDisable(GL_CULL_FACE); _plane->render(); _shader->deactivate(); // Restores GL State global::renderEngine->openglStateCache().resetBlendState(); global::renderEngine->openglStateCache().resetDepthState(); global::renderEngine->openglStateCache().resetPolygonAndClippingState(); } void RenderableHabitableZone::initializeShader() { _shader = global::renderEngine->buildRenderProgram( "HabitableZoneProgram", absPath("${MODULE_SPACE}/shaders/habitablezone_vs.glsl"), absPath("${MODULE_SPACE}/shaders/habitablezone_fs.glsl") ); ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); } void RenderableHabitableZone::updateUniformLocations() { ghoul::opengl::updateUniformLocations(*_shader, _uniformCache, UniformNames); } void RenderableHabitableZone::computeZone() { glm::dvec4 distancesInAu = computeKopparapuZoneBoundaries(_teff, _luminosity); constexpr const double AU = distanceconstants::AstronomicalUnit; const double inner = distancesInAu[0] * AU; const double innerConservative = distancesInAu[1] * AU; const double outerConservative = distancesInAu[2] * AU; const double outer = distancesInAu[3] * AU; double discWidth = 0.0; if (outer > 0.0) { discWidth = (outer - inner) / outer; } _size = static_cast(outer); _width = static_cast(discWidth); // Compute the coservative bounds normalized by the size of the disc, i.e. in [0, 1] _conservativeBounds = glm::vec2(innerConservative, outerConservative); _conservativeBounds /= _size; } glm::dvec4 RenderableHabitableZone::computeKopparapuZoneBoundaries(float teff, float luminosity) { // Kopparapu's formula only considers stars with teff in range [2600, 7200] K. // However, we want to use the formula for more stars, so add some flexibility to // the teff boundaries (see constructor). // OBS! This also prevents problems with too large teff values in the computation const glm::vec2 teffBounds = _kopparapuTeffInterval; if (teff > teffBounds.y || teff < teffBounds.x) { // For the other stars, use a method by : // https://www.planetarybiology.com/calculating_habitable_zone.html const double L = static_cast(luminosity); double inner = std::sqrt(L / 1.1); double outer = std::sqrt(L / 0.53); return glm::dvec4(inner, inner, outer, outer); } struct Coefficients { double seffSun; double a; double b; double c; double d; }; // Coefficients for planets of 1 Earth mass. Received from: // https://depts.washington.edu/naivpl/sites/default/files/HZ_coefficients.dat constexpr const Coefficients coefficients[] = { // Optimistic Inner boundary - Recent Venus {1.77600E+00, 2.13600E-04, 2.53300E-08, -1.33200E-11, -3.09700E-15}, // Conservative Inner boundary - Runaway greenhouse {1.10700E+00, 1.33200E-04, 1.58000E-08, -8.30800E-12, -1.93100E-15}, // Conservative Outer boundary - Maximum greenhouse {3.56000E-01, 6.17100E-05, 1.69800E-09, -3.19800E-12, -5.57500E-16}, // Optimistic Outer boundary - Early Mars {3.20000E-01, 5.54700E-05, 1.52600E-09, -2.87400E-12, -5.01100E-16} }; const double tstar = static_cast(teff - 5780.f); const double tstar2 = tstar * tstar; const double L = static_cast(luminosity); glm::dvec4 distances; for (int i = 0; i < 4; ++i) { const Coefficients& coeffs = coefficients[i]; double seff = coeffs.seffSun + (coeffs.a * tstar) + (coeffs.b * tstar2) + (coeffs.c * tstar * tstar2) + (coeffs.d * tstar2 * tstar2); distances[i] = std::pow(L / seff, 0.5); } return distances; } } // namespace openspace src/Root.cpp #include #include #include void GUI::Root::draw_line(DrawPoint start, DrawPoint end) { GUI::draw_line(start, end); } void GUI::Root::draw_rect(DrawPoint start, DrawPoint end) { GUI::draw_rect(start, end); } void GUI::Root::draw_rect(DrawPoint A, DrawPoint B, DrawPoint C, DrawPoint D) { GUI::draw_rect(A, B, C, D); } void GUI::Root::draw_triangle(DrawPoint A, DrawPoint B, DrawPoint C) { GUI::draw_triangle(A, B, C); } void GUI::Root::draw_text(int row, int column, mstd::wstring text, Color color) { GUI::draw_text(row, column, text, color); } void GUI::Root::draw_textShadow(int row, int column, mstd::wstring text, Color color) { GUI::draw_textShadow(row, column, text, color); } void GUI::Root::draw_translate(float x, float y) { GUI::_draw_translate(x, y); } void GUI::Root::_draw() { ContainerBase::_draw(); } GUI::Root::Root() : GUI::ContainerBase(0, 0, 0, 0) { }#pragma once #include namespace andromeda { namespace gfx { struct Mesh { ph::RawBuffer vertices; ph::RawBuffer indices; uint32_t num_vertices = 0; uint32_t num_indices = 0; }; } // namespace gfx } // namespace andromedaramkumarkoppu/NUCLEO-F767ZI-ESW /** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #include #include MainMenuPresenter::MainMenuPresenter(MainMenuView& v) : DemoPresenter(v), view(v) { } void MainMenuPresenter::activate() { } void MainMenuPresenter::deactivate() { } void MainMenuPresenter::setSelectedDemoScreen(Defines::DemoID elementIndex) { model->setSelectedDemoScreen(elementIndex); } void MainMenuPresenter::setPreviousSelectedMenuType(Defines::MainMenuType menuType) { model->setPreviousSelectedMainMenuType(menuType); } Defines::DemoID MainMenuPresenter::getSelectedDemoScreen() { return model->getSelectedDemoScreen(); } Defines::MainMenuType MainMenuPresenter::getPreviousSelectedMenuType() { return model->getPreviousSelectedMainMenuType(); } void MainMenuPresenter::screenSaverMinorTick() { view.screenSaverMinorTick(); } void MainMenuPresenter::gotoSTMenu() { // TODO Goto ST menu #ifndef SIMULATOR __HAL_RCC_RTC_ENABLE(); __HAL_RCC_PWR_CLK_ENABLE(); __HAL_RCC_BKPSRAM_CLK_ENABLE(); HAL_PWR_EnableBkUpAccess(); *(uint32_t *)(0x40024000) = 0x5AA55BBB; NVIC_SystemReset(); #endif } // -*- C++ -*- //! //! \file Fetch.cpp //! \brief Implementation of the CoreModel Fetch unit //! #include #include "Fetch.hpp" #include "sparta/events/StartupEvent.hpp" namespace core_example { const char * Fetch::name = "fetch"; // Dummy opcodes, but based on a really small piece of PowerPC... static std::vector dummy_opcodes = { { {0x7c01f214, 0xffffffff, {}, "add.", 0 }, ExampleInst::TargetUnit::ALU0, 1, false}, { {0x7c6f0f10, 0xffffffff, {}, "cntlzw", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c800000, 0xffffffff, {}, "add", 0 }, ExampleInst::TargetUnit::ALU0, 1, false}, { {0x7c700000, 0xffffffff, {}, "subf.", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c000000, 0xffffffff, {}, "and", 0 }, ExampleInst::TargetUnit::ALU0, 1, false}, { {0x7c000000, 0xffffffff, {}, "and", 0 }, ExampleInst::TargetUnit::ALU0, 1, false}, { {0x7c000710, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 1, false}, { {0x7c700000, 0xffffffff, {}, "cmp", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c700010, 0xffffffff, {}, "cmn", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c500000, 0xffffffff, {}, "cmp", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c500000, 0xffffffff, {}, "cmp", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0x7c400010, 0xffffffff, {}, "sub", 0 }, ExampleInst::TargetUnit::ALU1, 1, false}, { {0xfc800500, 0xffffffff, {}, "fabs",0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc000700, 0xffffffff, {}, "fctid.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc200d00, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc800700, 0xffffffff, {}, "fadd.",0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfcb10300, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfcb00ac0, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc000800, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc000d00, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc300a00, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 5, false}, { {0xfc800400, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 10, false}, { {0xfc800000, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 1, false}, { {0xfc800100, 0xffffffff, {}, "fadd.", 0 }, ExampleInst::TargetUnit::FPU, 1, false}, { {0xfc000110, 0xffffffff, {}, "fdiv", 0 }, ExampleInst::TargetUnit::FPU, 20, false}, { {0xfc800030, 0xffffffff, {}, "fdiv.", 0 }, ExampleInst::TargetUnit::FPU, 30, false}, { {0xfc100000, 0xffffffff, {}, "sync", 0 }, ExampleInst::TargetUnit::ROB, 1, false}, { {0x7ea00010, 0xffffffff, {}, "lwx", 0 }, ExampleInst::TargetUnit::LSU, 10, false}, { {0xfca00030, 0xffffffff, {}, "stw", 0 }, ExampleInst::TargetUnit::LSU, 10, true} }; // Fetch a random instruction or MaxIPC template void Fetch::fetchInstruction_() { const uint32_t upper = std::min(credits_inst_queue_, num_insts_to_fetch_); // Nothing to send. Don't need to schedule this again. if(upper == 0) { return; } InstGroup insts_to_send; for(uint32_t i = 0; i < upper; ++i) { ExampleInstPtr ex_inst; if(MaxIPC) { ex_inst = sparta::allocate_sparta_shared_pointer(example_inst_allocator, dummy_opcodes[i], getClock()); // This can be done instead, but you will lose about // ~20% performance in an experiment running 5M // instructions //ex_inst.reset(new ExampleInst(dummy_opcodes[i], getClock())); } else { ex_inst = sparta::allocate_sparta_shared_pointer(example_inst_allocator, dummy_opcodes[rand() % dummy_opcodes.size()], getClock()); } ex_inst->setUniqueID(++next_inst_id_); ex_inst->setVAdr(vaddr_); ex_inst->setSpeculative(speculative_path_); insts_to_send.emplace_back(ex_inst); if(SPARTA_EXPECT_FALSE(info_logger_)) { info_logger_ << "RANDOM: Sending: " << ex_inst << " down the pipe"; } speculative_path_ = (ex_inst->getUnit() == ExampleInst::TargetUnit::ROB); vaddr_ += 4; } out_fetch_queue_write_.send(insts_to_send); credits_inst_queue_ -= upper; if(credits_inst_queue_ > 0) { fetch_inst_event_->schedule(1); } if(SPARTA_EXPECT_FALSE(info_logger_)) { info_logger_ << "Fetch: send num_inst=" << insts_to_send.size() << " instructions, remaining credit=" << credits_inst_queue_; } } Fetch::Fetch(sparta::TreeNode * node, const FetchParameterSet * p) : sparta::Unit(node), num_insts_to_fetch_(p->num_to_fetch), next_pc_(node, "next_pc", &vaddr_) { in_fetch_queue_credits_. registerConsumerHandler(CREATE_SPARTA_HANDLER_WITH_DATA(Fetch, receiveFetchQueueCredits_, uint32_t)); if (p->fetch_max_ipc == true) { fetch_inst_event_.reset(new sparta::SingleCycleUniqueEvent<>(&unit_event_set_, "fetch_max_ipc", CREATE_SPARTA_HANDLER(Fetch, fetchInstruction_))); // Schedule a single event to start reading sparta::StartupEvent(node, CREATE_SPARTA_HANDLER(Fetch, fetchInstruction_)); } else { fetch_inst_event_.reset(new sparta::SingleCycleUniqueEvent<>(&unit_event_set_, "fetch_random", CREATE_SPARTA_HANDLER(Fetch, fetchInstruction_))); // Schedule a single event to start reading from a trace file sparta::StartupEvent(node, CREATE_SPARTA_HANDLER(Fetch, fetchInstruction_)); } in_fetch_flush_redirect_.registerConsumerHandler(CREATE_SPARTA_HANDLER_WITH_DATA(Fetch, flushFetch_, uint64_t)); srand(p->inst_rand_seed); } // Called when decode has room void Fetch::receiveFetchQueueCredits_(const uint32_t & dat) { credits_inst_queue_ += dat; if(SPARTA_EXPECT_FALSE(info_logger_)) { info_logger_ << "Fetch: receive num_decode_credits=" << dat << ", total decode_credits=" << credits_inst_queue_; } // Schedule a fetch event this cycle fetch_inst_event_->schedule(sparta::Clock::Cycle(0)); } // Called from Retire via in_fetch_flush_redirect_ port void Fetch::flushFetch_(const uint64_t & new_addr) { if(SPARTA_EXPECT_FALSE(info_logger_)) { info_logger_ << "Fetch: receive flush on new_addr=0x" << std::hex << new_addr << std::dec; } // New address to fetch from vaddr_ = new_addr; // Cancel all previously sent instructions on the outport out_fetch_queue_write_.cancel(); // No longer speculative speculative_path_ = false; } } 0 #include using json = nlohmann::json; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int /*argc*/, char ** argv) { const char* json_file = argv[1]; std::ifstream json_stream(json_file); json test_json = json::parse(json_stream); std::vector client_ips; auto cip_list = test_json["client_ips"]; for (auto it = cip_list.begin(); it != cip_list.end(); ++it) { auto client_ip = it.value (); client_ips.push_back (client_ip.get()); std::cout << client_ip.get(); } return 0; }inetcore/winhttp/v5/api/parseurl.cxx /*++ Copyright (c) 1995 Microsoft Corporation Module Name: parseurl.cxx Abstract: Contains functions to parse the basic URLs - FTP, Gopher, HTTP. An URL parser simply acts as a macro: it must break out the protocol-specific information from the URL and initiate opening the identified resource: all this can be accomplished by calling the relevant Internet protocol APIs. Code in this module is based on RFC1738 Contents: IsValidUrl DoesSchemeRequireSlashes ParseUrl CrackUrl EncodeUrlPath (HexCharToNumber) (NumberToHexChar) DecodeUrl DecodeUrlInSitu DecodeUrlStringInSitu GetUrlAddressInfo GetUrlAddress MapUrlSchemeName MapUrlScheme MapUrlSchemeToName Author: (rfirth) 26-Apr-1995 Environment: Win32(s) user-mode DLL Revision History: 26-Apr-1995 Created --*/ #include // // private manifests // #define RESERVED SAFE // // private macros // //#define HEX_CHAR_TO_NUMBER(ch) \ // ((ch <= '9') \ // ? (ch - '0') \ // : ((ch >= 'a') \ // ? ((ch - 'a') + 10) \ // : ((ch - 'A') + 10))) #define NUMBER_TO_HEX_CHAR(n) \ (((n) <= 9) ? ((char)(n) + '0') : (((char)(n) - 10) + 'A')) #define IS_UNSAFE_URL_CHARACTER(Char, Scheme) \ (((UCHAR)(Char) <= 0x20) || ((UCHAR)(Char) >= 0x7f) \ || (SafetyList[(Char) - 0x21] & (UNSAFE | Scheme))) #define IS_UNSAFE_URL_WIDECHARACTER(wChar, Scheme) \ (((WCHAR)(wChar) <= 0x0020) || ((WCHAR)(wChar) >= 0x007f) \ || (SafetyList[(wChar) - 0x0021] & (UNSAFE | Scheme))) // // private types // // // private prototypes // PRIVATE char HexCharToNumber( IN char ch ); PRIVATE char NumberToHexChar( IN int Number ); // // private data // // // SafetyList - the list of characters above 0x20 and below 0x7f that are // classified as safe, unsafe or scheme-specific. Safe characters do not need // to be escaped for any URL scheme. Unsafe characters must be escaped for all // URL schemes. Scheme-specific characters need only be escaped for the relevant // scheme(s) // const PRIVATE UCHAR SafetyList[] = { // // UNSAFE: 0x00..0x20 // SAFE | HOSTNAME, // 0x21 (!) UNSAFE, // 0x22 (") UNSAFE, // 0x23 (#) SAFE | HOSTNAME, // 0x24 ($) UNSAFE, // 0x25 (%) RESERVED | HOSTNAME, // 0x26 (&) SAFE | HOSTNAME, // 0x27 (') SAFE | HOSTNAME, // 0x28 (() SAFE | HOSTNAME, // 0x29 ()) SAFE | HOSTNAME, // 0x2A (*) SCHEME_GOPHER | HOSTNAME, // 0x2B (+) SAFE | HOSTNAME, // 0x2C (,) SAFE, // 0x2D (-) SAFE, // 0x2E (.) RESERVED | HOSTNAME, // 0x2F (/) SAFE, // 0x30 (0) SAFE, // 0x31 (1) SAFE, // 0x32 (2) SAFE, // 0x33 (3) SAFE, // 0x34 (4) SAFE, // 0x35 (5) SAFE, // 0x36 (6) SAFE, // 0x37 (7) SAFE, // 0x38 (8) SAFE, // 0x39 (9) RESERVED | HOSTNAME, // 0x3A (:) RESERVED | HOSTNAME, // 0x3B (;) UNSAFE, // 0x3C (<) RESERVED | HOSTNAME, // 0x3D (=) UNSAFE, // 0x3E (>) RESERVED | SCHEME_GOPHER | HOSTNAME, // 0x3F (?) RESERVED | HOSTNAME, // 0x40 (@) SAFE, // 0x41 (A) SAFE, // 0x42 (B) SAFE, // 0x43 (C) SAFE, // 0x44 (D) SAFE, // 0x45 (E) SAFE, // 0x46 (F) SAFE, // 0x47 (G) SAFE, // 0x48 (H) SAFE, // 0x49 (I) SAFE, // 0x4A (J) SAFE, // 0x4B (K) SAFE, // 0x4C (L) SAFE, // 0x4D (M) SAFE, // 0x4E (N) SAFE, // 0x4F (O) SAFE, // 0x50 (P) SAFE, // 0x51 (Q) SAFE, // 0x42 (R) SAFE, // 0x43 (S) SAFE, // 0x44 (T) SAFE, // 0x45 (U) SAFE, // 0x46 (V) SAFE, // 0x47 (W) SAFE, // 0x48 (X) SAFE, // 0x49 (Y) SAFE, // 0x5A (Z) UNSAFE, // 0x5B ([) UNSAFE, // 0x5C (\) UNSAFE, // 0x5D (]) UNSAFE, // 0x5E (^) SAFE, // 0x5F (_) UNSAFE, // 0x60 (`) SAFE, // 0x61 (a) SAFE, // 0x62 (b) SAFE, // 0x63 (c) SAFE, // 0x64 (d) SAFE, // 0x65 (e) SAFE, // 0x66 (f) SAFE, // 0x67 (g) SAFE, // 0x68 (h) SAFE, // 0x69 (i) SAFE, // 0x6A (j) SAFE, // 0x6B (k) SAFE, // 0x6C (l) SAFE, // 0x6D (m) SAFE, // 0x6E (n) SAFE, // 0x6F (o) SAFE, // 0x70 (p) SAFE, // 0x71 (q) SAFE, // 0x72 (r) SAFE, // 0x73 (s) SAFE, // 0x74 (t) SAFE, // 0x75 (u) SAFE, // 0x76 (v) SAFE, // 0x77 (w) SAFE, // 0x78 (x) SAFE, // 0x79 (y) SAFE, // 0x7A (z) UNSAFE, // 0x7B ({) UNSAFE, // 0x7C (|) UNSAFE, // 0x7D (}) UNSAFE // 0x7E (~) // // UNSAFE: 0x7F..0xFF // }; // // UrlSchemeList - the list of schemes that we support // typedef struct { LPSTR SchemeName; DWORD SchemeLength; INTERNET_SCHEME SchemeType; DWORD SchemeFlags; BOOL NeedSlashes; DWORD OpenFlags; } URL_SCHEME_INFO; const PRIVATE URL_SCHEME_INFO UrlSchemeList[] = { NULL, 0, INTERNET_SCHEME_DEFAULT, 0, FALSE, 0, "http", 4, INTERNET_SCHEME_HTTP, SCHEME_HTTP, TRUE, 0, "https", 5, INTERNET_SCHEME_HTTPS, SCHEME_HTTP, TRUE, WINHTTP_FLAG_SECURE, }; #define NUMBER_OF_URL_SCHEMES ARRAY_ELEMENTS(UrlSchemeList) BOOL ScanSchemes(LPTSTR pszToCheck, DWORD ccStr, PDWORD pwResult) { for (DWORD i=0; i 3) && (memcmp(&lpszUrl[schemeLength], "://", 3) == 0)) { skip = 3; // skip "://" haveSlashes = TRUE; } // // If we don't have slashes, make sure we don't need them. // If we have slashes, make sure they are required. // if ((!haveSlashes && !needSlashes) || (haveSlashes && needSlashes)) { if (ARGUMENT_PRESENT(lpSchemeType)) { *lpSchemeType = schemeType; } if (ARGUMENT_PRESENT(lpszSchemeName)) { *lpszSchemeName = lpszUrl; *lpdwSchemeNameLength = schemeLength; } lpszUrl += schemeLength + skip; dwUrlLength -= skip; if (isGeneric) { if (ARGUMENT_PRESENT(lpszUserName)) { *lpszUserName = NULL; *lpdwUserNameLength = 0; } if (ARGUMENT_PRESENT(lpszPassword)) { *lpszPassword = NULL; *lpdwPasswordLength = 0; } if (ARGUMENT_PRESENT(lpszHostName)) { *lpszHostName = NULL; *lpdwHostNameLength = 0; } if (ARGUMENT_PRESENT(lpServerPort)) { *lpServerPort = 0; } error = ERROR_SUCCESS; } else { error = GetUrlAddress(&lpszUrl, &dwUrlLength, lpszUserName, lpdwUserNameLength, lpszPassword, lpdwPasswordLength, lpszHostName, lpdwHostNameLength, lpServerPort, pHavePort ); } if (bEscape && (error == ERROR_SUCCESS)) { error = DecodeUrlInSitu(lpszUrl, &dwUrlLength); } if ((error == ERROR_SUCCESS) && ARGUMENT_PRESENT(lpszExtraInfo)) { *lpdwExtraInfoLength = 0; for (i = 0; i < (int)dwUrlLength; i++) { if (lpszUrl[i] == '?' || lpszUrl[i] == '#') { *lpszExtraInfo = &lpszUrl[i]; *lpdwExtraInfoLength = dwUrlLength - i; dwUrlLength -= *lpdwExtraInfoLength; } } } if ((error == ERROR_SUCCESS) && ARGUMENT_PRESENT(lpszUrlPath)) { *lpszUrlPath = lpszUrl; *lpdwUrlPathLength = dwUrlLength; } } else { error = ERROR_WINHTTP_UNRECOGNIZED_SCHEME; } quit: return error; } #define DEFAULT_REALLOC_SIZE 1024 DWORD EncodeUrlPath( IN DWORD Flags, IN DWORD SchemeFlags, IN LPSTR UrlPath, IN DWORD UrlPathLength, OUT LPSTR* pEncodedUrlPath, IN OUT LPDWORD EncodedUrlPathLength ) /*++ Routine Description: Encodes an URL-path. That is, escapes the string. Creates a new URL-path in which all the 'unsafe' and reserved characters for this scheme have been converted to escape sequences Arguments: Flags - controlling expansion SchemeFlags - which scheme we are encoding for - SCHEME_HTTP, etc. UrlPath - pointer to the unescaped string UrlPathLength - length of Url EncodedUrlPath - pointer to buffer where encoded URL will be written EncodedUrlPathLength - IN: size of EncodedUrlPath OUT: number of bytes written to EncodedUrlPath Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_INSUFFICIENT_BUFFER UrlPathLength not large enough to store encoded URL path --*/ { DWORD error; DWORD len; len = *EncodedUrlPathLength; LPSTR EncodedUrlPath = *pEncodedUrlPath; UCHAR ch; while(ch = (UCHAR)*UrlPath++) { // // check whether this character is safe. For now, we encode all unsafe // and scheme-specific characters the same way (i.e. irrespective of // scheme) // // We are allowing '/' to be copied unmodified // if (len < 3) { LPSTR pStr = (LPSTR)REALLOCATE_MEMORY(*pEncodedUrlPath, *EncodedUrlPathLength+DEFAULT_REALLOC_SIZE, LMEM_MOVEABLE); if (pStr) { EncodedUrlPath = pStr+*EncodedUrlPathLength-len; *pEncodedUrlPath = pStr; len += DEFAULT_REALLOC_SIZE; *EncodedUrlPathLength += DEFAULT_REALLOC_SIZE; } else { goto error; } } if (IS_UNSAFE_URL_CHARACTER(ch, SchemeFlags) && !((ch == '/') && (Flags & NO_ENCODE_PATH_SEP))) { *EncodedUrlPath++ = '%'; //*EncodedUrlPath++ = NumberToHexChar((int)ch / 16); *EncodedUrlPath++ = NUMBER_TO_HEX_CHAR((int)ch / 16); //*EncodedUrlPath++ = NumberToHexChar((int)ch % 16); *EncodedUrlPath++ = NUMBER_TO_HEX_CHAR((int)ch % 16); len -= 2; // extra --len below } else { *EncodedUrlPath++ = (signed char)ch; } --len; } *EncodedUrlPath = '\0'; *EncodedUrlPathLength -= len; error = ERROR_SUCCESS; quit: return error; error: error = ERROR_INSUFFICIENT_BUFFER; goto quit; } PRIVATE char HexCharToNumber( IN char ch ) /*++ Routine Description: Converts an ANSI character in the range '0'..'9' 'A'..'F' 'a'..'f' to its corresponding hexadecimal value (0..f) Arguments: ch - character to convert Return Value: char hexadecimal value of ch, as an 8-bit (signed) character value --*/ { return (ch <= '9') ? (ch - '0') : ((ch >= 'a') ? ((ch - 'a') + 10) : ((ch - 'A') + 10)); } PRIVATE char NumberToHexChar( IN int Number ) /*++ Routine Description: Converts a number in the range 0..15 to its ASCII character hex representation ('0'..'F') Arguments: Number - to convert Return Value: char character in above range --*/ { return (Number <= 9) ? (char)('0' + Number) : (char)('A' + (Number - 10)); } DWORD DecodeUrl( IN LPSTR Url, IN DWORD UrlLength, OUT LPSTR DecodedString, IN OUT LPDWORD DecodedLength ) /*++ Routine Description: Converts an URL string with embedded escape sequences (%xx) to a counted string It is safe to pass the same pointer for the string to convert, and the buffer for the converted results: if the current character is not escaped, it just gets overwritten, else the input pointer is moved ahead 2 characters further than the output pointer, which is benign Arguments: Url - pointer to URL string to convert UrlLength - number of characters in UrlString DecodedString - pointer to buffer that receives converted string DecodedLength - IN: number of characters in buffer OUT: number of characters converted Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_INVALID_URL UrlString couldn't be converted ERROR_INSUFFICIENT_BUFFER ConvertedString isn't large enough to hold all the converted UrlString --*/ { DWORD bufferRemaining; bufferRemaining = *DecodedLength; while (UrlLength && bufferRemaining) { char ch; if (*Url == '%') { // // BUGBUG - would %00 ever appear in an URL? // ++Url; if (isxdigit(*Url)) { ch = HexCharToNumber(*Url++) << 4; if (isxdigit(*Url)) { ch |= HexCharToNumber(*Url++); } else { return ERROR_WINHTTP_INVALID_URL; } } else { return ERROR_WINHTTP_INVALID_URL; } UrlLength -= 3; } else { ch = *Url++; --UrlLength; } *DecodedString++ = ch; --bufferRemaining; } if (UrlLength == 0) { *DecodedLength -= bufferRemaining; return ERROR_SUCCESS; } else { return ERROR_INSUFFICIENT_BUFFER; } } DWORD DecodeUrlInSitu( IN LPSTR BufferAddress, IN OUT LPDWORD BufferLength ) /*++ Routine Description: Decodes an URL string, if it contains escape sequences. The conversion is done in place, since we know that a string containing escapes is longer than the string with escape sequences (3 bytes) converted to characters (1 byte) Arguments: BufferAddress - pointer to the string to convert BufferLength - IN: number of characters to convert OUT: length of converted string Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_INVALID_URL ERROR_INSUFFICIENT_BUFFER --*/ { DWORD stringLength; stringLength = *BufferLength; if (memchr(BufferAddress, '%', stringLength)) { return DecodeUrl(BufferAddress, stringLength, BufferAddress, BufferLength ); } else { // // no escape character in the string, just return success // return ERROR_SUCCESS; } } DWORD DecodeUrlStringInSitu( IN LPSTR BufferAddress, IN OUT LPDWORD BufferLength ) /*++ Routine Description: Performs DecodeUrlInSitu() on a string and zero terminates it Assumes: 1. Even if no decoding is performed, *BufferLength is large enough to fit an extra '\0' character Arguments: BufferAddress - pointer to the string to convert BufferLength - IN: number of characters to convert OUT: length of converted string, excluding '\0' Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_INVALID_URL ERROR_INSUFFICIENT_BUFFER --*/ { DWORD error; error = DecodeUrlInSitu(BufferAddress, BufferLength); if (error == ERROR_SUCCESS) { BufferAddress[*BufferLength] = '\0'; } return error; } DWORD GetUrlAddressInfo( IN OUT LPSTR* Url, IN OUT LPDWORD UrlLength, OUT LPSTR* PartOne, OUT LPDWORD PartOneLength, OUT LPBOOL PartOneEscape, OUT LPSTR* PartTwo, OUT LPDWORD PartTwoLength, OUT LPBOOL PartTwoEscape ) /*++ Routine Description: Given a string of the form foo:bar, splits them into 2 counted strings about the ':' character. The address string may or may not contain a ':'. This function is intended to split into substrings the host:port and username:password strings commonly used in Internet address specifications and by association, in URLs Arguments: Url - pointer to pointer to string containing URL. On output this is advanced past the address parts UrlLength - pointer to length of URL in UrlString. On output this is reduced by the number of characters parsed PartOne - pointer which will receive first part of address string PartOneLength - pointer which will receive length of first part of address string PartOneEscape - TRUE on output if PartOne contains escape sequences PartTwo - pointer which will receive second part of address string PartTwoLength - pointer which will receive length of second part of address string PartOneEscape - TRUE on output if PartTwo contains escape sequences Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_INVALID_URL --*/ { LPSTR pString; LPSTR pColon; DWORD partLength; LPBOOL partEscape; DWORD length; // // parse out [:] or [:] (i.e. [:] // pString = *Url; pColon = NULL; partLength = 0; *PartOne = pString; *PartOneLength = 0; *PartOneEscape = FALSE; *PartTwoEscape = FALSE; partEscape = PartOneEscape; length = *UrlLength; while ((*pString != '/') && (*pString != '\0') && (length != 0)) { if (*pString == '%') { // // if there is a % in the string then it *must* (RFC 1738) be the // start of an escape sequence. This function just reports the // address of the substrings and their lengths; calling functions // must handle the escape sequences (i.e. it is their responsibility // to decide where to put the results) // *partEscape = TRUE; } if (*pString == ':') { if (pColon != NULL) { // // we don't expect more than 1 ':' // return ERROR_WINHTTP_INVALID_URL; } pColon = pString; *PartOneLength = partLength; if (partLength == 0) { *PartOne = NULL; } partLength = 0; partEscape = PartTwoEscape; } else { ++partLength; } ++pString; --length; } // // we either ended on the host (or user) name or the port number (or // password), one of which we don't know the length of // if (pColon == NULL) { *PartOneLength = partLength; *PartTwo = NULL; *PartTwoLength = 0; *PartTwoEscape = FALSE; } else { *PartTwoLength = partLength; *PartTwo = pColon + 1; // // in both the : and : cases, we cannot have // the second part without the first, although both parts being zero // length is OK (host name will be sorted out elsewhere, but (for now, // at least) I am allowing <>:<> for username:password, since I don't // see it expressly disallowed in the RFC. I may be revisiting this code // later...) // // N.B.: ftp://ftp.microsoft.com uses http://:0/-http-gw-internal-/menu.gif // if ((*PartOneLength == 0) && (partLength != 0)) { // return ERROR_WINHTTP_INVALID_URL; // } } // // update the URL pointer and length remaining // *Url = pString; *UrlLength = length; return ERROR_SUCCESS; } DWORD GetUrlAddress( IN OUT LPSTR* lpszUrl, OUT LPDWORD lpdwUrlLength, OUT LPSTR* lpszUserName OPTIONAL, OUT LPDWORD lpdwUserNameLength OPTIONAL, OUT LPSTR* lpszPassword OPTIONAL, OUT LPDWORD lpdwPasswordLength OPTIONAL, OUT LPSTR* lpszHostName OPTIONAL, OUT LPDWORD lpdwHostNameLength OPTIONAL, OUT LPINTERNET_PORT lpPort OPTIONAL, OUT LPBOOL pHavePort ) /*++ Routine Description: This function extracts any and all parts of the address information for a generic URL. If any of the address parts contain escaped characters (%nn) then they are converted in situ The generic addressing format (RFC 1738) is: :@: The addressing information cannot contain a password without a user name, or a port without a host name NB: ftp://ftp.microsoft.com uses URL's that have a port without a host name! (e.g. http://:0/-http-gw-internal-/menu.gif) Although only the lpszUrl and lpdwUrlLength fields are required, the address parts will be checked for presence and completeness Assumes: 1. If one of the optional lpsz fields is present (e.g. lpszUserName) then the accompanying lpdw field must also be supplied Arguments: lpszUrl - IN: pointer to the URL to parse OUT: URL remaining after address information N.B. The url-path is NOT canonicalized (unescaped) because it may contain protocol-specific information which must be parsed out by the protocol-specific parser lpdwUrlLength - returned length of the remainder of the URL after the address information lpszUserName - returned pointer to the user name This parameter can be omitted by those protocol parsers that do not require or expect user names in the URL lpdwUserNameLength - returned length of the user name part This parameter can be omitted by those protocol parsers that do not require or expect user names in the URL lpszPassword - returned pointer to the password This parameter can be omitted by those protocol parsers that do not require or expect user passwords in the URL lpdwPasswordLength - returned length of the password This parameter can be omitted by those protocol parsers that do not require or expect user passwords in the URL lpszHostName - returned pointer to the host name This parameter can be omitted by those protocol parsers that do not require the host name info lpdwHostNameLength - returned length of the host name This parameter can be omitted by those protocol parsers that do not require the host name info lpPort - returned value of the port field This parameter can be omitted by those protocol parsers that do not require or expect user port number pHavePort - returned boolean indicating whether a port was specified in the URL or not. This value is not returned if the lpPort parameter is omitted. Return Value: DWORD Success - ERROR_SUCCESS Failure - ERROR_WINHTTP_INVALID_URL We could not parse some part of the address info, or we found address info where the protocol parser didn't expect any ERROR_INSUFFICIENT_BUFFER We could not convert an escaped string --*/ { LPSTR pAt; DWORD urlLength; LPSTR pUrl; BOOL part1Escape; BOOL part2Escape; char portNumber[INTERNET_MAX_PORT_NUMBER_LENGTH + 1]; DWORD portNumberLength; LPSTR pPortNumber; DWORD error; LPSTR hostName; DWORD hostNameLength; pUrl = *lpszUrl; urlLength = strlen(pUrl); // // check to see if there is an '@' separating user name & password. If we // see a '/' or get to the end of the string before we see the '@' then // there is no username:password part // pAt = NULL; for (DWORD i = 0; i < urlLength; ++i) { if (pUrl[i] == '/') { break; } else if (pUrl[i] == '@') { pAt = &pUrl[i]; break; } } if (pAt != NULL) { DWORD addressPartLength; LPSTR userName; DWORD userNameLength; LPSTR password; DWORD passwordLength; addressPartLength = (DWORD) (pAt - pUrl); urlLength -= addressPartLength; error = GetUrlAddressInfo(&pUrl, &addressPartLength, &userName, &userNameLength, &part1Escape, &password, &passwordLength, &part2Escape ); if (error != ERROR_SUCCESS) { return error; } // // ensure there is no address information unparsed before the '@' // INET_ASSERT(addressPartLength == 0); INET_ASSERT(pUrl == pAt); if (ARGUMENT_PRESENT(lpszUserName)) { INET_ASSERT(ARGUMENT_PRESENT(lpdwUserNameLength)); // // convert the user name in situ // if (part1Escape) { INET_ASSERT(userName != NULL); INET_ASSERT(userNameLength != 0); error = DecodeUrlInSitu(userName, &userNameLength); if (error != ERROR_SUCCESS) { return error; } } *lpszUserName = userName; *lpdwUserNameLength = userNameLength; } if (ARGUMENT_PRESENT(lpszPassword)) { // // convert the password in situ // if (part2Escape) { INET_ASSERT(userName != NULL); INET_ASSERT(userNameLength != 0); INET_ASSERT(password != NULL); INET_ASSERT(passwordLength != 0); error = DecodeUrlInSitu(password, &passwordLength); if (error != ERROR_SUCCESS) { return error; } } *lpszPassword = password; *lpdwPasswordLength = ; } // // the URL pointer now points at the host:port fields (remember that // ExtractAddressParts() must have bumped pUrl up to the end of the // password field (if present) which ends at pAt) // ++pUrl; // // similarly, bump urlLength to account for the '@' // --urlLength; } else { // // no '@' therefore no username or password // if (ARGUMENT_PRESENT(lpszUserName)) { INET_ASSERT(ARGUMENT_PRESENT(lpdwUserNameLength)); *lpszUserName = NULL; *lpdwUserNameLength = 0; } if (ARGUMENT_PRESENT(lpszPassword)) { INET_ASSERT(ARGUMENT_PRESENT(lpdwPasswordLength)); *lpszPassword = NULL; *lpdwPasswordLength = 0; } } // // now get the host name and the optional port // pPortNumber = portNumber; portNumberLength = sizeof(portNumber); error = GetUrlAddressInfo(&pUrl, &urlLength, &hostName, &hostNameLength, &part1Escape, &pPortNumber, &portNumberLength, &part2Escape ); if (error != ERROR_SUCCESS) { return error; } // // the URL address information MUST contain the host name // // if ((hostName == NULL) || (hostNameLength == 0)) { // return ERROR_WINHTTP_INVALID_URL; // } if (ARGUMENT_PRESENT(lpszHostName)) { INET_ASSERT(ARGUMENT_PRESENT(lpdwHostNameLength)); // // if the host name contains escaped characters, convert them in situ // if (part1Escape) { error = DecodeUrlInSitu(hostName, &hostNameLength); if (error != ERROR_SUCCESS) { return error; } } *lpszHostName = hostName; *lpdwHostNameLength = hostNameLength; } // // if there is a port field, convert it if there are escaped characters, // check it for valid numeric characters, and convert it to a number // if (ARGUMENT_PRESENT(lpPort)) { if (portNumberLength != 0) { DWORD i; DWORD port; INET_ASSERT(pPortNumber != NULL); if (part2Escape) { error = DecodeUrlInSitu(pPortNumber, &portNumberLength); if (error != ERROR_SUCCESS) { return error; } } // // ensure all characters in the port number buffer are numeric, and // calculate the port number at the same time // for (i = 0, port = 0; i < portNumberLength; ++i) { if (!isdigit(*pPortNumber)) { return ERROR_WINHTTP_INVALID_URL; } port = port * 10 + (int)(*pPortNumber++ - '0'); // We won't allow ports larger than 65535 ((2^16)-1) // We have to check this every time to make sure that someone // doesn't try to overflow a DWORD. if (port > 65535) { return ERROR_WINHTTP_INVALID_URL; } } *lpPort = (INTERNET_PORT)port; if (ARGUMENT_PRESENT(pHavePort)) { *pHavePort = TRUE; } } else { *lpPort = INTERNET_INVALID_PORT_NUMBER; if (ARGUMENT_PRESENT(pHavePort)) { *pHavePort = FALSE; } } } // // update the URL pointer and the length of the url-path // *lpszUrl = pUrl; *lpdwUrlLength = urlLength; return ERROR_SUCCESS; } INTERNET_SCHEME MapUrlSchemeName( IN LPSTR lpszSchemeName, IN DWORD dwSchemeNameLength ) /*++ Routine Description: Maps a scheme name/length to a scheme name type Arguments: lpszSchemeName - pointer to name of scheme to map dwSchemeNameLength - length of scheme (if -1, lpszSchemeName is ASCIZ) Return Value: INTERNET_SCHEME --*/ { if (dwSchemeNameLength == (DWORD)-1) { dwSchemeNameLength = (DWORD)lstrlen(lpszSchemeName); } DWORD i; if (ScanSchemes(lpszSchemeName, dwSchemeNameLength, &i)) { return UrlSchemeList[i].SchemeType; } return INTERNET_SCHEME_UNKNOWN; } LPSTR MapUrlScheme( IN INTERNET_SCHEME Scheme, OUT LPDWORD lpdwSchemeNameLength ) /*++ Routine Description: Maps the enumerated scheme name type to the name Arguments: Scheme - enumerated scheme type to map lpdwSchemeNameLength - pointer to returned length of scheme name Return Value: LPSTR - pointer to scheme name or NULL --*/ { if ((Scheme >= INTERNET_SCHEME_FIRST) && (Scheme <= INTERNET_SCHEME_LAST)) { *lpdwSchemeNameLength = UrlSchemeList[Scheme].SchemeLength; return UrlSchemeList[Scheme].SchemeName; } *lpdwSchemeNameLength = 0; return NULL; } LPSTR MapUrlSchemeToName( IN INTERNET_SCHEME Scheme ) /*++ Routine Description: Maps the enumerated scheme name type to the name Arguments: Scheme - enumerated scheme type to map Return Value: LPSTR - pointer to scheme name or NULL --*/ { if ((Scheme >= INTERNET_SCHEME_FIRST) && (Scheme <= INTERNET_SCHEME_LAST)) { return UrlSchemeList[Scheme].SchemeName; } return NULL; } /* * ConvertUnicodeToMultiByte: * * dwFlags: WINHTTP_FLAG_NULL_CODEPAGE-> assumes correctly encoded string packaged into UTF8, no escaping done. WINHTTP_FLAG_VALID_HOSTNAME-> only for server name only the previous flag valid for server name passed in here. if both of these are not specified, then if dwCodePage is not INVALID, it'll be used to convert unicode string to ANSI. else UTF8 will be used. if ESCAPE && ESCAPE_PERCENT is specified, the ANSI url will be escaped (incl. %) else it will be escaped w/o escaping %s. */ DWORD ConvertUnicodeToMultiByte( LPCWSTR lpszObjectName, DWORD dwCodePage, MEMORYPACKET* pmp, DWORD dwFlags) { DWORD dwError = ERROR_SUCCESS; LPSTR pStr; WCHAR wc; LPCWSTR pwStr; BOOL bStrip0s = TRUE; DWORD dwUnicodeUrlSize; //determine size of string and/or safe characters if ((dwFlags & WINHTTP_FLAG_NULL_CODEPAGE) || (dwFlags & WINHTTP_FLAG_VALID_HOSTNAME)) { if (dwFlags & WINHTTP_FLAG_VALID_HOSTNAME) { for (pwStr = lpszObjectName; wc = *pwStr; ++pwStr) { if (IS_UNSAFE_URL_WIDECHARACTER(wc, HOSTNAME)) { dwError = ERROR_WINHTTP_INVALID_URL; goto done; } } pmp->dwAlloc = dwUnicodeUrlSize = (DWORD)(pwStr-lpszObjectName+1); } else { pmp->dwAlloc = dwUnicodeUrlSize = lstrlenW(lpszObjectName)+1; } } else { DWORD dwUnsafeChars = 0; // optimization to check for unsafe characters, and optimize the common case. // calculate the length, and while parsing the string, check if there are unsafeChars for(pwStr = lpszObjectName; wc = *pwStr; ++pwStr) { if (IS_UNSAFE_URL_WIDECHARACTER(wc, 0)) ++dwUnsafeChars; } dwUnicodeUrlSize = (DWORD)(pwStr-lpszObjectName+1); if (dwUnsafeChars == 0) { pmp->dwAlloc = dwUnicodeUrlSize; } else { bStrip0s = FALSE; } } //convert to MBCS if (bStrip0s) { INET_ASSERT(pmp->dwAlloc); pmp->psStr = (LPSTR)ALLOCATE_FIXED_MEMORY(pmp->dwAlloc); if (!pmp->psStr) { pmp->dwAlloc = 0; dwError = ERROR_NOT_ENOUGH_MEMORY; goto done; } pmp->dwSize = pmp->dwAlloc-1; for (pStr = pmp->psStr; wc = *lpszObjectName; ++lpszObjectName) { *(pStr)++ = (CHAR)wc; } *pStr = '\0'; } else { // convert with WideCharToMultiByte() pmp->dwAlloc = WideCharToMultiByte(dwCodePage, 0, lpszObjectName, dwUnicodeUrlSize, NULL, 0, NULL, NULL); if (pmp->dwAlloc) { pmp->psStr = (LPSTR)ALLOCATE_FIXED_MEMORY(pmp->dwAlloc); if (!pmp->psStr) { pmp->dwAlloc = 0; dwError = ERROR_NOT_ENOUGH_MEMORY; goto done; } pmp->dwSize = WideCharToMultiByte(dwCodePage, 0, lpszObjectName, dwUnicodeUrlSize, pmp->psStr, pmp->dwAlloc, NULL, NULL); if (!pmp->dwSize) { dwError = GetLastError(); goto done; } else pmp->dwSize -= 1; } else { dwError = GetLastError(); goto done; } } //escaping if (dwFlags & WINHTTP_FLAG_DEFAULT_ESCAPE) { INET_ASSERT (! (dwFlags & WINHTTP_FLAG_VALID_HOSTNAME)); static CHAR* hexArray = "0123456789ABCDEF"; UCHAR ch; DWORD dwUnsafeChars = 0; DWORD dwNewAlloc; LPSTR pDest, pNewStr; for(pStr = pmp->psStr; ch = *pStr; pStr = CharNextExA((WORD)dwCodePage, pStr, 0)) { if (IS_UNSAFE_URL_CHARACTER(ch, SCHEME_HTTP)) ++dwUnsafeChars; else if(ch == '?') break; } if (dwUnsafeChars == 0) goto done; dwNewAlloc = pmp->dwAlloc + dwUnsafeChars*2; pNewStr = pDest = (LPSTR)ALLOCATE_FIXED_MEMORY(dwNewAlloc); if (!pDest) { dwError = ERROR_NOT_ENOUGH_MEMORY; goto done; } BOOL bEscapePercent = (dwFlags & WINHTTP_FLAG_ESCAPE_PERCENT) ? TRUE : FALSE; BOOL bHitQuery = FALSE; LPSTR pNext; BOOL bLead; for (pStr = pmp->psStr; ch = *pStr;) { pNext = CharNextExA((WORD)dwCodePage, pStr, 0); bLead = TRUE; do { ch = *pStr; if (IS_UNSAFE_URL_CHARACTER(ch, SCHEME_HTTP) && (!bLead || (ch != '%') || bEscapePercent) ) { *pDest++ = '%'; *pDest++ = hexArray[ch>>4]; *pDest++ = hexArray[ch & 0x0f]; } else { *pDest++ = ch; if ((ch == '?') && bLead) { bHitQuery = TRUE; ++pStr; INET_ASSERT(pStr == pNext); break; } } bLead = FALSE; } while (++pStr != pNext); if (bHitQuery) break; } if (bHitQuery) { for ( ; ch = *pStr; pStr++) { *pDest++ = ch; } } *pDest = '\0'; FREE_FIXED_MEMORY(pmp->psStr); pmp->psStr = pNewStr; pmp->dwSize = (DWORD)(pDest-pNewStr); pmp->dwAlloc = dwNewAlloc; } done: if (pmp->psStr) pmp->dwAlloc = (pmp->dwAlloc > MP_MAX_STACK_USE) ? pmp->dwAlloc : MP_MAX_STACK_USE+1;// to force FREE in ~MEMORYPACKET return dwError; } #include "BFLoadProjectCommand.h" #include "BFDebug.h" namespace BlackFox::Editor { BFLoadProjectCommand::BFLoadProjectCommand(BFDataManager::Ptr dataManager) : BFCommandBase("Load Project", false) , m_dataManager(std::move(dataManager)) { } void BFLoadProjectCommand::execute(const BFProjectData& projectData) { BF_PRINT("Load project {}", projectData.name); const auto data = std::make_shared (projectData); m_dataManager->setActiveProject(data); //Add project to editor history BFEditorProjectHistory projectHistory; projectHistory.path = projectData.file(); projectHistory.lastUpdateTime = std::time(nullptr); m_dataManager->getEditorData()->addProjectToHistory(projectHistory); m_dataManager->getEditorData()->saveOrThrow(); } BFLoadProjectCommand* BFLoadProjectCommand::clone() const { return new BFLoadProjectCommand(m_dataManager); } } 0 // // core/Defines.hpp // pTK // // Created by on 2021-01-21. // #ifndef PTK_CORE_DEFINES_HPP #define PTK_CORE_DEFINES_HPP // Build type. #if !defined(PTK_DEBUG) && !defined(PTK_RELEASE) #ifdef NDEBUG #define PTK_RELEASE #else #define PTK_DEBUG #endif #endif // Enable debug options. #if defined(PTK_DEBUG) #if !defined(PTK_ENABLE_ASSERT) #define PTK_ENABLE_ASSERT #endif #endif // Check compiler. #if !defined(PTK_COMPILER_GCC) && defined(__GNUC__) #define PTK_COMPILER_GCC #elif !defined(PTK_COMPILER_CLANG) && defined(__clang__) #define PTK_COMPILER_CLANG #elif !defined(PTK_COMPILER_MSVC) && defined(_MSC_VER) #define PTK_COMPILER_MSVC #endif // Shared library defines. #if !defined(PTK_API) #if defined(PTK_SHARED) #if defined(PTK_COMPILER_MSVC) #if defined(PTK_EXPORTS) #define PTK_API __declspec(dllexport) #else #define PTK_API __declspec(dllimport) #endif #else #define PTK_API __attribute__((visibility("default"))) #endif #else #define PTK_API #endif #endif // Unused parameter. #if defined(PTK_COMPILER_GCC) #define UNUSED(x) x __attribute__((unused)) #elif defined(PTK_COMPILER_CLANG) #define UNUSED(x) x __attribute__((unused)) #elif defined(PTK_COMPILER_MSVC) #define UNUSED(x) __pragma(warning(suppress:4100)) x #else #define UNUSED(x) #endif // Enable Asserts #if defined(PTK_ENABLE_ASSERT) #define PTK_ASSERT(x, ...) if(!(x)) { PTK_ERROR("Assertion Failed: {0}", __VA_ARGS__); abort(); } #else #define PTK_ASSERT(...) #endif // Ignore all warnings (Begin) #if !defined(PTK_DISABLE_WARN_BEGIN) #if defined(PTK_COMPILER_GCC) // TODO #define PTK_DISABLE_WARN_BEGIN() #elif defined(PTK_COMPILER_CLANG) #define PTK_DISABLE_WARN_BEGIN() \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Weverything\"") #elif defined(PTK_COMPILER_MSVC) #define PTK_DISABLE_WARN_BEGIN() __pragma(warning(push, 0)) #else #define PTK_DISABLE_WARN_BEGIN() #endif #endif // Ignore all warnings (End) #if !defined(PTK_DISABLE_WARN_END) #if defined(PTK_COMPILER_GCC) // TODO #define PTK_DISABLE_WARN_END() #elif defined(PTK_COMPILER_CLANG) #define PTK_DISABLE_WARN_END() _Pragma("clang diagnostic pop"); #elif defined(PTK_COMPILER_MSVC) #define PTK_DISABLE_WARN_END() __pragma(warning(pop)) #else #define PTK_DISABLE_WARN_END() #endif #endif #endif // PTK_CORE_DEFINES_HPP #include "data_symbols.h" #include void data_symbols::add(string symbol_name, const char* data) { check_duplicates(symbol_name); check_cached_zeros(); strm_ << data; strm_ << 0_b; symbols_.emplace_back(std::move(symbol_name), current_offset_); current_offset_ = incr_check_overflow(current_offset_, static_cast(strlen(data) + 1)); } void data_symbols::add(string symbol_name, std::istream& is, dword num_bytes) { check_duplicates(symbol_name); check_cached_zeros(); std::copy_n(std::istreambuf_iterator(is), num_bytes, std::ostreambuf_iterator(strm_)); symbols_.emplace_back(std::move(symbol_name), current_offset_); current_offset_ = incr_check_overflow(current_offset_, num_bytes); } dword data_symbols::raw_size() { return static_cast(strm_.tellp()); } dword data_symbols::virtual_size() { return incr_check_overflow(raw_size(), cached_zeros_); } vector data_symbols::build() { auto str = strm_.str(); return {begin(str), end(str)}; } dword data_symbols::symbol(const char* name) const { const auto needle = std::find_if(begin(symbols_), end(symbols_), [&](const auto& sym) { return sym.first == name; }); if (needle == end(symbols_)) throw std::runtime_error{"symbol with given does not exist"}; return incr_check_overflow(needle->second, virtual_addr_); } void data_symbols::check_duplicates(const std::string& symbol_name) { const auto needle = std::find_if(begin(symbols_), end(symbols_), [&](const auto& sym) { return sym.first == symbol_name; }); if (needle != end(symbols_)) throw std::runtime_error{"symbol with given name alread added"}; } void data_symbols::check_cached_zeros() { for (size_t i = 0; i < cached_zeros_; ++i) strm_ << (byte)0; cached_zeros_ = 0; } /* * Copyright (c) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/PageScriptDebugServer.h" #include "bindings/core/v8/DOMWrapperWorld.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/ScriptSourceCode.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "bindings/core/v8/V8Window.h" #include "bindings/core/v8/WindowProxy.h" #include "core/dom/ExecutionContext.h" #include "core/frame/FrameConsole.h" #include "core/frame/FrameHost.h" #include "core/frame/LocalFrame.h" #include "core/frame/UseCounter.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/ScriptDebugListener.h" #include "core/page/Page.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" #include "wtf/StdLibExtras.h" #include "wtf/TemporaryChange.h" #include "wtf/text/StringBuilder.h" #include "gin/modules/console.h" #include "gin/converter.h" namespace blink { static LocalFrame* retrieveFrameWithGlobalObjectCheck(v8::Handle context) { if (context.IsEmpty()) return 0; // FIXME: This is a temporary hack for crbug.com/345014. // Currently it's possible that V8 can trigger Debugger::ProcessDebugEvent for a context // that is being initialized (i.e., inside Context::New() of the context). // We should fix the V8 side so that it won't trigger the event for a half-baked context // because there is no way in the embedder side to check if the context is half-baked or not. if (isMainThread() && DOMWrapperWorld::windowIsBeingInitialized()) return 0; v8::Handle global = V8Window::findInstanceInPrototypeChain(context->Global(), context->GetIsolate()); if (global.IsEmpty()) return 0; return toFrameIfNotDetached(context); } void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource) { if (preprocessorSource.isEmpty()) m_preprocessorSourceCode.clear(); else m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource)); m_scriptPreprocessor.clear(); } PageScriptDebugServer& PageScriptDebugServer::shared() { DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ()); return server; } v8::Isolate* PageScriptDebugServer::s_mainThreadIsolate = 0; void PageScriptDebugServer::setMainThreadIsolate(v8::Isolate* isolate) { s_mainThreadIsolate = isolate; } PageScriptDebugServer::PageScriptDebugServer() : ScriptDebugServer(s_mainThreadIsolate) , m_pausedPage(0) { } PageScriptDebugServer::~PageScriptDebugServer() { } void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page) { ScriptController& scriptController = page->mainFrame()->script(); v8::HandleScope scope(m_isolate); if (!m_listenersMap.size()) { v8::Debug::SetDebugEventListener(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this)); ensureDebuggerScriptCompiled(); } v8::Local debuggerContext = v8::Debug::GetDebugContext(); v8::Context::Scope contextScope(debuggerContext); v8::Local console = gin::Console::GetModule(m_isolate); debuggerContext->Global()->Set(gin::StringToV8(m_isolate, "console"), console); v8::Local debuggerScript = m_debuggerScript.newLocal(m_isolate); ASSERT(!debuggerScript->IsUndefined()); m_listenersMap.set(page, listener); WindowProxy* windowProxy = scriptController.existingWindowProxy(DOMWrapperWorld::mainWorld()); if (!windowProxy || !windowProxy->isContextInitialized()) return; v8::Local context = windowProxy->context(); v8::Handle getScriptsFunction = v8::Local::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts"))); v8::Handle argv[] = { context->GetEmbedderData(0) }; v8::Handle value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate); if (value.IsEmpty()) return; ASSERT(!value->IsUndefined() && value->IsArray()); v8::Handle scriptsArray = v8::Handle::Cast(value); for (unsigned i = 0; i < scriptsArray->Length(); ++i) dispatchDidParseSource(listener, v8::Handle::Cast(scriptsArray->Get(v8::Integer::New(m_isolate, i))), CompileSuccess); } void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page) { if (!m_listenersMap.contains(page)) return; if (m_pausedPage == page) continueProgram(); m_listenersMap.remove(page); if (m_listenersMap.isEmpty()) { discardDebuggerScript(); v8::Debug::SetDebugEventListener(0); // FIXME: Remove all breakpoints set by the agent. } } void PageScriptDebugServer::interruptAndRun(PassOwnPtr task) { ScriptDebugServer::interruptAndRun(task, s_mainThreadIsolate); } void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr clientMessageLoop) { m_clientMessageLoop = clientMessageLoop; } void PageScriptDebugServer::compileScript(ScriptState* scriptState, const String& expression, const String& sourceURL, String* scriptId, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtr* stackTrace) { ExecutionContext* executionContext = scriptState->executionContext(); RefPtr protect = executionContext->executingWindow()->frame(); ScriptDebugServer::compileScript(scriptState, expression, sourceURL, scriptId, exceptionDetailsText, lineNumber, columnNumber, stackTrace); if (!scriptId->isNull()) m_compiledScriptURLs.set(*scriptId, sourceURL); } void PageScriptDebugServer::clearCompiledScripts() { ScriptDebugServer::clearCompiledScripts(); m_compiledScriptURLs.clear(); } void PageScriptDebugServer::runScript(ScriptState* scriptState, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionDetailsText, int* lineNumber, int* columnNumber, RefPtr* stackTrace) { String sourceURL = m_compiledScriptURLs.take(scriptId); ExecutionContext* executionContext = scriptState->executionContext(); LocalFrame* frame = executionContext->executingWindow()->frame(); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt())); TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", TRACE_EVENT_SCOPE_PROCESS, "stack", InspectorCallStackEvent::currentCallStack()); RefPtr protect = frame; ScriptDebugServer::runScript(scriptState, scriptId, result, wasThrown, exceptionDetailsText, lineNumber, columnNumber, stackTrace); TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_PROCESS, "data", InspectorUpdateCountersEvent::data()); } ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle context) { v8::HandleScope scope(m_isolate); LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context); if (!frame) return 0; return m_listenersMap.get(frame->page()); } void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle context) { v8::HandleScope scope(m_isolate); LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(context); m_pausedPage = frame->page(); // Wait for continue or step command. m_clientMessageLoop->run(m_pausedPage); // The listener may have been removed in the nested loop. if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage)) listener->didContinue(); m_pausedPage = 0; } void PageScriptDebugServer::quitMessageLoopOnPause() { m_clientMessageLoop->quitNow(); } void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails) { v8::Handle eventContext = eventDetails.GetEventContext(); LocalFrame* frame = retrieveFrameWithGlobalObjectCheck(eventContext); if (!frame) return; if (!canPreprocess(frame)) return; v8::Handle eventData = eventDetails.GetEventData(); v8::Local debugContext = v8::Debug::GetDebugContext(); v8::Context::Scope contextScope(debugContext); v8::TryCatch tryCatch; //